Skip to content

Commit

Permalink
Merge branch 'master' into installer
Browse files Browse the repository at this point in the history
  • Loading branch information
imnasnainaec authored Oct 7, 2024
2 parents 2fa8685 + d5916c5 commit d10e3b1
Show file tree
Hide file tree
Showing 17 changed files with 1,497 additions and 3,792 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public/scripts/config.js
.eslintcache
Session.vim
scripts/*.js
!scripts/createBackendLicenses.js
!scripts/printVersion.js
!scripts/setRelease.js

Expand Down Expand Up @@ -58,6 +59,7 @@ mongo_database

# User Guide
docs/user_guide/site
backend_licenses.json

# Python
.tox
Expand Down
193 changes: 166 additions & 27 deletions Backend.Tests/Controllers/UserRoleControllerTests.cs

Large diffs are not rendered by default.

114 changes: 114 additions & 0 deletions Backend/Controllers/UserRoleController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BackendFramework.Helper;
using BackendFramework.Interfaces;
Expand Down Expand Up @@ -147,6 +148,13 @@ public async Task<IActionResult> CreateUserRole(string projectId, [FromBody, Bin
return NotFound(projectId);
}

// Prevent a second project owner
if (userRole.Role == Role.Owner
&& (await _userRoleRepo.GetAllUserRoles(projectId)).Any((role) => role.Role == Role.Owner))
{
return Forbid("This project already has an owner");
}

await _userRoleRepo.Create(userRole);
return Ok(userRole.Id);
}
Expand Down Expand Up @@ -183,6 +191,12 @@ public async Task<IActionResult> DeleteUserRole(string projectId, string userId)
return NotFound(userRoleId);
}

// Prevent deleting the project owner.
if (userRole.Role == Role.Owner)
{
return Forbid("Cannot use this function to remove the project owner's role");
}

// Prevent deleting role of another user who has more permissions than the actor.
if (!await _permissionService.ContainsProjectRole(HttpContext, userRole.Role, projectId))
{
Expand Down Expand Up @@ -212,6 +226,11 @@ public async Task<IActionResult> UpdateUserRole(
return Forbid();
}

// Prevent making a new project owner.
if (projectRole.Role == Role.Owner)
{
return Forbid("Cannot use this function to give a user the project owner role");
}
// Prevent upgrading another user to have more permissions than the actor.
if (!await _permissionService.ContainsProjectRole(HttpContext, projectRole.Role, projectId))
{
Expand Down Expand Up @@ -248,6 +267,11 @@ public async Task<IActionResult> UpdateUserRole(
return NotFound(userRoleId);
}

// Prevent downgrading the project owner.
if (userRole.Role == Role.Owner)
{
return Forbid("Cannot use this function to change the project owner's role");
}
// Prevent downgrading another user who has more permissions than the actor.
if (!await _permissionService.ContainsProjectRole(HttpContext, userRole.Role, projectId))
{
Expand All @@ -263,5 +287,95 @@ public async Task<IActionResult> UpdateUserRole(
_ => StatusCode(StatusCodes.Status304NotModified, userRoleId)
};
}

/// <summary>
/// Change project owner from user with first specified id to user with second specified id.
/// Can only be used by the project owner or a site admin.
/// </summary>
/// <returns> Id of updated UserRole </returns>
[HttpGet("changeowner/{oldUserId}/{newUserId}", Name = "ChangeOwner")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))]
public async Task<IActionResult> ChangeOwner(string projectId, string oldUserId, string newUserId)
{
// Ensure the actor has sufficient permission to change project owner
if (!await _permissionService.ContainsProjectRole(HttpContext, Role.Owner, projectId))
{
return Forbid();
}

// Ensure that the old and new owners' ids are different
if (oldUserId.Equals(newUserId, System.StringComparison.OrdinalIgnoreCase))
{
return BadRequest($"the user ids for the old and new owners should be different");
}

// Ensure the project exists
var proj = await _projRepo.GetProject(projectId);
if (proj is null)
{
return NotFound(projectId);
}

// Fetch the users
var oldOwner = await _userRepo.GetUser(oldUserId, false);
if (oldOwner is null)
{
return NotFound(oldUserId);
}
var newOwner = await _userRepo.GetUser(newUserId, false);
if (newOwner is null)
{
return NotFound(newUserId);
}

// Ensure that the user from whom ownership is being moved is the owner
if (!oldOwner.ProjectRoles.TryGetValue(projectId, out var oldRoleId))
{
return BadRequest($"{oldUserId} is not a project user");
}
var oldUserRole = await _userRoleRepo.GetUserRole(projectId, oldRoleId);
if (oldUserRole is null || oldUserRole.Role != Role.Owner)
{
return BadRequest($"{oldUserId} is not the project owner");
}

// Add or update the role of the new owner
ResultOfUpdate newResult;
if (!newOwner.ProjectRoles.TryGetValue(projectId, out var newRoleId))
{
// Generate the userRole
var newUsersRole = new UserRole { ProjectId = projectId, Role = Role.Owner };
newUsersRole = await _userRoleRepo.Create(newUsersRole);
newRoleId = newUsersRole.Id;

// Update the user
newOwner.ProjectRoles.Add(projectId, newRoleId);
newResult = await _userRepo.Update(newOwner.Id, newOwner);
}
else
{
// Update the user role
var newUsersRole = await _userRoleRepo.GetUserRole(projectId, newRoleId);
if (newUsersRole is null)
{
return NotFound(newRoleId);
}
newUsersRole.Role = Role.Owner;
newResult = await _userRoleRepo.Update(newRoleId, newUsersRole);
}
if (newResult != ResultOfUpdate.Updated)
{
return StatusCode(StatusCodes.Status304NotModified, newRoleId);
};

// Change the old owner to a project admin
oldUserRole.Role = Role.Administrator;
var oldResult = await _userRoleRepo.Update(oldRoleId, oldUserRole);
return oldResult switch
{
ResultOfUpdate.Updated => Ok(oldUserRole),
_ => StatusCode(StatusCodes.Status304NotModified, oldUserRole)
};
}
}
}
16 changes: 7 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,10 @@ A rapid word collection tool. See the [User Guide](https://sillsdev.github.io/Th
- If using [homebrew](https://formulae.brew.sh/formula/ffmpeg): `brew install ffmpeg`
- If manually installing from the FFmpeg website, install both `ffmpeg` and `ffprobe`

9. [dotnet-format](https://github.com/dotnet/format): `dotnet tool update --global dotnet-format --version 5.1.250801`
10. [dotnet-reportgenerator](https://github.com/danielpalme/ReportGenerator)
`dotnet tool update --global dotnet-reportgenerator-globaltool --version 5.0.4`
11. [dotnet-project-licenses](https://github.com/tomchavakis/nuget-license)
`dotnet tool update --global dotnet-project-licenses`
12. Tools for generating the self installer (Linux only):
9. [dotnet-reportgenerator](https://github.com/danielpalme/ReportGenerator)
`dotnet tool update --global dotnet-reportgenerator-globaltool --version 5.0.4`
10. [nuget-license](https://github.com/sensslen/nuget-license) `dotnet tool update --global nuget-project-license`
11. Tools for generating the self installer (Linux only):

- [makeself](https://makeself.io/) - a tool to make self-extracting archives in Unix
- [pandoc](https://pandoc.org/installing.html#linux) - a tool to convert Markdown documents to PDF.
Expand Down Expand Up @@ -589,8 +587,8 @@ When _Rancher Desktop_ is first run, you will be prompted to select a few initia
1. Verify that _Enable Kubernetes_ is checked.
2. Select the Kubernetes version marked as _stable, latest_.
3. Select your container runtime, either _containerd_ or _dockerd (moby)_:
- _containerd_ matches what is used on the NUC and uses the `k3s` Kubernetes engine. It requires that you run the
`build.py` script with the `--nerdctl` option.
- _containerd_ matches what is used on the NUC and uses the `k3s` Kubernetes engine. It requires that you set the
`CONTAINER_CLI` environment variable to `nerdctl` before running the `build.py` script.
- _dockerd_ uses the `k3d` (`k3s` in docker).
4. Select _Automatic_ or _Manual_ path setup.
5. Click _Accept_.
Expand Down Expand Up @@ -680,7 +678,7 @@ Notes:
export CONTAINER_CLI="nerdctl"
```

If you are using _Docker Desktop_ or _Rancher Desktop_ with the `dockerd` container runtime, clear this variable or
If you are using _Rancher Desktop_ with the `dockerd` container runtime or _Docker Desktop_, clear this variable or
set its value to `docker`.

- Run with the `--help` option to see all available options.
Expand Down
File renamed without changes.
File renamed without changes.
49 changes: 14 additions & 35 deletions deploy/scripts/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
"""
Build the containerd images for The Combine.
This script currently supports using 'docker' or 'nerdctl' to build the container
images. 'nerdctl' is recommended when using Rancher Desktop for the development
environment and 'docker' is recommended when using Docker Desktop with the 'containerd'
container engine.
This script currently supports using 'docker' or 'nerdctl' to build the container images.
The default is 'docker' unless the CONTAINER_CLI env var is set to 'nerdctl'.
'docker' is for Rancher Desktop with the 'dockerd' container runtime or Docker Desktop.
'nerdctl' is for Rancher Desktop with the 'containerd' container runtime.
When 'docker' is used for the build, the BuildKit backend will be enabled.
"""
Expand Down Expand Up @@ -190,11 +190,6 @@ def parse_args() -> Namespace:
"""Parse user command line arguments."""
parser = ArgumentParser(
description="Build containerd container images for project.",
epilog="""
NOTE:
The '--nerdctl' option is DEPRECATED and will be removed in future versions.
Set the environment variable CONTAINER_CLI to 'nerdctl' or 'docker' instead.
""",
formatter_class=RawFormatter,
)
parser.add_argument(
Expand All @@ -214,11 +209,6 @@ def parse_args() -> Namespace:
parser.add_argument(
"--repo", "-r", help="Push images to the specified Docker image repository."
)
parser.add_argument(
"--nerdctl",
action="store_true",
help="Use 'nerdctl' instead of 'docker' to build images.",
)
parser.add_argument(
"--namespace",
"-n",
Expand Down Expand Up @@ -264,7 +254,7 @@ def main() -> None:
logging.basicConfig(format="%(levelname)s:%(message)s", level=log_level)

# Setup required build engine - docker or nerdctl
container_cli = os.getenv("CONTAINER_CLI", "nerdctl" if args.nerdctl else "docker")
container_cli = os.getenv("CONTAINER_CLI", "docker")
match container_cli:
case "nerdctl":
build_cmd = [container_cli, "-n", args.namespace, "build"]
Expand All @@ -277,18 +267,18 @@ def main() -> None:
sys.exit(1)

# Setup build options
build_opts: List[str] = []
if args.quiet:
build_opts = ["--quiet"]
build_cmd += ["--quiet"]
else:
build_opts = ["--progress", "plain"]
build_cmd += ["--progress", "plain"]
if args.no_cache:
build_opts += ["--no-cache"]
build_cmd += ["--no-cache"]
if args.pull:
build_opts += ["--pull"]
build_cmd += ["--pull"]
if args.build_args is not None:
for build_arg in args.build_args:
build_opts += ["--build-arg", build_arg]
build_cmd += ["--build-arg", build_arg]
logging.debug(f"build_cmd: {build_cmd}")

if args.components is not None:
to_do = args.components
Expand All @@ -301,21 +291,10 @@ def main() -> None:
spec = build_specs[component]
spec.pre_build()
image_name = get_image_name(args.repo, spec.name, args.tag)
job_opts = ["-t", image_name, "-f", "Dockerfile", "."]
job_set[component] = JobQueue(component)
job_set[component].add_job(
Job(
build_cmd
+ build_opts
+ [
"-t",
image_name,
"-f",
"Dockerfile",
".",
],
spec.dir,
)
)
logging.debug(f"Adding job {build_cmd + job_opts}")
job_set[component].add_job(Job(build_cmd + job_opts, spec.dir))
if args.repo is not None:
if args.quiet:
push_args = ["--quiet"]
Expand Down
4 changes: 2 additions & 2 deletions deploy/scripts/install-combine.sh
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ install-kubernetes () {
cd ${DEPLOY_DIR}/ansible

if [ -d "${DEPLOY_DIR}/airgap-images" ] ; then
ansible-playbook playbook_desktop_setup.yaml -K -e k8s_user=`whoami` -e install_airgap_images=true
ansible-playbook playbook_desktop_setup.yml -K -e k8s_user=`whoami` -e install_airgap_images=true
else
ansible-playbook playbook_desktop_setup.yaml -K -e k8s_user=`whoami`
ansible-playbook playbook_desktop_setup.yml -K -e k8s_user=`whoami`
fi
}

Expand Down
10 changes: 5 additions & 5 deletions deploy/scripts/package_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,16 +72,16 @@ def package_k3s(dest_dir: Path) -> None:


def package_images(image_list: List[str], tar_file: Path) -> None:
container_cli = [os.getenv("CONTAINER_CLI", "docker")]
if container_cli[0] == "nerdctl":
container_cli.extend(["--namespace", "k8s.io"])
container_cli_cmd = [os.getenv("CONTAINER_CLI", "docker")]
if container_cli_cmd[0] == "nerdctl":
container_cli_cmd.extend(["--namespace", "k8s.io"])
# Pull each image
for image in image_list:
pull_cmd = container_cli + ["pull", image]
pull_cmd = container_cli_cmd + ["pull", image]
logging.debug(f"Running {pull_cmd}")
run_cmd(pull_cmd)
# Save pulled images into a .tar archive
run_cmd(container_cli + ["save"] + image_list + ["-o", str(tar_file)])
run_cmd(container_cli_cmd + ["save"] + image_list + ["-o", str(tar_file)])
# Compress the tarball
run_cmd(["zstd", "--rm", "--force", "--quiet", str(tar_file)])

Expand Down
1 change: 1 addition & 0 deletions deploy/scripts/setup_target.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python
"""Setup ssh connection between host and target."""

import argparse
import os
Expand Down
Loading

0 comments on commit d10e3b1

Please sign in to comment.