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

// Cedar entity structures
#[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,
}

// API structures
#[derive(Debug, serde::Deserialize)]
pub struct Project {
    pub id: u64,
    pub name: String,
    pub path: String,
    pub namespace: Namespace,
}

#[derive(Debug, serde::Deserialize)]
pub struct Namespace {
    pub id: u64,
    pub name: String,
    pub path: String,
    pub kind: String,
    pub full_path: String,
    pub parent_id: Option<u64>,
}

#[derive(Debug, serde::Deserialize)]
pub struct Member {
    pub id: u64,
    pub username: String,
    pub name: String,
    pub state: String,
    pub access_level: u8,
}

#[derive(Debug, serde::Deserialize)]
pub struct Group {
    pub id: u64,
    pub name: String,
    pub path: String,
    pub full_path: String,
    pub parent_id: Option<u64>,
}

pub struct EntitiesRepository {
    pub token: String,
    pub host: String,
    pub project_url: String,
}

impl EntitiesRepository {
    pub fn new(token: String, host: String, project: String) -> EntitiesRepository {
        EntitiesRepository {
            token: token,
            host: host.clone(),
            project_url: format!(
                "{}/api/v4/projects/{}",
                host.trim_end_matches('/'),
                urlencoding::encode(&project)
            ),
        }
    }

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

        let project: Project = http
            .get(&self.project_url)
            .header("PRIVATE-TOKEN", &self.token)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?;

        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": format!("{}/{}", project.namespace.full_path, project.path),
            }),
            parents: if project.namespace.kind == "group" {
                vec![CedarParent {
                    parent_type: "Group".to_string(),
                    id: project.namespace.id.to_string(),
                }]
            } else {
                vec![]
            },
        });

        let members_url = format!(
            "{}/api/v4/projects/{}/members/all",
            self.host.trim_end_matches('/'),
            project.id
        );

        let members: Vec<Member> = http
            .get(&members_url)
            .header("PRIVATE-TOKEN", &self.token)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?;

        for member in members {
            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,
                        "name": member.name,
                        "access_level": member.access_level,
                    }),
                    parents: vec![],
                });
            }
        }

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

        Ok(entities)
    }
}

pub fn fetch_group_hierarchy<'a>(
    client: &'a reqwest::Client,
    api_url: &'a str,
    token: &'a str,
    group_id: u64,
    entities: &'a mut Vec<CedarEntity>,
    processed_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 processed_groups.contains(&group_id) {
            return Ok(());
        }

        processed_groups.insert(group_id);

        let group_url = format!(
            "{}/api/v4/groups/{}",
            api_url.trim_end_matches('/'),
            group_id
        );

        let group: Group = client
            .get(&group_url)
            .header("PRIVATE-TOKEN", token)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?;

        let parents = if let Some(parent_id) = group.parent_id {
            fetch_group_hierarchy(
                client,
                api_url,
                token,
                parent_id,
                entities,
                processed_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,
            }),
            parents,
        });

        Ok(())
    })
}