rustfs-policy 0.0.3

Policy management for RustFS, providing a framework for defining and enforcing policies across the system.
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
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
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::error::Error as IamError;
use crate::error::{Error, Result};
use crate::policy::{INHERITED_POLICY_TYPE, Policy, Validator, iam_policy_claim_name_sa};
use crate::utils;
use crate::utils::extract_claims;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashMap;
use time::OffsetDateTime;
use time::macros::offset;

const ACCESS_KEY_MIN_LEN: usize = 3;
const ACCESS_KEY_MAX_LEN: usize = 20;
const SECRET_KEY_MIN_LEN: usize = 8;
const SECRET_KEY_MAX_LEN: usize = 40;

pub const ACCOUNT_ON: &str = "on";
pub const ACCOUNT_OFF: &str = "off";

const RESERVED_CHARS: &str = "=,";

// ContainsReservedChars - returns whether the input string contains reserved characters.
pub fn contains_reserved_chars(s: &str) -> bool {
    s.contains(RESERVED_CHARS)
}

// IsAccessKeyValid - validate access key for right length.
pub fn is_access_key_valid(access_key: &str) -> bool {
    access_key.len() >= ACCESS_KEY_MIN_LEN
}

// IsSecretKeyValid - validate secret key for right length.
pub fn is_secret_key_valid(secret_key: &str) -> bool {
    secret_key.len() >= SECRET_KEY_MIN_LEN
}

// #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
// struct CredentialHeader {
//     access_key: String,
//     scop: CredentialHeaderScope,
// }

// #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
// struct CredentialHeaderScope {
//     date: Date,
//     region: String,
//     service: ServiceType,
//     request: String,
// }

// impl TryFrom<&str> for CredentialHeader {
//     type Error = Error;
//     fn try_from(value: &str) -> Result<Self, Self::Error> {
//         let mut elem = value.trim().splitn(2, '=');
//         let (Some(h), Some(cred_elems)) = (elem.next(), elem.next()) else {
//             return Err(IamError::ErrCredMalformed));
//         };

//         if h != "Credential" {
//             return Err(IamError::ErrCredMalformed));
//         }

//         let mut cred_elems = cred_elems.trim().rsplitn(5, '/');

//         let Some(request) = cred_elems.next() else {
//             return Err(IamError::ErrCredMalformed));
//         };

//         let Some(service) = cred_elems.next() else {
//             return Err(IamError::ErrCredMalformed));
//         };

//         let Some(region) = cred_elems.next() else {
//             return Err(IamError::ErrCredMalformed));
//         };

//         let Some(date) = cred_elems.next() else {
//             return Err(IamError::ErrCredMalformed));
//         };

//         let Some(ak) = cred_elems.next() else {
//             return Err(IamError::ErrCredMalformed));
//         };

//         if ak.len() < 3 {
//             return Err(IamError::ErrCredMalformed));
//         }

//         if request != "aws4_request" {
//             return Err(IamError::ErrCredMalformed));
//         }

//         Ok(CredentialHeader {
//             access_key: ak.to_owned(),
//             scop: CredentialHeaderScope {
//                 date: {
//                     const FORMATTER: LazyCell<Vec<BorrowedFormatItem<'static>>> =
//                         LazyCell::new(|| time::format_description::parse("[year][month][day]").unwrap());

//                     Date::parse(date, &FORMATTER).map_err(|_| IamError::ErrCredMalformed))?
//                 },
//                 region: region.to_owned(),
//                 service: service.try_into()?,
//                 request: request.to_owned(),
//             },
//         })
//     }
// }

#[derive(Serialize, Deserialize, Clone, Default, Debug)]
pub struct Credentials {
    pub access_key: String,
    pub secret_key: String,
    pub session_token: String,
    pub expiration: Option<OffsetDateTime>,
    pub status: String,
    pub parent_user: String,
    pub groups: Option<Vec<String>>,
    pub claims: Option<HashMap<String, Value>>,
    pub name: Option<String>,
    pub description: Option<String>,
}

impl Credentials {
    // pub fn new(elem: &str) -> Result<Self> {
    //     let header: CredentialHeader = elem.try_into()?;
    //     Self::check_key_value(header)
    // }

    // pub fn check_key_value(_header: CredentialHeader) -> Result<Self> {
    //     todo!()
    // }

    pub fn is_expired(&self) -> bool {
        if self.expiration.is_none() {
            return false;
        }

        self.expiration
            .as_ref()
            .map(|e| time::OffsetDateTime::now_utc() > *e)
            .unwrap_or(false)
    }

    pub fn is_temp(&self) -> bool {
        !self.session_token.is_empty() && !self.is_expired()
    }

    pub fn is_service_account(&self) -> bool {
        const IAM_POLICY_CLAIM_NAME_SA: &str = "sa-policy";
        self.claims
            .as_ref()
            .map(|x| x.get(IAM_POLICY_CLAIM_NAME_SA).is_some_and(|_| !self.parent_user.is_empty()))
            .unwrap_or_default()
    }

