View Javadoc
1   /*
2    * Licensed to The Apereo Foundation under one or more contributor license
3    * agreements. See the NOTICE file distributed with this work for additional
4    * information regarding copyright ownership.
5    *
6    *
7    * The Apereo Foundation licenses this file to you under the Educational
8    * Community License, Version 2.0 (the "License"); you may not use this file
9    * except in compliance with the License. You may obtain a copy of the License
10   * at:
11   *
12   *   http://opensource.org/licenses/ecl2.txt
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   *
20   */
21  
22  package org.opencastproject.adminui.endpoint;
23  
24  import static com.entwinemedia.fn.data.json.Jsons.arr;
25  import static com.entwinemedia.fn.data.json.Jsons.f;
26  import static com.entwinemedia.fn.data.json.Jsons.obj;
27  import static com.entwinemedia.fn.data.json.Jsons.v;
28  import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
29  import static javax.servlet.http.HttpServletResponse.SC_CONFLICT;
30  import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
31  import static javax.servlet.http.HttpServletResponse.SC_OK;
32  import static org.apache.commons.lang3.StringUtils.trimToNull;
33  import static org.opencastproject.index.service.util.RestUtils.okJsonList;
34  import static org.opencastproject.util.RestUtil.R.conflict;
35  import static org.opencastproject.util.RestUtil.R.noContent;
36  import static org.opencastproject.util.doc.rest.RestParameter.Type.INTEGER;
37  import static org.opencastproject.util.doc.rest.RestParameter.Type.STRING;
38  
39  import org.opencastproject.adminui.util.TextFilter;
40  import org.opencastproject.authorization.xacml.manager.api.AclService;
41  import org.opencastproject.authorization.xacml.manager.api.AclServiceException;
42  import org.opencastproject.authorization.xacml.manager.api.AclServiceFactory;
43  import org.opencastproject.authorization.xacml.manager.api.ManagedAcl;
44  import org.opencastproject.authorization.xacml.manager.endpoint.JsonConv;
45  import org.opencastproject.authorization.xacml.manager.impl.ManagedAclImpl;
46  import org.opencastproject.index.service.resources.list.query.AclsListQuery;
47  import org.opencastproject.index.service.util.RestUtils;
48  import org.opencastproject.security.api.AccessControlEntry;
49  import org.opencastproject.security.api.AccessControlList;
50  import org.opencastproject.security.api.AccessControlParser;
51  import org.opencastproject.security.api.Organization;
52  import org.opencastproject.security.api.Role;
53  import org.opencastproject.security.api.RoleDirectoryService;
54  import org.opencastproject.security.api.SecurityService;
55  import org.opencastproject.util.NotFoundException;
56  import org.opencastproject.util.data.Option;
57  import org.opencastproject.util.doc.rest.RestParameter;
58  import org.opencastproject.util.doc.rest.RestQuery;
59  import org.opencastproject.util.doc.rest.RestResponse;
60  import org.opencastproject.util.doc.rest.RestService;
61  import org.opencastproject.util.requests.SortCriterion;
62  import org.opencastproject.util.requests.SortCriterion.Order;
63  
64  import com.entwinemedia.fn.Fn;
65  import com.entwinemedia.fn.Stream;
66  import com.entwinemedia.fn.StreamOp;
67  import com.entwinemedia.fn.data.Opt;
68  import com.entwinemedia.fn.data.json.Field;
69  import com.entwinemedia.fn.data.json.JObject;
70  import com.entwinemedia.fn.data.json.JValue;
71  
72  import org.apache.commons.lang3.ObjectUtils;
73  import org.apache.commons.lang3.StringUtils;
74  import org.json.simple.JSONArray;
75  import org.json.simple.JSONObject;
76  import org.osgi.service.component.ComponentContext;
77  import org.osgi.service.component.annotations.Activate;
78  import org.osgi.service.component.annotations.Component;
79  import org.osgi.service.component.annotations.Reference;
80  import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
81  import org.slf4j.Logger;
82  import org.slf4j.LoggerFactory;
83  
84  import java.io.IOException;
85  import java.util.ArrayList;
86  import java.util.Collections;
87  import java.util.Comparator;
88  import java.util.List;
89  import java.util.Map;
90  import java.util.Optional;
91  
92  import javax.ws.rs.DELETE;
93  import javax.ws.rs.FormParam;
94  import javax.ws.rs.GET;
95  import javax.ws.rs.POST;
96  import javax.ws.rs.PUT;
97  import javax.ws.rs.Path;
98  import javax.ws.rs.PathParam;
99  import javax.ws.rs.Produces;
100 import javax.ws.rs.QueryParam;
101 import javax.ws.rs.WebApplicationException;
102 import javax.ws.rs.core.MediaType;
103 import javax.ws.rs.core.Response;
104 
105 @Path("/admin-ng/acl")
106 @RestService(name = "acl", title = "Acl service",
107   abstractText = "Provides operations for acl",
108   notes = { "This service offers the default acl CRUD Operations for the admin UI.",
109             "<strong>Important:</strong> "
110               + "<em>This service is for exclusive use by the module admin-ui. Its API might change "
111               + "anytime without prior notice. Any dependencies other than the admin UI will be strictly ignored. "
112               + "DO NOT use this for integration of third-party applications.<em>"})
113 @Component(
114         immediate = true,
115         service = AclEndpoint.class,
116         property = {
117                 "service.description=Admin UI - ACL Endpoint",
118                 "opencast.service.type=org.opencastproject.adminui.AclEndpoint",
119                 "opencast.service.path=/admin-ng/acl",
120         }
121 )
122 @JaxrsResource
123 public class AclEndpoint {
124 
125   /** The logging facility */
126   private static final Logger logger = LoggerFactory.getLogger(AclEndpoint.class);
127 
128   /** The acl service factory */
129   private AclServiceFactory aclServiceFactory;
130 
131   /** The security service */
132   private SecurityService securityService;
133 
134   // The role directory service
135   private RoleDirectoryService roleDirectoryService;
136 
137   /**
138    * @param aclServiceFactory
139    *          the aclServiceFactory to set
140    */
141   @Reference
142   public void setAclServiceFactory(AclServiceFactory aclServiceFactory) {
143     this.aclServiceFactory = aclServiceFactory;
144   }
145 
146   /** OSGi callback for role directory service. */
147   @Reference
148   public void setRoleDirectoryService(RoleDirectoryService roleDirectoryService) {
149     this.roleDirectoryService = roleDirectoryService;
150   }
151 
152   /**
153    * @param securityService
154    *          the securityService to set
155    */
156   @Reference
157   public void setSecurityService(SecurityService securityService) {
158     this.securityService = securityService;
159   }
160 
161   /** OSGi callback. */
162   @Activate
163   protected void activate(ComponentContext cc) {
164     logger.info("Activate the Admin ui - Acl facade endpoint");
165   }
166 
167   private AclService aclService() {
168     return aclServiceFactory.serviceFor(securityService.getOrganization());
169   }
170 
171   @GET
172   @Path("acls.json")
173   @Produces(MediaType.APPLICATION_JSON)
174   @RestQuery(name = "allaclasjson", description = "Returns a list of acls", returnDescription = "Returns a JSON representation of the list of acls available the current user's organization", restParameters = {
175           @RestParameter(name = "filter", isRequired = false, description = "The filter used for the query. They should be formated like that: 'filter1:value1,filter2:value2'", type = STRING),
176           @RestParameter(name = "sort", isRequired = false, description = "The sort order. May include any of the following: NAME. Add '_DESC' to reverse the sort order (e.g. NAME_DESC).", type = STRING),
177           @RestParameter(defaultValue = "100", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING),
178           @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING) }, responses = { @RestResponse(responseCode = SC_OK, description = "The list of ACL's has successfully been returned") })
179   public Response getAclsAsJson(@QueryParam("filter") String filter, @QueryParam("sort") String sort,
180           @QueryParam("offset") int offset, @QueryParam("limit") int limit) throws IOException {
181     if (limit < 1)
182       limit = 100;
183     Opt<String> optSort = Opt.nul(trimToNull(sort));
184     Option<String> filterName = Option.none();
185     Option<String> filterText = Option.none();
186 
187     Map<String, String> filters = RestUtils.parseFilter(filter);
188     for (String name : filters.keySet()) {
189       String value = filters.get(name);
190       if (AclsListQuery.FILTER_NAME_NAME.equals(name)) {
191         filterName = Option.some(value);
192       } else if ((AclsListQuery.FILTER_TEXT_NAME.equals(name)) && (StringUtils.isNotBlank(value))) {
193         filterText = Option.some(value);
194       }
195     }
196 
197     // Filter acls by filter criteria
198     List<ManagedAcl> filteredAcls = new ArrayList<>();
199     for (ManagedAcl acl : aclService().getAcls()) {
200       // Filter list
201       if ((filterName.isSome() && !filterName.get().equals(acl.getName()))
202               || (filterText.isSome() && !TextFilter.match(filterText.get(), acl.getName()))) {
203         continue;
204       }
205       filteredAcls.add(acl);
206     }
207     int total = filteredAcls.size();
208 
209     // Sort by name, description or role
210     if (optSort.isSome()) {
211       final ArrayList<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
212       Collections.sort(filteredAcls, new Comparator<ManagedAcl>() {
213         @Override
214         public int compare(ManagedAcl acl1, ManagedAcl acl2) {
215           for (SortCriterion criterion : sortCriteria) {
216             Order order = criterion.getOrder();
217             switch (criterion.getFieldName()) {
218               case "name":
219                 if (order.equals(Order.Descending))
220                   return ObjectUtils.compare(acl2.getName(), acl1.getName());
221                 return ObjectUtils.compare(acl1.getName(), acl2.getName());
222               default:
223                 logger.info("Unkown sort type: {}", criterion.getFieldName());
224                 return 0;
225             }
226           }
227           return 0;
228         }
229       });
230     }
231 
232     // Apply Limit and offset
233     List<JValue> aclJSON = Stream.$(filteredAcls).drop(offset)
234             .apply(limit > 0 ? StreamOp.<ManagedAcl> id().take(limit) : StreamOp.<ManagedAcl> id()).map(fullManagedAcl)
235             .toList();
236     return okJsonList(aclJSON, offset, limit, total);
237   }
238 
239   @GET
240   @Path("roles.json")
241   @Produces(MediaType.APPLICATION_JSON)
242   @RestQuery(name = "getRoles", description = "Returns a list of roles",
243              returnDescription = "Returns a JSON representation of the roles with the given parameters under the "
244                                + "current user's organization.",
245              restParameters = {
246                @RestParameter(name = "query", isRequired = false, description = "The query.", type = STRING),
247                @RestParameter(name = "target", isRequired = false, description = "The target of the roles.",
248                               type = STRING),
249                @RestParameter(name = "limit", defaultValue = "100",
250                               description = "The maximum number of items to return per page.", isRequired = false,
251                               type = RestParameter.Type.STRING),
252                @RestParameter(name = "offset", defaultValue = "0", description = "The page number.", isRequired = false,
253                               type = RestParameter.Type.STRING) },
254              responses = { @RestResponse(responseCode = SC_OK, description = "The list of roles.") })
255   public Response getRoles(@QueryParam("query") String query, @QueryParam("target") String target,
256                            @QueryParam("offset") int offset, @QueryParam("limit") int limit) {
257 
258     String roleQuery = "%";
259     if (StringUtils.isNotBlank(query)) {
260       roleQuery = query.trim() + "%";
261     }
262 
263     Role.Target roleTarget = Role.Target.ALL;
264 
265     if (StringUtils.isNotBlank(target)) {
266       try {
267         roleTarget = Role.Target.valueOf(target.trim());
268       } catch (Exception e) {
269         logger.warn("Invalid target filter value {}", target);
270       }
271     }
272 
273     List<Role> roles = roleDirectoryService.findRoles(roleQuery, roleTarget, offset, limit);
274 
275     JSONArray jsonRoles = new JSONArray();
276     for (Role role: roles) {
277       JSONObject jsonRole = new JSONObject();
278       jsonRole.put("name", role.getName());
279       jsonRole.put("type", role.getType().toString());
280       jsonRole.put("description", role.getDescription());
281       jsonRole.put("organization", role.getOrganizationId());
282       jsonRoles.add(jsonRole);
283     }
284 
285     return Response.ok(jsonRoles.toJSONString()).build();
286   }
287 
288   @DELETE
289   @Path("{id}")
290   @RestQuery(name = "deleteacl", description = "Delete an ACL", returnDescription = "Delete an ACL", pathParameters = { @RestParameter(name = "id", isRequired = true, description = "The ACL identifier", type = INTEGER) }, responses = {
291           @RestResponse(responseCode = SC_OK, description = "The ACL has successfully been deleted"),
292           @RestResponse(responseCode = SC_NOT_FOUND, description = "The ACL has not been found"),
293           @RestResponse(responseCode = SC_CONFLICT, description = "The ACL could not be deleted, there are still references on it") })
294   public Response deleteAcl(@PathParam("id") long aclId) throws NotFoundException {
295     try {
296       if (!aclService().deleteAcl(aclId))
297         return conflict();
298     } catch (AclServiceException e) {
299       logger.warn("Error deleting manged acl with id '{}'", aclId, e);
300       throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
301     }
302     return noContent();
303   }
304 
305   @POST
306   @Path("")
307   @Produces(MediaType.APPLICATION_JSON)
308   @RestQuery(name = "createacl", description = "Create an ACL", returnDescription = "Create an ACL", restParameters = {
309           @RestParameter(name = "name", isRequired = true, description = "The ACL name", type = STRING),
310           @RestParameter(name = "acl", isRequired = true, description = "The access control list", type = STRING) }, responses = {
311           @RestResponse(responseCode = SC_OK, description = "The ACL has successfully been added"),
312           @RestResponse(responseCode = SC_CONFLICT, description = "An ACL with the same name already exists"),
313           @RestResponse(responseCode = SC_BAD_REQUEST, description = "Unable to parse the ACL") })
314   public Response createAcl(@FormParam("name") String name, @FormParam("acl") String accessControlList) {
315     final AccessControlList acl = parseAcl.apply(accessControlList);
316     Optional<ManagedAcl> managedAcl = aclService().createAcl(acl, name);
317     if (managedAcl.isEmpty()) {
318       logger.info("An ACL with the same name '{}' already exists", name);
319       throw new WebApplicationException(Response.Status.CONFLICT);
320     }
321     return RestUtils.okJson(full(managedAcl.get()));
322   }
323 
324   @PUT
325   @Path("{id}")
326   @Produces(MediaType.APPLICATION_JSON)
327   @RestQuery(name = "updateacl", description = "Update an ACL", returnDescription = "Update an ACL", pathParameters = { @RestParameter(name = "id", isRequired = true, description = "The ACL identifier", type = INTEGER) }, restParameters = {
328           @RestParameter(name = "name", isRequired = true, description = "The ACL name", type = STRING),
329           @RestParameter(name = "acl", isRequired = true, description = "The access control list", type = STRING) }, responses = {
330           @RestResponse(responseCode = SC_OK, description = "The ACL has successfully been updated"),
331           @RestResponse(responseCode = SC_NOT_FOUND, description = "The ACL has not been found"),
332           @RestResponse(responseCode = SC_BAD_REQUEST, description = "Unable to parse the ACL") })
333   public Response updateAcl(@PathParam("id") long aclId, @FormParam("name") String name,
334           @FormParam("acl") String accessControlList) throws NotFoundException {
335     final Organization org = securityService.getOrganization();
336     final AccessControlList acl = parseAcl.apply(accessControlList);
337     final ManagedAclImpl managedAcl = new ManagedAclImpl(aclId, name, org.getId(), acl);
338     if (!aclService().updateAcl(managedAcl)) {
339       logger.info("No ACL with id '{}' could be found under organization '{}'", aclId, org.getId());
340       throw new NotFoundException();
341     }
342     return RestUtils.okJson(full(managedAcl));
343   }
344 
345   @GET
346   @Path("{id}")
347   @Produces(MediaType.APPLICATION_JSON)
348   @RestQuery(name = "getacl", description = "Return the ACL by the given id", returnDescription = "Return the ACL by the given id", pathParameters = { @RestParameter(name = "id", isRequired = true, description = "The ACL identifier", type = INTEGER) }, responses = {
349           @RestResponse(responseCode = SC_OK, description = "The ACL has successfully been returned"),
350           @RestResponse(responseCode = SC_NOT_FOUND, description = "The ACL has not been found") })
351   public Response getAcl(@PathParam("id") long aclId) throws NotFoundException {
352     Optional<ManagedAcl> managedAcl = aclService().getAcl(aclId);
353     if (managedAcl.isPresent()) {
354       return RestUtils.okJson(full(managedAcl.get()));
355     }
356     logger.info("No ACL with id '{}' could by found", aclId);
357     throw new NotFoundException();
358   }
359 
360   private static final Fn<String, AccessControlList> parseAcl = new Fn<String, AccessControlList>() {
361     @Override
362     public AccessControlList apply(String acl) {
363       try {
364         return AccessControlParser.parseAcl(acl);
365       } catch (Exception e) {
366         logger.warn("Unable to parse ACL");
367         throw new WebApplicationException(Response.Status.BAD_REQUEST);
368       }
369     }
370   };
371 
372   public JObject full(AccessControlEntry ace) {
373     return obj(f(JsonConv.KEY_ROLE, v(ace.getRole())), f(JsonConv.KEY_ACTION, v(ace.getAction())),
374             f(JsonConv.KEY_ALLOW, v(ace.isAllow())));
375   }
376 
377   private final Fn<AccessControlEntry, JValue> fullAccessControlEntry = new Fn<AccessControlEntry, JValue>() {
378     @Override
379     public JValue apply(AccessControlEntry ace) {
380       return full(ace);
381     }
382   };
383 
384   public JObject full(AccessControlList acl) {
385     return obj(f(JsonConv.KEY_ACE, arr(Stream.$(acl.getEntries()).map(fullAccessControlEntry))));
386   }
387 
388   public JObject full(ManagedAcl acl) {
389     List<Field> fields = new ArrayList<>();
390     fields.add(f(JsonConv.KEY_ID, v(acl.getId())));
391     fields.add(f(JsonConv.KEY_NAME, v(acl.getName())));
392     fields.add(f(JsonConv.KEY_ORGANIZATION_ID, v(acl.getOrganizationId())));
393     fields.add(f(JsonConv.KEY_ACL, full(acl.getAcl())));
394     return obj(fields);
395   }
396 
397   private final Fn<ManagedAcl, JValue> fullManagedAcl = new Fn<ManagedAcl, JValue>() {
398     @Override
399     public JValue apply(ManagedAcl acl) {
400       return full(acl);
401     }
402   };
403 
404 }