Skip to content

Modern Docker Management, Designed for Everyone

11.7 KB
Raw Blame
package role

import (
	"context"
	"errors"

	"github.com/danielgtaylor/huma/v2"
	"github.com/getarcaneapp/arcane/types/v2/base"
	roletypes "github.com/getarcaneapp/arcane/types/v2/role"

	"github.com/getarcaneapp/arcane/backend/v2/internal/common"
	"github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
	"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
	"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
)

type RoleHandler struct {
	roleService *RoleService
}

type ListRolesInput struct {
	Search string `query:"search" doc:"Search by role name or description"`
	Sort   string `query:"sort" doc:"Column to sort by"`
	Order  string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`
	Start  int    `query:"start" default:"0" doc:"Start index for pagination"`
	Limit  int    `query:"limit" default:"20" doc:"Items per page"`
}

type GetRoleInput struct {
	ID string `path:"id" doc:"Role ID"`
}

type CreateRoleInput struct {
	Body roletypes.CreateRole
}

type UpdateRoleInput struct {
	ID   string `path:"id" doc:"Role ID"`
	Body roletypes.UpdateRole
}

type DeleteRoleInput struct {
	ID string `path:"id" doc:"Role ID"`
}

type ListUserRoleAssignmentsInput struct {
	UserID string `path:"userId" doc:"User ID"`
}

type SetUserRoleAssignmentsInput struct {
	UserID string `path:"userId" doc:"User ID"`
	Body   roletypes.SetUserAssignments
}

func (h *RoleHandler) ListRoles(ctx context.Context, input *ListRolesInput) (*handlerutil.Page[roletypes.Role], error) {
	params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
	roles, paginationResp, err := h.roleService.ListRoles(ctx, params)
	if err != nil {
		return nil, huma.Error500InternalServerError("failed to list roles: " + err.Error())
	}
	dtos := make([]roletypes.Role, len(roles))
	for i := range roles {
		dtos[i] = h.toRoleDTO(ctx, &roles[i])
	}
	return &handlerutil.Page[roletypes.Role]{
		Body: base.Paginated[roletypes.Role]{
			Success:    true,
			Data:       dtos,
			Pagination: handlerutil.PaginationResponse(paginationResp),
		},
	}, nil
}

func (h *RoleHandler) GetRole(ctx context.Context, input *GetRoleInput) (*handlerutil.Out[roletypes.Role], error) {
	role, err := h.roleService.GetRole(ctx, input.ID)
	if err != nil {
		if errors.Is(err, common.ErrRoleNotFound) {
			return nil, huma.Error404NotFound("role not found")
		}
		return nil, huma.Error500InternalServerError("failed to get role: " + err.Error())
	}
	return &handlerutil.Out[roletypes.Role]{
		Body: base.ApiResponse[roletypes.Role]{Success: true, Data: h.toRoleDTO(ctx, role)},
	}, nil
}

func (h *RoleHandler) CreateRole(ctx context.Context, input *CreateRoleInput) (*handlerutil.Out[roletypes.Role], error) {
	callerPS, _ := middleware.PermissionsFromContext(ctx)
	if err := h.roleService.ValidatePermissionsAgainstCaller(callerPS, input.Body.Permissions); err != nil {
		switch {
		case errors.Is(err, common.ErrUnknownPermission):
			return nil, huma.Error400BadRequest(err.Error())
		case errors.Is(err, common.ErrRolePermissionEscalation):
			return nil, huma.Error403Forbidden(err.Error())
		}
		return nil, huma.Error500InternalServerError("failed to validate role permissions: " + err.Error())
	}
	role, err := h.roleService.CreateRole(ctx, input.Body.Name, input.Body.Description, input.Body.Permissions)
	if err != nil {
		if errors.Is(err, common.ErrRoleNameTaken) {
			return nil, huma.Error409Conflict("role name already in use")
		}
		if errors.Is(err, common.ErrUnknownPermission) {
			return nil, huma.Error400BadRequest(err.Error())
		}
		return nil, huma.Error500InternalServerError("failed to create role: " + err.Error())
	}
	return &handlerutil.Out[roletypes.Role]{
		Body: base.ApiResponse[roletypes.Role]{Success: true, Data: h.toRoleDTO(ctx, role)},
	}, nil
}

func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*handlerutil.Out[roletypes.Role], error) {
	callerPS, _ := middleware.PermissionsFromContext(ctx)
	if err := h.roleService.ValidatePermissionsAgainstCaller(callerPS, input.Body.Permissions); err != nil {
		switch {
		case errors.Is(err, common.ErrUnknownPermission):
			return nil, huma.Error400BadRequest(err.Error())
		case errors.Is(err, common.ErrRolePermissionEscalation):
			return nil, huma.Error403Forbidden(err.Error())
		}
		return nil, huma.Error500InternalServerError("failed to validate role permissions: " + err.Error())
	}
	role, err := h.roleService.UpdateRole(ctx, input.ID, input.Body.Name, input.Body.Description, input.Body.Permissions)
	if err != nil {
		switch {
		case errors.Is(err, common.ErrRoleNotFound):
			return nil, huma.Error404NotFound("role not found")
		case errors.Is(err, common.ErrRoleBuiltIn):
			return nil, huma.Error403Forbidden("built-in roles cannot be modified")
		case errors.Is(err, common.ErrRoleNameTaken):
			return nil, huma.Error409Conflict("role name already in use")
		case errors.Is(err, common.ErrUnknownPermission):
			return nil, huma.Error400BadRequest(err.Error())
		case errors.Is(err, common.ErrNoGlobalAdminRemains):
			return nil, huma.Error409Conflict(err.Error())
		}
		return nil, huma.Error500InternalServerError("failed to update role: " + err.Error())
	}
	return &handlerutil.Out[roletypes.Role]{
		Body: base.ApiResponse[roletypes.Role]{Success: true, Data: h.toRoleDTO(ctx, role)},
	}, nil
}

func (h *RoleHandler) DeleteRole(ctx context.Context, input *DeleteRoleInput) (*handlerutil.Out[base.MessageResponse], error) {
	if err := h.roleService.DeleteRole(ctx, input.ID); err != nil {
		switch {
		case errors.Is(err, common.ErrRoleNotFound):
			return nil, huma.Error404NotFound("role not found")
		case errors.Is(err, common.ErrRoleBuiltIn):
			return nil, huma.Error403Forbidden("built-in roles cannot be deleted")
		case errors.Is(err, common.ErrNoGlobalAdminRemains), errors.Is(err, common.ErrRoleUsedByFederatedCredential):
			return nil, huma.Error409Conflict(err.Error())
		}
		return nil, huma.Error500InternalServerError("failed to delete role: " + err.Error())
	}
	return handlerutil.MessageOutput("role deleted", ""), nil
}

func (h *RoleHandler) GetPermissionsManifest(_ context.Context, _ *struct{}) (*handlerutil.Out[roletypes.PermissionsManifest], error) {
	return &handlerutil.Out[roletypes.PermissionsManifest]{
		Body: base.ApiResponse[roletypes.PermissionsManifest]{Success: true, Data: buildPermissionsManifestInternal()},
	}, nil
}

func (h *RoleHandler) ListUserRoleAssignments(ctx context.Context, input *ListUserRoleAssignmentsInput) (*handlerutil.Out[[]roletypes.RoleAssignment], error) {
	rows, err := h.roleService.ListUserAssignments(ctx, input.UserID)
	if err != nil {
		return nil, huma.Error500InternalServerError("failed to list assignments: " + err.Error())
	}
	dtos := make([]roletypes.RoleAssignment, len(rows))
	for i := range rows {
		dtos[i] = toAssignmentDTOInternal(&rows[i])
	}
	return &handlerutil.Out[[]roletypes.RoleAssignment]{
		Body: base.ApiResponse[[]roletypes.RoleAssignment]{Success: true, Data: dtos},
	}, nil
}

func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUserRoleAssignmentsInput) (*handlerutil.Out[[]roletypes.RoleAssignment], error) {
	desired := make([]UserRoleAssignment, len(input.Body.Assignments))
	for i, a := range input.Body.Assignments {
		desired[i] = UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID}
	}
	if err := h.roleService.ReplaceUserAssignments(ctx, input.UserID, RoleAssignmentSourceManual, desired); err != nil {
		switch {
		case errors.Is(err, common.ErrUserNotFound):
			return nil, huma.Error404NotFound(err.Error())
		case errors.Is(err, common.ErrInvalidRoleAssignment):
			return nil, huma.Error400BadRequest(err.Error())
		case errors.Is(err, common.ErrNoGlobalAdminRemains):
			return nil, huma.Error409Conflict(err.Error())
		}
		return nil, huma.Error500InternalServerError("failed to set assignments: " + err.Error())
	}
	rows, err := h.roleService.ListUserAssignments(ctx, input.UserID)
	if err != nil {
		return nil, huma.Error500InternalServerError("failed to read back assignments: " + err.Error())
	}
	dtos := make([]roletypes.RoleAssignment, len(rows))
	for i := range rows {
		dtos[i] = toAssignmentDTOInternal(&rows[i])
	}
	return &handlerutil.Out[[]roletypes.RoleAssignment]{
		Body: base.ApiResponse[[]roletypes.RoleAssignment]{Success: true, Data: dtos},
	}, nil
}

func (h *RoleHandler) toRoleDTO(ctx context.Context, r *Role) roletypes.Role {
	out := roletypes.Role{
		ID:          r.ID,
		Name:        r.Name,
		Description: r.Description,
		Permissions: []string(r.Permissions),
		BuiltIn:     r.BuiltIn,
		CreatedAt:   r.CreatedAt,
		UpdatedAt:   r.UpdatedAt,
	}
	if count, err := h.roleService.CountUsersAssignedToRole(ctx, r.ID); err == nil {
		out.AssignedUserCount = count
	}
	return out
}

func toAssignmentDTOInternal(r *UserRoleAssignment) roletypes.RoleAssignment {
	return roletypes.RoleAssignment{
		ID:            r.ID,
		UserID:        r.UserID,
		RoleID:        r.RoleID,
		EnvironmentID: r.EnvironmentID,
		Source:        r.Source,
		CreatedAt:     r.CreatedAt,
	}
}

// buildPermissionsManifestInternal maps the authz-owned permission catalog into
// the public API manifest shape used by the frontend role editor.
func buildPermissionsManifestInternal() roletypes.PermissionsManifest {
	catalog := authz.PermissionCatalog()
	resources := make([]roletypes.PermissionResource, len(catalog))
	for i, resource := range catalog {
		actions := make([]roletypes.PermissionAction, len(resource.Actions))
		for j, action := range resource.Actions {
			actions[j] = roletypes.PermissionAction{
				Key:         action.Key,
				Permission:  action.Permission,
				Label:       action.Label,
				Description: action.Description,
				Requires:    requiredPermissionsForPickerInternal(action.Permission),
			}
		}
		resources[i] = roletypes.PermissionResource{
			Key:     resource.Key,
			Label:   resource.Label,
			Scope:   resource.Scope,
			Actions: actions,
		}
	}
	return roletypes.PermissionsManifest{
		Resources:      resources,
		AccessSurfaces: buildAccessSurfaceManifestInternal(),
		Presets: []roletypes.PermissionPreset{
			{
				Key:         "editor",
				Label:       "All permissions (non-admin)",
				Description: "Matches the built-in Editor permission set.",
				Permissions: authz.BuiltInEditorPermissions(),
			},
			{
				Key:         "global-admin",
				Label:       "Global Admin",
				Description: "Select every permission in the manifest.",
				Permissions: authz.AllPermissions(),
			},
		},
	}
}

func buildAccessSurfaceManifestInternal() []roletypes.AccessSurface {
	surfaces := authz.AccessSurfaces()
	out := make([]roletypes.AccessSurface, len(surfaces))
	for i, surface := range surfaces {
		out[i] = roletypes.AccessSurface{
			ID:            surface.ID,
			Kind:          surface.Kind,
			URL:           surface.URL,
			Label:         surface.Label,
			AccessMode:    surface.AccessMode,
			MatchMode:     surface.MatchMode,
			ScopeMode:     surface.ScopeMode,
			Permissions:   append([]string(nil), surface.Permissions...),
			Children:      append([]string(nil), surface.Children...),
			FallbackOrder: surface.FallbackOrder,
		}
	}
	return out
}

func requiredPermissionsForPickerInternal(permission string) []string {
	switch permission {
	case authz.PermSettingsWrite,
		authz.PermApiKeysList,
		authz.PermApiKeysRead,
		authz.PermApiKeysCreate,
		authz.PermApiKeysUpdate,
		authz.PermApiKeysDelete,
		authz.PermFederatedList,
		authz.PermFederatedRead,
		authz.PermFederatedCreate,
		authz.PermFederatedUpdate,
		authz.PermFederatedDelete,
		authz.PermUsersList,
		authz.PermUsersRead,
		authz.PermUsersCreate,
		authz.PermUsersUpdate,
		authz.PermUsersDelete,
		authz.PermRolesList,
		authz.PermRolesRead,
		authz.PermWebhooksList,
		authz.PermWebhooksCreate,
		authz.PermWebhooksUpdate,
		authz.PermWebhooksDelete,
		authz.PermNotificationsManage,
		authz.PermDiagnosticsRead:
		return []string{authz.PermSettingsRead}
	default:
		return nil
	}
}