1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use cyfs_base::*;
use cyfs_core::*;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{Map, Value};
use std::str::FromStr;

#[derive(Clone, Copy, Eq, Debug, PartialEq)]
pub enum RequestProtocol {
    Native,
    Meta,
    Sync,
    HttpBdt,
    HttpLocal,
    HttpLocalAuth,
    DatagramBdt,
    // bdt层的chunk数据传输
    DataBdt,
}

impl RequestProtocol {
    pub fn is_local(&self) -> bool {
        match *self {
            Self::Native | Self::HttpLocal | Self::HttpLocalAuth => true,
            Self::HttpBdt | Self::DatagramBdt | Self::DataBdt => false,
            Self::Meta | Self::Sync => false,
        }
    }

    pub fn is_remote(&self) -> bool {
        !self.is_local()
    }

    pub fn is_require_acl(&self) -> bool {
        match *self {
            Self::HttpBdt | Self::DatagramBdt | Self::DataBdt => true,
            Self::Native | Self::HttpLocal | Self::Meta | Self::Sync | Self::HttpLocalAuth => false,
        }
    }

    pub fn as_str(&self) -> &str {
        match *self {
            Self::Native => "native",
            Self::Meta => "meta",
            Self::Sync => "sync",
            Self::HttpBdt => "http-bdt",
            Self::HttpLocal => "http-local",
            Self::HttpLocalAuth => "http-local-auth",
            Self::DatagramBdt => "datagram-bdt",
            Self::DataBdt => "data-bdt",
        }
    }
}

impl ToString for RequestProtocol {
    fn to_string(&self) -> String {
        self.as_str().to_owned()
    }
}

impl FromStr for RequestProtocol {
    type Err = BuckyError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let ret = match value {
            "native" => Self::Native,
            "meta" => Self::Meta,
            "sync" => Self::Sync,
            "http-bdt" => Self::HttpBdt,
            "http-local" => Self::HttpLocal,
            "http-local-auth" => Self::HttpLocalAuth,
            "datagram-bdt" => Self::DatagramBdt,
            "data-bdt" => Self::DataBdt,
            v @ _ => {
                let msg = format!("unknown request input protocol: {}", v);
                error!("{}", msg);

                return Err(BuckyError::new(BuckyErrorCode::InvalidParam, msg));
            }
        };

        Ok(ret)
    }
}

// source device's zone info
#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum DeviceZoneCategory {
    CurrentDevice = 0,
    CurrentZone = 1,
    FriendZone = 2,
    OtherZone = 3,
}

impl DeviceZoneCategory {
    pub fn as_str(&self) -> &str {
        match self {
            Self::CurrentDevice => "current-device",
            Self::CurrentZone => "current-zone",
            Self::FriendZone => "friend-zone",
            Self::OtherZone => "other-zone",
        }
    }

    pub fn is_included(&self, target: Self) -> bool {
        *self as u8 <= target as u8
    }
}

impl ToString for DeviceZoneCategory {
    fn to_string(&self) -> String {
        self.as_str().to_owned()
    }
}

impl FromStr for DeviceZoneCategory {
    type Err = BuckyError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let ret = match s {
            "current-device" => Self::CurrentDevice,
            "current-zone" => Self::CurrentZone,
            "friend-zone" => Self::FriendZone,
            "other-zone" => Self::OtherZone,
            _ => {
                let msg = format!("unknown device zone category: {}", s);
                error!("{}", msg);

                return Err(BuckyError::new(BuckyErrorCode::InvalidParam, msg));
            }
        };

        Ok(ret)
    }
}
impl Into<AccessGroup> for DeviceZoneCategory {
    fn into(self) -> AccessGroup {
        match self {
            DeviceZoneCategory::CurrentDevice => AccessGroup::CurrentDevice,
            DeviceZoneCategory::CurrentZone => AccessGroup::CurrentZone,
            DeviceZoneCategory::FriendZone => AccessGroup::FriendZone,
            DeviceZoneCategory::OtherZone => AccessGroup::OthersZone,
        }
    }
}

#[derive(Clone, Debug)]
pub struct DeviceZoneInfo {
    pub device: Option<DeviceId>,
    pub zone: Option<ObjectId>,
    pub zone_category: DeviceZoneCategory,
}

impl DeviceZoneInfo {
    pub fn new_local() -> Self {
        Self {
            device: None,
            zone: None,
            zone_category: DeviceZoneCategory::CurrentDevice,
        }
    }

    pub fn new_current_zone() -> Self {
        Self {
            device: None,
            zone: None,
            zone_category: DeviceZoneCategory::CurrentZone,
        }
    }

