use of co.cask.cdap.security.spi.authorization.UnauthorizedException in project cdap by caskdata.
the class DatasetServiceClient method addInstance.
public void addInstance(String datasetInstanceName, String datasetType, DatasetProperties props, @Nullable KerberosPrincipalId owner) throws DatasetManagementException {
String ownerPrincipal = owner == null ? null : owner.getPrincipal();
DatasetInstanceConfiguration creationProperties = new DatasetInstanceConfiguration(datasetType, props.getProperties(), props.getDescription(), ownerPrincipal);
HttpResponse response = doPut("datasets/" + datasetInstanceName, GSON.toJson(creationProperties));
if (HttpResponseStatus.CONFLICT.code() == response.getResponseCode()) {
throw new InstanceConflictException(String.format("Failed to add instance %s due to conflict, details: %s", datasetInstanceName, response));
}
if (HttpResponseStatus.FORBIDDEN.code() == response.getResponseCode()) {
throw new DatasetManagementException(String.format("Failed to add instance %s, details: %s", datasetInstanceName, response), new UnauthorizedException(response.getResponseBodyAsString()));
}
if (HttpResponseStatus.OK.code() != response.getResponseCode()) {
throw new DatasetManagementException(String.format("Failed to add instance %s, details: %s", datasetInstanceName, response));
}
}
use of co.cask.cdap.security.spi.authorization.UnauthorizedException in project cdap by caskdata.
the class SystemArtifactsAuthorizationTest method testAuthorizationForSystemArtifacts.
@Test
public void testAuthorizationForSystemArtifacts() throws Exception {
artifactRepository.addSystemArtifacts();
// alice should not be able to refresh system artifacts because she does not have admin privileges on namespace
// system
SecurityRequestContext.setUserId(ALICE.getName());
try {
artifactRepository.addSystemArtifacts();
Assert.fail("Adding system artifacts should have failed because alice does not have admin privileges on " + "the namespace system.");
} catch (UnauthorizedException expected) {
// expected
}
// grant alice admin privileges on the CDAP system namespace
authorizer.grant(Authorizable.fromEntityId(NamespaceId.SYSTEM), ALICE, Collections.singleton(Action.ADMIN));
Assert.assertEquals(Collections.singleton(new Privilege(NamespaceId.SYSTEM, Action.ADMIN)), authorizer.listPrivileges(ALICE));
// refreshing system artifacts should succeed now
artifactRepository.addSystemArtifacts();
SecurityRequestContext.setUserId("bob");
// deleting a system artifact should fail because bob does not have admin privileges on the artifact
try {
artifactRepository.deleteArtifact(Id.Artifact.fromEntityId(SYSTEM_ARTIFACT));
Assert.fail("Deleting a system artifact should have failed because alice does not have admin privileges on " + "the artifact.");
} catch (UnauthorizedException expected) {
// expected
}
// grant alice admin privileges on test namespace
SecurityRequestContext.setUserId(ALICE.getName());
NamespaceId namespaceId = new NamespaceId("test");
authorizer.grant(Authorizable.fromEntityId(namespaceId), ALICE, Collections.singleton(Action.ADMIN));
namespaceAdmin.create(new NamespaceMeta.Builder().setName(namespaceId.getNamespace()).build());
// test that system artifacts are available to everyone
List<ArtifactSummary> artifacts = artifactRepository.getArtifactSummaries(namespaceId, true);
Assert.assertEquals(1, artifacts.size());
ArtifactSummary artifactSummary = artifacts.get(0);
Assert.assertEquals(SYSTEM_ARTIFACT.getArtifact(), artifactSummary.getName());
Assert.assertEquals(SYSTEM_ARTIFACT.getVersion(), artifactSummary.getVersion());
Assert.assertEquals(SYSTEM_ARTIFACT.getNamespace(), artifactSummary.getScope().name().toLowerCase());
// test the getArtifact API
ArtifactDetail artifactDetail = artifactRepository.getArtifact(Id.Artifact.fromEntityId(SYSTEM_ARTIFACT));
co.cask.cdap.api.artifact.ArtifactId artifactId = artifactDetail.getDescriptor().getArtifactId();
Assert.assertEquals(SYSTEM_ARTIFACT.getArtifact(), artifactId.getName());
Assert.assertEquals(SYSTEM_ARTIFACT.getVersion(), artifactId.getVersion().getVersion());
Assert.assertEquals(SYSTEM_ARTIFACT.getNamespace(), artifactId.getScope().name().toLowerCase());
namespaceAdmin.delete(namespaceId);
// enforce on the system artifact should fail in unit test, since we do not have auto-grant now
try {
authorizer.enforce(SYSTEM_ARTIFACT, ALICE, EnumSet.allOf(Action.class));
Assert.fail();
} catch (UnauthorizedException e) {
// expected
}
try {
artifactRepository.deleteArtifact(Id.Artifact.fromEntityId(SYSTEM_ARTIFACT));
Assert.fail();
} catch (UnauthorizedException e) {
// expected
}
// deleting system artifact should succeed if alice has ADMIN on the artifact
authorizer.grant(Authorizable.fromEntityId(SYSTEM_ARTIFACT), ALICE, EnumSet.of(Action.ADMIN));
artifactRepository.deleteArtifact(Id.Artifact.fromEntityId(SYSTEM_ARTIFACT));
// clean up privilege
authorizer.revoke(Authorizable.fromEntityId(SYSTEM_ARTIFACT));
authorizer.revoke(Authorizable.fromEntityId(namespaceId));
}
use of co.cask.cdap.security.spi.authorization.UnauthorizedException in project cdap by caskdata.
the class StreamClient method getEvents.
/**
* Reads events from a stream
*
* @param streamId ID of the stream
* @param start Timestamp in milliseconds or now-xs format to start reading event from (inclusive)
* @param end Timestamp in milliseconds or now-xs format for the last event to read (exclusive)
* @param limit Maximum number of events to read
* @param callback Callback to invoke for each stream event read. If the callback function returns {@code false}
* upon invocation, it will stops the reading
* @throws IOException If fails to read from stream
* @throws StreamNotFoundException If the given stream does not exists
*/
public void getEvents(StreamId streamId, String start, String end, int limit, Function<? super StreamEvent, Boolean> callback) throws IOException, StreamNotFoundException, UnauthenticatedException, UnauthorizedException {
long startTime = TimeMathParser.parseTime(start, TimeUnit.MILLISECONDS);
long endTime = TimeMathParser.parseTime(end, TimeUnit.MILLISECONDS);
URL url = config.resolveNamespacedURLV3(streamId.getParent(), String.format("streams/%s/events?start=%d&end=%d&limit=%d", streamId.getStream(), startTime, endTime, limit));
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
AccessToken accessToken = config.getAccessToken();
if (accessToken != null) {
urlConn.setRequestProperty(HttpHeaders.AUTHORIZATION, accessToken.getTokenType() + " " + accessToken.getValue());
}
if (urlConn instanceof HttpsURLConnection && !config.isVerifySSLCert()) {
try {
HttpRequests.disableCertCheck((HttpsURLConnection) urlConn);
} catch (Exception e) {
// TODO: Log "Got exception while disabling SSL certificate check for request.getURL()"
}
}
try {
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new UnauthenticatedException("Unauthorized status code received from the server.");
}
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
throw new StreamNotFoundException(streamId);
}
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
return;
}
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
throw new UnauthorizedException(CharStreams.toString(new InputStreamReader(urlConn.getErrorStream(), Charsets.UTF_8)));
}
// The response is an array of stream event object
InputStream inputStream = urlConn.getInputStream();
JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, Charsets.UTF_8));
jsonReader.beginArray();
while (jsonReader.peek() != JsonToken.END_ARRAY) {
Boolean result = callback.apply(GSON.<StreamEvent>fromJson(jsonReader, StreamEvent.class));
if (result == null || !result) {
break;
}
}
drain(inputStream);
// No need to close reader, the urlConn.disconnect in finally will close all underlying streams
} finally {
urlConn.disconnect();
}
}
use of co.cask.cdap.security.spi.authorization.UnauthorizedException in project cdap by caskdata.
the class RESTClient method execute.
public HttpResponse execute(HttpRequest request, int... allowedErrorCodes) throws IOException, UnauthenticatedException, DisconnectedException, UnauthorizedException {
int currentTry = 0;
HttpResponse response;
int responseCode;
boolean allowUnavailable = ArrayUtils.contains(allowedErrorCodes, HttpURLConnection.HTTP_UNAVAILABLE);
do {
onRequest(request, currentTry);
response = HttpRequests.execute(request, clientConfig.getDefaultRequestConfig());
responseCode = response.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_UNAVAILABLE || allowUnavailable) {
// only retry if unavailable
break;
}
currentTry++;
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
break;
}
} while (currentTry <= clientConfig.getUnavailableRetryLimit());
onResponse(request, response, currentTry);
if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new UnauthenticatedException("Unauthorized status code received from the server.");
}
if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
throw new UnauthorizedException(response.getResponseBodyAsString());
}
if (!isSuccessful(responseCode) && !ArrayUtils.contains(allowedErrorCodes, responseCode)) {
throw new IOException(responseCode + ": " + response.getResponseBodyAsString());
}
return response;
}
use of co.cask.cdap.security.spi.authorization.UnauthorizedException in project cdap by caskdata.
the class ProgramLifecycleHttpHandler method updateLogLevels.
private void updateLogLevels(FullHttpRequest request, HttpResponder responder, String namespace, String appName, String appVersion, String type, String programName, @Nullable String component, String runId) throws Exception {
ProgramType programType = getProgramType(type);
if (programType == null) {
throw new BadRequestException("Invalid program type provided");
}
try {
// we are decoding the body to Map<String, String> instead of Map<String, LogEntry.Level> here since Gson will
// serialize invalid enum values to null, which is allowed for log level, instead of throw an Exception.
lifecycleService.updateProgramLogLevels(new ApplicationId(namespace, appName, appVersion).program(programType, programName), transformLogLevelsMap(decodeArguments(request)), component, runId);
responder.sendStatus(HttpResponseStatus.OK);
} catch (JsonSyntaxException e) {
throw new BadRequestException("Invalid JSON in body");
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
} catch (SecurityException e) {
throw new UnauthorizedException("Unauthorized to update the log levels");
}
}
Aggregations