From 889a41c6a834debafc16cb76abade0fdc8c2bd5b Mon Sep 17 00:00:00 2001
From: Wim <wim@42.be>
Date: Wed, 28 Sep 2022 01:25:40 +0200
Subject: [PATCH] Do not allow organisation owners add themselves as
 collaborator (#20043)

We're already checking for repo owners, but we also need to check for
organisation owners that try to add themselves as collaborator

Closes #17966
---
 options/locale/locale_en-US.ini |  1 +
 routers/web/repo/setting.go     | 13 +++++++++++++
 2 files changed, 14 insertions(+)

diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini
index b62395e546..991ebf344f 100644
--- a/options/locale/locale_en-US.ini
+++ b/options/locale/locale_en-US.ini
@@ -1898,6 +1898,7 @@ settings.confirm_delete = Delete Repository
 settings.add_collaborator = Add Collaborator
 settings.add_collaborator_success = The collaborator has been added.
 settings.add_collaborator_inactive_user = Can not add an inactive user as a collaborator.
+settings.add_collaborator_owner = Can not add an owner as a collaborator.
 settings.add_collaborator_duplicate = The collaborator is already added to this repository.
 settings.delete_collaborator = Remove
 settings.collaborator_deletion = Remove Collaborator
diff --git a/routers/web/repo/setting.go b/routers/web/repo/setting.go
index 267940c8d2..e7abec0d3e 100644
--- a/routers/web/repo/setting.go
+++ b/routers/web/repo/setting.go
@@ -917,6 +917,19 @@ func CollaborationPost(ctx *context.Context) {
 		return
 	}
 
+	// find the owner team of the organization the repo belongs too and
+	// check if the user we're trying to add is an owner.
+	if ctx.Repo.Repository.Owner.IsOrganization() {
+		if isOwner, err := organization.IsOrganizationOwner(ctx, ctx.Repo.Repository.Owner.ID, u.ID); err != nil {
+			ctx.ServerError("IsOrganizationOwner", err)
+			return
+		} else if isOwner {
+			ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_owner"))
+			ctx.Redirect(setting.AppSubURL + ctx.Req.URL.EscapedPath())
+			return
+		}
+	}
+
 	if err = repo_module.AddCollaborator(ctx.Repo.Repository, u); err != nil {
 		ctx.ServerError("AddCollaborator", err)
 		return