    pub fn new_friend_zone() -> Self {
        Self {
            device: None,
            zone: None,
            zone_category: DeviceZoneCategory::FriendZone,
        }
    }

    pub fn new_other_zone() -> Self {
        Self {
            device: None,
            zone: None,
            zone_category: DeviceZoneCategory::OtherZone,
        }
    }

    pub fn is_current_device(&self) -> bool {
        match self.zone_category {
            DeviceZoneCategory::CurrentDevice => true,
            _ => false,
        }
    }

    pub fn is_current_zone(&self) -> bool {
        match self.zone_category {
            DeviceZoneCategory::CurrentDevice | DeviceZoneCategory::CurrentZone => true,
            _ => false,
        }
    }

    pub fn is_friend_zone(&self) -> bool {
        match self.zone_category {
            DeviceZoneCategory::CurrentDevice
            | DeviceZoneCategory::CurrentZone
            | DeviceZoneCategory::FriendZone => true,
            _ => false,
        }
    }
}

// The identy info of a request
#[derive(Clone)]
pub struct RequestSourceInfo {
    pub protocol: RequestProtocol,
    pub zone: DeviceZoneInfo,
    pub dec: ObjectId,

    // is passed the acl verified for target-dec-id
    pub verified: Option<ObjectId>,
}

impl std::fmt::Debug for RequestSourceInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self, f)
    }
}

impl std::fmt::Display for RequestSourceInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "protocol={}, zone=({:?}-{:?}-{:?}), dec={}, verified={:?}",
            self.protocol.as_str(),
            self.zone.zone_category,
            self.zone.device,
            self.zone.zone,
            cyfs_core::dec_id_to_string(&self.dec),
            self.verified,
        )
    }
}

impl RequestSourceInfo {
    pub fn new_local_system() -> Self {
        Self {
            protocol: RequestProtocol::Native,
            zone: DeviceZoneInfo::new_local(),
            dec: get_system_dec_app().to_owned(),
            verified: None,
        }
    }

    pub fn new_local_anonymouse() -> Self {
        Self {
            protocol: RequestProtocol::Native,
            zone: DeviceZoneInfo::new_local(),
            dec: get_anonymous_dec_app().to_owned(),
            verified: None,
        }
    }

    // dec-id = anonymous-dec-id if None
    pub fn new_local_dec(dec: Option<ObjectId>) -> Self {
        Self {
            protocol: RequestProtocol::Native,
            zone: DeviceZoneInfo::new_local(),
            dec: dec.unwrap_or(get_anonymous_dec_app().to_owned()),
            verified: None,
        }
    }

    // dec-id = system-dec-id if None
    pub fn new_local_dec_or_system(dec: Option<ObjectId>) -> Self {
        Self {
            protocol: RequestProtocol::Native,
            zone: DeviceZoneInfo::new_local(),
            dec: dec.unwrap_or(get_system_dec_app().to_owned()),
            verified: None,
        }
    }

    // dec-id = anonymous-dec-id if None
    pub fn new_zone_dec(dec: Option<ObjectId>) -> Self {
        Self {
            protocol: RequestProtocol::Native,
            zone: DeviceZoneInfo::new_current_zone(),
            dec: dec.unwrap_or(get_anonymous_dec_app().to_owned()),
            verified: None,
        }
    }

    // dec-id = anonymous-dec-id if None
    pub fn new_friend_zone_dec(dec: Option<ObjectId>) -> Self {
        Self {
            protocol: RequestProtocol::Native,
            zone: DeviceZoneInfo::new_friend_zone(),
            dec: dec.unwrap_or(get_anonymous_dec_app().to_owned()),
            verified: None,
        }
    }

    // dec-id = anonymous-dec-id if None
    pub fn new_other_zone_dec(dec: Option<ObjectId>) -> Self {
        Self {
            protocol: RequestProtocol::Native,
            zone: DeviceZoneInfo::new_other_zone(),
            dec: dec.unwrap_or(get_anonymous_dec_app().to_owned()),
            verified: None,
        }
    }

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

    pub fn set_dec(&mut self, dec_id: ObjectId) {
        self.dec = dec_id;
    }

    pub fn dec(mut self, dec_id: ObjectId) -> Self {
        self.set_dec(dec_id);
        self
    }

    pub fn is_system_dec(&self) -> bool {
        self.dec == *get_system_dec_app()
    }

    pub fn is_anonymous_dec_app(&self) -> bool {
        self.dec == *get_anonymous_dec_app()
    }

    // return none if is anonymous dec
    pub fn get_opt_dec(&self) -> Option<&ObjectId> {
        if self.is_anonymous_dec_app() {
            None
        } else {
            Some(&self.dec)
        }
    }

