gitlab.rs 22.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//! This module defines gitlab related actions and enforcements.
//!
//! ## Features
//!
//! - ensure the integrity of the Arch Linux root group
//!   - add staff members with minimal access
//!   - ensure nobody except devops has higher privileges

use crate::args::Action;
use crate::state::{State, User};

use crate::components::gitlab::types::*;

use crate::util;

16
use itertools::Itertools;
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
use std::env;
use std::sync::Arc;

use anyhow::{bail, Context, Result};
use log::{debug, error, info, trace, warn};
use tokio::sync::{Mutex, MutexGuard};

use gitlab::api::{AsyncQuery, Query};
use gitlab::{AsyncGitlab, Gitlab, GitlabBuilder};

use gitlab::api::common::{AccessLevel, VisibilityLevel};
use gitlab::api::groups::members::{AddGroupMember, GroupMembers, RemoveGroupMember};
use gitlab::api::projects::{FeatureAccessLevel, Projects};
use gitlab::api::users::ExternalProvider;

Levente Polyak's avatar
Levente Polyak committed
32
33
const DEFAULT_ARCH_LINUX_GROUP_ACCESS_LEVEL: AccessLevel = AccessLevel::Minimal;
const DEFAULT_STAFF_GROUP_ACCESS_LEVEL: AccessLevel = AccessLevel::Reporter;
34
35
const DEVOPS_INFRASTRUCTURE_ACCESS_LEVEL: AccessLevel = AccessLevel::Developer;

36
pub const GITLAB_OWNER: &str = "archceo";
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
const MAIN_BRANCH: &str = "main";
const ALL_TAGS: &str = "*";

pub struct GitLabGlue {
    client: AsyncGitlab,
    state: Arc<Mutex<State>>,
}

impl GitLabGlue {
    pub async fn new(state: Arc<Mutex<State>>) -> Result<GitLabGlue> {
        let token = &env::var("GLUEBUDDY_GITLAB_TOKEN")
            .context("Missing env var GLUEBUDDY_GITLAB_TOKEN")?;
        let client = GitlabBuilder::new("gitlab.archlinux.org", token)
            .build_async()
            .await?;
        Ok(GitLabGlue { client, state })
    }

    pub async fn gather(&self) -> Result<()> {
        self.gather_gitlab_user_ids().await?;
        Ok(())
    }

    pub async fn gather_gitlab_user_ids(&self) -> Result<()> {
        info!("Gathering GitLab state");
        let mut state = self.state.lock().await;
        for user in &mut state.users.values_mut() {
            let username = &user.username;
            let users_endpoint = gitlab::api::users::Users::builder()
                .external_provider(
                    ExternalProvider::builder()
                        .uid(username)
                        .name("saml")
                        .build()
                        .unwrap(),
                )
                .active(())
                .external(false)
                .build()
                .unwrap();
            let users: Vec<GitLabUser> = users_endpoint.query_async(&self.client).await?;
            if users.is_empty() {
                warn!("Failed to query GitLab user for {}", username);
                continue;
            } else if users.len() > 1 {
                bail!(
                    "Somehow got {} GitLab user results for {}",
                    users.len(),
                    username
                )
            }
            let gitlab_user = users
                .first()
                .with_context(|| format!("Failed to query GitLab user for {}", username))?;
            debug!(
                "Successfully retrieved user {} to GitLab id {}",
                gitlab_user.username, gitlab_user.id
            );
            if user.username != gitlab_user.username {
                error!(
                    "Username mismatch between keycloak and GitLab: {} vs {}",
                    user.username, gitlab_user.username
                );
            }
            user.gitlab_id = Some(gitlab_user.id);
        }

        Ok(())
    }

    pub async fn run(&self, action: Action) -> Result<()> {
        self.update_gitlab_group_members(&action).await?;
Levente Polyak's avatar
Levente Polyak committed
109
        self.update_gitlab_staff_group_members(&action).await?;
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
        self.update_infrastructure_members(&action).await?;
        Ok(())
    }

