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