    pub fn set_verified(&mut self, target_dec_id: ObjectId) {
        assert!(self.verified.is_none());
        self.verified = Some(target_dec_id);
    }

    pub fn is_verified(&self, target_dec_id: &ObjectId) -> bool {
        match &self.verified {
            Some(id) => {
                if id == target_dec_id {
                    true
                } else {
                    if self.is_system_dec() {
                        true
                    } else {
                        warn!("request source pass verify but target_dec_id not match! pass={}, required={}",
                        cyfs_core::dec_id_to_string(&id), cyfs_core::dec_id_to_string(&target_dec_id));

                        false
                    }
                }
            }
            None => false,
        }
    }

    pub fn is_fuzzy_verified(&self) -> bool {
        self.verified.is_some()
    }

    pub fn check_target_dec_permission(&self, op_target_dec: &Option<ObjectId>) -> bool {
        self.check_target_dec_permission2(op_target_dec.as_ref())
    }

    pub fn check_target_dec_permission2(&self, op_target_dec: Option<&ObjectId>) -> bool {
        if self.is_system_dec() {
            true
        } else {
            match op_target_dec {
                Some(target) => self.compare_dec(target),
                None => {
                    // target_dec_id is none then equal as current dec
                    true
                }
            }
        }
    }

    pub fn is_current_device(&self) -> bool {
        self.zone.is_current_device()
    }

    pub fn is_current_zone(&self) -> bool {
        self.zone.is_current_zone()
    }

    pub fn compare_zone_category(&self, zone_category: DeviceZoneCategory) -> bool {
        self.zone.zone_category.is_included(zone_category)
    }

    pub fn compare_zone(&self, zone: &ObjectId) -> bool {
        self.zone.device.as_ref().map(|v| v.object_id()) == Some(zone)
            || self.zone.zone.as_ref() == Some(zone)
    }

    pub fn compare_dec(&self, dec: &ObjectId) -> bool {
        self.dec == *dec
    }

    pub fn mask(&self, own_dec_id: &ObjectId, permissions: impl Into<AccessPermissions>) -> u32 {
        let permissions = permissions.into();
        let mut access = AccessString::new(0);
        if self.dec == *own_dec_id {
            access.set_group_permissions(AccessGroup::OwnerDec, permissions);
        } else {
            access.set_group_permissions(AccessGroup::OthersDec, permissions);
        }

        /*
        A and B two dec
        A creates objX, the permission is the default permission, that is, B in the same zone can access
        B After obtaining the ID of objX, configure the rpath permission so that objX can be accessed outside the zone

        The key point here is that this behavior is inevitable. As long as B can access the obj, 
        it is theoretically impossible to prevent B from spreading the obj out of the zone? 
        So if other dec is allowed to access in the same zone at the object level access(Only true at the object access layer), 
        it can be allowed
        */
        if self.is_fuzzy_verified() {
            access.set_group_permissions(AccessGroup::CurrentDevice, permissions);
            access.set_group_permissions(AccessGroup::CurrentZone, permissions);
        } else {
            let group = self.zone.zone_category.into();
            access.set_group_permissions(group, permissions);
        }

        access.value()
    }

    pub fn owner_dec_mask(&self, permissions: impl Into<AccessPermissions>) -> u32 {
        let permissions = permissions.into();

        let mut access = AccessString::new(0);
        access.set_group_permissions(AccessGroup::OwnerDec, permissions);

        let group = self.zone.zone_category.into();
        access.set_group_permissions(group, permissions);

        access.value()
    }

    pub fn other_dec_mask(&self, permissions: impl Into<AccessPermissions>) -> u32 {
        let permissions = permissions.into();

        let mut access = AccessString::new(0);
        access.set_group_permissions(AccessGroup::OthersDec, permissions);

        let group = self.zone.zone_category.into();
        access.set_group_permissions(group, permissions);

        access.value()
    }

    pub fn check_current_zone(&self, service: &str) -> BuckyResult<()> {
        if !self.is_current_zone() {
            let msg = format!(
                "{} service valid only in current zone! source device={:?}, category={}",
                service,
                self.zone.device,
                self.zone.zone_category.as_str(),
            );
            error!("{}", msg);

            return Err(BuckyError::new(BuckyErrorCode::PermissionDenied, msg));
        }

        Ok(())
    }

    pub fn check_current_device(&self, service: &str) -> BuckyResult<()> {
        if !self.is_current_device() {
            let msg = format!(
                "{} service valid only on current device! source device={:?}, category={}",
                service,
                self.zone.device,
                self.zone.zone_category.as_str(),
            );
            error!("{}", msg);

            return Err(BuckyError::new(BuckyErrorCode::PermissionDenied, msg));
        }

        Ok(())
    }
}