    async fn update_gitlab_group_members(&self, action: &Action) -> Result<()> {
        let group = "archlinux";
        let archlinux_group_members = self.get_group_members(group).await?;

        let mut summary = PlanSummary::new("GitLab 'Arch Linux' group members");
        let state = self.state.lock().await;

        let gitlab_group_member_names = archlinux_group_members
            .iter()
            .map(|e| e.username.clone())
            .collect::<Vec<_>>();

        let staff = state.staff();
        for staff in &staff {
            if !gitlab_group_member_names.contains(&staff.username) {
129
                if self
Levente Polyak's avatar
Levente Polyak committed
130
                    .add_group_member(action, &staff, group, DEFAULT_ARCH_LINUX_GROUP_ACCESS_LEVEL)
131
132
                    .await?
                {
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
                    summary.add += 1;
                }
            }
        }

        for member in &archlinux_group_members {
            let user = staff.iter().find(|user| user.username.eq(&member.username));
            match user {
                None => {
                    if self
                        .remove_group_member(action, &state, member, group)
                        .await?
                    {
                        summary.destroy += 1;
                    }
                }
                Some(user) => {
150
                    if self
Levente Polyak's avatar
Levente Polyak committed
151
152
153
154
155
156
157
                        .enforce_group_role(
                            action,
                            user,
                            member,
                            group,
                            DEFAULT_ARCH_LINUX_GROUP_ACCESS_LEVEL,
                        )
Levente Polyak's avatar
Levente Polyak committed
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
                        .await?
                    {
                        summary.change += 1;
                    }
                }
            }
        }

        println!("{}", summary);
        println!("{}", util::format_separator());

        Ok(())
    }

    async fn update_gitlab_staff_group_members(&self, action: &Action) -> Result<()> {
        let group = "archlinux/teams/staff";
        let archlinux_group_members = self.get_group_members(group).await?;

        let mut summary = PlanSummary::new("GitLab 'Arch Linux/Teams/Staff' group members");
        let state = self.state.lock().await;

        let gitlab_group_member_names = archlinux_group_members
            .iter()
            .map(|e| e.username.clone())
            .collect::<Vec<_>>();

        let staff = state.staff();
        for staff in &staff {
            if !gitlab_group_member_names.contains(&staff.username) {
                if self
                    .add_group_member(action, &staff, group, DEFAULT_STAFF_GROUP_ACCESS_LEVEL)
                    .await?
                {
                    summary.add += 1;
                }
            }
        }

        for member in &archlinux_group_members {
            let user = staff.iter().find(|user| user.username.eq(&member.username));
            match user {
                None => {
                    if self
                        .remove_group_member(action, &state, member, group)
                        .await?
                    {
                        summary.destroy += 1;
                    }
                }
                Some(user) => {
                    if self
Levente Polyak's avatar
Levente Polyak committed
209
210
211
212
213
214
215
                        .enforce_group_role(
                            action,
                            user,
                            member,
                            group,
                            DEFAULT_STAFF_GROUP_ACCESS_LEVEL,
                        )
216
217
                        .await?
                    {
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
                        summary.change += 1;
                    }
                }
            }
        }

        println!("{}", summary);
        println!("{}", util::format_separator());

        Ok(())
    }