    pub fn is_implied_policy(&self) -> bool {
        if self.is_service_account() {
            return self
                .claims
                .as_ref()
                .map(|x| x.get(&iam_policy_claim_name_sa()).is_some_and(|v| v == INHERITED_POLICY_TYPE))
                .unwrap_or_default();
        }

        false
    }

    pub fn is_valid(&self) -> bool {
        if self.status == "off" {
            return false;
        }

        self.access_key.len() >= 3 && self.secret_key.len() >= 8 && !self.is_expired()
    }

    pub fn is_owner(&self) -> bool {
        false
    }
}

pub fn generate_credentials() -> Result<(String, String)> {
    let ak = utils::gen_access_key(20)?;
    let sk = utils::gen_secret_key(40)?;
    Ok((ak, sk))
}

pub fn get_new_credentials_with_metadata(claims: &HashMap<String, Value>, token_secret: &str) -> Result<Credentials> {
    let (ak, sk) = generate_credentials()?;

    create_new_credentials_with_metadata(&ak, &sk, claims, token_secret)
}

pub fn create_new_credentials_with_metadata(
    ak: &str,
    sk: &str,
    claims: &HashMap<String, Value>,
    token_secret: &str,
) -> Result<Credentials> {
    if ak.len() < ACCESS_KEY_MIN_LEN || ak.len() > ACCESS_KEY_MAX_LEN {
        return Err(IamError::InvalidAccessKeyLength);
    }

    if sk.len() < SECRET_KEY_MIN_LEN || sk.len() > SECRET_KEY_MAX_LEN {
        return Err(IamError::InvalidAccessKeyLength);
    }

    if token_secret.is_empty() {
        return Ok(Credentials {
            access_key: ak.to_owned(),
            secret_key: sk.to_owned(),
            status: ACCOUNT_OFF.to_owned(),
            ..Default::default()
        });
    }

    let expiration = {
        if let Some(v) = claims.get("exp") {
            if let Some(expiry) = v.as_i64() {
                Some(OffsetDateTime::from_unix_timestamp(expiry)?.to_offset(offset!(+8)))
            } else {
                None
            }
        } else {
            None
        }
    };

    let token = utils::generate_jwt(&claims, token_secret)?;

    Ok(Credentials {
        access_key: ak.to_owned(),
        secret_key: sk.to_owned(),
        session_token: token,
        status: ACCOUNT_ON.to_owned(),
        expiration,
        ..Default::default()
    })
}

pub fn get_claims_from_token_with_secret<T: DeserializeOwned>(token: &str, secret: &str) -> Result<T> {
    let ms = extract_claims::<T>(token, secret)?;
    // TODO SessionPolicyName
    Ok(ms.claims)
}

pub fn jwt_sign<T: Serialize>(claims: &T, token_secret: &str) -> Result<String> {
    let token = utils::generate_jwt(claims, token_secret)?;
    Ok(token)
}

#[derive(Default)]
pub struct CredentialsBuilder {
    session_policy: Option<Policy>,
    access_key: String,
    secret_key: String,
    name: Option<String>,
    description: Option<String>,
    expiration: Option<OffsetDateTime>,
    allow_site_replicator_account: bool,
    claims: Option<serde_json::Value>,
    parent_user: String,
    groups: Option<Vec<String>>,
}

impl CredentialsBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn session_policy(mut self, policy: Option<Policy>) -> Self {
        self.session_policy = policy;
        self
    }

    pub fn access_key(mut self, access_key: String) -> Self {
        self.access_key = access_key;
        self
    }

    pub fn secret_key(mut self, secret_key: String) -> Self {
        self.secret_key = secret_key;
        self
    }

    pub fn name(mut self, name: String) -> Self {
        self.name = Some(name);
        self
    }

    pub fn description(mut self, description: String) -> Self {
        self.description = Some(description);
        self
    }

    pub fn expiration(mut self, expiration: Option<OffsetDateTime>) -> Self {
        self.expiration = expiration;
        self
    }

    pub fn allow_site_replicator_account(mut self, allow_site_replicator_account: bool) -> Self {
        self.allow_site_replicator_account = allow_site_replicator_account;
        self
    }

    pub fn claims(mut self, claims: serde_json::Value) -> Self {
        self.claims = Some(claims);
        self
    }

    pub fn parent_user(mut self, parent_user: String) -> Self {
        self.parent_user = parent_user;
        self
    }

    pub fn groups(mut self, groups: Vec<String>) -> Self {
        self.groups = Some(groups);
        self
    }

    pub fn try_build(self) -> Result<Credentials> {
        self.try_into()
    }
}

