multistore 0.4.0

Runtime-agnostic core library for the S3 proxy gateway
Documentation
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
//! Shared types used across the proxy.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

/// Owner identity for S3 ListBuckets responses.
#[derive(Debug, Clone, Serialize)]
pub struct BucketOwner {
    #[serde(rename = "ID")]
    pub id: String,
    #[serde(rename = "DisplayName")]
    pub display_name: String,
}

/// Configuration for a virtual bucket exposed by the proxy.
#[derive(Clone, Serialize, Deserialize)]
pub struct BucketConfig {
    /// The virtual bucket name exposed to clients.
    pub name: String,

    /// Provider type: "s3", "az", "gcs", etc.
    pub backend_type: String,

    /// Optional prefix to prepend to all keys when forwarding.
    pub backend_prefix: Option<String>,

    /// Whether this bucket allows anonymous (unsigned) access.
    pub anonymous_access: bool,

    /// IAM role ARNs that are allowed to access this bucket.
    /// Empty means only anonymous access (if enabled) or long-lived credentials.
    #[serde(default)]
    pub allowed_roles: Vec<String>,

    /// Provider-specific config passed to the object_store builder.
    /// Keys are the short aliases accepted by each provider's ConfigKey::from_str().
    /// S3: "endpoint", "bucket_name", "region", "access_key_id", "secret_access_key", "skip_signature"
    /// Azure: "account_name", "container_name", "access_key", "skip_signature"
    /// GCS: "bucket_name", "service_account_key", "skip_signature"
    #[serde(default)]
    pub backend_options: HashMap<String, String>,
}

/// Keys in `backend_options` that hold secret values.
const REDACTED_OPTION_KEYS: &[&str] = &[
    "secret_access_key",
    "access_key",
    "service_account_key",
    "token",
];

impl fmt::Debug for BucketConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let redacted_opts: HashMap<&str, &str> = self
            .backend_options
            .iter()
            .map(|(k, v)| {
                let val = if REDACTED_OPTION_KEYS.contains(&k.as_str()) {
                    "[REDACTED]"
                } else {
                    v.as_str()
                };
                (k.as_str(), val)
            })
            .collect();

        f.debug_struct("BucketConfig")
            .field("name", &self.name)
            .field("backend_type", &self.backend_type)
            .field("backend_prefix", &self.backend_prefix)
            .field("anonymous_access", &self.anonymous_access)
            .field("allowed_roles", &self.allowed_roles)
            .field("backend_options", &redacted_opts)
            .finish()
    }
}

/// Known backend provider types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendType {
    /// Amazon S3 or S3-compatible storage.
    S3,
    /// Azure Blob Storage.
    Azure,
    /// Google Cloud Storage.
    Gcs,
}

impl BucketConfig {
    /// Parse the `backend_type` string into a known [`BackendType`].
    pub fn parsed_backend_type(&self) -> Option<BackendType> {
        match self.backend_type.as_str() {
            "s3" => Some(BackendType::S3),
            "az" | "azure" => Some(BackendType::Azure),
            "gcs" | "gs" => Some(BackendType::Gcs),
            _ => None,
        }
    }

    /// Whether this backend supports S3-style multipart uploads via raw HTTP.
    pub fn supports_s3_multipart(&self) -> bool {
        matches!(self.parsed_backend_type(), Some(BackendType::S3))
    }

    /// Look up a value in `backend_options`.
    pub fn option(&self, key: &str) -> Option<&str> {
        self.backend_options.get(key).map(|s| s.as_str())
    }
}

/// Configuration for an IAM role that can be assumed via STS.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoleConfig {
    /// The role identifier (used as the RoleArn in AssumeRoleWithWebIdentity).
    pub role_id: String,

    /// Human-readable name.
    pub name: String,

    /// OIDC provider URLs trusted by this role (e.g., "https://token.actions.githubusercontent.com").
    #[serde(default)]
    pub trusted_oidc_issuers: Vec<String>,

    /// Required audience claim value.
    pub required_audience: Option<String>,

    /// Conditions on the subject claim (glob patterns).
    /// e.g., "repo:myorg/myrepo:ref:refs/heads/main"
    #[serde(default)]
    pub subject_conditions: Vec<String>,

    /// Buckets and prefixes this role can access.
    #[serde(default)]
    pub allowed_scopes: Vec<AccessScope>,

    /// Maximum session duration in seconds.
    pub max_session_duration_secs: u64,
}