    async fn update_infrastructure_members(&self, action: &Action) -> Result<()> {
        let project = "archlinux/infrastructure";
        let project_members = self.get_project_members(project).await?;

        let mut summary = PlanSummary::new("GitLab 'Arch Linux/Infrastructure' project members");
        let state = self.state.lock().await;

237
238
239
240
241
242
243
244
245
246
247
248
249
250
        for member in &project_members {
            if self.remove_project_member(action, member, project).await? {
                summary.destroy += 1;
            }
        }

        println!("{}", summary);
        println!("{}", util::format_separator());

        let mut summary = PlanSummary::new("GitLab 'Arch Linux/Teams/DevOps' group members");
        let devops_group = "archlinux/teams/devops";
        let group_members = self.get_group_members(devops_group).await?;

        let group_member_names = group_members
251
252
253
254
255
256
            .iter()
            .map(|e| e.username.clone())
            .collect::<Vec<_>>();

        let devops = state.devops();
        for staff in &devops {
257
            if !group_member_names.contains(&staff.username) {
258
                if self
259
260
261
262
263
264
                    .add_group_member(
                        action,
                        &staff,
                        devops_group,
                        DEVOPS_INFRASTRUCTURE_ACCESS_LEVEL,
                    )
265
266
267
268
269
270
271
                    .await?
                {
                    summary.add += 1;
                }
            }
        }

272
        for member in &group_members {
273
274
275
276
277
            let user = devops
                .iter()
                .find(|user| user.username.eq(&member.username));
            match user {
                None => {
278
279
280
281
282
                    if self
                        .remove_group_member(action, &state, member, devops_group)
                        .await?
                    {
                        summary.destroy += 1;
283
284
                    }
                }
285
286
287
288
289
290
291
292
293
294
295
296
297
298
                Some(user) => match util::access_level_from_u64(member.access_level) {
                    DEVOPS_INFRASTRUCTURE_ACCESS_LEVEL => {}
                    _ => {
                        if self
                            .enforce_group_role(
                                action,
                                user,
                                member,
                                devops_group,
                                DEVOPS_INFRASTRUCTURE_ACCESS_LEVEL,
                            )
                            .await?
                        {
                            summary.change += 1;
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
            }
        }

        println!("{}", summary);
        println!("{}", util::format_separator());

        Ok(())
    }

    async fn get_group_members(&self, group: &str) -> Result<Vec<GitLabMember>> {
        let members_endpoint = gitlab::api::groups::members::GroupMembers::builder()
            .group(group)
            .build()
            .unwrap();
        let gitlab_group_members: Vec<GitLabMember> =
            gitlab::api::paged(members_endpoint, gitlab::api::Pagination::All)
                .query_async(&self.client)
                .await?;
        Ok(gitlab_group_members)
    }

    async fn get_project_members(&self, project: &str) -> Result<Vec<GitLabMember>> {
        let endpoint = gitlab::api::projects::members::ProjectMembers::builder()
            .project(project)
            .build()
            .unwrap();
        let members: Vec<GitLabMember> = gitlab::api::paged(endpoint, gitlab::api::Pagination::All)
            .query_async(&self.client)
            .await?;
        Ok(members)
    }

334
335
336
337
338
339
340
    async fn add_group_member(
        &self,
        action: &Action,
        user: &User,
        group: &str,
        access_level: AccessLevel,
    ) -> Result<bool> {
341
342
        let staff_username = &user.username;
        if user.gitlab_id.is_none() {
343
            debug!(
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
                "Skip adding {} to GitLab group: no GitLab user found",
                staff_username
            );
            return Ok(false);
        }
        let gitlab_id = user
            .gitlab_id
            .with_context(|| format!("Failed to unwrap GitLab user for {}", staff_username))?;

        debug!("Adding user {} to GitLab group '{}'", user.username, group);
        util::print_diff(
            &"",
            util::format_gitlab_member_access(group, &user.username, access_level).as_str(),
        )?;
        match action {
            Action::Apply => {
                let endpoint = gitlab::api::groups::members::AddGroupMember::builder()
                    .group(group)
                    .user(gitlab_id)
                    .access_level(access_level)
                    .build()
                    .unwrap();
                gitlab::api::ignore(endpoint)
                    .query_async(&self.client)
                    .await
                    .unwrap();
            }
            _ => {}
        }
        Ok(true)
    }

    async fn remove_group_member<'a>(
        &self,
        action: &Action,
        state: &MutexGuard<'a, State>,
        member: &GitLabMember,
        group: &str,
    ) -> Result<bool> {
        if state.user_may_have_gitlab_archlinux_group_access(&member.username) {
            return Ok(false);
        }
        debug!("User {} must not be in group {}", &member.username, group);
        util::print_diff(
            util::format_gitlab_member_access(
                group,
                &member.username,
                util::access_level_from_u64(member.access_level),
            )
            .as_str(),
            &"",
        )?;
        match action {
            Action::Apply => {
                let endpoint = gitlab::api::groups::members::RemoveGroupMember::builder()
                    .group(group)
                    .user(member.id)
                    .build()
                    .unwrap();
                gitlab::api::ignore(endpoint)
                    .query_async(&self.client)
                    .await
                    .unwrap();
            }
            _ => {}
        }
        Ok(true)
    }

    async fn enforce_group_role<'a>(
        &self,
        action: &Action,
        user: &User,
        group_member: &GitLabMember,
        group: &str,
419
        expected_access_level: AccessLevel,
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
    ) -> Result<bool> {
        let access_level = util::access_level_from_u64(group_member.access_level);
        if access_level.eq(&expected_access_level) {
            trace!(
                "User {} has expected access_level {} in group {}",
                user.username,
                expected_access_level.as_str(),
                group,
            );
            return Ok(false);
        }

        debug!(
            "User {} should have access_level {} instead of {} in group {}",
            user.username,
            expected_access_level.as_str(),
            access_level.as_str(),
            group,
        );
        util::print_diff(
            util::format_gitlab_member_access(group, &user.username, access_level).as_str(),
            util::format_gitlab_member_access(group, &user.username, expected_access_level)
                .as_str(),
        )?;
        match action {
            Action::Apply => {
                let endpoint = gitlab::api::groups::members::EditGroupMember::builder()
                    .group(group)
                    .user(group_member.id)
                    .access_level(expected_access_level)
                    .build()
                    .unwrap();
                gitlab::api::ignore(endpoint)
                    .query_async(&self.client)
                    .await
                    .unwrap();
            }
            _ => {}
        }
        Ok(true)
    }

    async fn add_project_member(
        &self,
        action: &Action,
        user: &User,
        project: &str,
        access_level: AccessLevel,
    ) -> Result<bool> {
        let staff_username = &user.username;
        if user.gitlab_id.is_none() {
            warn!(
                "Skip adding {} to GitLab project: no GitLab user found",
                staff_username
            );
            return Ok(false);
        }
        let gitlab_id = user
            .gitlab_id
            .with_context(|| format!("Failed to unwrap GitLab user for {}", staff_username))?;

        debug!(
            "Adding user {} to GitLab project '{}'",
            user.username, project
        );
        util::print_diff(
            &"",
            util::format_gitlab_member_access(project, &user.username, access_level).as_str(),
        )?;
        match action {
            Action::Apply => {
                let endpoint = gitlab::api::projects::members::AddProjectMember::builder()
                    .project(project)
                    .user(gitlab_id)
                    .access_level(access_level)
                    .build()
                    .unwrap();
                gitlab::api::ignore(endpoint)
                    .query_async(&self.client)
                    .await
                    .unwrap();
            }
            _ => {}
        }
        Ok(true)
    }

    async fn remove_project_member<'a>(
        &self,
        action: &Action,
        member: &GitLabMember,
        project: &str,
    ) -> Result<bool> {
        debug!(
            "User {} must not be in project {}",
            &member.username, project
        );
        util::print_diff(
            util::format_gitlab_member_access(
                project,
                &member.username,
                util::access_level_from_u64(member.access_level),
            )
            .as_str(),
            &"",
        )?;
        match action {
            Action::Apply => {
                let endpoint = gitlab::api::projects::members::RemoveProjectMember::builder()
                    .project(project)
                    .user(member.id)
                    .build()
                    .unwrap();
                gitlab::api::ignore(endpoint)
                    .query_async(&self.client)
                    .await
                    .unwrap();
            }
            _ => {}
        }
        Ok(true)
    }

