001/* 002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Benoit Delbosc 018 */ 019package org.nuxeo.elasticsearch.http.readonly.filter; 020 021import org.json.JSONException; 022import org.json.JSONObject; 023import org.nuxeo.ecm.core.security.SecurityService; 024import org.nuxeo.elasticsearch.http.readonly.AbstractSearchRequestFilterImpl; 025 026/** 027 * Rewrite an Elsaticsearch search request to add security filter. 028 * 029 * URI Search are turned into Request body search. 030 * 031 * @since 7.3 032 */ 033public class DefaultSearchRequestFilter extends AbstractSearchRequestFilterImpl { 034 035 @Override 036 public String getPayload() throws JSONException { 037 if (principal.isAdministrator()) { 038 return payload; 039 } 040 if (filteredPayload == null) { 041 String[] principals = SecurityService.getPrincipalsToCheck(principal); 042 if (payload.contains("\\")) { 043 // JSONObject removes backslash so we need to hide them 044 payload = payload.replaceAll("\\\\", BACKSLASH_MARKER); 045 } 046 JSONObject payloadJson = new JSONObject(payload); 047 JSONObject query; 048 if (payloadJson.has("query")) { 049 query = payloadJson.getJSONObject("query"); 050 051 payloadJson.remove("query"); 052 } else { 053 query = new JSONObject("{\"match_all\":{}}"); 054 } 055 JSONObject filter = new JSONObject().put("terms", new JSONObject().put("ecm:acl", principals)); 056 JSONObject newQuery = new JSONObject().put("bool", 057 new JSONObject().put("must", query).put("filter", filter)); 058 payloadJson.put("query", newQuery); 059 filteredPayload = payloadJson.toString(); 060 if (filteredPayload.contains(BACKSLASH_MARKER)) { 061 filteredPayload = filteredPayload.replaceAll(BACKSLASH_MARKER, "\\\\"); 062 } 063 064 } 065 return filteredPayload; 066 } 067 068}