impl TryFrom<CredentialsBuilder> for Credentials {
    type Error = Error;
    fn try_from(mut value: CredentialsBuilder) -> std::result::Result<Self, Self::Error> {
        if value.parent_user.is_empty() {
            return Err(IamError::InvalidArgument);
        }

        if (value.access_key.is_empty() && !value.secret_key.is_empty())
            || (!value.access_key.is_empty() && value.secret_key.is_empty())
        {
            return Err(Error::other("Either ak or sk is empty"));
        }

        if value.parent_user == value.access_key.as_str() {
            return Err(IamError::InvalidArgument);
        }

        if value.access_key == "site-replicator-0" && !value.allow_site_replicator_account {
            return Err(IamError::InvalidArgument);
        }

        let mut claim = serde_json::json!({
            "parent": value.parent_user
        });

        if let Some(p) = value.session_policy {
            p.is_valid()?;
            let policy_buf = serde_json::to_vec(&p).map_err(|_| IamError::InvalidArgument)?;
            if policy_buf.len() > 4096 {
                return Err(Error::other("session policy is too large"));
            }
            claim["sessionPolicy"] = serde_json::json!(base64_simd::STANDARD.encode_to_string(&policy_buf));
            claim["sa-policy"] = serde_json::json!("embedded-policy");
        } else {
            claim["sa-policy"] = serde_json::json!("inherited-policy");
        }

        if let Some(Value::Object(obj)) = value.claims {
            for (key, value) in obj {
                if claim.get(&key).is_some() {
                    continue;
                }
                claim[key] = value;
            }
        }

        if value.access_key.is_empty() {
            value.access_key = utils::gen_access_key(20)?;
        }

        if value.secret_key.is_empty() {
            value.access_key = utils::gen_secret_key(40)?;
        }

        claim["accessKey"] = json!(&value.access_key);

        let mut cred = Credentials {
            status: "on".into(),
            parent_user: value.parent_user,
            groups: value.groups,
            name: value.name,
            description: value.description,
            ..Default::default()
        };

        if !value.secret_key.is_empty() {
            let session_token = rustfs_crypto::jwt_encode(value.access_key.as_bytes(), &claim)
                .map_err(|_| Error::other("session policy is too large"))?;
            cred.session_token = session_token;
            // cred.expiration = Some(
            //     OffsetDateTime::from_unix_timestamp(
            //         claim
            //             .get("exp")
            //             .and_then(|x| x.as_i64())
            //             .ok_or(Error::StringError("invalid exp".into()))?,
            //     )
            //     .map_err(|_| Error::StringError("invalie timestamp".into()))?,
            // );
        } else {
            // cred.expiration =
            // Some(OffsetDateTime::from_unix_timestamp(0).map_err(|_| Error::StringError("invalie timestamp".into()))?);
        }

        cred.expiration = value.expiration;
        cred.access_key = value.access_key;
        cred.secret_key = value.secret_key;

        Ok(cred)
    }
}

// #[cfg(test)]
// #[allow(non_snake_case)]
// mod tests {
//     use test_case::test_case;
//     use time::Date;

//     use super::CredentialHeader;
//     use super::CredentialHeaderScope;
//     use crate::service_type::ServiceType;

//     #[test_case(
//         "Credential=aaaaaaaaaaaaaaaaaaaa/20241127/us-east-1/s3/aws4_request" =>
//         CredentialHeader{
//             access_key: "aaaaaaaaaaaaaaaaaaaa".into(),
//             scop: CredentialHeaderScope {
//                 date: Date::from_calendar_date(2024, time::Month::November, 27).unwrap(),
//                 region: "us-east-1".to_owned(),
//                 service: ServiceType::S3,
//                 request: "aws4_request".into(),
//             }
//         };
//         "1")]
//     #[test_case(
//         "Credential=aaaaaaaaaaa/aaaaaaaaa/20241127/us-east-1/s3/aws4_request" =>
//         CredentialHeader{
//             access_key: "aaaaaaaaaaa/aaaaaaaaa".into(),
//             scop: CredentialHeaderScope {
//                 date: Date::from_calendar_date(2024, time::Month::November, 27).unwrap(),
//                 region: "us-east-1".to_owned(),
//                 service: ServiceType::S3,
//                 request: "aws4_request".into(),
//             }
//         };
//         "2")]
//     #[test_case(
//         "Credential=aaaaaaaaaaa/aaaaaaaaa/20241127/us-east-1/sts/aws4_request" =>
//         CredentialHeader{
//             access_key: "aaaaaaaaaaa/aaaaaaaaa".into(),
//             scop: CredentialHeaderScope {
//                 date: Date::from_calendar_date(2024, time::Month::November, 27).unwrap(),
//                 region: "us-east-1".to_owned(),
//                 service: ServiceType::STS,
//                 request: "aws4_request".into(),
//             }
//         };
//         "3")]
//     fn test_CredentialHeader_from_str_successful(input: &str) -> CredentialHeader {
//         CredentialHeader::try_from(input).unwrap()
//     }

//     #[test_case("Credential")]
//     #[test_case("Cred=")]
//     #[test_case("Credential=abc")]
//     #[test_case("Credential=a/20241127/us-east-1/s3/aws4_request")]
//     #[test_case("Credential=aa/20241127/us-east-1/s3/aws4_request")]
//     #[test_case("Credential=aaaa/20241127/us-east-1/asa/aws4_request")]
//     #[test_case("Credential=aaaa/20241127/us-east-1/sts/aws4a_request")]
//     fn test_credential_header_from_str_failed(input: &str) {
//         if CredentialHeader::try_from(input).is_ok() {
//             unreachable!()
//         }
//     }
// }