    async fn edit_project_member(
        &self,
        action: &Action,
        user: &User,
        member: &GitLabMember,
        project: &str,
        access_level: AccessLevel,
    ) -> Result<bool> {
        let staff_username = &user.username;
        if user.gitlab_id.is_none() {
553
            debug!(
554
555
556
557
558
559
560
561
562
563
564
565
566
567
                "Skip adding {} to GitLab project: no GitLab user found",
                staff_username
            );
            return Ok(false);
        }
        let gitlab_id = user
            .gitlab_id
            .with_context(|| format!("Failed to unwrap GitLab user for {}", staff_username))?;

        debug!(
            "Adding user {} to GitLab project '{}'",
            user.username, project
        );
        util::print_diff(
568
569
570
571
572
573
            util::format_gitlab_member_access(
                project,
                &user.username,
                util::access_level_from_u64(member.access_level),
            )
            .as_str(),
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
            util::format_gitlab_member_access(project, &user.username, access_level).as_str(),
        )?;
        match action {
            Action::Apply => {
                let endpoint = gitlab::api::projects::members::EditProjectMember::builder()
                    .project(project)
                    .user(gitlab_id)
                    .access_level(access_level)
                    .build()
                    .unwrap();
                gitlab::api::ignore(endpoint)
                    .query_async(&self.client)
                    .await
                    .unwrap();
            }
            _ => {}
        }
        Ok(true)
    }

