summaryrefslogtreecommitdiff
path: root/src/authorization/entities.rs
blob: 8d7d178fa858041382cf6c880a07ccda4340d0c0 (plain)
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
use crate::gitlab::Api;
use serde::Serialize;
use std::collections::HashSet;

// Cedar entity structures
// Note: We define custom types instead of using cedar_policy::Entity directly because:
// 1. Cedar's Entity type is for runtime use, not JSON serialization
// 2. These types ensure our JSON output matches Cedar's expected format exactly
// 3. The #[serde(rename)] attributes handle Cedar's specific field naming requirements
#[derive(Debug, Serialize)]
pub struct CedarEntity {
    pub uid: CedarUid,
    pub attrs: serde_json::Value,
    pub parents: Vec<CedarParent>,
}

#[derive(Debug, Serialize)]
pub struct CedarUid {
    #[serde(rename = "type")]
    pub entity_type: String,
    pub id: String,
}

#[derive(Debug, Serialize)]
pub struct CedarParent {
    #[serde(rename = "type")]
    pub parent_type: String,
    pub id: String,
}

pub struct EntitiesRepository {
    api: Api,
}

impl EntitiesRepository {
    pub fn new(api: Api) -> EntitiesRepository {
        EntitiesRepository { api: api }
    }

    pub async fn all(
        &self,
        project_path: String,
    ) -> Result<Vec<CedarEntity>, Box<dyn std::error::Error>> {
        let mut entities = Vec::new();
        let mut groups = HashSet::new();

        let project = self.api.get_project(&project_path).await?;

        // Create member list first
        let member_ids: Vec<String> = self
            .api
            .get_project_members(project.id)
            .await?
            .iter()
            .filter(|m| m.state == "active")
            .map(|m| format!("User::\"{}\"", m.id))
            .collect();

        entities.push(CedarEntity {
            uid: CedarUid {
                entity_type: "Project".to_string(),
                id: project.id.to_string(),
            },
            attrs: serde_json::json!({
                "name": project.name,
                "path": project.path,
                "full_path": project.path_with_namespace,
                "visibility": project.visibility,
                "archived": project.archived.unwrap_or(false),
                "members": member_ids,
            }),
            parents: if project.namespace.kind == "group" {
                vec![CedarParent {
                    parent_type: "Group".to_string(),
                    id: project.namespace.id.to_string(),
                }]
            } else {
                vec![]
            },
        });

        // Get all members again to create User entities
        for member in self.api.get_project_members(project.id).await? {
            if member.state == "active" {
                entities.push(CedarEntity {
                    uid: CedarUid {
                        entity_type: "User".to_string(),
                        id: member.id.to_string(),
                    },
                    attrs: serde_json::json!({
                        "username": member.username,
                        "access_level": member.access_level,
                        "admin": false, // Would need to fetch from user API for real admin status
                        "blocked": false, // Would need to fetch from user API for real blocked status
                        "external": false, // Would need to fetch from user API for real external status
                    }),
                    parents: vec![],
                });
            }
        }

        if project.namespace.kind == "group" {
            self.fetch_hierarchy(project.namespace.id, &mut entities, &mut groups)
                .await?;
        }

        Ok(entities)
    }

    /// Validates that the entities can be parsed by Cedar
    pub fn is_valid(entities: &[CedarEntity]) -> Result<(), Box<dyn std::error::Error>> {
        let json = serde_json::to_string(entities)?;
        cedar_policy::Entities::from_json_str(&json, None)?;
        Ok(())
    }

    fn fetch_hierarchy<'a>(
        &'a self,
        group_id: u64,
        entities: &'a mut Vec<CedarEntity>,
        groups: &'a mut HashSet<u64>,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<(), Box<dyn std::error::Error>>> + 'a>,
    > {
        Box::pin(async move {
            if groups.contains(&group_id) {
                return Ok(());
            }

            groups.insert(group_id);

            let group = self.api.get_group(group_id).await?;

            let parents = if let Some(parent_id) = group.parent_id {
                self.fetch_hierarchy(parent_id, entities, groups).await?;
                vec![CedarParent {
                    parent_type: "Group".to_string(),
                    id: parent_id.to_string(),
                }]
            } else {
                vec![]
            };

            entities.push(CedarEntity {
                uid: CedarUid {
                    entity_type: "Group".to_string(),
                    id: group.id.to_string(),
                },
                attrs: serde_json::json!({
                    "name": group.name,
                    "path": group.path,
                    "full_path": group.full_path,
                    "visibility": "private", // Groups don't have visibility in our simplified model
                    "members": [], // Would need group members API to populate
                }),
                parents,
            });

            Ok(())
        })
    }
}