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  package org.opencastproject.external.endpoint;
22  
23  import static org.apache.commons.lang3.StringUtils.isBlank;
24  import static org.apache.commons.lang3.StringUtils.isNotBlank;
25  import static org.opencastproject.util.DateTimeSupport.fromUTC;
26  import static org.opencastproject.util.DateTimeSupport.toUTC;
27  import static org.opencastproject.util.doc.rest.RestParameter.Type.STRING;
28  
29  import org.opencastproject.external.common.ApiMediaType;
30  import org.opencastproject.external.common.ApiResponseBuilder;
31  import org.opencastproject.security.urlsigning.exception.UrlSigningException;
32  import org.opencastproject.security.urlsigning.service.UrlSigningService;
33  import org.opencastproject.util.DateTimeSupport;
34  import org.opencastproject.util.OsgiUtil;
35  import org.opencastproject.util.RestUtil.R;
36  import org.opencastproject.util.doc.rest.RestParameter;
37  import org.opencastproject.util.doc.rest.RestQuery;
38  import org.opencastproject.util.doc.rest.RestResponse;
39  import org.opencastproject.util.doc.rest.RestService;
40  
41  import com.google.gson.JsonObject;
42  
43  import org.joda.time.DateTime;
44  import org.joda.time.DateTimeConstants;
45  import org.osgi.service.cm.ConfigurationException;
46  import org.osgi.service.cm.ManagedService;
47  import org.osgi.service.component.annotations.Activate;
48  import org.osgi.service.component.annotations.Component;
49  import org.osgi.service.component.annotations.Reference;
50  import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
51  import org.slf4j.Logger;
52  import org.slf4j.LoggerFactory;
53  
54  import java.text.ParseException;
55  import java.util.Date;
56  import java.util.Dictionary;
57  import java.util.Optional;
58  
59  import javax.servlet.http.HttpServletResponse;
60  import javax.ws.rs.FormParam;
61  import javax.ws.rs.HeaderParam;
62  import javax.ws.rs.POST;
63  import javax.ws.rs.Path;
64  import javax.ws.rs.Produces;
65  import javax.ws.rs.core.Response;
66  
67  @Path("/api/security")
68  @Produces({ ApiMediaType.JSON, ApiMediaType.VERSION_1_0_0, ApiMediaType.VERSION_1_1_0, ApiMediaType.VERSION_1_2_0,
69              ApiMediaType.VERSION_1_3_0, ApiMediaType.VERSION_1_4_0, ApiMediaType.VERSION_1_5_0,
70              ApiMediaType.VERSION_1_6_0, ApiMediaType.VERSION_1_7_0, ApiMediaType.VERSION_1_8_0,
71              ApiMediaType.VERSION_1_9_0, ApiMediaType.VERSION_1_10_0, ApiMediaType.VERSION_1_11_0 })
72  @RestService(name = "externalapisecurity", title = "External API Security Service", notes = {}, abstractText = "Provides security operations related to the external API")
73  @Component(
74      immediate = true,
75      service = { SecurityEndpoint.class,ManagedService.class },
76      property = {
77          "service.description=External API - Security Endpoint",
78          "opencast.service.type=org.opencastproject.external.security",
79          "opencast.service.path=/api/security"
80      }
81  )
82  @JaxrsResource
83  public class SecurityEndpoint implements ManagedService {
84  
85    protected static final String URL_SIGNING_EXPIRES_DURATION_SECONDS_KEY = "url.signing.expires.seconds";
86  
87    /** The default time before a piece of signed content expires. 2 Hours. */
88    protected static final long DEFAULT_URL_SIGNING_EXPIRE_DURATION = 2 * 60 * 60;
89  
90    /** The logging facility */
91    private static final Logger log = LoggerFactory.getLogger(SecurityEndpoint.class);
92  
93    private long expireSeconds = DEFAULT_URL_SIGNING_EXPIRE_DURATION;
94  
95    /* OSGi service references */
96    private UrlSigningService urlSigningService;
97  
98    /** OSGi DI */
99    @Reference
100   void setUrlSigningService(UrlSigningService urlSigningService) {
101     this.urlSigningService = urlSigningService;
102   }
103 
104   /** OSGi activation method */
105   @Activate
106   void activate() {
107     log.info("Activating External API - Security Endpoint");
108   }
109 
110   @Override
111   public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
112     if (properties == null) {
113       log.info("No configuration available, using defaults");
114       return;
115     }
116 
117     Optional<Long> expiration = OsgiUtil.getOptCfg(properties, URL_SIGNING_EXPIRES_DURATION_SECONDS_KEY)
118             .map(Long::parseLong);
119     if (expiration.isPresent()) {
120       expireSeconds = expiration.get();
121       log.info("The property {} has been configured to expire signed URLs in {}.",
122               URL_SIGNING_EXPIRES_DURATION_SECONDS_KEY, DateTimeSupport.humanReadableTime(expireSeconds));
123     } else {
124       expireSeconds = DEFAULT_URL_SIGNING_EXPIRE_DURATION;
125       log.info("The property {} has not been configured, so the default is being used to expire signed URLs in {}.",
126               URL_SIGNING_EXPIRES_DURATION_SECONDS_KEY, DateTimeSupport.humanReadableTime(expireSeconds));
127     }
128   }
129 
130   @POST
131   @Path("sign")
132   @RestQuery(name = "signurl", description = "Returns a signed URL that can be played back for the indicated period of time, while access is optionally restricted to the specified IP address.", returnDescription = "", restParameters = {
133           @RestParameter(name = "url", isRequired = true, description = "The linke to encode.", type = STRING),
134           @RestParameter(name = "valid-until", description = "Until when is the signed url valid", isRequired = false, type = STRING),
135           @RestParameter(name = "valid-source", description = "The IP address from which the url can be accessed", isRequired = false, type = STRING) }, responses = {
136                   @RestResponse(description = "The signed URL is returned.", responseCode = HttpServletResponse.SC_OK),
137                   @RestResponse(description = "The caller is not authorized to have the link signed.", responseCode = HttpServletResponse.SC_UNAUTHORIZED) })
138   public Response signUrl(@HeaderParam("Accept") String acceptHeader, @FormParam("url") String url,
139           @FormParam("valid-until") String validUntilUtc, @FormParam("valid-source") String validSource) {
140     if (isBlank(url))
141       return R.badRequest("Query parameter 'url' is mandatory");
142 
143     final DateTime validUntil;
144     if (isNotBlank(validUntilUtc)) {
145       try {
146         validUntil = new DateTime(fromUTC(validUntilUtc));
147       } catch (IllegalStateException | ParseException e) {
148         return R.badRequest("Query parameter 'valid-until' is not a valid ISO-8601 date string");
149       }
150     } else {
151       validUntil = new DateTime(new Date().getTime() + expireSeconds * DateTimeConstants.MILLIS_PER_SECOND);
152     }
153 
154     if (urlSigningService.accepts(url)) {
155       String signedUrl = "";
156       try {
157         signedUrl = urlSigningService.sign(url, validUntil, null, validSource);
158       } catch (UrlSigningException e) {
159         log.warn("Error while trying to sign url '{}':", url, e);
160         JsonObject errorJson = new JsonObject();
161         errorJson.addProperty("error", "Error while signing url");
162         return ApiResponseBuilder.Json.ok(acceptHeader, errorJson);
163       }
164 
165       JsonObject successJson = new JsonObject();
166       successJson.addProperty("url", signedUrl);
167       successJson.addProperty("valid-until", toUTC(validUntil.getMillis()));
168       return ApiResponseBuilder.Json.ok(acceptHeader, successJson);
169     } else {
170       JsonObject errorJson = new JsonObject();
171       errorJson.addProperty("error", "Given URL cannot be signed");
172       return ApiResponseBuilder.Json.ok(acceptHeader, errorJson);
173     }
174   }
175 }