    fn apply_project_settings(client: &Gitlab, project: &GroupProjects) -> Result<bool> {
        if project.visibility == ProjectVisibilityLevel::Public
            && project.request_access_enabled == false
            && project.container_registry_enabled == false
            && project.snippets_access_level == ProjectFeatureAccessLevel::Disabled
        {
            return Ok(false);
        }
        debug!("edit project settings for {}", project.name);
        let endpoint = gitlab::api::projects::EditProject::builder()
            .project(project.id)
            .visibility(VisibilityLevel::Public)
            .request_access_enabled(false)
            .container_registry_enabled(false)
            .snippets_access_level(FeatureAccessLevel::Disabled)
            .build()
            .unwrap();
        gitlab::api::ignore(endpoint).query(client).unwrap();
        Ok(true)
    }
}

fn get_protected_branch(
    client: &Gitlab,
    project: &GroupProjects,
    branch: &str,
) -> Result<ProtectedBranch> {
    let endpoint = gitlab::api::projects::protected_branches::ProtectedBranch::builder()
        .project(project.id)
        .name(branch)
        .build()
        .unwrap();
    let protected_branch: ProtectedBranch = endpoint.query(client)?;
    Ok(protected_branch)
}

fn protect_branch(
    client: &Gitlab,
    project: &GroupProjects,
    branch: &str,
) -> Result<ProtectedBranch> {
    // protect main branch
    let endpoint = gitlab::api::projects::protected_branches::ProtectBranch::builder()
        .project(project.id)
        .name(branch)
        .push_access_level(
            gitlab::api::projects::protected_branches::ProtectedAccessLevel::Developer,
        )
        .merge_access_level(
            gitlab::api::projects::protected_branches::ProtectedAccessLevel::Developer,
        )
        .build()
        .unwrap();
    let result: ProtectedBranch = endpoint.query(client)?;
    Ok(result)
}

fn unprotect_branch(client: &Gitlab, project: &GroupProjects, branch: &str) -> Result<()> {
    let endpoint = gitlab::api::projects::protected_branches::UnprotectBranch::builder()
        .project(project.id)
        .name(branch)
        .build()
        .unwrap();
    let _: () = gitlab::api::ignore(endpoint).query(client)?;
    Ok(())
}

fn get_protected_tag(client: &Gitlab, project: &GroupProjects, tag: &str) -> Result<ProtectedTag> {
    let endpoint = gitlab::api::projects::protected_tags::ProtectedTag::builder()
        .project(project.id)
        .name(tag)
        .build()
        .unwrap();
    let protected_tag: ProtectedTag = endpoint.query(client)?;
    Ok(protected_tag)
}

fn unprotect_tag(client: &Gitlab, project: &GroupProjects, tag: &str) -> Result<()> {
    let endpoint = gitlab::api::projects::protected_tags::UnprotectTag::builder()
        .project(project.id)
        .name(tag)
        .build()
        .unwrap();
    let _: () = gitlab::api::ignore(endpoint).query(client)?;
    Ok(())
}

fn protect_tag(client: &Gitlab, project: &GroupProjects, tag: &str) -> Result<ProtectedTag> {
    debug!("protecting tag * for project {}", project.name);
    let endpoint = gitlab::api::projects::protected_tags::ProtectTag::builder()
        .project(project.id)
        .name(tag)
        .create_access_level(gitlab::api::common::ProtectedAccessLevel::Developer)
        .build()
        .unwrap();
    let result: ProtectedTag = endpoint.query(client)?;
    Ok(result)
}