Skip to main content

s3_endpoint/
config.rs

1use std::{
2    collections::{BTreeSet, HashMap},
3    fmt,
4    num::{NonZeroU64, NonZeroUsize},
5    path::PathBuf,
6    str::FromStr,
7    time::Duration,
8};
9
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13use crate::s3::types::BucketName;
14
15/// Runtime configuration for the S3 endpoint.
16#[derive(Clone, Debug)]
17pub struct Config {
18    /// Root directory used for object data, metadata, multipart sessions, and temp files.
19    pub storage_root: PathBuf,
20    /// Authentication and authorization configuration.
21    pub auth: AuthConfig,
22    /// Optional base domain for virtual-hosted-style bucket addressing.
23    pub virtual_host_base_domain: Option<String>,
24    /// Upload size and concurrency limits.
25    pub upload_limits: UploadLimits,
26}
27
28impl Config {
29    /// Creates a configuration with default auth and upload limits for a storage root.
30    pub fn new(storage_root: PathBuf) -> Self {
31        Self {
32            storage_root,
33            auth: AuthConfig::default(),
34            virtual_host_base_domain: None,
35            upload_limits: UploadLimits::default(),
36        }
37    }
38
39    /// Validates auth and upload-limit settings.
40    ///
41    /// Returns an error when any limit is zero, multipart minimum part size is
42    /// larger than the maximum part size, auth fields are malformed, or
43    /// configured bucket/action allow-lists contain unsupported values.
44    pub fn validate(&self) -> Result<(), ConfigError> {
45        self.upload_limits.validate()?;
46        self.auth.validate()
47    }
48
49    /// Creates a fluent configuration builder for a storage root.
50    pub fn builder(storage_root: impl Into<PathBuf>) -> ConfigBuilder {
51        ConfigBuilder {
52            config: Self::new(storage_root.into()),
53        }
54    }
55}
56
57/// Fluent builder for [`Config`].
58#[derive(Clone, Debug)]
59pub struct ConfigBuilder {
60    config: Config,
61}
62
63impl ConfigBuilder {
64    /// Replaces the authentication configuration.
65    pub fn auth(mut self, auth: AuthConfig) -> Self {
66        self.config.auth = auth;
67        self
68    }
69
70    /// Sets whether unsigned anonymous requests are accepted.
71    pub fn allow_anonymous(mut self, allow_anonymous: bool) -> Self {
72        self.config.auth.allow_anonymous = allow_anonymous;
73        self
74    }
75
76    /// Sets the SigV4 signing region.
77    pub fn region(mut self, region: impl Into<String>) -> Self {
78        self.config.auth.region = region.into();
79        self
80    }
81
82    /// Sets the optional virtual-hosted-style base domain.
83    pub fn virtual_host_base_domain(mut self, domain: impl Into<String>) -> Self {
84        self.config.virtual_host_base_domain = Some(domain.into());
85        self
86    }
87
88    /// Clears virtual-hosted-style addressing support.
89    pub fn without_virtual_host_base_domain(mut self) -> Self {
90        self.config.virtual_host_base_domain = None;
91        self
92    }
93
94    /// Replaces upload size and concurrency limits.
95    pub fn upload_limits(mut self, upload_limits: UploadLimits) -> Self {
96        self.config.upload_limits = upload_limits;
97        self
98    }
99
100    /// Returns the constructed configuration.
101    pub fn build(self) -> Config {
102        self.config
103    }
104}
105
106/// Low-level I/O buffer sizes used by upload summarization, multipart
107/// completion, and object streaming.
108#[derive(Clone, Debug, Eq, PartialEq)]
109pub struct IoTuning {
110    /// Buffer size used while summarizing staged uploads.
111    pub upload_summary_buffer_size: usize,
112    /// Buffer size used while copying multipart parts into the final object.
113    pub multipart_complete_buffer_size: usize,
114    /// Chunk size used while streaming object responses.
115    pub object_stream_buffer_size: usize,
116}
117
118impl Default for IoTuning {
119    fn default() -> Self {
120        const DEFAULT_BUFFER_SIZE: usize = 64 * 1024;
121        Self {
122            upload_summary_buffer_size: DEFAULT_BUFFER_SIZE,
123            multipart_complete_buffer_size: DEFAULT_BUFFER_SIZE,
124            object_stream_buffer_size: DEFAULT_BUFFER_SIZE,
125        }
126    }
127}
128
129impl IoTuning {
130    /// Creates a fluent I/O tuning builder using default buffer sizes.
131    pub fn builder() -> IoTuningBuilder {
132        IoTuningBuilder {
133            tuning: Self::default(),
134        }
135    }
136
137    /// Validates configured buffer sizes.
138    pub fn validate(&self) -> Result<(), ConfigError> {
139        if self.upload_summary_buffer_size == 0 {
140            return Err(ConfigError::InvalidIoTuning(
141                "upload_summary_buffer_size must be greater than 0",
142            ));
143        }
144        if self.multipart_complete_buffer_size == 0 {
145            return Err(ConfigError::InvalidIoTuning(
146                "multipart_complete_buffer_size must be greater than 0",
147            ));
148        }
149        if self.object_stream_buffer_size == 0 {
150            return Err(ConfigError::InvalidIoTuning(
151                "object_stream_buffer_size must be greater than 0",
152            ));
153        }
154        Ok(())
155    }
156}
157
158/// Fluent builder for [`IoTuning`].
159#[derive(Clone, Debug)]
160pub struct IoTuningBuilder {
161    tuning: IoTuning,
162}
163
164impl IoTuningBuilder {
165    /// Sets the staged upload summary buffer size.
166    pub fn upload_summary_buffer_size(mut self, value: usize) -> Self {
167        self.tuning.upload_summary_buffer_size = value;
168        self
169    }
170
171    /// Sets the multipart completion copy buffer size.
172    pub fn multipart_complete_buffer_size(mut self, value: usize) -> Self {
173        self.tuning.multipart_complete_buffer_size = value;
174        self
175    }
176
177    /// Sets the object response stream chunk size.
178    pub fn object_stream_buffer_size(mut self, value: usize) -> Self {
179        self.tuning.object_stream_buffer_size = value;
180        self
181    }
182
183    /// Returns the constructed I/O tuning.
184    pub fn build(self) -> IoTuning {
185        self.tuning
186    }
187}
188
189/// Multipart cleanup and lifecycle tuning.
190#[derive(Clone, Debug, Eq, PartialEq)]
191pub struct MultipartLifecycle {
192    /// Whether startup initialization removes terminal and stale temporary upload data.
193    pub cleanup_on_startup: bool,
194    /// Whether terminal completed/aborted upload directories are removed on startup.
195    pub remove_terminal_uploads_on_startup: bool,
196    /// Whether stale multipart `*.tmp` files are removed on startup.
197    pub remove_stale_temp_files_on_startup: bool,
198    /// Maximum age for incomplete multipart uploads loaded on startup.
199    pub abort_incomplete_after: Option<Duration>,
200}
201
202impl Default for MultipartLifecycle {
203    fn default() -> Self {
204        Self {
205            cleanup_on_startup: true,
206            remove_terminal_uploads_on_startup: true,
207            remove_stale_temp_files_on_startup: true,
208            abort_incomplete_after: None,
209        }
210    }
211}
212
213impl MultipartLifecycle {
214    /// Creates a fluent multipart lifecycle builder using default cleanup behavior.
215    pub fn builder() -> MultipartLifecycleBuilder {
216        MultipartLifecycleBuilder {
217            lifecycle: Self::default(),
218        }
219    }
220}
221
222/// Fluent builder for [`MultipartLifecycle`].
223#[derive(Clone, Debug)]
224pub struct MultipartLifecycleBuilder {
225    lifecycle: MultipartLifecycle,
226}
227
228impl MultipartLifecycleBuilder {
229    /// Sets whether startup cleanup is enabled.
230    pub fn cleanup_on_startup(mut self, enabled: bool) -> Self {
231        self.lifecycle.cleanup_on_startup = enabled;
232        self
233    }
234
235    /// Sets whether terminal completed/aborted uploads are removed on startup.
236    pub fn remove_terminal_uploads_on_startup(mut self, enabled: bool) -> Self {
237        self.lifecycle.remove_terminal_uploads_on_startup = enabled;
238        self
239    }
240
241    /// Sets whether stale multipart temporary files are removed on startup.
242    pub fn remove_stale_temp_files_on_startup(mut self, enabled: bool) -> Self {
243        self.lifecycle.remove_stale_temp_files_on_startup = enabled;
244        self
245    }
246
247    /// Sets the maximum age for incomplete multipart uploads loaded on startup.
248    pub fn abort_incomplete_after(mut self, duration: Duration) -> Self {
249        self.lifecycle.abort_incomplete_after = Some(duration);
250        self
251    }
252
253    /// Clears the incomplete multipart upload age limit.
254    pub fn without_abort_incomplete_after(mut self) -> Self {
255        self.lifecycle.abort_incomplete_after = None;
256        self
257    }
258
259    /// Returns the constructed lifecycle tuning.
260    pub fn build(self) -> MultipartLifecycle {
261        self.lifecycle
262    }
263}
264
265/// Upload size and concurrency limits.
266#[derive(Clone, Debug)]
267pub struct UploadLimits {
268    /// Maximum decoded object size in bytes.
269    pub max_object_size: u64,
270    /// Maximum decoded multipart part size in bytes.
271    pub max_part_size: u64,
272    /// Minimum size for each non-final multipart part in bytes.
273    pub min_non_final_part_size: u64,
274    /// Maximum number of concurrent S3 requests admitted by the router.
275    pub max_concurrent_s3_requests: usize,
276    /// Maximum number of concurrent `PutObject` writers.
277    pub max_active_object_writers: usize,
278    /// Maximum number of concurrent multipart `UploadPart` writers.
279    pub max_active_multipart_part_writers: usize,
280    /// Maximum number of concurrent aws-chunked decoders.
281    pub max_active_aws_chunked_decoders: usize,
282}
283
284impl Default for UploadLimits {
285    fn default() -> Self {
286        const GIB: u64 = 1024 * 1024 * 1024;
287        const MIB: u64 = 1024 * 1024;
288        Self {
289            max_object_size: 10_000 * 5 * GIB,
290            max_part_size: 5 * GIB,
291            min_non_final_part_size: 5 * MIB,
292            max_concurrent_s3_requests: 256,
293            max_active_object_writers: 64,
294            max_active_multipart_part_writers: 128,
295            max_active_aws_chunked_decoders: 64,
296        }
297    }
298}
299
300impl UploadLimits {
301    /// Creates a fluent upload-limit builder using production-oriented defaults.
302    pub fn builder() -> UploadLimitsBuilder {
303        UploadLimitsBuilder {
304            limits: Self::default_s3_compatible(),
305        }
306    }
307
308    /// Returns the default S3-compatible upload limits.
309    pub fn default_s3_compatible() -> Self {
310        Self::default()
311    }
312
313    /// Returns smaller limits intended for local development and tests.
314    pub fn local_development() -> Self {
315        const MIB: u64 = 1024 * 1024;
316        Self {
317            max_object_size: 1024 * MIB,
318            max_part_size: 512 * MIB,
319            min_non_final_part_size: 5 * MIB,
320            max_concurrent_s3_requests: 64,
321            max_active_object_writers: 16,
322            max_active_multipart_part_writers: 32,
323            max_active_aws_chunked_decoders: 16,
324        }
325    }
326
327    /// Validates all upload limits.
328    ///
329    /// Returns an error when a limit is zero or when
330    /// `min_non_final_part_size > max_part_size`.
331    pub fn validate(&self) -> Result<(), ConfigError> {
332        let limits = self.validated()?;
333        if limits.min_non_final_part_size > limits.max_part_size {
334            return Err(ConfigError::InvalidUploadLimit(
335                "min_non_final_part_size must be less than or equal to max_part_size",
336            ));
337        }
338        Ok(())
339    }
340
341    /// Converts raw numeric limits into non-zero validated limits.
342    ///
343    /// Returns an error when any configured limit is zero.
344    pub fn validated(&self) -> Result<ValidatedUploadLimits, ConfigError> {
345        Ok(ValidatedUploadLimits {
346            max_object_size: PositiveUploadLimit::new(
347                self.max_object_size,
348                "max_object_size must be greater than 0",
349            )?,
350            max_part_size: PositiveUploadLimit::new(
351                self.max_part_size,
352                "max_part_size must be greater than 0",
353            )?,
354            min_non_final_part_size: PositiveUploadLimit::new(
355                self.min_non_final_part_size,
356                "min_non_final_part_size must be greater than 0",
357            )?,
358            max_concurrent_s3_requests: PositiveAdmissionLimit::new(
359                self.max_concurrent_s3_requests,
360                "max_concurrent_s3_requests must be greater than 0",
361            )?,
362            max_active_object_writers: PositiveAdmissionLimit::new(
363                self.max_active_object_writers,
364                "max_active_object_writers must be greater than 0",
365            )?,
366            max_active_multipart_part_writers: PositiveAdmissionLimit::new(
367                self.max_active_multipart_part_writers,
368                "max_active_multipart_part_writers must be greater than 0",
369            )?,
370            max_active_aws_chunked_decoders: PositiveAdmissionLimit::new(
371                self.max_active_aws_chunked_decoders,
372                "max_active_aws_chunked_decoders must be greater than 0",
373            )?,
374        })
375    }
376}
377
378/// Fluent builder for [`UploadLimits`].
379#[derive(Clone, Debug)]
380pub struct UploadLimitsBuilder {
381    limits: UploadLimits,
382}
383
384impl UploadLimitsBuilder {
385    /// Sets the maximum decoded object size in bytes.
386    pub fn max_object_size(mut self, value: u64) -> Self {
387        self.limits.max_object_size = value;
388        self
389    }
390
391    /// Sets the maximum decoded multipart part size in bytes.
392    pub fn max_part_size(mut self, value: u64) -> Self {
393        self.limits.max_part_size = value;
394        self
395    }
396
397    /// Sets the minimum size for each non-final multipart part in bytes.
398    pub fn min_non_final_part_size(mut self, value: u64) -> Self {
399        self.limits.min_non_final_part_size = value;
400        self
401    }
402
403    /// Sets the maximum number of concurrently admitted S3 requests.
404    pub fn max_concurrent_s3_requests(mut self, value: usize) -> Self {
405        self.limits.max_concurrent_s3_requests = value;
406        self
407    }
408
409    /// Sets the maximum number of active `PutObject` writers.
410    pub fn max_active_object_writers(mut self, value: usize) -> Self {
411        self.limits.max_active_object_writers = value;
412        self
413    }
414
415    /// Sets the maximum number of active multipart part writers.
416    pub fn max_active_multipart_part_writers(mut self, value: usize) -> Self {
417        self.limits.max_active_multipart_part_writers = value;
418        self
419    }
420
421    /// Sets the maximum number of active aws-chunked decoders.
422    pub fn max_active_aws_chunked_decoders(mut self, value: usize) -> Self {
423        self.limits.max_active_aws_chunked_decoders = value;
424        self
425    }
426
427    /// Returns the constructed upload limits.
428    pub fn build(self) -> UploadLimits {
429        self.limits
430    }
431}
432
433/// Non-zero byte limit for upload sizes.
434#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
435pub struct PositiveUploadLimit(NonZeroU64);
436
437impl PositiveUploadLimit {
438    fn new(value: u64, error: &'static str) -> Result<Self, ConfigError> {
439        NonZeroU64::new(value)
440            .map(Self)
441            .ok_or(ConfigError::InvalidUploadLimit(error))
442    }
443
444    /// Returns the configured byte limit.
445    pub fn get(self) -> u64 {
446        self.0.get()
447    }
448}
449
450/// Non-zero limit for request or worker admission.
451#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
452pub struct PositiveAdmissionLimit(NonZeroUsize);
453
454impl PositiveAdmissionLimit {
455    fn new(value: usize, error: &'static str) -> Result<Self, ConfigError> {
456        NonZeroUsize::new(value)
457            .map(Self)
458            .ok_or(ConfigError::InvalidUploadLimit(error))
459    }
460
461    /// Returns the configured admission limit.
462    pub fn get(self) -> usize {
463        self.0.get()
464    }
465}
466
467/// Upload limits after zero-value validation.
468#[derive(Clone, Copy, Debug, Eq, PartialEq)]
469pub struct ValidatedUploadLimits {
470    /// Maximum decoded object size in bytes.
471    pub max_object_size: PositiveUploadLimit,
472    /// Maximum decoded multipart part size in bytes.
473    pub max_part_size: PositiveUploadLimit,
474    /// Minimum size for each non-final multipart part in bytes.
475    pub min_non_final_part_size: PositiveUploadLimit,
476    /// Maximum number of concurrent S3 requests.
477    pub max_concurrent_s3_requests: PositiveAdmissionLimit,
478    /// Maximum number of concurrent `PutObject` writers.
479    pub max_active_object_writers: PositiveAdmissionLimit,
480    /// Maximum number of concurrent multipart `UploadPart` writers.
481    pub max_active_multipart_part_writers: PositiveAdmissionLimit,
482    /// Maximum number of concurrent aws-chunked decoders.
483    pub max_active_aws_chunked_decoders: PositiveAdmissionLimit,
484}
485
486/// Configuration validation error.
487#[derive(Debug, Error, Eq, PartialEq)]
488pub enum ConfigError {
489    /// Upload limit validation failed.
490    #[error("invalid upload limit: {0}")]
491    InvalidUploadLimit(&'static str),
492
493    /// I/O tuning validation failed.
494    #[error("invalid I/O tuning: {0}")]
495    InvalidIoTuning(&'static str),
496
497    /// Auth configuration validation failed.
498    #[error("invalid auth configuration: {0}")]
499    InvalidAuthConfig(&'static str),
500}
501
502/// Validated access key identifier.
503#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
504pub struct AccessKeyId(String);
505
506impl AccessKeyId {
507    /// Parses an access key ID.
508    ///
509    /// Returns an error when the value is empty or contains whitespace or
510    /// control characters.
511    pub fn parse(value: impl Into<String>) -> Result<Self, ConfigError> {
512        let value = value.into();
513        validate_access_key_id(&value)?;
514        Ok(Self(value))
515    }
516
517    /// Returns the access key ID as a string slice.
518    pub fn as_str(&self) -> &str {
519        &self.0
520    }
521}
522
523impl fmt::Display for AccessKeyId {
524    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
525        formatter.write_str(&self.0)
526    }
527}
528
529/// Secret key value with a redacted `Debug` implementation.
530#[derive(Clone, Eq, PartialEq)]
531pub struct SecretKey(String);
532
533impl SecretKey {
534    /// Parses a secret key.
535    ///
536    /// Returns an error when the value is empty or contains control characters.
537    pub fn parse(value: impl Into<String>) -> Result<Self, ConfigError> {
538        let value = value.into();
539        validate_secret_key(&value)?;
540        Ok(Self(value))
541    }
542
543    /// Returns the raw secret key for signing verification.
544    pub(crate) fn as_str(&self) -> &str {
545        &self.0
546    }
547}
548
549impl fmt::Debug for SecretKey {
550    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
551        formatter.write_str("<redacted>")
552    }
553}
554
555/// Authentication, credential, and allow-list configuration.
556#[derive(Clone)]
557pub struct AuthConfig {
558    /// Whether unsigned anonymous requests are allowed.
559    pub allow_anonymous: bool,
560    /// Primary access key ID.
561    pub access_key_id: String,
562    /// Primary secret key. This value is redacted from `Debug` output.
563    pub secret_key: String,
564    /// Optional primary session token. This value is redacted from `Debug` output.
565    pub session_token: Option<String>,
566    /// SigV4 signing region.
567    pub region: String,
568    /// Maximum accepted SigV4 timestamp skew in seconds.
569    pub max_skew_seconds: i64,
570    /// Optional bucket allow-list. Empty means all buckets are allowed.
571    pub allowed_buckets: BTreeSet<String>,
572    /// Optional action allow-list. Empty means all implemented actions are allowed.
573    pub allowed_actions: BTreeSet<S3Action>,
574    /// Additional access keys.
575    pub credentials: Vec<AccessKeyConfig>,
576}
577
578impl fmt::Debug for AuthConfig {
579    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
580        formatter
581            .debug_struct("AuthConfig")
582            .field("allow_anonymous", &self.allow_anonymous)
583            .field("access_key_id", &self.access_key_id)
584            .field("secret_key", &"<redacted>")
585            .field(
586                "session_token",
587                &self.session_token.as_ref().map(|_| "<redacted>"),
588            )
589            .field("region", &self.region)
590            .field("max_skew_seconds", &self.max_skew_seconds)
591            .field("allowed_buckets", &self.allowed_buckets)
592            .field("allowed_actions", &self.allowed_actions)
593            .field("credentials", &self.credentials)
594            .finish()
595    }
596}
597
598impl Default for AuthConfig {
599    fn default() -> Self {
600        Self {
601            allow_anonymous: false,
602            access_key_id: "test".to_owned(),
603            secret_key: "testsecret".to_owned(),
604            session_token: None,
605            region: "us-east-1".to_owned(),
606            max_skew_seconds: 900,
607            allowed_buckets: BTreeSet::new(),
608            allowed_actions: BTreeSet::new(),
609            credentials: Vec::new(),
610        }
611    }
612}
613
614impl AuthConfig {
615    /// Creates a fluent authentication configuration builder.
616    pub fn builder() -> AuthConfigBuilder {
617        AuthConfigBuilder {
618            config: Self::default(),
619        }
620    }
621
622    /// Validates primary and additional credential configuration.
623    ///
624    /// Returns an error when credential strings are malformed, the region is
625    /// invalid, skew is negative, allow-list buckets are invalid, or access key
626    /// IDs are duplicated.
627    pub fn validate(&self) -> Result<(), ConfigError> {
628        validate_access_key_id(&self.access_key_id)?;
629        validate_secret_key(&self.secret_key)?;
630        validate_session_token(self.session_token.as_deref())?;
631        if !is_valid_region(&self.region) {
632            return Err(ConfigError::InvalidAuthConfig(
633                "region must be a non-empty lowercase AWS region identifier",
634            ));
635        }
636        if self.max_skew_seconds < 0 {
637            return Err(ConfigError::InvalidAuthConfig(
638                "max_skew_seconds must be greater than or equal to 0",
639            ));
640        }
641        for bucket in &self.allowed_buckets {
642            BucketName::parse(bucket.clone()).map_err(|_| {
643                ConfigError::InvalidAuthConfig("allowed_buckets must contain valid bucket names")
644            })?;
645        }
646        let mut access_key_ids = BTreeSet::from([self.access_key_id.as_str()]);
647        for credential in &self.credentials {
648            credential.validate()?;
649            if !access_key_ids.insert(credential.access_key_id.as_str()) {
650                return Err(ConfigError::InvalidAuthConfig(
651                    "credential access_key_id values must be unique",
652                ));
653            }
654        }
655        Ok(())
656    }
657
658    /// Returns whether the anonymous/global allow-lists permit an action on a bucket.
659    pub fn permits(&self, bucket: &BucketName, action: S3Action) -> bool {
660        (self.allowed_buckets.is_empty() || self.allowed_buckets.contains(bucket.as_str()))
661            && (self.allowed_actions.is_empty() || self.allowed_actions.contains(&action))
662    }
663}
664
665/// Fluent builder for [`AuthConfig`].
666#[derive(Clone)]
667pub struct AuthConfigBuilder {
668    config: AuthConfig,
669}
670
671impl fmt::Debug for AuthConfigBuilder {
672    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
673        formatter
674            .debug_struct("AuthConfigBuilder")
675            .field("config", &self.config)
676            .finish()
677    }
678}
679
680impl AuthConfigBuilder {
681    /// Sets whether unsigned anonymous requests are accepted.
682    pub fn allow_anonymous(mut self, allow_anonymous: bool) -> Self {
683        self.config.allow_anonymous = allow_anonymous;
684        self
685    }
686
687    /// Sets the primary access key ID.
688    pub fn access_key_id(mut self, access_key_id: impl Into<String>) -> Self {
689        self.config.access_key_id = access_key_id.into();
690        self
691    }
692
693    /// Sets the primary secret key.
694    pub fn secret_key(mut self, secret_key: impl Into<String>) -> Self {
695        self.config.secret_key = secret_key.into();
696        self
697    }
698
699    /// Sets both primary credential fields.
700    pub fn primary_credentials(
701        mut self,
702        access_key_id: impl Into<String>,
703        secret_key: impl Into<String>,
704    ) -> Self {
705        self.config.access_key_id = access_key_id.into();
706        self.config.secret_key = secret_key.into();
707        self
708    }
709
710    /// Sets the optional primary session token.
711    pub fn session_token(mut self, session_token: impl Into<String>) -> Self {
712        self.config.session_token = Some(session_token.into());
713        self
714    }
715
716    /// Clears the primary session token.
717    pub fn without_session_token(mut self) -> Self {
718        self.config.session_token = None;
719        self
720    }
721
722    /// Sets the SigV4 signing region.
723    pub fn region(mut self, region: impl Into<String>) -> Self {
724        self.config.region = region.into();
725        self
726    }
727
728    /// Sets the maximum accepted SigV4 timestamp skew in seconds.
729    pub fn max_skew_seconds(mut self, seconds: i64) -> Self {
730        self.config.max_skew_seconds = seconds;
731        self
732    }
733
734    /// Replaces the global bucket allow-list.
735    pub fn allowed_buckets<I, S>(mut self, buckets: I) -> Self
736    where
737        I: IntoIterator<Item = S>,
738        S: Into<String>,
739    {
740        self.config.allowed_buckets = buckets.into_iter().map(Into::into).collect();
741        self
742    }
743
744    /// Adds one bucket to the global allow-list.
745    pub fn allow_bucket(mut self, bucket: impl Into<String>) -> Self {
746        self.config.allowed_buckets.insert(bucket.into());
747        self
748    }
749
750    /// Replaces the global action allow-list.
751    pub fn allowed_actions<I>(mut self, actions: I) -> Self
752    where
753        I: IntoIterator<Item = S3Action>,
754    {
755        self.config.allowed_actions = actions.into_iter().collect();
756        self
757    }
758
759    /// Adds one action to the global allow-list.
760    pub fn allow_action(mut self, action: S3Action) -> Self {
761        self.config.allowed_actions.insert(action);
762        self
763    }
764
765    /// Replaces the additional credential entries.
766    pub fn credentials<I>(mut self, credentials: I) -> Self
767    where
768        I: IntoIterator<Item = AccessKeyConfig>,
769    {
770        self.config.credentials = credentials.into_iter().collect();
771        self
772    }
773
774    /// Adds one additional credential entry.
775    pub fn credential(mut self, credential: AccessKeyConfig) -> Self {
776        self.config.credentials.push(credential);
777        self
778    }
779
780    /// Returns the constructed authentication configuration.
781    pub fn build(self) -> AuthConfig {
782        self.config
783    }
784}
785
786/// Validated authentication state indexed for request-time lookup.
787#[derive(Clone)]
788pub struct AuthState {
789    allow_anonymous: bool,
790    region: String,
791    max_skew_seconds: i64,
792    anonymous_allowed_buckets: BTreeSet<String>,
793    credentials: HashMap<String, StoredAccessKey>,
794}
795
796impl fmt::Debug for AuthState {
797    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
798        formatter
799            .debug_struct("AuthState")
800            .field("allow_anonymous", &self.allow_anonymous)
801            .field("region", &self.region)
802            .field("max_skew_seconds", &self.max_skew_seconds)
803            .field("anonymous_allowed_buckets", &self.anonymous_allowed_buckets)
804            .field("credential_count", &self.credentials.len())
805            .finish()
806    }
807}
808
809impl AuthState {
810    /// Builds request-time auth state from configuration.
811    ///
812    /// Returns an error when `config` fails validation.
813    pub fn new(config: &AuthConfig) -> Result<Self, ConfigError> {
814        config.validate()?;
815        let mut credentials = HashMap::with_capacity(config.credentials.len() + 1);
816        let primary = StoredAccessKey {
817            access_key_id: AccessKeyId::parse(config.access_key_id.clone())?,
818            secret_key: SecretKey::parse(config.secret_key.clone())?,
819            session_token: config.session_token.clone(),
820            active: true,
821            allowed_buckets: config.allowed_buckets.clone(),
822            allowed_actions: config.allowed_actions.clone(),
823        };
824        credentials.insert(primary.access_key_id.as_str().to_owned(), primary);
825        for credential in &config.credentials {
826            let credential = StoredAccessKey {
827                access_key_id: AccessKeyId::parse(credential.access_key_id.clone())?,
828                secret_key: SecretKey::parse(credential.secret_key.clone())?,
829                session_token: credential.session_token.clone(),
830                active: credential.active,
831                allowed_buckets: credential.allowed_buckets.clone(),
832                allowed_actions: credential.allowed_actions.clone(),
833            };
834            credentials.insert(credential.access_key_id.as_str().to_owned(), credential);
835        }
836
837        Ok(Self {
838            allow_anonymous: config.allow_anonymous,
839            region: config.region.clone(),
840            max_skew_seconds: config.max_skew_seconds,
841            anonymous_allowed_buckets: config.allowed_buckets.clone(),
842            credentials,
843        })
844    }
845
846    /// Returns whether unsigned anonymous requests may be authenticated.
847    pub(crate) fn allow_anonymous(&self) -> bool {
848        self.allow_anonymous
849    }
850
851    /// Returns the configured SigV4 region.
852    pub(crate) fn region(&self) -> &str {
853        &self.region
854    }
855
856    /// Returns the maximum accepted SigV4 timestamp skew in seconds.
857    pub(crate) fn max_skew_seconds(&self) -> i64 {
858        self.max_skew_seconds
859    }
860
861    /// Returns whether anonymous requests may access `bucket`.
862    pub(crate) fn permits_anonymous_bucket(&self, bucket: &BucketName) -> bool {
863        self.anonymous_allowed_buckets.is_empty()
864            || self.anonymous_allowed_buckets.contains(bucket.as_str())
865    }
866
867    /// Looks up an active or inactive configured access key by ID.
868    pub(crate) fn credential(&self, access_key_id: &str) -> Option<ConfiguredAccessKey<'_>> {
869        self.credentials
870            .get(access_key_id)
871            .map(StoredAccessKey::as_configured)
872    }
873
874    /// Returns whether a configured credential may perform `action` on `bucket`.
875    pub(crate) fn permits_credential(
876        &self,
877        access_key_id: &str,
878        bucket: &BucketName,
879        action: S3Action,
880    ) -> bool {
881        let Some(credential) = self.credential(access_key_id) else {
882            return false;
883        };
884        (credential.allowed_buckets.is_empty()
885            || credential.allowed_buckets.contains(bucket.as_str()))
886            && (credential.allowed_actions.is_empty()
887                || credential.allowed_actions.contains(&action))
888    }
889}
890
891#[derive(Clone)]
892struct StoredAccessKey {
893    access_key_id: AccessKeyId,
894    secret_key: SecretKey,
895    session_token: Option<String>,
896    active: bool,
897    allowed_buckets: BTreeSet<String>,
898    allowed_actions: BTreeSet<S3Action>,
899}
900
901impl StoredAccessKey {
902    fn as_configured(&self) -> ConfiguredAccessKey<'_> {
903        ConfiguredAccessKey {
904            access_key_id: self.access_key_id.clone(),
905            secret_key: self.secret_key.clone(),
906            session_token: self.session_token.as_deref(),
907            active: self.active,
908            allowed_buckets: &self.allowed_buckets,
909            allowed_actions: &self.allowed_actions,
910        }
911    }
912}
913
914/// Additional access key entry.
915#[derive(Clone)]
916pub struct AccessKeyConfig {
917    /// Access key ID.
918    pub access_key_id: String,
919    /// Secret key. This value is redacted from `Debug` output.
920    pub secret_key: String,
921    /// Optional session token. This value is redacted from `Debug` output.
922    pub session_token: Option<String>,
923    /// Whether this credential can authenticate requests.
924    pub active: bool,
925    /// Optional bucket allow-list. Empty inherits no restriction beyond global auth config.
926    pub allowed_buckets: BTreeSet<String>,
927    /// Optional action allow-list. Empty permits all implemented actions for this credential.
928    pub allowed_actions: BTreeSet<S3Action>,
929}
930
931impl fmt::Debug for AccessKeyConfig {
932    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
933        formatter
934            .debug_struct("AccessKeyConfig")
935            .field("access_key_id", &self.access_key_id)
936            .field("secret_key", &"<redacted>")
937            .field(
938                "session_token",
939                &self.session_token.as_ref().map(|_| "<redacted>"),
940            )
941            .field("active", &self.active)
942            .field("allowed_buckets", &self.allowed_buckets)
943            .field("allowed_actions", &self.allowed_actions)
944            .finish()
945    }
946}
947
948impl AccessKeyConfig {
949    /// Creates a fluent additional access-key builder.
950    pub fn builder(
951        access_key_id: impl Into<String>,
952        secret_key: impl Into<String>,
953    ) -> AccessKeyConfigBuilder {
954        AccessKeyConfigBuilder {
955            config: Self {
956                access_key_id: access_key_id.into(),
957                secret_key: secret_key.into(),
958                session_token: None,
959                active: true,
960                allowed_buckets: BTreeSet::new(),
961                allowed_actions: BTreeSet::new(),
962            },
963        }
964    }
965
966    fn validate(&self) -> Result<(), ConfigError> {
967        validate_access_key_id(&self.access_key_id)?;
968        validate_secret_key(&self.secret_key)?;
969        validate_session_token(self.session_token.as_deref())?;
970        for bucket in &self.allowed_buckets {
971            BucketName::parse(bucket.clone()).map_err(|_| {
972                ConfigError::InvalidAuthConfig("allowed_buckets must contain valid bucket names")
973            })?;
974        }
975        Ok(())
976    }
977}
978
979/// Fluent builder for [`AccessKeyConfig`].
980#[derive(Clone)]
981pub struct AccessKeyConfigBuilder {
982    config: AccessKeyConfig,
983}
984
985impl fmt::Debug for AccessKeyConfigBuilder {
986    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
987        formatter
988            .debug_struct("AccessKeyConfigBuilder")
989            .field("config", &self.config)
990            .finish()
991    }
992}
993
994impl AccessKeyConfigBuilder {
995    /// Sets the optional session token.
996    pub fn session_token(mut self, session_token: impl Into<String>) -> Self {
997        self.config.session_token = Some(session_token.into());
998        self
999    }
1000
1001    /// Clears the optional session token.
1002    pub fn without_session_token(mut self) -> Self {
1003        self.config.session_token = None;
1004        self
1005    }
1006
1007    /// Sets whether this credential can authenticate requests.
1008    pub fn active(mut self, active: bool) -> Self {
1009        self.config.active = active;
1010        self
1011    }
1012
1013    /// Replaces the bucket allow-list.
1014    pub fn allowed_buckets<I, S>(mut self, buckets: I) -> Self
1015    where
1016        I: IntoIterator<Item = S>,
1017        S: Into<String>,
1018    {
1019        self.config.allowed_buckets = buckets.into_iter().map(Into::into).collect();
1020        self
1021    }
1022
1023    /// Adds one bucket to the allow-list.
1024    pub fn allow_bucket(mut self, bucket: impl Into<String>) -> Self {
1025        self.config.allowed_buckets.insert(bucket.into());
1026        self
1027    }
1028
1029    /// Replaces the action allow-list.
1030    pub fn allowed_actions<I>(mut self, actions: I) -> Self
1031    where
1032        I: IntoIterator<Item = S3Action>,
1033    {
1034        self.config.allowed_actions = actions.into_iter().collect();
1035        self
1036    }
1037
1038    /// Adds one action to the allow-list.
1039    pub fn allow_action(mut self, action: S3Action) -> Self {
1040        self.config.allowed_actions.insert(action);
1041        self
1042    }
1043
1044    /// Returns the constructed access-key configuration.
1045    pub fn build(self) -> AccessKeyConfig {
1046        self.config
1047    }
1048}
1049
1050pub(crate) struct ConfiguredAccessKey<'a> {
1051    pub(crate) access_key_id: AccessKeyId,
1052    pub(crate) secret_key: SecretKey,
1053    pub(crate) session_token: Option<&'a str>,
1054    pub(crate) active: bool,
1055    pub(crate) allowed_buckets: &'a BTreeSet<String>,
1056    pub(crate) allowed_actions: &'a BTreeSet<S3Action>,
1057}
1058
1059/// Implemented S3 IAM-style actions used by the simple allow-list authorizer.
1060#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
1061pub enum S3Action {
1062    /// `s3:PutObject`.
1063    PutObject,
1064    /// `s3:GetObject`.
1065    GetObject,
1066    /// `s3:HeadObject`.
1067    HeadObject,
1068    /// `s3:DeleteObject`.
1069    DeleteObject,
1070    /// `s3:CreateMultipartUpload`.
1071    CreateMultipartUpload,
1072    /// `s3:UploadPart`.
1073    UploadPart,
1074    /// `s3:CompleteMultipartUpload`.
1075    CompleteMultipartUpload,
1076    /// `s3:AbortMultipartUpload`.
1077    AbortMultipartUpload,
1078    /// `s3:ListMultipartUploadParts`.
1079    ListMultipartUploadParts,
1080    /// `s3:HeadBucket`.
1081    HeadBucket,
1082}
1083
1084impl S3Action {
1085    /// Returns the canonical IAM-style action string.
1086    pub fn as_str(self) -> &'static str {
1087        match self {
1088            Self::PutObject => "s3:PutObject",
1089            Self::GetObject => "s3:GetObject",
1090            Self::HeadObject => "s3:HeadObject",
1091            Self::DeleteObject => "s3:DeleteObject",
1092            Self::CreateMultipartUpload => "s3:CreateMultipartUpload",
1093            Self::UploadPart => "s3:UploadPart",
1094            Self::CompleteMultipartUpload => "s3:CompleteMultipartUpload",
1095            Self::AbortMultipartUpload => "s3:AbortMultipartUpload",
1096            Self::ListMultipartUploadParts => "s3:ListMultipartUploadParts",
1097            Self::HeadBucket => "s3:HeadBucket",
1098        }
1099    }
1100}
1101
1102impl FromStr for S3Action {
1103    type Err = ConfigError;
1104
1105    fn from_str(value: &str) -> Result<Self, Self::Err> {
1106        match value {
1107            "s3:PutObject" | "PutObject" | "put-object" => Ok(Self::PutObject),
1108            "s3:GetObject" | "GetObject" | "get-object" => Ok(Self::GetObject),
1109            "s3:HeadObject" | "HeadObject" | "head-object" => Ok(Self::HeadObject),
1110            "s3:DeleteObject" | "DeleteObject" | "delete-object" => Ok(Self::DeleteObject),
1111            "s3:CreateMultipartUpload" | "CreateMultipartUpload" | "create-multipart-upload" => {
1112                Ok(Self::CreateMultipartUpload)
1113            }
1114            "s3:UploadPart" | "UploadPart" | "upload-part" => Ok(Self::UploadPart),
1115            "s3:CompleteMultipartUpload"
1116            | "CompleteMultipartUpload"
1117            | "complete-multipart-upload" => Ok(Self::CompleteMultipartUpload),
1118            "s3:AbortMultipartUpload" | "AbortMultipartUpload" | "abort-multipart-upload" => {
1119                Ok(Self::AbortMultipartUpload)
1120            }
1121            "s3:ListMultipartUploadParts"
1122            | "ListMultipartUploadParts"
1123            | "list-multipart-upload-parts" => Ok(Self::ListMultipartUploadParts),
1124            "s3:HeadBucket" | "HeadBucket" | "head-bucket" => Ok(Self::HeadBucket),
1125            _ => Err(ConfigError::InvalidAuthConfig(
1126                "allowed_actions must contain supported S3 action names",
1127            )),
1128        }
1129    }
1130}
1131
1132fn is_valid_region(region: &str) -> bool {
1133    let mut bytes = region.bytes();
1134    let Some(first) = bytes.next() else {
1135        return false;
1136    };
1137    if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
1138        return false;
1139    }
1140
1141    let mut previous = first;
1142    for byte in bytes {
1143        if !byte.is_ascii_lowercase() && !byte.is_ascii_digit() && byte != b'-' {
1144            return false;
1145        }
1146        previous = byte;
1147    }
1148
1149    previous.is_ascii_lowercase() || previous.is_ascii_digit()
1150}
1151
1152fn validate_access_key_id(value: &str) -> Result<(), ConfigError> {
1153    if value.is_empty() {
1154        return Err(ConfigError::InvalidAuthConfig(
1155            "access_key_id must not be empty",
1156        ));
1157    }
1158    if value
1159        .bytes()
1160        .any(|byte| byte.is_ascii_control() || byte.is_ascii_whitespace())
1161    {
1162        return Err(ConfigError::InvalidAuthConfig(
1163            "access_key_id must not contain whitespace or control characters",
1164        ));
1165    }
1166    Ok(())
1167}
1168
1169fn validate_secret_key(value: &str) -> Result<(), ConfigError> {
1170    if value.is_empty() {
1171        return Err(ConfigError::InvalidAuthConfig(
1172            "secret_key must not be empty",
1173        ));
1174    }
1175    if value.bytes().any(|byte| byte.is_ascii_control()) {
1176        return Err(ConfigError::InvalidAuthConfig(
1177            "secret_key must not contain control characters",
1178        ));
1179    }
1180    Ok(())
1181}
1182
1183fn validate_session_token(value: Option<&str>) -> Result<(), ConfigError> {
1184    if value.is_some_and(str::is_empty) {
1185        return Err(ConfigError::InvalidAuthConfig(
1186            "session_token must not be empty when configured",
1187        ));
1188    }
1189    Ok(())
1190}
1191
1192#[cfg(test)]
1193mod tests {
1194    use super::*;
1195
1196    #[test]
1197    fn auth_config_debug_redacts_secret_values() {
1198        let config = AuthConfig {
1199            secret_key: "super-secret".to_owned(),
1200            session_token: Some("session-secret".to_owned()),
1201            credentials: vec![AccessKeyConfig {
1202                access_key_id: "client".to_owned(),
1203                secret_key: "client-secret".to_owned(),
1204                session_token: Some("client-session".to_owned()),
1205                active: true,
1206                allowed_buckets: BTreeSet::new(),
1207                allowed_actions: BTreeSet::new(),
1208            }],
1209            ..AuthConfig::default()
1210        };
1211
1212        let debug = format!("{config:?}");
1213
1214        assert!(debug.contains("secret_key: \"<redacted>\""));
1215        assert!(debug.contains("session_token: Some(\"<redacted>\")"));
1216        assert!(!debug.contains("super-secret"));
1217        assert!(!debug.contains("session-secret"));
1218        assert!(!debug.contains("client-secret"));
1219        assert!(!debug.contains("client-session"));
1220    }
1221
1222    #[test]
1223    fn secret_key_debug_redacts_value() {
1224        let secret = SecretKey::parse("super-secret").expect("secret");
1225
1226        assert_eq!(format!("{secret:?}"), "<redacted>");
1227        assert!(!format!("{secret:?}").contains("super-secret"));
1228    }
1229
1230    #[test]
1231    fn access_key_id_validates_like_auth_config() {
1232        assert_eq!(
1233            AccessKeyId::parse("client")
1234                .expect("access key id")
1235                .as_str(),
1236            "client"
1237        );
1238        assert_eq!(
1239            AccessKeyId::parse("bad key"),
1240            Err(ConfigError::InvalidAuthConfig(
1241                "access_key_id must not contain whitespace or control characters"
1242            ))
1243        );
1244    }
1245
1246    #[test]
1247    fn default_auth_config_is_valid() {
1248        AuthConfig::default().validate().expect("valid auth config");
1249    }
1250
1251    #[test]
1252    fn config_builder_sets_embedded_server_options() {
1253        let limits = UploadLimits::builder()
1254            .max_object_size(1024)
1255            .max_part_size(512)
1256            .min_non_final_part_size(128)
1257            .max_concurrent_s3_requests(8)
1258            .max_active_object_writers(2)
1259            .max_active_multipart_part_writers(4)
1260            .max_active_aws_chunked_decoders(3)
1261            .build();
1262        let auth = AuthConfig::builder()
1263            .allow_anonymous(true)
1264            .primary_credentials("client", "secret")
1265            .session_token("token")
1266            .region("eu-west-1")
1267            .max_skew_seconds(60)
1268            .allow_bucket("media")
1269            .allow_action(S3Action::PutObject)
1270            .credential(
1271                AccessKeyConfig::builder("extra", "extra-secret")
1272                    .allow_bucket("archive")
1273                    .allow_action(S3Action::GetObject)
1274                    .build(),
1275            )
1276            .build();
1277
1278        let config = Config::builder("/tmp/s3-data")
1279            .auth(auth)
1280            .virtual_host_base_domain("s3.test")
1281            .upload_limits(limits)
1282            .build();
1283
1284        assert_eq!(config.storage_root, PathBuf::from("/tmp/s3-data"));
1285        assert_eq!(config.virtual_host_base_domain.as_deref(), Some("s3.test"));
1286        assert!(config.auth.allow_anonymous);
1287        assert_eq!(config.auth.access_key_id, "client");
1288        assert_eq!(config.auth.secret_key, "secret");
1289        assert_eq!(config.auth.session_token.as_deref(), Some("token"));
1290        assert_eq!(config.auth.region, "eu-west-1");
1291        assert_eq!(config.auth.max_skew_seconds, 60);
1292        assert!(config.auth.allowed_buckets.contains("media"));
1293        assert!(config.auth.allowed_actions.contains(&S3Action::PutObject));
1294        assert_eq!(config.auth.credentials.len(), 1);
1295        assert_eq!(config.auth.credentials[0].access_key_id, "extra");
1296        assert!(
1297            config.auth.credentials[0]
1298                .allowed_buckets
1299                .contains("archive")
1300        );
1301        assert_eq!(config.upload_limits.max_object_size, 1024);
1302        assert_eq!(config.upload_limits.max_part_size, 512);
1303        assert_eq!(config.upload_limits.min_non_final_part_size, 128);
1304        assert_eq!(config.upload_limits.max_concurrent_s3_requests, 8);
1305        assert_eq!(config.upload_limits.max_active_object_writers, 2);
1306        assert_eq!(config.upload_limits.max_active_multipart_part_writers, 4);
1307        assert_eq!(config.upload_limits.max_active_aws_chunked_decoders, 3);
1308    }
1309
1310    #[test]
1311    fn upload_limit_presets_are_valid() {
1312        UploadLimits::default_s3_compatible()
1313            .validate()
1314            .expect("default limits");
1315        UploadLimits::local_development()
1316            .validate()
1317            .expect("local development limits");
1318    }
1319
1320    #[test]
1321    fn auth_config_rejects_empty_access_key_id() {
1322        let config = AuthConfig {
1323            access_key_id: String::new(),
1324            ..AuthConfig::default()
1325        };
1326
1327        assert_eq!(
1328            config.validate(),
1329            Err(ConfigError::InvalidAuthConfig(
1330                "access_key_id must not be empty"
1331            ))
1332        );
1333    }
1334
1335    #[test]
1336    fn auth_config_rejects_access_key_id_whitespace_or_control_characters() {
1337        let config = AuthConfig {
1338            access_key_id: "bad key".to_owned(),
1339            ..AuthConfig::default()
1340        };
1341
1342        assert_eq!(
1343            config.validate(),
1344            Err(ConfigError::InvalidAuthConfig(
1345                "access_key_id must not contain whitespace or control characters"
1346            ))
1347        );
1348
1349        let config = AuthConfig {
1350            access_key_id: "bad\nkey".to_owned(),
1351            ..AuthConfig::default()
1352        };
1353
1354        assert_eq!(
1355            config.validate(),
1356            Err(ConfigError::InvalidAuthConfig(
1357                "access_key_id must not contain whitespace or control characters"
1358            ))
1359        );
1360    }
1361
1362    #[test]
1363    fn auth_config_rejects_empty_secret_key() {
1364        let config = AuthConfig {
1365            secret_key: String::new(),
1366            ..AuthConfig::default()
1367        };
1368
1369        assert_eq!(
1370            config.validate(),
1371            Err(ConfigError::InvalidAuthConfig(
1372                "secret_key must not be empty"
1373            ))
1374        );
1375    }
1376
1377    #[test]
1378    fn auth_config_rejects_secret_key_control_characters() {
1379        let config = AuthConfig {
1380            secret_key: "bad\nsecret".to_owned(),
1381            ..AuthConfig::default()
1382        };
1383
1384        assert_eq!(
1385            config.validate(),
1386            Err(ConfigError::InvalidAuthConfig(
1387                "secret_key must not contain control characters"
1388            ))
1389        );
1390    }
1391
1392    #[test]
1393    fn auth_config_rejects_empty_session_token() {
1394        let config = AuthConfig {
1395            session_token: Some(String::new()),
1396            ..AuthConfig::default()
1397        };
1398
1399        assert_eq!(
1400            config.validate(),
1401            Err(ConfigError::InvalidAuthConfig(
1402                "session_token must not be empty when configured"
1403            ))
1404        );
1405    }
1406
1407    #[test]
1408    fn auth_config_rejects_invalid_region() {
1409        for region in ["", "US-EAST-1", "-us-east-1", "us-east-1-", "us_east_1"] {
1410            let config = AuthConfig {
1411                region: region.to_owned(),
1412                ..AuthConfig::default()
1413            };
1414
1415            assert_eq!(
1416                config.validate(),
1417                Err(ConfigError::InvalidAuthConfig(
1418                    "region must be a non-empty lowercase AWS region identifier"
1419                ))
1420            );
1421        }
1422    }
1423
1424    #[test]
1425    fn auth_config_rejects_negative_max_skew() {
1426        let config = AuthConfig {
1427            max_skew_seconds: -1,
1428            ..AuthConfig::default()
1429        };
1430
1431        assert_eq!(
1432            config.validate(),
1433            Err(ConfigError::InvalidAuthConfig(
1434                "max_skew_seconds must be greater than or equal to 0"
1435            ))
1436        );
1437    }
1438
1439    #[test]
1440    fn auth_config_rejects_invalid_allowed_bucket() {
1441        let config = AuthConfig {
1442            allowed_buckets: BTreeSet::from(["bad/bucket".to_owned()]),
1443            ..AuthConfig::default()
1444        };
1445
1446        assert_eq!(
1447            config.validate(),
1448            Err(ConfigError::InvalidAuthConfig(
1449                "allowed_buckets must contain valid bucket names"
1450            ))
1451        );
1452    }
1453
1454    #[test]
1455    fn auth_config_empty_allow_lists_permit_everything() {
1456        let config = AuthConfig::default();
1457        let bucket = BucketName::parse("any-bucket").expect("bucket");
1458
1459        assert!(config.permits(&bucket, S3Action::PutObject));
1460        assert!(config.permits(&bucket, S3Action::AbortMultipartUpload));
1461    }
1462
1463    #[test]
1464    fn auth_config_enforces_bucket_and_action_allow_lists() {
1465        let config = AuthConfig {
1466            allowed_buckets: BTreeSet::from(["allowed-bucket".to_owned()]),
1467            allowed_actions: BTreeSet::from([S3Action::PutObject]),
1468            ..AuthConfig::default()
1469        };
1470        let allowed_bucket = BucketName::parse("allowed-bucket").expect("bucket");
1471        let denied_bucket = BucketName::parse("denied-bucket").expect("bucket");
1472
1473        assert!(config.permits(&allowed_bucket, S3Action::PutObject));
1474        assert!(!config.permits(&denied_bucket, S3Action::PutObject));
1475        assert!(!config.permits(&allowed_bucket, S3Action::CreateMultipartUpload));
1476    }
1477
1478    #[test]
1479    fn auth_config_rejects_duplicate_credential_access_key_ids() {
1480        let config = AuthConfig {
1481            credentials: vec![AccessKeyConfig {
1482                access_key_id: "test".to_owned(),
1483                secret_key: "other-secret".to_owned(),
1484                session_token: None,
1485                active: true,
1486                allowed_buckets: BTreeSet::new(),
1487                allowed_actions: BTreeSet::new(),
1488            }],
1489            ..AuthConfig::default()
1490        };
1491
1492        assert_eq!(
1493            config.validate(),
1494            Err(ConfigError::InvalidAuthConfig(
1495                "credential access_key_id values must be unique"
1496            ))
1497        );
1498    }
1499
1500    #[test]
1501    fn auth_state_indexes_primary_and_additional_credentials() {
1502        let config = AuthConfig {
1503            credentials: vec![AccessKeyConfig {
1504                access_key_id: "client".to_owned(),
1505                secret_key: "client-secret".to_owned(),
1506                session_token: Some("client-session".to_owned()),
1507                active: false,
1508                allowed_buckets: BTreeSet::from(["client-bucket".to_owned()]),
1509                allowed_actions: BTreeSet::from([S3Action::PutObject]),
1510            }],
1511            ..AuthConfig::default()
1512        };
1513        let state = AuthState::new(&config).expect("auth state");
1514
1515        let primary = state.credential("test").expect("primary credential");
1516        assert_eq!(primary.access_key_id.as_str(), "test");
1517        assert!(primary.active);
1518
1519        let client = state.credential("client").expect("client credential");
1520        assert_eq!(client.access_key_id.as_str(), "client");
1521        assert_eq!(client.secret_key.as_str(), "client-secret");
1522        assert_eq!(client.session_token, Some("client-session"));
1523        assert!(!client.active);
1524        let bucket = BucketName::parse("client-bucket").expect("bucket");
1525        assert!(state.permits_credential("client", &bucket, S3Action::PutObject));
1526        assert!(!state.permits_credential("client", &bucket, S3Action::CreateMultipartUpload));
1527    }
1528
1529    #[test]
1530    fn auth_state_debug_redacts_credential_values() {
1531        let config = AuthConfig {
1532            secret_key: "super-secret".to_owned(),
1533            session_token: Some("session-secret".to_owned()),
1534            credentials: vec![AccessKeyConfig {
1535                access_key_id: "client".to_owned(),
1536                secret_key: "client-secret".to_owned(),
1537                session_token: Some("client-session".to_owned()),
1538                active: true,
1539                allowed_buckets: BTreeSet::new(),
1540                allowed_actions: BTreeSet::new(),
1541            }],
1542            ..AuthConfig::default()
1543        };
1544        let state = AuthState::new(&config).expect("auth state");
1545
1546        let debug = format!("{state:?}");
1547
1548        assert!(debug.contains("credential_count: 2"));
1549        assert!(!debug.contains("super-secret"));
1550        assert!(!debug.contains("session-secret"));
1551        assert!(!debug.contains("client-secret"));
1552        assert!(!debug.contains("client-session"));
1553    }
1554
1555    #[test]
1556    fn s3_action_parses_iam_and_cli_names() {
1557        assert_eq!("s3:PutObject".parse::<S3Action>(), Ok(S3Action::PutObject));
1558        assert_eq!("s3:GetObject".parse::<S3Action>(), Ok(S3Action::GetObject));
1559        assert_eq!("get-object".parse::<S3Action>(), Ok(S3Action::GetObject));
1560        assert_eq!(
1561            "s3:HeadObject".parse::<S3Action>(),
1562            Ok(S3Action::HeadObject)
1563        );
1564        assert_eq!("head-object".parse::<S3Action>(), Ok(S3Action::HeadObject));
1565        assert_eq!(
1566            "s3:DeleteObject".parse::<S3Action>(),
1567            Ok(S3Action::DeleteObject)
1568        );
1569        assert_eq!(
1570            "CreateMultipartUpload".parse::<S3Action>(),
1571            Ok(S3Action::CreateMultipartUpload)
1572        );
1573        assert_eq!("upload-part".parse::<S3Action>(), Ok(S3Action::UploadPart));
1574        assert_eq!(
1575            "complete-multipart-upload".parse::<S3Action>(),
1576            Ok(S3Action::CompleteMultipartUpload)
1577        );
1578        assert_eq!(
1579            "abort-multipart-upload".parse::<S3Action>(),
1580            Ok(S3Action::AbortMultipartUpload)
1581        );
1582        assert_eq!(
1583            "list-multipart-upload-parts".parse::<S3Action>(),
1584            Ok(S3Action::ListMultipartUploadParts)
1585        );
1586        assert_eq!("head-bucket".parse::<S3Action>(), Ok(S3Action::HeadBucket));
1587    }
1588
1589    #[test]
1590    fn s3_action_rejects_unsupported_actions() {
1591        assert_eq!(
1592            "s3:ListBucket".parse::<S3Action>(),
1593            Err(ConfigError::InvalidAuthConfig(
1594                "allowed_actions must contain supported S3 action names"
1595            ))
1596        );
1597    }
1598
1599    #[test]
1600    fn default_upload_limits_are_valid() {
1601        UploadLimits::default().validate().expect("valid limits");
1602    }
1603
1604    #[test]
1605    fn upload_limits_return_positive_validated_values() {
1606        let limits = UploadLimits {
1607            max_object_size: 10,
1608            max_part_size: 8,
1609            min_non_final_part_size: 4,
1610            ..Default::default()
1611        }
1612        .validated()
1613        .expect("validated limits");
1614
1615        assert_eq!(limits.max_object_size.get(), 10);
1616        assert_eq!(limits.max_part_size.get(), 8);
1617        assert_eq!(limits.min_non_final_part_size.get(), 4);
1618        assert_eq!(limits.max_concurrent_s3_requests.get(), 256);
1619        assert_eq!(limits.max_active_object_writers.get(), 64);
1620        assert_eq!(limits.max_active_multipart_part_writers.get(), 128);
1621        assert_eq!(limits.max_active_aws_chunked_decoders.get(), 64);
1622    }
1623
1624    #[test]
1625    fn upload_limits_reject_zero_values() {
1626        let limits = UploadLimits {
1627            max_object_size: 0,
1628            ..UploadLimits::default()
1629        };
1630        assert_eq!(
1631            limits.validate(),
1632            Err(ConfigError::InvalidUploadLimit(
1633                "max_object_size must be greater than 0"
1634            ))
1635        );
1636
1637        let limits = UploadLimits {
1638            max_part_size: 0,
1639            ..UploadLimits::default()
1640        };
1641        assert_eq!(
1642            limits.validate(),
1643            Err(ConfigError::InvalidUploadLimit(
1644                "max_part_size must be greater than 0"
1645            ))
1646        );
1647
1648        let limits = UploadLimits {
1649            min_non_final_part_size: 0,
1650            ..UploadLimits::default()
1651        };
1652        assert_eq!(
1653            limits.validate(),
1654            Err(ConfigError::InvalidUploadLimit(
1655                "min_non_final_part_size must be greater than 0"
1656            ))
1657        );
1658
1659        let limits = UploadLimits {
1660            max_concurrent_s3_requests: 0,
1661            ..UploadLimits::default()
1662        };
1663        assert_eq!(
1664            limits.validate(),
1665            Err(ConfigError::InvalidUploadLimit(
1666                "max_concurrent_s3_requests must be greater than 0"
1667            ))
1668        );
1669
1670        let limits = UploadLimits {
1671            max_active_object_writers: 0,
1672            ..UploadLimits::default()
1673        };
1674        assert_eq!(
1675            limits.validate(),
1676            Err(ConfigError::InvalidUploadLimit(
1677                "max_active_object_writers must be greater than 0"
1678            ))
1679        );
1680
1681        let limits = UploadLimits {
1682            max_active_multipart_part_writers: 0,
1683            ..UploadLimits::default()
1684        };
1685        assert_eq!(
1686            limits.validate(),
1687            Err(ConfigError::InvalidUploadLimit(
1688                "max_active_multipart_part_writers must be greater than 0"
1689            ))
1690        );
1691
1692        let limits = UploadLimits {
1693            max_active_aws_chunked_decoders: 0,
1694            ..UploadLimits::default()
1695        };
1696        assert_eq!(
1697            limits.validate(),
1698            Err(ConfigError::InvalidUploadLimit(
1699                "max_active_aws_chunked_decoders must be greater than 0"
1700            ))
1701        );
1702    }
1703
1704    #[test]
1705    fn upload_limits_reject_min_part_size_larger_than_max_part_size() {
1706        let limits = UploadLimits {
1707            max_object_size: 100,
1708            max_part_size: 4,
1709            min_non_final_part_size: 5,
1710            ..Default::default()
1711        };
1712
1713        assert_eq!(
1714            limits.validate(),
1715            Err(ConfigError::InvalidUploadLimit(
1716                "min_non_final_part_size must be less than or equal to max_part_size"
1717            ))
1718        );
1719    }
1720}