/// Defines what a credential is allowed to access.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessScope {
    /// The virtual bucket name this scope grants access to.
    pub bucket: String,
    /// Allowed key prefixes. Empty means full bucket access.
    pub prefixes: Vec<String>,
    /// The set of S3 actions permitted under this scope.
    pub actions: Vec<Action>,
}

/// S3 actions that can be authorized.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Action {
    GetObject,
    HeadObject,
    PutObject,
    ListBucket,
    CreateMultipartUpload,
    UploadPart,
    CompleteMultipartUpload,
    AbortMultipartUpload,
    DeleteObject,
}

/// A long-lived access credential stored in the config backend.
#[derive(Clone, Serialize, Deserialize)]
pub struct StoredCredential {
    /// The access key ID used in SigV4 authentication.
    pub access_key_id: String,
    /// The secret key used for HMAC signing.
    pub secret_access_key: String,
    /// Human-readable identity of the credential owner.
    pub principal_name: String,
    /// The buckets and actions this credential is authorized for.
    pub allowed_scopes: Vec<AccessScope>,
    /// When this credential was created.
    pub created_at: DateTime<Utc>,
    /// Optional expiration time; `None` means the credential does not expire.
    pub expires_at: Option<DateTime<Utc>>,
    /// Whether this credential is active and can be used for authentication.
    pub enabled: bool,
}

impl fmt::Debug for StoredCredential {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StoredCredential")
            .field("access_key_id", &self.access_key_id)
            .field("secret_access_key", &"[REDACTED]")
            .field("principal_name", &self.principal_name)
            .field("allowed_scopes", &self.allowed_scopes)
            .field("created_at", &self.created_at)
            .field("expires_at", &self.expires_at)
            .field("enabled", &self.enabled)
            .finish()
    }
}

/// Temporary credentials minted by the STS API.
#[derive(Clone, Serialize, Deserialize)]
pub struct TemporaryCredentials {
    /// The temporary access key ID.
    pub access_key_id: String,
    /// The temporary secret key for HMAC signing.
    pub secret_access_key: String,
    /// The session token that must accompany requests using these credentials.
    pub session_token: String,
    /// When these temporary credentials expire.
    pub expiration: DateTime<Utc>,
    /// The buckets and actions these credentials are authorized for.
    pub allowed_scopes: Vec<AccessScope>,
    /// The IAM role that was assumed to produce these credentials.
    pub assumed_role_id: String,
    /// The identity (e.g. OIDC subject) that assumed the role.
    pub source_identity: String,
}

impl fmt::Debug for TemporaryCredentials {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TemporaryCredentials")
            .field("access_key_id", &self.access_key_id)
            .field("secret_access_key", &"[REDACTED]")
            .field("session_token", &"[REDACTED]")
            .field("expiration", &self.expiration)
            .field("allowed_scopes", &self.allowed_scopes)
            .field("assumed_role_id", &self.assumed_role_id)
            .field("source_identity", &self.source_identity)
            .finish()
    }
}

/// The authenticated identity after credential verification.
///
/// This is the output of the authentication pipeline. It contains only
/// the information downstream consumers need — not the raw credentials
/// used during signature verification.
#[derive(Debug, Clone)]
pub struct AuthenticatedIdentity {
    pub principal_name: String,
    pub allowed_scopes: Vec<AccessScope>,
}

/// Represents the resolved identity after authentication.
#[derive(Debug, Clone)]
pub enum ResolvedIdentity {
    Anonymous,
    Authenticated(AuthenticatedIdentity),
}

/// The parsed S3 operation extracted from an incoming request.
#[derive(Debug, Clone)]
pub enum S3Operation {
    GetObject {
        bucket: String,
        key: String,
    },
    HeadObject {
        bucket: String,
        key: String,
    },
    PutObject {
        bucket: String,
        key: String,
    },
    CreateMultipartUpload {
        bucket: String,
        key: String,
    },
    UploadPart {
        bucket: String,
        key: String,
        upload_id: String,
        part_number: u32,
    },
    CompleteMultipartUpload {
        bucket: String,
        key: String,
        upload_id: String,
    },
    AbortMultipartUpload {
        bucket: String,
        key: String,
        upload_id: String,
    },
    DeleteObject {
        bucket: String,
        key: String,
    },
    ListBucket {
        bucket: String,
        /// Raw query string from the incoming request, forwarded to the backend.
        /// The proxy may modify `prefix` (prepend backend_prefix) and inject
        /// defaults for `max-keys` and `list-type`.
        raw_query: Option<String>,
    },
    /// List all virtual buckets exposed by the proxy.
    ListBuckets,
}