impl JsonCodec<Self> for DeviceZoneInfo {
    fn encode_json(&self) -> Map<String, Value> {
        let mut obj = Map::new();
        JsonCodecHelper::encode_option_string_field(&mut obj, "device", self.device.as_ref());
        JsonCodecHelper::encode_option_string_field(&mut obj, "zone", self.zone.as_ref());
        JsonCodecHelper::encode_string_field(
            &mut obj,
            "zone_category",
            self.zone_category.as_str(),
        );

        obj
    }

    fn decode_json(obj: &Map<String, Value>) -> BuckyResult<Self> {
        Ok(Self {
            device: JsonCodecHelper::decode_option_string_field(obj, "device")?,
            zone: JsonCodecHelper::decode_option_string_field(obj, "zone")?,
            zone_category: JsonCodecHelper::decode_string_field(obj, "zone_category")?,
        })
    }
}

impl JsonCodec<Self> for RequestSourceInfo {
    fn encode_json(&self) -> Map<String, Value> {
        let mut obj = Map::new();
        JsonCodecHelper::encode_field(&mut obj, "zone", &self.zone);
        JsonCodecHelper::encode_string_field(&mut obj, "dec", &self.dec);
        JsonCodecHelper::encode_string_field(&mut obj, "protocol", &self.protocol);
        JsonCodecHelper::encode_option_string_field(&mut obj, "verified", self.verified.as_ref());

        obj
    }

    fn decode_json(obj: &Map<String, Value>) -> BuckyResult<Self> {
        Ok(Self {
            zone: JsonCodecHelper::decode_field(obj, "zone")?,
            dec: JsonCodecHelper::decode_string_field(obj, "dec")?,
            protocol: JsonCodecHelper::decode_string_field(obj, "protocol")?,
            verified: JsonCodecHelper::decode_option_string_field(obj, "verified")?,
        })
    }
}

impl Serialize for DeviceZoneCategory {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for DeviceZoneCategory {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_str(TStringVisitor::<Self>::new())
    }
}

impl Into<OpEnvSourceInfo> for RequestSourceInfo {
    fn into(self) -> OpEnvSourceInfo {
        OpEnvSourceInfo {
            dec: self.dec,
            device: self.zone.device,
        }
    }
}
#[cfg(test)]
mod test {
    use super::*;

    fn other_dec_read() {
        let dec = ObjectId::default();
        let source = RequestSourceInfo {
            zone: DeviceZoneInfo {
                device: None,
                zone: None,
                zone_category: DeviceZoneCategory::CurrentDevice,
            },
            dec,
            protocol: RequestProtocol::Native,
            verified: None,
        };

        let system = ObjectId::default();
        let mask = source.mask(&system, RequestOpType::Read);

        let default = AccessString::default().value();
        assert_ne!(default & mask, mask)
    }

    #[test]
    fn test_verified() {
        let owner = ObjectId::default();
        let dec_a = cyfs_core::DecApp::generate_id(owner.clone(), "dec-a");
        let dec_b = cyfs_core::DecApp::generate_id(owner.clone(), "dec-b");

        let source = RequestSourceInfo {
            zone: DeviceZoneInfo {
                device: None,
                zone: None,
                zone_category: DeviceZoneCategory::OtherZone,
            },
            dec: dec_a.clone(),
            protocol: RequestProtocol::HttpBdt,
            verified: None,
        };

        {
            let mut source = source.clone();
            let object_access = AccessString::default().value();

            let mask = source.mask(&dec_b, RequestOpType::Read);
            assert_ne!(object_access & mask, mask);

            source.set_verified(dec_a);
            let mask = source.mask(&dec_b, RequestOpType::Read);
            assert_eq!(object_access & mask, mask);
        }

        {
            let mut source = source.clone();

            // remove other dec access
            let mut access = AccessString::default();
            access.clear_group_permissions(AccessGroup::OthersDec);
            let object_access = access.value();

            let mask = source.mask(&dec_b, RequestOpType::Read);
            assert_ne!(object_access & mask, mask);

            source.set_verified(dec_a);
            let mask = source.mask(&dec_b, RequestOpType::Read);
            assert_ne!(object_access & mask, mask);
        }

        {
            let mut source = source.clone();

            // remove other dec access
            let mut access = AccessString::default();
            access.clear_group_permissions(AccessGroup::CurrentZone);
            let object_access = access.value();

            let mask = source.mask(&dec_b, RequestOpType::Read);
            assert_ne!(object_access & mask, mask);

            source.set_verified(dec_a);
            let mask = source.mask(&dec_b, RequestOpType::Read);
            assert_ne!(object_access & mask, mask);
        }
    }
}