From 37066729346ecbb33f8b8448c3cf4ea1db457402 Mon Sep 17 00:00:00 2001 From: Neel Date: Tue, 17 Nov 2026 13:27:27 -0500 Subject: [PATCH 1/3] feat: allowing engines to add dependencies --- .../auth/ProjectAuthorizationResource.java | 1624 +++++++++-------- .../ProjectAuthorizationResourceTest.java | 62 +- 2 files changed, 859 insertions(+), 827 deletions(-) diff --git a/src/prerna/semoss/web/services/local/auth/ProjectAuthorizationResource.java b/src/prerna/semoss/web/services/local/auth/ProjectAuthorizationResource.java index 00dbbc55..a2fe4418 100644 --- a/src/prerna/semoss/web/services/local/auth/ProjectAuthorizationResource.java +++ b/src/prerna/semoss/web/services/local/auth/ProjectAuthorizationResource.java @@ -1,799 +1,825 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.semoss.web.services.local.auth; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.ToNumberPolicy; - -import jakarta.annotation.security.PermitAll; -import jakarta.servlet.ServletContext; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.ws.rs.GET; -import jakarta.ws.rs.POST; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.QueryParam; -import jakarta.ws.rs.core.Context; -import jakarta.ws.rs.core.MultivaluedMap; -import jakarta.ws.rs.core.Response; -import prerna.auth.AccessPermissionEnum; -import prerna.auth.User; -import prerna.auth.access.ModelUsageLimit; -import prerna.auth.utils.AbstractSecurityUtils; -import prerna.auth.utils.SecurityAdminUtils; -import prerna.auth.utils.SecurityModelUsageLimitUtils; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.graph.utility.MsGraphUtility; -import prerna.io.connector.ms.MicrosoftGraphUserLookup; -import prerna.om.Insight; -import prerna.reactor.project.MyProjectsReactor; -import prerna.sablecc2.om.GenRowStruct; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.semoss.web.services.local.ResourceUtility; -import prerna.web.services.util.WebUtility; - -@Path("/auth/project") -@PermitAll -public class ProjectAuthorizationResource { - - private static final String ADMINS_ONLY = "This functionality is limited to only admins"; - /** - * The field for a model usage limit, as JSON, empty for no limit defined. A - * propagation without it keeps the limit of a person whose access to a model - * changes. - */ - private static final String USAGE_LIMIT = "usageLimit"; - /** Reads JSON rows, keeping whole numbers whole */ - private static final Gson ROW_GSON = new GsonBuilder().setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) - .create(); - - @Context - protected ServletContext context; - - /** - * Get the projects the user has access to - * - * @param request - * @return - */ - @GET - @Produces("application/json") - @Path("getProjects") - public Response getProjectsGET(@Context HttpServletRequest request, - @QueryParam("projectId") List projectFilter, @QueryParam("filterWord") String searchTerm, - @QueryParam("limit") Integer limit, @QueryParam("offset") Integer offset, - @QueryParam("onlyFavorites") Boolean favoritesOnly, @QueryParam("metaKeys") List metaKeys, - // @QueryParam("metaFilters") Map metaFilters, - @QueryParam("noMeta") Boolean noMeta, @QueryParam("userT") Boolean includeUserTracking) { - String term = WebUtility.inputSQLSanitizer(searchTerm); - List projects = WebUtility.inputSanitizer(projectFilter); - List keys = WebUtility.inputSanitizer(metaKeys); - return ResourceUtility.respond(request, "list the projects they can access", user -> { - MyProjectsReactor reactor = new MyProjectsReactor(); - reactor.In(); - Insight temp = new Insight(); - temp.setUser(user); - reactor.setInsight(temp); - if (term != null) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(term, PixelDataType.CONST_STRING)); - reactor.getNounStore().addNoun(ReactorKeysEnum.FILTER_WORD.getKey(), struct); - } - if (limit != null) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(limit, PixelDataType.CONST_INT)); - reactor.getNounStore().addNoun(ReactorKeysEnum.LIMIT.getKey(), struct); - } - if (offset != null) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(offset, PixelDataType.CONST_INT)); - reactor.getNounStore().addNoun(ReactorKeysEnum.OFFSET.getKey(), struct); - } - if (favoritesOnly != null) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(favoritesOnly, PixelDataType.BOOLEAN)); - reactor.getNounStore().addNoun(ReactorKeysEnum.ONLY_FAVORITES.getKey(), struct); - } - if (projects != null && !projects.isEmpty()) { - GenRowStruct struct = new GenRowStruct(); - for (String project : projects) { - struct.add(new NounMetadata(project, PixelDataType.CONST_STRING)); - } - reactor.getNounStore().addNoun(ReactorKeysEnum.PROJECT.getKey(), struct); - } - if (keys != null && !keys.isEmpty()) { - GenRowStruct struct = new GenRowStruct(); - for (String metaK : keys) { - struct.add(new NounMetadata(metaK, PixelDataType.CONST_STRING)); - } - reactor.getNounStore().addNoun(ReactorKeysEnum.META_KEYS.getKey(), struct); - } - // if(metaFilters != null) { - // GenRowStruct struct = new GenRowStruct(); - // struct.add(new NounMetadata(metaFilters, PixelDataType.MAP)); - // reactor.getNounStore().addNoun(ReactorKeysEnum.META_FILTERS.getKey(), - // struct); - // } - if (noMeta != null) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(noMeta, PixelDataType.BOOLEAN)); - reactor.getNounStore().addNoun(ReactorKeysEnum.NO_META.getKey(), struct); - } - if (includeUserTracking != null) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(includeUserTracking, PixelDataType.BOOLEAN)); - reactor.getNounStore().addNoun(ReactorKeysEnum.INCLUDE_USERTRACKING_KEY.getKey(), struct); - } - - return reactor.execute().getValue(); - }); - } - - @POST - @Produces("application/json") - @Path("getProjects") - public Response getProjectsPOST(@Context HttpServletRequest request) { - return ResourceUtility.respond(request, "list the projects they can access", user -> { - MyProjectsReactor reactor = new MyProjectsReactor(); - reactor.In(); - Insight temp = new Insight(); - temp.setUser(user); - reactor.setInsight(temp); - - Map parameterMap = request.getParameterMap(); - - if (parameterMap.containsKey("filterWord") && parameterMap.get("filterWord") != null - && parameterMap.get("filterWord").length > 0) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(parameterMap.get("filterWord")[0], PixelDataType.CONST_STRING)); - reactor.getNounStore().addNoun(ReactorKeysEnum.FILTER_WORD.getKey(), struct); - } - if (parameterMap.containsKey("limit") && parameterMap.get("limit") != null - && parameterMap.get("limit").length > 0) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(parameterMap.get("limit")[0], PixelDataType.CONST_INT)); - reactor.getNounStore().addNoun(ReactorKeysEnum.LIMIT.getKey(), struct); - } - if (parameterMap.containsKey("offset") && parameterMap.get("offset") != null - && parameterMap.get("offset").length > 0) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(parameterMap.get("offset")[0], PixelDataType.CONST_INT)); - reactor.getNounStore().addNoun(ReactorKeysEnum.OFFSET.getKey(), struct); - } - if (parameterMap.containsKey("projectId") && parameterMap.get("projectId") != null - && parameterMap.get("projectId").length > 0) { - GenRowStruct struct = new GenRowStruct(); - String[] projectFilter = parameterMap.get("projectId"); - for (String project : projectFilter) { - struct.add(new NounMetadata(project, PixelDataType.CONST_STRING)); - } - reactor.getNounStore().addNoun(ReactorKeysEnum.PROJECT.getKey(), struct); - } - if (parameterMap.containsKey("metaKeys") && parameterMap.get("metaKeys") != null - && parameterMap.get("metaKeys").length > 0) { - GenRowStruct struct = new GenRowStruct(); - String[] metaKeys = parameterMap.get("metaKeys"); - for (String metaK : metaKeys) { - struct.add(new NounMetadata(metaK, PixelDataType.CONST_STRING)); - } - reactor.getNounStore().addNoun(ReactorKeysEnum.META_KEYS.getKey(), struct); - } - if (parameterMap.containsKey("metaFilters") && parameterMap.get("metaFilters") != null - && parameterMap.get("metaFilters").length > 0) { - Map metaFilters = new Gson() - .fromJson(WebUtility.jsonSanitizer(parameterMap.get("metaFilters")[0]), Map.class); - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(metaFilters, PixelDataType.MAP)); - reactor.getNounStore().addNoun(ReactorKeysEnum.META_FILTERS.getKey(), struct); - } - if (parameterMap.containsKey("noMeta") && parameterMap.get("noMeta") != null - && parameterMap.get("noMeta").length > 0) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(parameterMap.get("noMeta")[0], PixelDataType.BOOLEAN)); - reactor.getNounStore().addNoun(ReactorKeysEnum.NO_META.getKey(), struct); - } - if (parameterMap.containsKey("userT") && parameterMap.get("userT") != null - && parameterMap.get("userT").length > 0) { - GenRowStruct struct = new GenRowStruct(); - struct.add(new NounMetadata(parameterMap.get("userT")[0], PixelDataType.BOOLEAN)); - reactor.getNounStore().addNoun(ReactorKeysEnum.INCLUDE_USERTRACKING_KEY.getKey(), struct); - } - - return reactor.execute().getValue(); - }); - } - - /** - * Get the user app permission level - * - * @param request - * @param form - * @return - */ - @GET - @Produces("application/json") - @Path("getUserProjectPermission") - public Response getUserProjectPermission(@Context HttpServletRequest request, - @QueryParam("projectId") String projectId, @QueryParam("searchTerm") String searchTerm) { - String project = WebUtility.inputSanitizer(projectId); - String action = "read their permission on project " + project; - return ResourceUtility.respond(request, action, user -> { - String permission = SecurityProjectUtils.getActualUserProjectPermission(user, project); - if (permission == null) { - // are you discoverable? - if (SecurityProjectUtils.projectIsDiscoverable(project)) { - permission = "DISCOVERABLE"; - } else { - throw new IllegalAccessException("User does not have access to this project"); - } - } - - Map ret = new HashMap<>(); - ret.put("permission", permission); - return ret; - }); - } - - /** - * Get the project users and their permissions - * - * @param request - * @param form - * @return - */ - @GET - @Produces("application/json") - @Path("getProjectUsers") - public Response getProjectUsers(@Context HttpServletRequest request, @QueryParam("projectId") String projectId, - @QueryParam("userId") String userId, @QueryParam("searchTerm") String searchTerm, - @QueryParam("permission") String permission, @QueryParam("limit") long limit, - @QueryParam("offset") long offset) { - String project = WebUtility.inputSanitizer(projectId); - String member = WebUtility.inputSQLSanitizer(userId); - String term = WebUtility.inputSQLSanitizer(searchTerm); - String level = WebUtility.inputSanitizer(permission); - String searchParam = term != null ? term : member; - return ResourceUtility.respond(request, "list the users of project " + project, user -> { - List> members = SecurityProjectUtils.getProjectUsers(user, project, searchParam, level, - limit, offset); - long totalMembers = SecurityProjectUtils.getProjectUsersCount(user, project, searchParam, level); - Map ret = new HashMap<>(); - ret.put("totalMembers", totalMembers); - ret.put("members", members); - return ret; - }); - } - - /** - * Add a user to an app - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("addProjectUserPermission") - public Response addProjectUserPermission(@Context HttpServletRequest request, MultivaluedMap form) { - String newUserId = WebUtility.inputSQLSanitizer(form.getFirst("id")); - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - String permission = WebUtility.inputSanitizer(form.getFirst("permission")); - String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); - return ResourceUtility.respond(request, "add user " + newUserId + " to project " + projectId, user -> { - if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - String level = AccessPermissionEnum.require(permission); - SecurityProjectUtils.addProjectUser(user, newUserId, projectId, level, endDate); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * Propagate project dependent permissions. The person's usage limit on the - * models the project depends on is sent as {@code usageLimit} (JSON, empty for - * no limit defined). Without it, a person added to a model gets no limit and a - * person whose access to a model changes keeps their limit. Only a model's - * owners set a limit that differs from the current one. - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("propagateProjectDependencyPermission") - public Response propagateProjectDependencyPermission(@Context HttpServletRequest request, - MultivaluedMap form) { - String newUserId = WebUtility.inputSQLSanitizer(form.getFirst("id")); - String newUserType = WebUtility.inputSanitizer(form.getFirst("type")); - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - String requestedPermission = WebUtility.inputSanitizer(form.getFirst("permission")); - String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); - - boolean usageLimitSent = form.containsKey(USAGE_LIMIT); - String usageLimit = form.getFirst(USAGE_LIMIT); - return ResourceUtility.respond(request, "give user " + newUserId + " access to project " + projectId, user -> { - // Determine if admin right are required to add users and, if so, if requester - // has those rights. - if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - requireProjectEditor(user, projectId); - String level = AccessPermissionEnum.require(requestedPermission); - - if (usageLimitSent) { - return SecurityProjectUtils.propagateProjectPermission(user, projectId, newUserId, newUserType, level, - endDate, SecurityModelUsageLimitUtils.readJson(usageLimit)); - } - return SecurityProjectUtils.propagateProjectPermission(user, projectId, newUserId, newUserType, level, - endDate); - }); - } - - /** - * Propagate project dependent permissions, in bulk. Each row of - * {@code userpermissions} can carry the person's usage limit on the models the - * project depends on as {@code usageLimit}. Without it, a person whose access - * to a model changes keeps their limit. - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("propagateProjectDependencyPermissions") - public Response propagateProjectDependencyPermissions(@Context HttpServletRequest request, - MultivaluedMap form) { - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); - return ResourceUtility.respond(request, "give users access to project " + projectId, user -> { - List> requests = ROW_GSON.fromJson(form.getFirst("userpermissions"), List.class); - - // Determine if admin right are required to add users and, if so, if requester - // has those rights. - if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - requireProjectEditor(user, projectId); - // every row is checked before the first one is propagated - AccessPermissionEnum.requireEach(requests); - - Map userRet = new HashMap<>(); - for (Map userRequest : requests) { - String newUserId = textOf(userRequest.get("userid")); - String newUserType = textOf(userRequest.get("type")); - String requestedPermission = textOf(userRequest.get("permission")); - Map responses; - if (userRequest.containsKey(USAGE_LIMIT)) { - responses = SecurityProjectUtils.propagateProjectPermission(user, projectId, newUserId, newUserType, - requestedPermission, endDate, readUsageLimit(userRequest.get(USAGE_LIMIT))); - } else { - responses = SecurityProjectUtils.propagateProjectPermission(user, projectId, newUserId, newUserType, - requestedPermission, endDate); - } - userRet.put(newUserId, responses); - } - - Map ret = new HashMap<>(); - ret.put("success", true); - ret.put("users", userRet); - return ret; - }); - } - - /** - * Edit user permission for a project - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("editProjectUserPermission") - public Response editProjectUserPermission(@Context HttpServletRequest request, - MultivaluedMap form) { - String existingUserId = WebUtility.inputSQLSanitizer(form.getFirst("id")); - String existingUserType = WebUtility.inputSQLSanitizer(form.getFirst("type")); - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - String newPermission = WebUtility.inputSanitizer(form.getFirst("permission")); - String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); - return ResourceUtility.respond(request, "edit user " + existingUserId + " on project " + projectId, user -> { - if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - SecurityProjectUtils.editProjectUserPermission(user, existingUserId, existingUserType, projectId, - AccessPermissionEnum.require(newPermission), endDate); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * Edit user permission for project, in bulk - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("editProjectUserPermissions") - public Response editProjectUserPermissions(@Context HttpServletRequest request, - MultivaluedMap form) { - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); - return ResourceUtility.respond(request, "edit user permissions on project " + projectId, user -> { - if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - List> requests = new Gson().fromJson(form.getFirst("userpermissions"), List.class); - AccessPermissionEnum.requireEach(requests); - SecurityProjectUtils.editProjectUserPermissions(user, projectId, requests, endDate); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * Remove user permission for an app - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("removeProjectUserPermission") - public Response removeProjectUserPermission(@Context HttpServletRequest request, - MultivaluedMap form) { - String existingUserId = WebUtility.inputSQLSanitizer(form.getFirst("id")); - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - String action = "remove user " + existingUserId + " from project " + projectId; - return ResourceUtility.respond(request, action, user -> { - if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - SecurityProjectUtils.removeProjectUser(user, existingUserId, projectId); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * Set whether a project can be cloned as a template by users who can view it. - * - * @param request current request - * @param form projectId and template boolean - * @return operation status - */ - @POST - @Produces("application/json") - @Path("setProjectTemplate") - public Response setProjectTemplate(@Context HttpServletRequest request, MultivaluedMap form) { - String projectIdInput = form.getFirst("projectId"); - String templateInput = form.getFirst("template"); - String projectId = WebUtility.inputSanitizer(projectIdInput); - boolean isTemplate = Boolean.parseBoolean(templateInput); - return ResourceUtility.respond(request, "set whether project " + projectId + " is a template", user -> { - if (projectIdInput == null || projectIdInput.trim().isEmpty() || templateInput == null - || !("true".equalsIgnoreCase(templateInput) || "false".equalsIgnoreCase(templateInput))) { - throw new IllegalArgumentException("projectId and a true or false template value are required"); - } - SecurityProjectUtils.setProjectTemplate(user, projectId, isTemplate); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * Get the app as being global (read only) for the entire semoss instance - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("setProjectGlobal") - public Response setProjectGlobal(@Context HttpServletRequest request, MultivaluedMap form) { - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - boolean isPublic = Boolean.parseBoolean(form.getFirst("public")); - String action = "make project " + projectId + (isPublic ? " public" : " private"); - return ResourceUtility.respond(request, action, user -> { - if (AbstractSecurityUtils.adminOnlyProjectSetPublic(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - SecurityProjectUtils.setProjectGlobal(user, projectId, isPublic); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * Set the project as being discoverable for the entire semoss instance - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("setProjectDiscoverable") - public Response setProjectDiscoverable(@Context HttpServletRequest request, MultivaluedMap form) { - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - boolean isDiscoverable = Boolean.parseBoolean(form.getFirst("discoverable")); - String action = "make project " + projectId + (isDiscoverable ? " discoverable" : " not discoverable"); - return ResourceUtility.respond(request, action, user -> { - if (AbstractSecurityUtils.adminOnlyProjectSetDiscoverable(projectId) - && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - SecurityProjectUtils.setProjectDiscoverable(user, projectId, isDiscoverable); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * Set the app visibility for the user to be seen - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("setProjectVisibility") - public Response setProjectVisibility(@Context HttpServletRequest request, MultivaluedMap form) { - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - boolean visible = Boolean.parseBoolean(form.getFirst("visibility")); - String action = (visible ? "show" : "hide") + " project " + projectId; - return ResourceUtility.respond(request, action, user -> { - SecurityProjectUtils.setProjectVisibility(user, projectId, visible); - return true; - }); - } - - /** - * Set the app as favorited by the user - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("setProjectFavorite") - public Response setProjectFavorite(@Context HttpServletRequest request, MultivaluedMap form) { - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - boolean isFavorite = Boolean.parseBoolean(form.getFirst("isFavorite")); - String action = (isFavorite ? "favorite" : "unfavorite") + " project " + projectId; - return ResourceUtility.respond(request, action, user -> { - SecurityProjectUtils.setProjectFavorite(user, projectId, isFavorite); - return true; - }); - } - - /** - * Get users with no access to a given app - * - * @param request - * @param form - * @return - */ - @GET - @Produces("application/json") - @Path("getProjectUsersNoCredentials") - public Response getProjectUsersNoCredentials(@Context HttpServletRequest request, - @QueryParam("projectId") String projectId, @QueryParam("searchTerm") String searchTerm, - @QueryParam("limit") long limit, @QueryParam("offset") long offset, - @QueryParam(MicrosoftGraphUserLookup.LOOKUP_PARAM) String msGraphLookup) { - String project = WebUtility.inputSanitizer(projectId); - String term = WebUtility.inputSQLSanitizer(searchTerm); - return ResourceUtility.respond(request, "find people to add to project " + project, user -> { - // when the directory is not used - // then we will look at our security db - if (!MicrosoftGraphUserLookup.useDirectory(msGraphLookup)) { - return SecurityProjectUtils.getProjectUsersNoCredentials(user, project, term, limit, offset); - } - return MsGraphUtility.getProjectUsers(request, user, project, term, limit, offset, false); - }); - } - - /** - * approval of user access requests - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("approveProjectUserAccessRequest") - public Response approveProjectUserAccessRequest(@Context HttpServletRequest request, - MultivaluedMap form) { - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); - return ResourceUtility.respond(request, "approve access requests for project " + projectId, user -> { - if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - // adding user permissions and updating user access requests in bulk - List> requests = new Gson().fromJson(form.getFirst("requests"), List.class); - AccessPermissionEnum.requireEach(requests); - SecurityProjectUtils.approveProjectUserAccessRequests(user, projectId, requests, endDate); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * deny of user access requests - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("denyProjectUserAccessRequest") - public Response denyProjectUserAccessRequest(@Context HttpServletRequest request, - MultivaluedMap form) { - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - return ResourceUtility.respond(request, "deny access requests for project " + projectId, user -> { - if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - // updating user access requests in bulk - List requestids = new Gson().fromJson(form.getFirst("requestids"), List.class); - requestids = WebUtility.inputSQLSanitizer(requestids); - SecurityProjectUtils.denyProjectUserAccessRequests(user, projectId, requestids); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * Add user permissions in bulk to a project - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("addProjectUserPermissions") - public Response addProjectUserPermissions(@Context HttpServletRequest request, - MultivaluedMap form) { - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); - return ResourceUtility.respond(request, "add users to project " + projectId, user -> { - if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - // adding user permissions in bulk - List> permission = AccessPermissionEnum - .requireEach(new Gson().fromJson(form.getFirst("userpermissions"), List.class)); - // users picked from the Microsoft directory may not be in the security db yet - if (MicrosoftGraphUserLookup.isEnabled()) { - MicrosoftGraphUserLookup.addMissingUsers(user, permission); - } - - SecurityProjectUtils.addProjectUserPermissions(user, projectId, permission, endDate); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * Remove user permissions for an project, in bulk - * - * @param request - * @param form - * @return - */ - @POST - @Produces("application/json") - @Path("removeProjectUserPermissions") - public Response removeProjectUserPermissions(@Context HttpServletRequest request, - MultivaluedMap form) { - String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); - return ResourceUtility.respond(request, "remove users from project " + projectId, user -> { - List ids = new Gson().fromJson(form.getFirst("ids"), List.class); - if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { - throw new IllegalAccessException(ADMINS_ONLY); - } - SecurityProjectUtils.removeProjectUsers(user, ids, projectId); - Map ret = new HashMap<>(); - ret.put("success", true); - return ret; - }); - } - - /** - * Reads a row's {@code usageLimit}, sent as a JSON object or as JSON text. - * - * @param value the value sent, which may be null - * @return the limit, or null for no limit defined - * @throws IllegalArgumentException when the value is not a limit - */ - private static ModelUsageLimit readUsageLimit(Object value) { - if (value == null || value instanceof String) { - return SecurityModelUsageLimitUtils.readJson((String) value); - } - return SecurityModelUsageLimitUtils.readJson(ROW_GSON.toJson(value)); - } - - /** - * Reads a value from one of the posted user permission requests as text. - * - * @param value a row's value, which may be null - * @return the value as text, or null - */ - private static String textOf(Object value) { - return value == null ? null : value.toString(); - } - - /** - * Refuses a user who cannot edit the project. Propagating a project's - * permissions gives people access to everything it depends on, so it is - * limited to the project's editors. - * - * @param user the signed in user - * @param projectId the project - * @throws IllegalAccessException when the user cannot edit the project - */ - private static void requireProjectEditor(User user, String projectId) throws IllegalAccessException { - if (!SecurityProjectUtils.userCanEditProject(user, projectId)) { - throw new IllegalAccessException( - "Project " + projectId + " does not exist or user does not have access to edit it"); - } - } - -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.semoss.web.services.local.auth; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.ToNumberPolicy; + +import jakarta.annotation.security.PermitAll; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import prerna.auth.AccessPermissionEnum; +import prerna.auth.User; +import prerna.auth.access.ModelUsageLimit; +import prerna.auth.utils.AbstractSecurityUtils; +import prerna.auth.utils.CatalogTypes; +import prerna.auth.utils.SecurityEngineUtils; +import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityModelUsageLimitUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityProjectUtils; +import prerna.graph.utility.MsGraphUtility; +import prerna.io.connector.ms.MicrosoftGraphUserLookup; +import prerna.om.Insight; +import prerna.reactor.project.MyProjectsReactor; +import prerna.sablecc2.om.GenRowStruct; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.semoss.web.services.local.ResourceUtility; +import prerna.web.services.util.WebUtility; + +@Path("/auth/project") +@PermitAll +public class ProjectAuthorizationResource { + + private static final String ADMINS_ONLY = "This functionality is limited to only admins"; + /** + * The field for a model usage limit, as JSON, empty for no limit defined. A + * propagation without it keeps the limit of a person whose access to a model + * changes. + */ + private static final String USAGE_LIMIT = "usageLimit"; + /** Reads JSON rows, keeping whole numbers whole */ + private static final Gson ROW_GSON = new GsonBuilder().setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) + .create(); + + @Context + protected ServletContext context; + + /** + * Get the projects the user has access to + * + * @param request + * @return + */ + @GET + @Produces("application/json") + @Path("getProjects") + public Response getProjectsGET(@Context HttpServletRequest request, + @QueryParam("projectId") List projectFilter, @QueryParam("filterWord") String searchTerm, + @QueryParam("limit") Integer limit, @QueryParam("offset") Integer offset, + @QueryParam("onlyFavorites") Boolean favoritesOnly, @QueryParam("metaKeys") List metaKeys, + // @QueryParam("metaFilters") Map metaFilters, + @QueryParam("noMeta") Boolean noMeta, @QueryParam("userT") Boolean includeUserTracking) { + String term = WebUtility.inputSQLSanitizer(searchTerm); + List projects = WebUtility.inputSanitizer(projectFilter); + List keys = WebUtility.inputSanitizer(metaKeys); + return ResourceUtility.respond(request, "list the projects they can access", user -> { + MyProjectsReactor reactor = new MyProjectsReactor(); + reactor.In(); + Insight temp = new Insight(); + temp.setUser(user); + reactor.setInsight(temp); + if (term != null) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(term, PixelDataType.CONST_STRING)); + reactor.getNounStore().addNoun(ReactorKeysEnum.FILTER_WORD.getKey(), struct); + } + if (limit != null) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(limit, PixelDataType.CONST_INT)); + reactor.getNounStore().addNoun(ReactorKeysEnum.LIMIT.getKey(), struct); + } + if (offset != null) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(offset, PixelDataType.CONST_INT)); + reactor.getNounStore().addNoun(ReactorKeysEnum.OFFSET.getKey(), struct); + } + if (favoritesOnly != null) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(favoritesOnly, PixelDataType.BOOLEAN)); + reactor.getNounStore().addNoun(ReactorKeysEnum.ONLY_FAVORITES.getKey(), struct); + } + if (projects != null && !projects.isEmpty()) { + GenRowStruct struct = new GenRowStruct(); + for (String project : projects) { + struct.add(new NounMetadata(project, PixelDataType.CONST_STRING)); + } + reactor.getNounStore().addNoun(ReactorKeysEnum.PROJECT.getKey(), struct); + } + if (keys != null && !keys.isEmpty()) { + GenRowStruct struct = new GenRowStruct(); + for (String metaK : keys) { + struct.add(new NounMetadata(metaK, PixelDataType.CONST_STRING)); + } + reactor.getNounStore().addNoun(ReactorKeysEnum.META_KEYS.getKey(), struct); + } + // if(metaFilters != null) { + // GenRowStruct struct = new GenRowStruct(); + // struct.add(new NounMetadata(metaFilters, PixelDataType.MAP)); + // reactor.getNounStore().addNoun(ReactorKeysEnum.META_FILTERS.getKey(), + // struct); + // } + if (noMeta != null) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(noMeta, PixelDataType.BOOLEAN)); + reactor.getNounStore().addNoun(ReactorKeysEnum.NO_META.getKey(), struct); + } + if (includeUserTracking != null) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(includeUserTracking, PixelDataType.BOOLEAN)); + reactor.getNounStore().addNoun(ReactorKeysEnum.INCLUDE_USERTRACKING_KEY.getKey(), struct); + } + + return reactor.execute().getValue(); + }); + } + + @POST + @Produces("application/json") + @Path("getProjects") + public Response getProjectsPOST(@Context HttpServletRequest request) { + return ResourceUtility.respond(request, "list the projects they can access", user -> { + MyProjectsReactor reactor = new MyProjectsReactor(); + reactor.In(); + Insight temp = new Insight(); + temp.setUser(user); + reactor.setInsight(temp); + + Map parameterMap = request.getParameterMap(); + + if (parameterMap.containsKey("filterWord") && parameterMap.get("filterWord") != null + && parameterMap.get("filterWord").length > 0) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(parameterMap.get("filterWord")[0], PixelDataType.CONST_STRING)); + reactor.getNounStore().addNoun(ReactorKeysEnum.FILTER_WORD.getKey(), struct); + } + if (parameterMap.containsKey("limit") && parameterMap.get("limit") != null + && parameterMap.get("limit").length > 0) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(parameterMap.get("limit")[0], PixelDataType.CONST_INT)); + reactor.getNounStore().addNoun(ReactorKeysEnum.LIMIT.getKey(), struct); + } + if (parameterMap.containsKey("offset") && parameterMap.get("offset") != null + && parameterMap.get("offset").length > 0) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(parameterMap.get("offset")[0], PixelDataType.CONST_INT)); + reactor.getNounStore().addNoun(ReactorKeysEnum.OFFSET.getKey(), struct); + } + if (parameterMap.containsKey("projectId") && parameterMap.get("projectId") != null + && parameterMap.get("projectId").length > 0) { + GenRowStruct struct = new GenRowStruct(); + String[] projectFilter = parameterMap.get("projectId"); + for (String project : projectFilter) { + struct.add(new NounMetadata(project, PixelDataType.CONST_STRING)); + } + reactor.getNounStore().addNoun(ReactorKeysEnum.PROJECT.getKey(), struct); + } + if (parameterMap.containsKey("metaKeys") && parameterMap.get("metaKeys") != null + && parameterMap.get("metaKeys").length > 0) { + GenRowStruct struct = new GenRowStruct(); + String[] metaKeys = parameterMap.get("metaKeys"); + for (String metaK : metaKeys) { + struct.add(new NounMetadata(metaK, PixelDataType.CONST_STRING)); + } + reactor.getNounStore().addNoun(ReactorKeysEnum.META_KEYS.getKey(), struct); + } + if (parameterMap.containsKey("metaFilters") && parameterMap.get("metaFilters") != null + && parameterMap.get("metaFilters").length > 0) { + Map metaFilters = new Gson() + .fromJson(WebUtility.jsonSanitizer(parameterMap.get("metaFilters")[0]), Map.class); + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(metaFilters, PixelDataType.MAP)); + reactor.getNounStore().addNoun(ReactorKeysEnum.META_FILTERS.getKey(), struct); + } + if (parameterMap.containsKey("noMeta") && parameterMap.get("noMeta") != null + && parameterMap.get("noMeta").length > 0) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(parameterMap.get("noMeta")[0], PixelDataType.BOOLEAN)); + reactor.getNounStore().addNoun(ReactorKeysEnum.NO_META.getKey(), struct); + } + if (parameterMap.containsKey("userT") && parameterMap.get("userT") != null + && parameterMap.get("userT").length > 0) { + GenRowStruct struct = new GenRowStruct(); + struct.add(new NounMetadata(parameterMap.get("userT")[0], PixelDataType.BOOLEAN)); + reactor.getNounStore().addNoun(ReactorKeysEnum.INCLUDE_USERTRACKING_KEY.getKey(), struct); + } + + return reactor.execute().getValue(); + }); + } + + /** + * Get the user app permission level + * + * @param request + * @param form + * @return + */ + @GET + @Produces("application/json") + @Path("getUserProjectPermission") + public Response getUserProjectPermission(@Context HttpServletRequest request, + @QueryParam("projectId") String projectId, @QueryParam("searchTerm") String searchTerm) { + String project = WebUtility.inputSanitizer(projectId); + String action = "read their permission on project " + project; + return ResourceUtility.respond(request, action, user -> { + String permission = SecurityProjectUtils.getActualUserProjectPermission(user, project); + if (permission == null) { + // are you discoverable? + if (SecurityProjectUtils.projectIsDiscoverable(project)) { + permission = "DISCOVERABLE"; + } else { + throw new IllegalAccessException("User does not have access to this project"); + } + } + + Map ret = new HashMap<>(); + ret.put("permission", permission); + return ret; + }); + } + + /** + * Get the project users and their permissions + * + * @param request + * @param form + * @return + */ + @GET + @Produces("application/json") + @Path("getProjectUsers") + public Response getProjectUsers(@Context HttpServletRequest request, @QueryParam("projectId") String projectId, + @QueryParam("userId") String userId, @QueryParam("searchTerm") String searchTerm, + @QueryParam("permission") String permission, @QueryParam("limit") long limit, + @QueryParam("offset") long offset) { + String project = WebUtility.inputSanitizer(projectId); + String member = WebUtility.inputSQLSanitizer(userId); + String term = WebUtility.inputSQLSanitizer(searchTerm); + String level = WebUtility.inputSanitizer(permission); + String searchParam = term != null ? term : member; + return ResourceUtility.respond(request, "list the users of project " + project, user -> { + List> members = SecurityProjectUtils.getProjectUsers(user, project, searchParam, level, + limit, offset); + long totalMembers = SecurityProjectUtils.getProjectUsersCount(user, project, searchParam, level); + Map ret = new HashMap<>(); + ret.put("totalMembers", totalMembers); + ret.put("members", members); + return ret; + }); + } + + /** + * Add a user to an app + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("addProjectUserPermission") + public Response addProjectUserPermission(@Context HttpServletRequest request, MultivaluedMap form) { + String newUserId = WebUtility.inputSQLSanitizer(form.getFirst("id")); + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + String permission = WebUtility.inputSanitizer(form.getFirst("permission")); + String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); + return ResourceUtility.respond(request, "add user " + newUserId + " to project " + projectId, user -> { + if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + String level = AccessPermissionEnum.require(permission); + SecurityProjectUtils.addProjectUser(user, newUserId, projectId, level, endDate); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * Gives a person access to the engines and projects an engine or project + * depends on, or asks their owners for it. The engine or project is + * {@code catalogId}, with its engine type or project type as the optional + * {@code catalogType}. The person's usage limit on the + * models it depends on is sent as {@code usageLimit} (JSON, empty for + * no limit defined). Without it, a person added to a model gets no limit and a + * person whose access to a model changes keeps their limit. Only a model's + * owners set a limit that differs from the current one. + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("propagateCatalogDependencyPermission") + public Response propagateCatalogDependencyPermission(@Context HttpServletRequest request, + MultivaluedMap form) { + String newUserId = WebUtility.inputSQLSanitizer(form.getFirst("id")); + String newUserType = WebUtility.inputSanitizer(form.getFirst("type")); + String catalogId = WebUtility.inputSanitizer(form.getFirst("catalogId")); + String catalogType = WebUtility.inputSanitizer(form.getFirst("catalogType")); + String requestedPermission = WebUtility.inputSanitizer(form.getFirst("permission")); + String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); + + boolean usageLimitSent = form.containsKey(USAGE_LIMIT); + String usageLimit = form.getFirst(USAGE_LIMIT); + return ResourceUtility.respond(request, + "give user " + newUserId + " access to the dependencies of " + catalogId, user -> { + requireCatalogDependencyEditor(user, catalogId, catalogType); + String level = AccessPermissionEnum.require(requestedPermission); + + if (usageLimitSent) { + return SecurityCatalogDependencyUtils.propagatePermission(user, catalogId, newUserId, newUserType, level, + endDate, SecurityModelUsageLimitUtils.readJson(usageLimit)); + } + return SecurityCatalogDependencyUtils.propagatePermission(user, catalogId, newUserId, newUserType, level, + endDate); + }); + } + + /** + * Gives people access to the engines and projects an engine or project depends + * on, in bulk, as {@link #propagateCatalogDependencyPermission} does for one. + * Each row of {@code userpermissions} can carry the person's usage limit on the + * models it depends on as {@code usageLimit}. Without it, a person whose access + * to a model changes keeps their limit. + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("propagateCatalogDependencyPermissions") + public Response propagateCatalogDependencyPermissions(@Context HttpServletRequest request, + MultivaluedMap form) { + String catalogId = WebUtility.inputSanitizer(form.getFirst("catalogId")); + String catalogType = WebUtility.inputSanitizer(form.getFirst("catalogType")); + String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); + return ResourceUtility.respond(request, "give users access to the dependencies of " + catalogId, user -> { + List> requests = ROW_GSON.fromJson(form.getFirst("userpermissions"), List.class); + + requireCatalogDependencyEditor(user, catalogId, catalogType); + // every row is checked before the first one is propagated + AccessPermissionEnum.requireEach(requests); + + Map userRet = new HashMap<>(); + for (Map userRequest : requests) { + String newUserId = textOf(userRequest.get("userid")); + String newUserType = textOf(userRequest.get("type")); + String requestedPermission = textOf(userRequest.get("permission")); + Map responses; + if (userRequest.containsKey(USAGE_LIMIT)) { + responses = SecurityCatalogDependencyUtils.propagatePermission(user, catalogId, newUserId, newUserType, + requestedPermission, endDate, readUsageLimit(userRequest.get(USAGE_LIMIT))); + } else { + responses = SecurityCatalogDependencyUtils.propagatePermission(user, catalogId, newUserId, newUserType, + requestedPermission, endDate); + } + userRet.put(newUserId, responses); + } + + Map ret = new HashMap<>(); + ret.put("success", true); + ret.put("users", userRet); + return ret; + }); + } + + /** + * Edit user permission for a project + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("editProjectUserPermission") + public Response editProjectUserPermission(@Context HttpServletRequest request, + MultivaluedMap form) { + String existingUserId = WebUtility.inputSQLSanitizer(form.getFirst("id")); + String existingUserType = WebUtility.inputSQLSanitizer(form.getFirst("type")); + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + String newPermission = WebUtility.inputSanitizer(form.getFirst("permission")); + String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); + return ResourceUtility.respond(request, "edit user " + existingUserId + " on project " + projectId, user -> { + if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + SecurityProjectUtils.editProjectUserPermission(user, existingUserId, existingUserType, projectId, + AccessPermissionEnum.require(newPermission), endDate); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * Edit user permission for project, in bulk + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("editProjectUserPermissions") + public Response editProjectUserPermissions(@Context HttpServletRequest request, + MultivaluedMap form) { + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); + return ResourceUtility.respond(request, "edit user permissions on project " + projectId, user -> { + if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + List> requests = new Gson().fromJson(form.getFirst("userpermissions"), List.class); + AccessPermissionEnum.requireEach(requests); + SecurityProjectUtils.editProjectUserPermissions(user, projectId, requests, endDate); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * Remove user permission for an app + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("removeProjectUserPermission") + public Response removeProjectUserPermission(@Context HttpServletRequest request, + MultivaluedMap form) { + String existingUserId = WebUtility.inputSQLSanitizer(form.getFirst("id")); + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + String action = "remove user " + existingUserId + " from project " + projectId; + return ResourceUtility.respond(request, action, user -> { + if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + SecurityProjectUtils.removeProjectUser(user, existingUserId, projectId); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * Set whether a project can be cloned as a template by users who can view it. + * + * @param request current request + * @param form projectId and template boolean + * @return operation status + */ + @POST + @Produces("application/json") + @Path("setProjectTemplate") + public Response setProjectTemplate(@Context HttpServletRequest request, MultivaluedMap form) { + String projectIdInput = form.getFirst("projectId"); + String templateInput = form.getFirst("template"); + String projectId = WebUtility.inputSanitizer(projectIdInput); + boolean isTemplate = Boolean.parseBoolean(templateInput); + return ResourceUtility.respond(request, "set whether project " + projectId + " is a template", user -> { + if (projectIdInput == null || projectIdInput.trim().isEmpty() || templateInput == null + || !("true".equalsIgnoreCase(templateInput) || "false".equalsIgnoreCase(templateInput))) { + throw new IllegalArgumentException("projectId and a true or false template value are required"); + } + SecurityProjectUtils.setProjectTemplate(user, projectId, isTemplate); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * Get the app as being global (read only) for the entire semoss instance + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("setProjectGlobal") + public Response setProjectGlobal(@Context HttpServletRequest request, MultivaluedMap form) { + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + boolean isPublic = Boolean.parseBoolean(form.getFirst("public")); + String action = "make project " + projectId + (isPublic ? " public" : " private"); + return ResourceUtility.respond(request, action, user -> { + if (AbstractSecurityUtils.adminOnlyProjectSetPublic(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + SecurityProjectUtils.setProjectGlobal(user, projectId, isPublic); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * Set the project as being discoverable for the entire semoss instance + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("setProjectDiscoverable") + public Response setProjectDiscoverable(@Context HttpServletRequest request, MultivaluedMap form) { + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + boolean isDiscoverable = Boolean.parseBoolean(form.getFirst("discoverable")); + String action = "make project " + projectId + (isDiscoverable ? " discoverable" : " not discoverable"); + return ResourceUtility.respond(request, action, user -> { + if (AbstractSecurityUtils.adminOnlyProjectSetDiscoverable(projectId) + && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + SecurityProjectUtils.setProjectDiscoverable(user, projectId, isDiscoverable); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * Set the app visibility for the user to be seen + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("setProjectVisibility") + public Response setProjectVisibility(@Context HttpServletRequest request, MultivaluedMap form) { + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + boolean visible = Boolean.parseBoolean(form.getFirst("visibility")); + String action = (visible ? "show" : "hide") + " project " + projectId; + return ResourceUtility.respond(request, action, user -> { + SecurityProjectUtils.setProjectVisibility(user, projectId, visible); + return true; + }); + } + + /** + * Set the app as favorited by the user + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("setProjectFavorite") + public Response setProjectFavorite(@Context HttpServletRequest request, MultivaluedMap form) { + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + boolean isFavorite = Boolean.parseBoolean(form.getFirst("isFavorite")); + String action = (isFavorite ? "favorite" : "unfavorite") + " project " + projectId; + return ResourceUtility.respond(request, action, user -> { + SecurityProjectUtils.setProjectFavorite(user, projectId, isFavorite); + return true; + }); + } + + /** + * Get users with no access to a given app + * + * @param request + * @param form + * @return + */ + @GET + @Produces("application/json") + @Path("getProjectUsersNoCredentials") + public Response getProjectUsersNoCredentials(@Context HttpServletRequest request, + @QueryParam("projectId") String projectId, @QueryParam("searchTerm") String searchTerm, + @QueryParam("limit") long limit, @QueryParam("offset") long offset, + @QueryParam(MicrosoftGraphUserLookup.LOOKUP_PARAM) String msGraphLookup) { + String project = WebUtility.inputSanitizer(projectId); + String term = WebUtility.inputSQLSanitizer(searchTerm); + return ResourceUtility.respond(request, "find people to add to project " + project, user -> { + // when the directory is not used + // then we will look at our security db + if (!MicrosoftGraphUserLookup.useDirectory(msGraphLookup)) { + return SecurityProjectUtils.getProjectUsersNoCredentials(user, project, term, limit, offset); + } + return MsGraphUtility.getProjectUsers(request, user, project, term, limit, offset, false); + }); + } + + /** + * approval of user access requests + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("approveProjectUserAccessRequest") + public Response approveProjectUserAccessRequest(@Context HttpServletRequest request, + MultivaluedMap form) { + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); + return ResourceUtility.respond(request, "approve access requests for project " + projectId, user -> { + if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + // adding user permissions and updating user access requests in bulk + List> requests = new Gson().fromJson(form.getFirst("requests"), List.class); + AccessPermissionEnum.requireEach(requests); + SecurityProjectUtils.approveProjectUserAccessRequests(user, projectId, requests, endDate); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * deny of user access requests + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("denyProjectUserAccessRequest") + public Response denyProjectUserAccessRequest(@Context HttpServletRequest request, + MultivaluedMap form) { + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + return ResourceUtility.respond(request, "deny access requests for project " + projectId, user -> { + if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + // updating user access requests in bulk + List requestids = new Gson().fromJson(form.getFirst("requestids"), List.class); + requestids = WebUtility.inputSQLSanitizer(requestids); + SecurityProjectUtils.denyProjectUserAccessRequests(user, projectId, requestids); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * Add user permissions in bulk to a project + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("addProjectUserPermissions") + public Response addProjectUserPermissions(@Context HttpServletRequest request, + MultivaluedMap form) { + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + String endDate = WebUtility.inputSanitizer(form.getFirst("endDate")); + return ResourceUtility.respond(request, "add users to project " + projectId, user -> { + if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + // adding user permissions in bulk + List> permission = AccessPermissionEnum + .requireEach(new Gson().fromJson(form.getFirst("userpermissions"), List.class)); + // users picked from the Microsoft directory may not be in the security db yet + if (MicrosoftGraphUserLookup.isEnabled()) { + MicrosoftGraphUserLookup.addMissingUsers(user, permission); + } + + SecurityProjectUtils.addProjectUserPermissions(user, projectId, permission, endDate); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * Remove user permissions for an project, in bulk + * + * @param request + * @param form + * @return + */ + @POST + @Produces("application/json") + @Path("removeProjectUserPermissions") + public Response removeProjectUserPermissions(@Context HttpServletRequest request, + MultivaluedMap form) { + String projectId = WebUtility.inputSanitizer(form.getFirst("projectId")); + return ResourceUtility.respond(request, "remove users from project " + projectId, user -> { + List ids = new Gson().fromJson(form.getFirst("ids"), List.class); + if (AbstractSecurityUtils.adminOnlyProjectAddAccess(projectId) && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + SecurityProjectUtils.removeProjectUsers(user, ids, projectId); + Map ret = new HashMap<>(); + ret.put("success", true); + return ret; + }); + } + + /** + * Reads a row's {@code usageLimit}, sent as a JSON object or as JSON text. + * + * @param value the value sent, which may be null + * @return the limit, or null for no limit defined + * @throws IllegalArgumentException when the value is not a limit + */ + private static ModelUsageLimit readUsageLimit(Object value) { + if (value == null || value instanceof String) { + return SecurityModelUsageLimitUtils.readJson((String) value); + } + return SecurityModelUsageLimitUtils.readJson(ROW_GSON.toJson(value)); + } + + /** + * Reads a value from one of the posted user permission requests as text. + * + * @param value a row's value, which may be null + * @return the value as text, or null + */ + private static String textOf(Object value) { + return value == null ? null : value.toString(); + } + + /** + * Refuses a user who cannot edit the project. Propagating a project's + * permissions gives people access to everything it depends on, so it is + * limited to the project's editors. + * + * @param user the signed in user + * @param projectId the project + * @throws IllegalAccessException when the user cannot edit the project + */ + /** + * Checks that a user can give people access to what an engine or project + * depends on: they can edit it, and they are an admin when only admins can add + * people to it. + * + * @param catalogId the engine id or project id + * @param catalogType its engine type or project type, or null to read it + * @throws IllegalAccessException when they cannot + */ + private static void requireCatalogDependencyEditor(User user, String catalogId, String catalogType) + throws IllegalAccessException { + String type = SecurityCatalogDependencyUtils.resolveCatalogType(catalogId, catalogType); + boolean isProject = CatalogTypes.isProjectType(type); + boolean adminOnly = isProject ? AbstractSecurityUtils.adminOnlyProjectAddAccess(catalogId) + : AbstractSecurityUtils.adminOnlyEngineAddAccess(catalogId); + if (adminOnly && !SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalAccessException(ADMINS_ONLY); + } + if (isProject) { + requireProjectEditor(user, catalogId); + } else if (!SecurityEngineUtils.userCanEditEngine(user, catalogId)) { + throw new IllegalAccessException( + "Engine " + catalogId + " does not exist or user does not have access to edit it"); + } + } + + private static void requireProjectEditor(User user, String projectId) throws IllegalAccessException { + if (!SecurityProjectUtils.userCanEditProject(user, projectId)) { + throw new IllegalAccessException( + "Project " + projectId + " does not exist or user does not have access to edit it"); + } + } + +} diff --git a/test/prerna/semoss/web/services/local/auth/ProjectAuthorizationResourceTest.java b/test/prerna/semoss/web/services/local/auth/ProjectAuthorizationResourceTest.java index b276b45e..dc36f5de 100644 --- a/test/prerna/semoss/web/services/local/auth/ProjectAuthorizationResourceTest.java +++ b/test/prerna/semoss/web/services/local/auth/ProjectAuthorizationResourceTest.java @@ -68,6 +68,7 @@ import prerna.auth.utils.AbstractSecurityUtils; import prerna.auth.utils.SecurityAdminUtils; import prerna.auth.utils.SecurityModelUsageLimitUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.graph.utility.MsGraphUtility; import prerna.io.connector.ms.MicrosoftGraphUserLookup; @@ -289,10 +290,10 @@ void keepsEveryAccessChangeToAdminsWhenTheProjectSaysSo() throws Exception { form("projectId", "p1", "userpermissions", "[]")), resource.removeProjectUserPermission(requestFor(user), form("id", "bob", "projectId", "p1")), resource.removeProjectUserPermissions(requestFor(user), form("projectId", "p1", "ids", "[]")), - resource.propagateProjectDependencyPermission(requestFor(user), - form("id", "bob", "type", "NATIVE", "projectId", "p1", "permission", "EDIT")), - resource.propagateProjectDependencyPermissions(requestFor(user), - form("projectId", "p1", "userpermissions", "[]")), + resource.propagateCatalogDependencyPermission(requestFor(user), + form("id", "bob", "type", "NATIVE", "catalogId", "p1", "permission", "EDIT")), + resource.propagateCatalogDependencyPermissions(requestFor(user), + form("catalogId", "p1", "userpermissions", "[]")), resource.approveProjectUserAccessRequest(requestFor(user), form("projectId", "p1", "requests", "[]")), resource.denyProjectUserAccessRequest(requestFor(user), @@ -409,16 +410,16 @@ void refusesToPropagateTheAccessOfAProjectTheUserCannotEdit() throws Exception { try (Statics statics = new Statics()) { statics.project.when(() -> SecurityProjectUtils.userCanEditProject(user, "p1")).thenReturn(false); - Response one = resource.propagateProjectDependencyPermission(requestFor(user), form("id", "bob", "type", - "NATIVE", "projectId", "p1", "permission", "OWNER")); - Response many = resource.propagateProjectDependencyPermissions(requestFor(user), form("projectId", "p1", + Response one = resource.propagateCatalogDependencyPermission(requestFor(user), form("id", "bob", "type", + "NATIVE", "catalogId", "p1", "permission", "OWNER")); + Response many = resource.propagateCatalogDependencyPermissions(requestFor(user), form("catalogId", "p1", "userpermissions", "[{\"userid\":\"bob\",\"type\":\"NATIVE\",\"permission\":\"OWNER\"}]")); for (Response response : List.of(one, many)) { assertEquals(403, response.getStatus()); assertEquals("Project p1 does not exist or user does not have access to edit it", errorOf(response)); } - statics.project.verify(() -> SecurityProjectUtils.propagateProjectPermission(any(), any(), any(), any(), + statics.catalog.verify(() -> SecurityCatalogDependencyUtils.propagatePermission(any(), any(), any(), any(), any(), any()), never()); } } @@ -433,9 +434,9 @@ void refusesAnUnknownLevelWithoutSavingIt(String level) throws Exception { List responses = List.of( resource.addProjectUserPermission(requestFor(user), form("id", "bob", "projectId", "p1", "permission", level)), resource.editProjectUserPermission(requestFor(user), form("id", "bob", "type", "NATIVE", "projectId", "p1", "permission", level)), - resource.propagateProjectDependencyPermission(requestFor(user), form("id", "bob", "type", "NATIVE", - "projectId", "p1", "permission", level)), - resource.propagateProjectDependencyPermissions(requestFor(user), form("projectId", "p1", + resource.propagateCatalogDependencyPermission(requestFor(user), form("id", "bob", "type", "NATIVE", + "catalogId", "p1", "permission", level)), + resource.propagateCatalogDependencyPermissions(requestFor(user), form("catalogId", "p1", "userpermissions", rows)), resource.addProjectUserPermissions(requestFor(user), form("projectId", "p1", "userpermissions", rows)), resource.editProjectUserPermissions(requestFor(user), form("projectId", "p1", "userpermissions", rows)), @@ -447,7 +448,7 @@ void refusesAnUnknownLevelWithoutSavingIt(String level) throws Exception { assertEquals("The permission must be OWNER, EDIT or READ_ONLY. Received value = " + level, errorOf(response)); } - statics.project.verify(() -> SecurityProjectUtils.propagateProjectPermission(any(), any(), any(), any(), + statics.catalog.verify(() -> SecurityCatalogDependencyUtils.propagatePermission(any(), any(), any(), any(), any(), any()), never()); statics.project.verify(() -> SecurityProjectUtils.addProjectUser(any(), any(), any(), any(), any()), never()); @@ -477,11 +478,11 @@ void propagatesAccessToTheProjectsDependenciesWithTheLoginType() throws Exceptio User user = signedIn("alice"); Map outcome = Map.of("accessGranted", List.of("m1")); try (Statics statics = new Statics()) { - statics.project.when(() -> SecurityProjectUtils.propagateProjectPermission(user, "p1", "bob", "NATIVE", + statics.catalog.when(() -> SecurityCatalogDependencyUtils.propagatePermission(user, "p1", "bob", "NATIVE", "READ_ONLY", "2027-01-01")).thenReturn(outcome); - Response response = resource.propagateProjectDependencyPermission(requestFor(user), form("id", "bob", - "type", "NATIVE", "projectId", "p1", "permission", "READ_ONLY", "endDate", "2027-01-01")); + Response response = resource.propagateCatalogDependencyPermission(requestFor(user), form("id", "bob", + "type", "NATIVE", "catalogId", "p1", "permission", "READ_ONLY", "endDate", "2027-01-01")); assertEquals(200, response.getStatus()); assertEquals(Map.of("accessGranted", List.of("m1")), body(response)); @@ -496,11 +497,11 @@ void propagatesTheUsageLimitItIsSent() throws Exception { try (Statics statics = new Statics()) { statics.limits.when(() -> SecurityModelUsageLimitUtils.readJson("{}")).thenReturn(limit); - Response response = resource.propagateProjectDependencyPermission(requestFor(user), form("id", "bob", - "type", "NATIVE", "projectId", "p1", "permission", "READ_ONLY", "usageLimit", "{}")); + Response response = resource.propagateCatalogDependencyPermission(requestFor(user), form("id", "bob", + "type", "NATIVE", "catalogId", "p1", "permission", "READ_ONLY", "usageLimit", "{}")); assertEquals(200, response.getStatus()); - statics.project.verify(() -> SecurityProjectUtils.propagateProjectPermission(user, "p1", "bob", "NATIVE", + statics.catalog.verify(() -> SecurityCatalogDependencyUtils.propagatePermission(user, "p1", "bob", "NATIVE", "READ_ONLY", null, limit)); } } @@ -513,13 +514,13 @@ void propagatesEveryRowWithItsOwnLimitAndKeepsLimitsForRowsWithout() throws Exce + "{\"userid\":\"carol\",\"type\":\"LDAP\",\"permission\":\"READ_ONLY\"}]"; try (Statics statics = new Statics()) { statics.limits.when(() -> SecurityModelUsageLimitUtils.readJson("{\"unlimited\":true}")).thenReturn(limit); - statics.project.when(() -> SecurityProjectUtils.propagateProjectPermission(user, "p1", "bob", "NATIVE", + statics.catalog.when(() -> SecurityCatalogDependencyUtils.propagatePermission(user, "p1", "bob", "NATIVE", "EDIT", null, limit)).thenReturn(Map.of("accessGranted", List.of("m1"))); - statics.project.when(() -> SecurityProjectUtils.propagateProjectPermission(user, "p1", "carol", "LDAP", + statics.catalog.when(() -> SecurityCatalogDependencyUtils.propagatePermission(user, "p1", "carol", "LDAP", "READ_ONLY", null)).thenReturn(Map.of("newRequestAdded", List.of("m1"))); - Response response = resource.propagateProjectDependencyPermissions(requestFor(user), - form("projectId", "p1", "userpermissions", rows)); + Response response = resource.propagateCatalogDependencyPermissions(requestFor(user), + form("catalogId", "p1", "userpermissions", rows)); assertEquals(200, response.getStatus()); Map payload = (Map) body(response); @@ -537,10 +538,10 @@ void readsARowLimitSentAsJsonText() throws Exception { try (Statics statics = new Statics()) { statics.limits.when(() -> SecurityModelUsageLimitUtils.readJson("{}")).thenReturn(limit); - resource.propagateProjectDependencyPermissions(requestFor(user), - form("projectId", "p1", "userpermissions", rows)); + resource.propagateCatalogDependencyPermissions(requestFor(user), + form("catalogId", "p1", "userpermissions", rows)); - statics.project.verify(() -> SecurityProjectUtils.propagateProjectPermission(user, "p1", "bob", "NATIVE", + statics.catalog.verify(() -> SecurityCatalogDependencyUtils.propagatePermission(user, "p1", "bob", "NATIVE", "EDIT", null, limit)); } } @@ -552,11 +553,11 @@ void refusesAnUnreadableRowLimitWith400() throws Exception { try (Statics statics = new Statics()) { statics.limits.when(() -> SecurityModelUsageLimitUtils.readJson(anyString())).thenCallRealMethod(); - Response response = resource.propagateProjectDependencyPermissions(requestFor(user), - form("projectId", "p1", "userpermissions", rows)); + Response response = resource.propagateCatalogDependencyPermissions(requestFor(user), + form("catalogId", "p1", "userpermissions", rows)); assertEquals(400, response.getStatus()); - statics.project.verify(() -> SecurityProjectUtils.propagateProjectPermission(any(), any(), any(), any(), + statics.catalog.verify(() -> SecurityCatalogDependencyUtils.propagatePermission(any(), any(), any(), any(), any(), any(), any()), never()); } } @@ -774,6 +775,8 @@ private static final class Statics implements AutoCloseable { private final MockedStatic security = Mockito.mockStatic(AbstractSecurityUtils.class); private final MockedStatic admin = Mockito.mockStatic(SecurityAdminUtils.class); private final MockedStatic project = Mockito.mockStatic(SecurityProjectUtils.class); + private final MockedStatic catalog = Mockito + .mockStatic(SecurityCatalogDependencyUtils.class); private final MockedStatic limits = Mockito .mockStatic(SecurityModelUsageLimitUtils.class); private final MockedStatic directory = Mockito @@ -783,6 +786,8 @@ private static final class Statics implements AutoCloseable { private Statics() { // propagation needs edit access to the project; yes unless a test says no project.when(() -> SecurityProjectUtils.userCanEditProject(any(), anyString())).thenReturn(true); + // the dependencies propagated are a project's unless a test says otherwise + catalog.when(() -> SecurityCatalogDependencyUtils.resolveCatalogType(anyString(), any())).thenReturn("CODE"); } @Override @@ -790,6 +795,7 @@ public void close() { graph.close(); directory.close(); limits.close(); + catalog.close(); project.close(); admin.close(); security.close(); From d0de31b92e7af04eac201c8681f71410cdaee00c Mon Sep 17 00:00:00 2001 From: Neel Date: Thu, 19 Nov 2026 11:53:28 -0500 Subject: [PATCH 2/3] feat: update catalog dependencies to include engine-engine dependencies and automatically sync --- .../services/local/EngineRouteResource.java | 1115 +++++++++-------- 1 file changed, 560 insertions(+), 555 deletions(-) diff --git a/src/prerna/semoss/web/services/local/EngineRouteResource.java b/src/prerna/semoss/web/services/local/EngineRouteResource.java index adbef9f6..caf2a4ae 100644 --- a/src/prerna/semoss/web/services/local/EngineRouteResource.java +++ b/src/prerna/semoss/web/services/local/EngineRouteResource.java @@ -1,555 +1,560 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.semoss.web.services.local; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.stream.Collectors; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.filefilter.WildcardFileFilter; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import jakarta.annotation.security.PermitAll; -import jakarta.servlet.ServletContext; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.ws.rs.Consumes; -import jakarta.ws.rs.GET; -import jakarta.ws.rs.POST; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.PathParam; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.core.Context; -import jakarta.ws.rs.core.EntityTag; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Request; -import jakarta.ws.rs.core.Response; -import prerna.auth.User; -import prerna.auth.utils.SecurityEngineUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.engine.api.IEngine; -import prerna.engine.impl.CaseInsensitiveProperties; -import prerna.engine.impl.SmssUtilities; -import prerna.io.connector.couch.CouchException; -import prerna.io.connector.couch.CouchUtil; -import prerna.io.connector.secrets.ISecrets; -import prerna.io.connector.secrets.SecretsFactory; -import prerna.notifications.NotificationDbUtils; -import prerna.upload.CatalogImageUploader; -import prerna.util.Constants; -import prerna.util.DefaultImageGeneratorUtil; -import prerna.util.EmailUtility; -import prerna.util.EngineUtility; -import prerna.util.NotificationConstants; -import prerna.util.Utility; -import prerna.web.services.util.CatalogImageResponse; -import prerna.web.services.util.WebUtility; - -@Path("/e-{engineId}") -@PermitAll -public class EngineRouteResource { - - private static final Logger classLogger = LogManager.getLogger(EngineRouteResource.class); - - public static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create(); - - /** - * Append {@code key=} to a pixel argument list when the body has a - * non-null, non-empty value for the given key. The leading {@code ", "} is - * added on the assumption that the caller already wrote at least one argument - * before this one. - */ - public static void appendIfPresent(StringBuilder pixel, Map body, String key) { - Object value = body.get(key); - if (value == null) { - return; - } - if (value instanceof String && ((String) value).isEmpty()) { - return; - } - pixel.append(", ").append(key).append("=").append(GSON.toJson(value)); - } - - /** - * Build an error response with the standard error message envelope used by the - * engine resource endpoints. - */ - public static Response error(String message, int status) { - Map errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, message); - return WebUtility.getResponse(errorMap, status); - } - - /** - * Verify that the given user is allowed to interact with this engine. The user - * is allowed if they either have explicit view permission or the engine is - * marked discoverable. - * - * @param user the calling user - * @param engineId the engine id being accessed - * @return {@code true} when access is granted - * @throws IllegalAccessException if the engine does not exist or the user has - * no view/discoverable access - */ - private boolean canAccessOrDiscoverableEngine(User user, String engineId) throws IllegalAccessException { - if (!SecurityEngineUtils.userCanViewEngine(user, engineId) - && !SecurityEngineUtils.engineIsDiscoverable(engineId)) { - throw new IllegalAccessException("Engine " + engineId + " does not exist or user does not have access"); - } - - return true; - } - - /** - * Return the {@link IEngine.CATALOG_TYPE} for this engine. - */ - @GET - @Path("/type") - @Produces("application/json;charset=utf-8") - public Response getEngineType(@Context HttpServletRequest request, @PathParam("engineId") String engineId) { - engineId = WebUtility.inputSanitizer(engineId); - - User user; - try { - user = ResourceUtility.getUser(request); - } catch (IllegalAccessException e) { - return error("User session is invalid", 401); - } - try { - canAccessOrDiscoverableEngine(user, engineId); - } catch (IllegalAccessException e) { - return error(e.getMessage(), 401); - } - - IEngine.CATALOG_TYPE engineType; - try { - engineType = (IEngine.CATALOG_TYPE) SecurityEngineUtils.getEngineTypeAndSubtype(engineId)[0]; - } catch (Exception e) { - classLogger.error("Failed to look up engine type for engine '{}'", engineId, e); - return error("Unknown engine with id " + engineId, 400); - } - - Map ret = new HashMap<>(); - ret.put("engineId", engineId); - ret.put("engineType", engineType.toString()); - return WebUtility.getResponse(ret, 200); - } - - /** - * Replace the smss file backing this engine with the contents supplied in the - * {@code smss} form parameter. Only the engine owner (or an admin) may call - * this. The engine id, alias, and type are validated to be unchanged. Any - * concealed sensitive values (e.g. passwords) are unconcealed against the - * current values before persisting. - *

- * If a secret store is configured the new values are written there and the - * engine is reopened. Otherwise the smss file on disk is rewritten in place, - * with a best-effort rollback to the previous contents if reopening the engine - * with the new file fails. - *

- * On success this also pushes the updated smss to cloud storage (when in a - * cluster), records a notification, and emails the user. - * - * @param request the incoming HTTP request (provides the user session and the - * {@code smss} parameter) - * @param engineId the engine to update - * @return 200 with {@code {"success": true}} on success; 400 with an error - * envelope on validation/IO failure; 401 if the user is not the engine - * owner - */ - @POST - @Path("/updateSmssFile") - @Produces("application/json;charset=utf-8") - public Response updateSmssFile(@Context HttpServletRequest request, @PathParam("engineId") String engineId) { - // not required for containment. userIsOwner below resolves engineId against - // the ENGINE table, so a traversal value is rejected before it reaches the - // smss file path - engineId = WebUtility.safePathSegment(WebUtility.inputSanitizer(engineId)); - if (!WebUtility.isSafePathSegment(engineId)) { - Map errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Invalid engine id"); - return WebUtility.getResponse(errorMap, 400); - } - - User user = null; - try { - user = ResourceUtility.getUser(request); - } catch (IllegalAccessException e) { - Map errorMap = new HashMap<>(); - errorMap.put("error", "User session is invalid"); - return WebUtility.getResponse(errorMap, 401); - } - if (!SecurityEngineUtils.userIsOwner(user, engineId)) { - Map errorMap = new HashMap<>(); - errorMap.put("error", "Engine " + engineId - + " does not exist or user does not have permissions to update the smss. " - + "User must be the owner to perform this function."); - return WebUtility.getResponse(errorMap, 401); - } - - try { - return WebUtility.getResponse(saveSmssFile(user, engineId, request.getParameter("smss")), 200); - } catch (IllegalArgumentException e) { - return ResourceUtility.errorResponse(e.getMessage(), 400); - } - } - - /** - * Saves new smss content for an engine and opens the engine again with it. The - * engine's id, name and type stay as they are, and the hidden values the new - * content left untouched are kept. With a secret store the values go there; - * otherwise the smss file is written, and put back as it was when the engine - * does not open with the new content. The caller has checked that the user may - * update the engine: its owner, or an admin through the admin endpoint. - * - * @param user the user saving the smss, for the notification - * @param engineId the engine - * @param newSmssContent the new content of the smss file - * @return the response body, which says the save went through - * @throws IllegalArgumentException when the content cannot be saved, with the - * reason - */ - public static Map saveSmssFile(User user, String engineId, String newSmssContent) { - IEngine engine = Utility.getEngine(engineId); - String currentSmssFileLocation = engine.getSmssFilePath(); - File currentSmssFile = new File(currentSmssFileLocation); - if (!currentSmssFile.exists() || !currentSmssFile.isFile()) { - throw new IllegalArgumentException("Could not find current engie smss file"); - } - - Properties currentSmssProperties = engine.getSmssProp(); - - // validate the new SMSS - // that the user is not doing something they cannot do - // like update the engine id / alias - { - Properties newProp = new CaseInsensitiveProperties(Utility.loadPropertiesString(newSmssContent)); - if (!newProp.get(Constants.ENGINE).equals(currentSmssProperties.get(Constants.ENGINE)) - || !newProp.get(Constants.ENGINE_ALIAS).equals(currentSmssProperties.get(Constants.ENGINE_ALIAS)) - || !newProp.get(Constants.ENGINE_TYPE).equals(currentSmssProperties.get(Constants.ENGINE_TYPE))) { - throw new IllegalArgumentException("The engine id, engine name, and engine type cannot be changed"); - } - } - - // this section is for secrets - ISecrets secretStore = SecretsFactory.getSecretConnector(); - if (secretStore != null) { - try { - Map currentSecrets = secretStore.getEngineSecrets(engine.getCatalogType(), - engine.getEngineId(), engine.getEngineName()); - - String unconcealedNewSmssContent = SmssUtilities.unconcealSmssSensitiveInfo(newSmssContent, - currentSmssProperties, currentSecrets); - Properties newProp = new CaseInsensitiveProperties( - Utility.loadPropertiesString(unconcealedNewSmssContent)); - - secretStore.writeEngineSecrets(engine.getCatalogType(), engine.getEngineId(), engine.getEngineName(), - newProp.stringPropertyNames().stream().collect(Collectors.toMap(key -> key, newProp::get))); - - } catch (Exception e) { - classLogger.error("An error occurred saving the engine details in the secret store", e); - throw new IllegalArgumentException( - "An error occurred initializing the new engine details. Detailed message = " + e.getMessage()); - } - - try { - engine.close(); - engine.open(currentSmssFileLocation); - } catch (Exception e) { - classLogger.error("Failed to reopen engine '{}' after writing updated secrets to the secret store", - engineId, e); - throw new IllegalArgumentException( - "An error occurred re-connecting to the engine with the new credentials. Detailed message = " - + e.getMessage()); - } - - // the smss file is unchanged and the new values live in the secret store, so - // the other nodes only need to close the engine to read them on next use - ClusterUtil.publishEngineClose(engineId); - - Map success = new HashMap<>(); - success.put("success", true); - return success; - } - - // using the current smss properties - // and the new file contents - // unconceal any hidden values that have not been altered - String unconcealedNewSmssContent = SmssUtilities.unconcealSmssSensitiveInfo(newSmssContent, - currentSmssProperties); - - // read the current smss as text in case of an error - String currentSmssContent = null; - try { - currentSmssContent = new String(Files.readAllBytes(Paths.get(currentSmssFile.toURI()))); - } catch (IOException e) { - throw new IllegalArgumentException( - "An error occurred reading the current engine smss details. Detailed message = " + e.getMessage()); - } - - try { - engine.close(); - } catch (Exception e) { - classLogger.error("Failed to close engine '{}' before overwriting its smss file", engineId, e); - throw new IllegalArgumentException( - "An error occurred closing the engine. Detailed message = " + e.getMessage()); - } - try { - try (FileWriter fw = new FileWriter(currentSmssFile, false)) { - fw.write(unconcealedNewSmssContent); - } - engine.open(currentSmssFileLocation); - } catch (Exception e) { - classLogger.error( - "Failed to write new smss content or reopen engine '{}' with the new properties; attempting rollback", - engineId, e); - // reset the values - try { - // close the engine again - engine.close(); - } catch (IOException e1) { - classLogger.error("Failed to close engine '{}' while rolling back smss update", engineId, e1); - } - currentSmssFile.delete(); - try (FileWriter fw = new FileWriter(currentSmssFile, false)) { - fw.write(currentSmssContent); - engine.open(currentSmssFileLocation); - } catch (Exception e2) { - classLogger.error( - "Failed to restore previous smss for engine '{}' during rollback - engine is left in an unrecoverable state", - engineId, e2); - throw new IllegalArgumentException( - "A fatal error occurred and could not revert the engine to an operational state. " - + "Detailed message = " + e2.getMessage()); - } - throw new IllegalArgumentException( - "An error occurred initializing the new engine details. Detailed message = " + e.getMessage()); - } - - // push to cloud - ClusterUtil.pushEngineSmss(engineId, engine.getCatalogType()); - if (Utility.isNotificationDatabaseEnabled()) { - // Adding notification - String engineType = String.valueOf(SecurityEngineUtils.getEngineType(engineId)).toLowerCase(); - NotificationDbUtils.createNotification(user, null, null, engineId, NotificationConstants.Type.SMSS_UPDATE, - engineType, NotificationConstants.Priority.MEDIUM, null, null, - NotificationConstants.DisplaySurface.BELL); - - // Adding email notification - EmailUtility.sendSmssUpdateEmailNotification(user, engineId, EmailUtility.RESOURCE_TYPE.ENGINE); - } - - Map success = new HashMap<>(); - success.put("success", true); - return success; - } - - /* - * Code below is around engine images - */ - - /** - * Replace this engine's catalog image with one multipart file named - * {@code file}. Requires edit permission; accepts PNG, JPEG, or GIF up to 10 - * MiB. - */ - @POST - @Path("/image/upload") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Produces(MediaType.APPLICATION_JSON) - public Response uploadImage(@Context ServletContext context, @Context HttpServletRequest request, - @PathParam("engineId") String engineId) { - return CatalogImageUploader.upload(context, request, engineId, false); - } - - /** - * Download the image associated with this engine. The lookup falls through - * three sources in order: CouchDB (if enabled), cloud storage (if running in - * cluster mode), and finally the engine's local version folder. If no image - * exists locally the shared stock image is served without copying it. The - * optional {@code theme=light|dark} query parameter selects the stock artwork - * theme. - *

- * Honors HTTP {@code If-None-Match} via an entity tag built from the file's - * path, last-modified timestamp, and size, so an unchanged image returns 304. - * - * @param coreRequest the JAX-RS request, used for cache precondition evaluation - * @param request the underlying HTTP request (provides the user session) - * @param engineId the engine whose image is being downloaded - * @return 200 with the image bytes (or the appropriate 3xx via - * {@link Request#evaluatePreconditions}); 400 if the image cannot be - * resolved; 401 if the user has no view/discoverable access - */ - @GET - @Path("/image/download") - @Produces({ "image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml", - MediaType.APPLICATION_OCTET_STREAM }) - public Response imageDownload(@Context final Request coreRequest, @Context HttpServletRequest request, - @PathParam("engineId") String engineId) { - // not required for containment. getEngineTypeAndSubtype and - // canAccessOrDiscoverableEngine below resolve engineId against the ENGINE - // table, - // so a traversal value is rejected before it reaches the image path - engineId = WebUtility.safePathSegment(WebUtility.inputSanitizer(engineId)); - if (!WebUtility.isSafePathSegment(engineId)) { - Map errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Invalid engine id"); - return WebUtility.getResponse(errorMap, 400); - } - - User user = null; - try { - user = ResourceUtility.getUser(request); - } catch (IllegalAccessException e) { - Map errorMap = new HashMap<>(); - errorMap.put("error", "User session is invalid"); - return WebUtility.getResponse(errorMap, 401); - } - - IEngine.CATALOG_TYPE engineType = null; - Object[] typeAndSubtype = null; - try { - typeAndSubtype = SecurityEngineUtils.getEngineTypeAndSubtype(engineId); - engineType = (IEngine.CATALOG_TYPE) typeAndSubtype[0]; - } catch (Exception e) { - Map errorMap = new HashMap<>(); - errorMap.put("error", "Unknown engine with id " + engineId); - return WebUtility.getResponse(errorMap, 400); - } - try { - canAccessOrDiscoverableEngine(user, engineId); - } catch (IllegalAccessException e) { - Map errorMap = new HashMap<>(); - errorMap.put("error", e.getMessage()); - return WebUtility.getResponse(errorMap, 401); - } - - String engineName = SecurityEngineUtils.getEngineAliasForId(engineId); - String engineNameAndId = SmssUtilities.getUniqueName(engineName, engineId); - - // will define these here up front - String couchSelector = null; - String engineVersionPath = null; - try { - couchSelector = EngineUtility.getCouchSelector(engineType); - engineVersionPath = EngineUtility.getSpecificEngineVersionFolder(engineType, engineNameAndId); - } catch (Exception e) { - classLogger.error( - "Failed to resolve couch selector or engine version folder for engine '{}' (type {}) during image download", - engineNameAndId, engineType, e); - Map returnMap = new HashMap<>(); - returnMap.put(Constants.ERROR_MESSAGE, - "Unknown engine type '" + engineType + "' for engine " + engineNameAndId); - return WebUtility.getResponse(returnMap, 400); - } - - String imageTheme = request.getParameter("theme"); - File exportFile = null; - // is the image in couch db - if (CouchUtil.COUCH_ENABLED) { - try { - Map selectors = new HashMap<>(); - selectors.put(couchSelector, engineId); - return CatalogImageResponse.withBrowserCache(coreRequest, - CouchUtil.download(couchSelector, selectors, imageTheme)); - } catch (CouchException e) { - classLogger.error( - "Failed to download engine image from CouchDB for engine '{}' using selector '{}'; falling through to other sources", - engineId, couchSelector, e); - } - } - // is the image in cloud storage - else if (ClusterUtil.IS_CLUSTER) { - try { - exportFile = ClusterUtil.getEngineAndProjectImage(engineId, engineType, imageTheme); - } catch (Exception e) { - classLogger.error("Failed to fetch engine image from cluster storage for engine '{}' (type {})", - engineId, engineType, e); - Map errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Error sending image file"); - return WebUtility.getResponse(errorMap, 400); - } - // is the image local in engine folder - } else { - exportFile = findImageFile(engineVersionPath); - if (exportFile == null) { - // Resolve the shared stock file without creating an engine asset. - String fileLocation = engineVersionPath + "/" + "image.png"; - exportFile = DefaultImageGeneratorUtil.getStockImageForPath(fileLocation, imageTheme); - } - } - - if (exportFile != null && exportFile.exists()) { - String exportName = engineId + "_Image." + FilenameUtils.getExtension(exportFile.getAbsolutePath()); - EntityTag etag = new EntityTag(Integer.toHexString(exportFile.getAbsolutePath().hashCode()) + "-" - + exportFile.lastModified() + "-" + exportFile.length()); - return CatalogImageResponse.withBrowserCache(coreRequest, Response.ok(exportFile) - .header("Content-Disposition", "attachment; filename=" + exportName).tag(etag).build()); - } else { - Map errorMap = new HashMap<>(); - errorMap.put(Constants.ERROR_MESSAGE, "Error sending image file"); - return WebUtility.getResponse(errorMap, 400); - } - } - - /** - * Find an image in the directory - * - * @param folderDirectory - * @return - */ - private File findImageFile(String folderDirectory) { - List extensions = new ArrayList<>(); - extensions.add("image.png"); - extensions.add("image.jpeg"); - extensions.add("image.jpg"); - extensions.add("image.gif"); - extensions.add("image.svg"); - FileFilter imageExtensionFilter = WildcardFileFilter.builder().setWildcards(extensions).get(); - File baseFolder = new File(WebUtility.normalizePath(folderDirectory)); - File[] imageFiles = baseFolder.listFiles(imageExtensionFilter); - if (imageFiles != null && imageFiles.length > 0) { - return imageFiles[0]; - } - return null; - } - -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.semoss.web.services.local; + +import prerna.auth.utils.CatalogDependencyDerivation; +import java.io.File; +import java.io.FileFilter; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; + +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import jakarta.annotation.security.PermitAll; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.EntityTag; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Request; +import jakarta.ws.rs.core.Response; +import prerna.auth.User; +import prerna.auth.utils.SecurityEngineUtils; +import prerna.cluster.util.ClusterUtil; +import prerna.engine.api.IEngine; +import prerna.engine.impl.CaseInsensitiveProperties; +import prerna.engine.impl.SmssUtilities; +import prerna.io.connector.couch.CouchException; +import prerna.io.connector.couch.CouchUtil; +import prerna.io.connector.secrets.ISecrets; +import prerna.io.connector.secrets.SecretsFactory; +import prerna.notifications.NotificationDbUtils; +import prerna.upload.CatalogImageUploader; +import prerna.util.Constants; +import prerna.util.DefaultImageGeneratorUtil; +import prerna.util.EmailUtility; +import prerna.util.EngineUtility; +import prerna.util.NotificationConstants; +import prerna.util.Utility; +import prerna.web.services.util.CatalogImageResponse; +import prerna.web.services.util.WebUtility; + +@Path("/e-{engineId}") +@PermitAll +public class EngineRouteResource { + + private static final Logger classLogger = LogManager.getLogger(EngineRouteResource.class); + + public static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create(); + + /** + * Append {@code key=} to a pixel argument list when the body has a + * non-null, non-empty value for the given key. The leading {@code ", "} is + * added on the assumption that the caller already wrote at least one argument + * before this one. + */ + public static void appendIfPresent(StringBuilder pixel, Map body, String key) { + Object value = body.get(key); + if (value == null) { + return; + } + if (value instanceof String && ((String) value).isEmpty()) { + return; + } + pixel.append(", ").append(key).append("=").append(GSON.toJson(value)); + } + + /** + * Build an error response with the standard error message envelope used by the + * engine resource endpoints. + */ + public static Response error(String message, int status) { + Map errorMap = new HashMap<>(); + errorMap.put(Constants.ERROR_MESSAGE, message); + return WebUtility.getResponse(errorMap, status); + } + + /** + * Verify that the given user is allowed to interact with this engine. The user + * is allowed if they either have explicit view permission or the engine is + * marked discoverable. + * + * @param user the calling user + * @param engineId the engine id being accessed + * @return {@code true} when access is granted + * @throws IllegalAccessException if the engine does not exist or the user has + * no view/discoverable access + */ + private boolean canAccessOrDiscoverableEngine(User user, String engineId) throws IllegalAccessException { + if (!SecurityEngineUtils.userCanViewEngine(user, engineId) + && !SecurityEngineUtils.engineIsDiscoverable(engineId)) { + throw new IllegalAccessException("Engine " + engineId + " does not exist or user does not have access"); + } + + return true; + } + + /** + * Return the {@link IEngine.CATALOG_TYPE} for this engine. + */ + @GET + @Path("/type") + @Produces("application/json;charset=utf-8") + public Response getEngineType(@Context HttpServletRequest request, @PathParam("engineId") String engineId) { + engineId = WebUtility.inputSanitizer(engineId); + + User user; + try { + user = ResourceUtility.getUser(request); + } catch (IllegalAccessException e) { + return error("User session is invalid", 401); + } + try { + canAccessOrDiscoverableEngine(user, engineId); + } catch (IllegalAccessException e) { + return error(e.getMessage(), 401); + } + + IEngine.CATALOG_TYPE engineType; + try { + engineType = (IEngine.CATALOG_TYPE) SecurityEngineUtils.getEngineTypeAndSubtype(engineId)[0]; + } catch (Exception e) { + classLogger.error("Failed to look up engine type for engine '{}'", engineId, e); + return error("Unknown engine with id " + engineId, 400); + } + + Map ret = new HashMap<>(); + ret.put("engineId", engineId); + ret.put("engineType", engineType.toString()); + return WebUtility.getResponse(ret, 200); + } + + /** + * Replace the smss file backing this engine with the contents supplied in the + * {@code smss} form parameter. Only the engine owner (or an admin) may call + * this. The engine id, alias, and type are validated to be unchanged. Any + * concealed sensitive values (e.g. passwords) are unconcealed against the + * current values before persisting. + *

+ * If a secret store is configured the new values are written there and the + * engine is reopened. Otherwise the smss file on disk is rewritten in place, + * with a best-effort rollback to the previous contents if reopening the engine + * with the new file fails. + *

+ * On success this also pushes the updated smss to cloud storage (when in a + * cluster), records a notification, and emails the user. + * + * @param request the incoming HTTP request (provides the user session and the + * {@code smss} parameter) + * @param engineId the engine to update + * @return 200 with {@code {"success": true}} on success; 400 with an error + * envelope on validation/IO failure; 401 if the user is not the engine + * owner + */ + @POST + @Path("/updateSmssFile") + @Produces("application/json;charset=utf-8") + public Response updateSmssFile(@Context HttpServletRequest request, @PathParam("engineId") String engineId) { + // not required for containment. userIsOwner below resolves engineId against + // the ENGINE table, so a traversal value is rejected before it reaches the + // smss file path + engineId = WebUtility.safePathSegment(WebUtility.inputSanitizer(engineId)); + if (!WebUtility.isSafePathSegment(engineId)) { + Map errorMap = new HashMap<>(); + errorMap.put(Constants.ERROR_MESSAGE, "Invalid engine id"); + return WebUtility.getResponse(errorMap, 400); + } + + User user = null; + try { + user = ResourceUtility.getUser(request); + } catch (IllegalAccessException e) { + Map errorMap = new HashMap<>(); + errorMap.put("error", "User session is invalid"); + return WebUtility.getResponse(errorMap, 401); + } + if (!SecurityEngineUtils.userIsOwner(user, engineId)) { + Map errorMap = new HashMap<>(); + errorMap.put("error", "Engine " + engineId + + " does not exist or user does not have permissions to update the smss. " + + "User must be the owner to perform this function."); + return WebUtility.getResponse(errorMap, 401); + } + + try { + return WebUtility.getResponse(saveSmssFile(user, engineId, request.getParameter("smss")), 200); + } catch (IllegalArgumentException e) { + return ResourceUtility.errorResponse(e.getMessage(), 400); + } + } + + /** + * Saves new smss content for an engine and opens the engine again with it. The + * engine's id, name and type stay as they are, and the hidden values the new + * content left untouched are kept. With a secret store the values go there; + * otherwise the smss file is written, and put back as it was when the engine + * does not open with the new content. The caller has checked that the user may + * update the engine: its owner, or an admin through the admin endpoint. + * + * @param user the user saving the smss, for the notification + * @param engineId the engine + * @param newSmssContent the new content of the smss file + * @return the response body, which says the save went through + * @throws IllegalArgumentException when the content cannot be saved, with the + * reason + */ + public static Map saveSmssFile(User user, String engineId, String newSmssContent) { + IEngine engine = Utility.getEngine(engineId); + String currentSmssFileLocation = engine.getSmssFilePath(); + File currentSmssFile = new File(currentSmssFileLocation); + if (!currentSmssFile.exists() || !currentSmssFile.isFile()) { + throw new IllegalArgumentException("Could not find current engie smss file"); + } + + Properties currentSmssProperties = engine.getSmssProp(); + + // validate the new SMSS + // that the user is not doing something they cannot do + // like update the engine id / alias + { + Properties newProp = new CaseInsensitiveProperties(Utility.loadPropertiesString(newSmssContent)); + if (!newProp.get(Constants.ENGINE).equals(currentSmssProperties.get(Constants.ENGINE)) + || !newProp.get(Constants.ENGINE_ALIAS).equals(currentSmssProperties.get(Constants.ENGINE_ALIAS)) + || !newProp.get(Constants.ENGINE_TYPE).equals(currentSmssProperties.get(Constants.ENGINE_TYPE))) { + throw new IllegalArgumentException("The engine id, engine name, and engine type cannot be changed"); + } + } + + // this section is for secrets + ISecrets secretStore = SecretsFactory.getSecretConnector(); + if (secretStore != null) { + try { + Map currentSecrets = secretStore.getEngineSecrets(engine.getCatalogType(), + engine.getEngineId(), engine.getEngineName()); + + String unconcealedNewSmssContent = SmssUtilities.unconcealSmssSensitiveInfo(newSmssContent, + currentSmssProperties, currentSecrets); + Properties newProp = new CaseInsensitiveProperties( + Utility.loadPropertiesString(unconcealedNewSmssContent)); + + secretStore.writeEngineSecrets(engine.getCatalogType(), engine.getEngineId(), engine.getEngineName(), + newProp.stringPropertyNames().stream().collect(Collectors.toMap(key -> key, newProp::get))); + + } catch (Exception e) { + classLogger.error("An error occurred saving the engine details in the secret store", e); + throw new IllegalArgumentException( + "An error occurred initializing the new engine details. Detailed message = " + e.getMessage()); + } + + try { + engine.close(); + engine.open(currentSmssFileLocation); + } catch (Exception e) { + classLogger.error("Failed to reopen engine '{}' after writing updated secrets to the secret store", + engineId, e); + throw new IllegalArgumentException( + "An error occurred re-connecting to the engine with the new credentials. Detailed message = " + + e.getMessage()); + } + + // the smss file is unchanged and the new values live in the secret store, so + // the other nodes only need to close the engine to read them on next use + ClusterUtil.publishEngineClose(engineId); + // the smss may name a different judge model, vector database or embedder + CatalogDependencyDerivation.syncSmss(user, engineId, engine.getCatalogType().name(), engine.getSmssProp()); + + Map success = new HashMap<>(); + success.put("success", true); + return success; + } + + // using the current smss properties + // and the new file contents + // unconceal any hidden values that have not been altered + String unconcealedNewSmssContent = SmssUtilities.unconcealSmssSensitiveInfo(newSmssContent, + currentSmssProperties); + + // read the current smss as text in case of an error + String currentSmssContent = null; + try { + currentSmssContent = new String(Files.readAllBytes(Paths.get(currentSmssFile.toURI()))); + } catch (IOException e) { + throw new IllegalArgumentException( + "An error occurred reading the current engine smss details. Detailed message = " + e.getMessage()); + } + + try { + engine.close(); + } catch (Exception e) { + classLogger.error("Failed to close engine '{}' before overwriting its smss file", engineId, e); + throw new IllegalArgumentException( + "An error occurred closing the engine. Detailed message = " + e.getMessage()); + } + try { + try (FileWriter fw = new FileWriter(currentSmssFile, false)) { + fw.write(unconcealedNewSmssContent); + } + engine.open(currentSmssFileLocation); + } catch (Exception e) { + classLogger.error( + "Failed to write new smss content or reopen engine '{}' with the new properties; attempting rollback", + engineId, e); + // reset the values + try { + // close the engine again + engine.close(); + } catch (IOException e1) { + classLogger.error("Failed to close engine '{}' while rolling back smss update", engineId, e1); + } + currentSmssFile.delete(); + try (FileWriter fw = new FileWriter(currentSmssFile, false)) { + fw.write(currentSmssContent); + engine.open(currentSmssFileLocation); + } catch (Exception e2) { + classLogger.error( + "Failed to restore previous smss for engine '{}' during rollback - engine is left in an unrecoverable state", + engineId, e2); + throw new IllegalArgumentException( + "A fatal error occurred and could not revert the engine to an operational state. " + + "Detailed message = " + e2.getMessage()); + } + throw new IllegalArgumentException( + "An error occurred initializing the new engine details. Detailed message = " + e.getMessage()); + } + + // push to cloud + ClusterUtil.pushEngineSmss(engineId, engine.getCatalogType()); + if (Utility.isNotificationDatabaseEnabled()) { + // Adding notification + String engineType = String.valueOf(SecurityEngineUtils.getEngineType(engineId)).toLowerCase(); + NotificationDbUtils.createNotification(user, null, null, engineId, NotificationConstants.Type.SMSS_UPDATE, + engineType, NotificationConstants.Priority.MEDIUM, null, null, + NotificationConstants.DisplaySurface.BELL); + + // Adding email notification + EmailUtility.sendSmssUpdateEmailNotification(user, engineId, EmailUtility.RESOURCE_TYPE.ENGINE); + } + // the smss may name a different judge model, vector database or embedder + CatalogDependencyDerivation.syncSmss(user, engineId, engine.getCatalogType().name(), engine.getSmssProp()); + + Map success = new HashMap<>(); + success.put("success", true); + return success; + } + + /* + * Code below is around engine images + */ + + /** + * Replace this engine's catalog image with one multipart file named + * {@code file}. Requires edit permission; accepts PNG, JPEG, or GIF up to 10 + * MiB. + */ + @POST + @Path("/image/upload") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + public Response uploadImage(@Context ServletContext context, @Context HttpServletRequest request, + @PathParam("engineId") String engineId) { + return CatalogImageUploader.upload(context, request, engineId, false); + } + + /** + * Download the image associated with this engine. The lookup falls through + * three sources in order: CouchDB (if enabled), cloud storage (if running in + * cluster mode), and finally the engine's local version folder. If no image + * exists locally the shared stock image is served without copying it. The + * optional {@code theme=light|dark} query parameter selects the stock artwork + * theme. + *

+ * Honors HTTP {@code If-None-Match} via an entity tag built from the file's + * path, last-modified timestamp, and size, so an unchanged image returns 304. + * + * @param coreRequest the JAX-RS request, used for cache precondition evaluation + * @param request the underlying HTTP request (provides the user session) + * @param engineId the engine whose image is being downloaded + * @return 200 with the image bytes (or the appropriate 3xx via + * {@link Request#evaluatePreconditions}); 400 if the image cannot be + * resolved; 401 if the user has no view/discoverable access + */ + @GET + @Path("/image/download") + @Produces({ "image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml", + MediaType.APPLICATION_OCTET_STREAM }) + public Response imageDownload(@Context final Request coreRequest, @Context HttpServletRequest request, + @PathParam("engineId") String engineId) { + // not required for containment. getEngineTypeAndSubtype and + // canAccessOrDiscoverableEngine below resolve engineId against the ENGINE + // table, + // so a traversal value is rejected before it reaches the image path + engineId = WebUtility.safePathSegment(WebUtility.inputSanitizer(engineId)); + if (!WebUtility.isSafePathSegment(engineId)) { + Map errorMap = new HashMap<>(); + errorMap.put(Constants.ERROR_MESSAGE, "Invalid engine id"); + return WebUtility.getResponse(errorMap, 400); + } + + User user = null; + try { + user = ResourceUtility.getUser(request); + } catch (IllegalAccessException e) { + Map errorMap = new HashMap<>(); + errorMap.put("error", "User session is invalid"); + return WebUtility.getResponse(errorMap, 401); + } + + IEngine.CATALOG_TYPE engineType = null; + Object[] typeAndSubtype = null; + try { + typeAndSubtype = SecurityEngineUtils.getEngineTypeAndSubtype(engineId); + engineType = (IEngine.CATALOG_TYPE) typeAndSubtype[0]; + } catch (Exception e) { + Map errorMap = new HashMap<>(); + errorMap.put("error", "Unknown engine with id " + engineId); + return WebUtility.getResponse(errorMap, 400); + } + try { + canAccessOrDiscoverableEngine(user, engineId); + } catch (IllegalAccessException e) { + Map errorMap = new HashMap<>(); + errorMap.put("error", e.getMessage()); + return WebUtility.getResponse(errorMap, 401); + } + + String engineName = SecurityEngineUtils.getEngineAliasForId(engineId); + String engineNameAndId = SmssUtilities.getUniqueName(engineName, engineId); + + // will define these here up front + String couchSelector = null; + String engineVersionPath = null; + try { + couchSelector = EngineUtility.getCouchSelector(engineType); + engineVersionPath = EngineUtility.getSpecificEngineVersionFolder(engineType, engineNameAndId); + } catch (Exception e) { + classLogger.error( + "Failed to resolve couch selector or engine version folder for engine '{}' (type {}) during image download", + engineNameAndId, engineType, e); + Map returnMap = new HashMap<>(); + returnMap.put(Constants.ERROR_MESSAGE, + "Unknown engine type '" + engineType + "' for engine " + engineNameAndId); + return WebUtility.getResponse(returnMap, 400); + } + + String imageTheme = request.getParameter("theme"); + File exportFile = null; + // is the image in couch db + if (CouchUtil.COUCH_ENABLED) { + try { + Map selectors = new HashMap<>(); + selectors.put(couchSelector, engineId); + return CatalogImageResponse.withBrowserCache(coreRequest, + CouchUtil.download(couchSelector, selectors, imageTheme)); + } catch (CouchException e) { + classLogger.error( + "Failed to download engine image from CouchDB for engine '{}' using selector '{}'; falling through to other sources", + engineId, couchSelector, e); + } + } + // is the image in cloud storage + else if (ClusterUtil.IS_CLUSTER) { + try { + exportFile = ClusterUtil.getEngineAndProjectImage(engineId, engineType, imageTheme); + } catch (Exception e) { + classLogger.error("Failed to fetch engine image from cluster storage for engine '{}' (type {})", + engineId, engineType, e); + Map errorMap = new HashMap<>(); + errorMap.put(Constants.ERROR_MESSAGE, "Error sending image file"); + return WebUtility.getResponse(errorMap, 400); + } + // is the image local in engine folder + } else { + exportFile = findImageFile(engineVersionPath); + if (exportFile == null) { + // Resolve the shared stock file without creating an engine asset. + String fileLocation = engineVersionPath + "/" + "image.png"; + exportFile = DefaultImageGeneratorUtil.getStockImageForPath(fileLocation, imageTheme); + } + } + + if (exportFile != null && exportFile.exists()) { + String exportName = engineId + "_Image." + FilenameUtils.getExtension(exportFile.getAbsolutePath()); + EntityTag etag = new EntityTag(Integer.toHexString(exportFile.getAbsolutePath().hashCode()) + "-" + + exportFile.lastModified() + "-" + exportFile.length()); + return CatalogImageResponse.withBrowserCache(coreRequest, Response.ok(exportFile) + .header("Content-Disposition", "attachment; filename=" + exportName).tag(etag).build()); + } else { + Map errorMap = new HashMap<>(); + errorMap.put(Constants.ERROR_MESSAGE, "Error sending image file"); + return WebUtility.getResponse(errorMap, 400); + } + } + + /** + * Find an image in the directory + * + * @param folderDirectory + * @return + */ + private File findImageFile(String folderDirectory) { + List extensions = new ArrayList<>(); + extensions.add("image.png"); + extensions.add("image.jpeg"); + extensions.add("image.jpg"); + extensions.add("image.gif"); + extensions.add("image.svg"); + FileFilter imageExtensionFilter = WildcardFileFilter.builder().setWildcards(extensions).get(); + File baseFolder = new File(WebUtility.normalizePath(folderDirectory)); + File[] imageFiles = baseFolder.listFiles(imageExtensionFilter); + if (imageFiles != null && imageFiles.length > 0) { + return imageFiles[0]; + } + return null; + } + +} From 3a0f3c2df52d5375dbff71830a89e80dc8ff9a88 Mon Sep 17 00:00:00 2001 From: Neel Date: Mon, 23 Nov 2026 11:52:31 -0500 Subject: [PATCH 3/3] feat: record SMSS dependencies before the save's steps that can fail The engine SMSS save now records the engine's automatic dependencies right after it reopens, before the cluster push, notification and email, so one of those failing no longer leaves them out of date. Co-Authored-By: Claude Opus 5.5 --- .../services/local/EngineRouteResource.java | 12 ++++++------ .../local/EngineRouteResourceTest.java | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/prerna/semoss/web/services/local/EngineRouteResource.java b/src/prerna/semoss/web/services/local/EngineRouteResource.java index 68165df0..a9170e5d 100644 --- a/src/prerna/semoss/web/services/local/EngineRouteResource.java +++ b/src/prerna/semoss/web/services/local/EngineRouteResource.java @@ -341,15 +341,15 @@ private static Map saveSmssFileWhileLocked(User user, SecurityAd "An error occurred re-connecting to the engine with the new credentials. Detailed message = " + e.getMessage()); } + // the smss may name a different judge model, vector database or embedder; recorded + // first, since the engine is open with it now and the steps after can fail + CatalogDependencyDerivation.syncSmss(user, engineId, engine.getCatalogType().name(), engine.getSmssProp()); syncDisplayNameToSecurityDb(user, adminUtils, engineId, oldDisplayName, newDisplayName); // the smss file is unchanged and the new values live in the secret store, so // the other nodes only need to close the engine to read them on next use ClusterUtil.publishEngineClose(engineId); - // the smss may name a different judge model, vector database or embedder - CatalogDependencyDerivation.syncSmss(user, engineId, engine.getCatalogType().name(), engine.getSmssProp()); - Map success = new HashMap<>(); success.put("success", true); success.put(SmssEditCopy.SMSS_HASH, SmssEditCopy.read(engine).getSmssHash()); @@ -409,6 +409,9 @@ private static Map saveSmssFileWhileLocked(User user, SecurityAd throw new IllegalArgumentException( "An error occurred initializing the new engine details. Detailed message = " + e.getMessage()); } + // the smss may name a different judge model, vector database or embedder; recorded + // first, since the engine is open with it now and the steps after can fail + CatalogDependencyDerivation.syncSmss(user, engineId, engine.getCatalogType().name(), engine.getSmssProp()); syncDisplayNameToSecurityDb(user, adminUtils, engineId, oldDisplayName, newDisplayName); // push to cloud @@ -424,9 +427,6 @@ private static Map saveSmssFileWhileLocked(User user, SecurityAd EmailUtility.sendSmssUpdateEmailNotification(user, engineId, EmailUtility.RESOURCE_TYPE.ENGINE); } - // the smss may name a different judge model, vector database or embedder - CatalogDependencyDerivation.syncSmss(user, engineId, engine.getCatalogType().name(), engine.getSmssProp()); - Map success = new HashMap<>(); success.put("success", true); success.put(SmssEditCopy.SMSS_HASH, SmssEditCopy.read(engine).getSmssHash()); diff --git a/test/prerna/semoss/web/services/local/EngineRouteResourceTest.java b/test/prerna/semoss/web/services/local/EngineRouteResourceTest.java index 67a86428..5ba33c6a 100644 --- a/test/prerna/semoss/web/services/local/EngineRouteResourceTest.java +++ b/test/prerna/semoss/web/services/local/EngineRouteResourceTest.java @@ -67,6 +67,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.StreamingOutput; import prerna.auth.User; +import prerna.auth.utils.CatalogDependencyDerivation; import prerna.auth.utils.SecurityAdminUtils; import prerna.auth.utils.SecurityEngineUtils; import prerna.cluster.util.ClusterUtil; @@ -400,6 +401,24 @@ void rewritesTheSmssAndReopensTheEngine() throws Exception { } } + @Test + void recordsTheSmssDependenciesBeforeTheClusterPushThatCanFail() throws Exception { + try (Statics s = new Statics(); + MockedStatic derivation = Mockito + .mockStatic(CatalogDependencyDerivation.class)) { + s.security.when(() -> SecurityEngineUtils.userIsOwner(this.user, "db1")).thenReturn(true); + IEngine engine = engineWithSmss(this.tempDir.resolve("db1.smss")); + s.utilityValues.put("getEngine", engine); + s.cluster.when(() -> ClusterUtil.pushEngineSmss("db1", IEngine.CATALOG_TYPE.DATABASE)) + .thenThrow(new IllegalArgumentException("cloud is down")); + + assertBody(new EngineRouteResource().updateSmssFile(smssRequest(CURRENT_SMSS), "db1"), 400, + "cloud is down"); + derivation.verify(() -> CatalogDependencyDerivation.syncSmss(eq(this.user), eq("db1"), eq("DATABASE"), + any())); + } + } + @Test void notifiesTheUserOfAnSmssUpdate() throws Exception { try (Statics s = new Statics()) {