impl S3Operation {
    /// The HTTP method implied by this operation.
    pub fn method(&self) -> http::Method {
        match self {
            S3Operation::GetObject { .. }
            | S3Operation::ListBucket { .. }
            | S3Operation::ListBuckets => http::Method::GET,
            S3Operation::HeadObject { .. } => http::Method::HEAD,
            S3Operation::PutObject { .. } | S3Operation::UploadPart { .. } => http::Method::PUT,
            S3Operation::DeleteObject { .. } | S3Operation::AbortMultipartUpload { .. } => {
                http::Method::DELETE
            }
            S3Operation::CreateMultipartUpload { .. }
            | S3Operation::CompleteMultipartUpload { .. } => http::Method::POST,
        }
    }

    /// The authorization action for this operation.
    pub fn action(&self) -> Action {
        match self {
            S3Operation::GetObject { .. } => Action::GetObject,
            S3Operation::HeadObject { .. } => Action::HeadObject,
            S3Operation::PutObject { .. } => Action::PutObject,
            S3Operation::ListBucket { .. } => Action::ListBucket,
            S3Operation::CreateMultipartUpload { .. } => Action::CreateMultipartUpload,
            S3Operation::UploadPart { .. } => Action::UploadPart,
            S3Operation::CompleteMultipartUpload { .. } => Action::CompleteMultipartUpload,
            S3Operation::AbortMultipartUpload { .. } => Action::AbortMultipartUpload,
            S3Operation::DeleteObject { .. } => Action::DeleteObject,
            S3Operation::ListBuckets => Action::ListBucket,
        }
    }

    /// The bucket name, if any.
    pub fn bucket(&self) -> Option<&str> {
        match self {
            S3Operation::GetObject { bucket, .. }
            | S3Operation::HeadObject { bucket, .. }
            | S3Operation::PutObject { bucket, .. }
            | S3Operation::ListBucket { bucket, .. }
            | S3Operation::CreateMultipartUpload { bucket, .. }
            | S3Operation::UploadPart { bucket, .. }
            | S3Operation::CompleteMultipartUpload { bucket, .. }
            | S3Operation::AbortMultipartUpload { bucket, .. }
            | S3Operation::DeleteObject { bucket, .. } => Some(bucket),
            S3Operation::ListBuckets => None,
        }
    }

    /// The object key, if any. Returns empty string for non-object operations.
    pub fn key(&self) -> &str {
        match self {
            S3Operation::GetObject { key, .. }
            | S3Operation::HeadObject { key, .. }
            | S3Operation::PutObject { key, .. }
            | S3Operation::CreateMultipartUpload { key, .. }
            | S3Operation::UploadPart { key, .. }
            | S3Operation::CompleteMultipartUpload { key, .. }
            | S3Operation::AbortMultipartUpload { key, .. }
            | S3Operation::DeleteObject { key, .. } => key,
            S3Operation::ListBucket { .. } | S3Operation::ListBuckets => "",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_action() {
        let op = S3Operation::GetObject {
            bucket: "b".into(),
            key: "k".into(),
        };
        assert_eq!(op.action(), Action::GetObject);

        let op = S3Operation::PutObject {
            bucket: "b".into(),
            key: "k".into(),
        };
        assert_eq!(op.action(), Action::PutObject);

        let op = S3Operation::ListBucket {
            bucket: "b".into(),
            raw_query: None,
        };
        assert_eq!(op.action(), Action::ListBucket);

        assert_eq!(S3Operation::ListBuckets.action(), Action::ListBucket);

        let op = S3Operation::DeleteObject {
            bucket: "b".into(),
            key: "k".into(),
        };
        assert_eq!(op.action(), Action::DeleteObject);
    }

    #[test]
    fn test_bucket() {
        let op = S3Operation::GetObject {
            bucket: "my-bucket".into(),
            key: "k".into(),
        };
        assert_eq!(op.bucket(), Some("my-bucket"));

        assert_eq!(S3Operation::ListBuckets.bucket(), None);
    }

    #[test]
    fn test_key() {
        let op = S3Operation::GetObject {
            bucket: "b".into(),
            key: "my/key.txt".into(),
        };
        assert_eq!(op.key(), "my/key.txt");

        let op = S3Operation::ListBucket {
            bucket: "b".into(),
            raw_query: Some("prefix=foo/".into()),
        };
        assert_eq!(op.key(), "");

        assert_eq!(S3Operation::ListBuckets.key(), "");
    }
}