Skip to content

Commit

Permalink
ci: spotless changes
Browse files Browse the repository at this point in the history
  • Loading branch information
at88mph committed Nov 21, 2024
1 parent eccc7c9 commit 53ae84e
Show file tree
Hide file tree
Showing 14 changed files with 214 additions and 140 deletions.
63 changes: 62 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import org.apache.tools.ant.filters.ReplaceTokens
plugins {
id 'war'
id "com.github.node-gradle.node" version "3.0.1"
id 'com.diffplug.spotless' version '6.25.0'
id 'com.diffplug.spotless' version '6.13.0'

// IntelliJ IDEA plugin here to allow integration tests to appear properly in IDEs.
id 'idea'
id 'jacoco'
id 'org.jetbrains.dokka' version '1.6.0'
}

node {
Expand Down Expand Up @@ -72,3 +74,62 @@ processResources.dependsOn 'buildReactApp'
assemble.dependsOn 'copyDevToDist'

clean.delete << file('src/main/webapp/dist')

spotless {
java {
// Use the default importOrder configuration
importOrder()
// Remove unused imports
removeUnusedImports()
// Google Java Format, Android Open Source Project style which uses 4 spaces for indentation
palantirJavaFormat()
// Format annotations on a single line
formatAnnotations()
}
format 'misc', {
target '*.gradle'
trimTrailingWhitespace()
indentWithSpaces(4)
endWithNewline()
}
}
check.dependsOn spotlessCheck

// Create Java Code Coverage Reports
jacocoTestReport {
reports {
xml.enabled true
html.enabled true
}
}
check.dependsOn jacocoTestReport

// Create JavaDoc
javadoc {
destinationDir = file("${buildDir}/docs/javadoc")
}

// Create Java Documentation using Dokka for Github Markdown and HTML
tasks.dokkaGfm.configure {
outputDirectory.set(file("${buildDir}/docs/dokka/gfm"))
dokkaSourceSets {
register("main") {
sourceRoots.from(file("src/main/java"))
}
}
}
tasks.dokkaHtml.configure {
outputDirectory.set(file("${buildDir}/docs/dokka/html"))
dokkaSourceSets {
register("main") {
sourceRoots.from(file("src/main/java"))
}
configureEach {
jdkVersion.set(11)
sourceLink {
localDirectory.set(file("src/main/java"))
remoteUrl.set("https://github.com/opencadc/science-portal/tree/main/src/main/java")
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
package org.opencadc.scienceportal;


import ca.nrc.cadc.auth.AuthMethod;
import ca.nrc.cadc.reg.Standards;
import ca.nrc.cadc.reg.client.LocalAuthority;
import ca.nrc.cadc.reg.client.RegistryClient;
import ca.nrc.cadc.util.StringUtil;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.Set;
import org.apache.commons.configuration2.CombinedConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.PropertiesConfiguration;
Expand All @@ -18,28 +24,18 @@
import org.json.JSONObject;
import org.opencadc.token.Client;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.Set;


public class ApplicationConfiguration {

// Included in the JSP
public static final long BUILD_TIME_MS = new Date().getTime();

public static final String FIRST_PARTY_COOKIE_NAME = "__Host-science-portal-auth";
public static final String DEFAULT_CONFIG_FILE_PATH = System.getProperty("user.home")
+ "/config/org.opencadc.science-portal.properties";
public static final String DEFAULT_CONFIG_FILE_PATH =
System.getProperty("user.home") + "/config/org.opencadc.science-portal.properties";
private static final Logger LOGGER = Logger.getLogger(ApplicationConfiguration.class);
private final Configuration configuration;
private final String filePath;


public ApplicationConfiguration() {
this.filePath = ApplicationConfiguration.DEFAULT_CONFIG_FILE_PATH;

Expand All @@ -49,9 +45,9 @@ public ApplicationConfiguration() {
combinedConfiguration.addConfiguration(new SystemConfiguration());

final Parameters parameters = new Parameters();
final FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class).configure(
parameters.properties().setFileName(filePath));
final FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(
PropertiesConfiguration.class)
.configure(parameters.properties().setFileName(filePath));

try {
combinedConfiguration.addConfiguration(builder.getConfiguration());
Expand Down Expand Up @@ -89,11 +85,14 @@ public String getTokenCacheURLString() {
* @return String array, never null.
*/
public String[] getTabLabels() {
final String[] tabLabelArray = Arrays.stream(configuration.getString(ConfigurationKey.TAB_LABELS.propertyName).split(","))
.map(String::trim)
.toArray(String[]::new);
final String[] tabLabelArray = Arrays.stream(configuration
.getString(ConfigurationKey.TAB_LABELS.propertyName)
.split(","))
.map(String::trim)
.toArray(String[]::new);
if (tabLabelArray.length == 0) {
throw new IllegalStateException("Configuration property " + ConfigurationKey.TAB_LABELS.propertyName + " is missing" + this.filePath);
throw new IllegalStateException("Configuration property " + ConfigurationKey.TAB_LABELS.propertyName
+ " is missing" + this.filePath);
}

return tabLabelArray;
Expand All @@ -110,9 +109,9 @@ public JSONObject getHeaderURLs() {

Arrays.stream(ApplicationStandards.values()).forEach(applicationStandard -> {
try {
jsonObject.put(applicationStandard.standardID.toString(),
registryClient.getAccessURL(RegistryClient.Query.APPLICATIONS,
applicationStandard.standardID));
jsonObject.put(
applicationStandard.standardID.toString(),
registryClient.getAccessURL(RegistryClient.Query.APPLICATIONS, applicationStandard.standardID));
} catch (Exception e) {
LOGGER.warn("Unable to get Applications URL for " + applicationStandard.standardID, e);
}
Expand All @@ -123,7 +122,8 @@ public JSONObject getHeaderURLs() {
final Set<URI> credEndpoints = localAuthority.getServiceURIs(Standards.CRED_PROXY_10);
if (!credEndpoints.isEmpty()) {
final URI credServiceID = credEndpoints.stream().findFirst().orElseThrow(IllegalStateException::new);
final URL credServiceURL = registryClient.getServiceURL(credServiceID, Standards.CRED_PROXY_10, AuthMethod.CERT);
final URL credServiceURL =
registryClient.getServiceURL(credServiceID, Standards.CRED_PROXY_10, AuthMethod.CERT);

if (credServiceURL != null) {
jsonObject.put("ivo://cadc.nrc.ca/cred", credServiceURL.toExternalForm());
Expand All @@ -140,8 +140,8 @@ String getStringValue(final String key, final boolean required) {
final String val = this.configuration.getString(key);

if (required && !StringUtil.hasText(val)) {
throw new IllegalStateException("Configuration property " + key + " is missing or invalid at "
+ this.filePath);
throw new IllegalStateException(
"Configuration property " + key + " is missing or invalid at " + this.filePath);
} else {
return val;
}
Expand Down Expand Up @@ -172,18 +172,23 @@ public String getOIDCScope() {
}

public boolean isOIDCConfigured() {
return StringUtil.hasText(getOIDCClientID()) && StringUtil.hasText(getOIDCClientSecret())
&& StringUtil.hasText(getOIDCCallbackURI()) && StringUtil.hasText(getOIDCScope())
return StringUtil.hasText(getOIDCClientID())
&& StringUtil.hasText(getOIDCClientSecret())
&& StringUtil.hasText(getOIDCCallbackURI())
&& StringUtil.hasText(getOIDCScope())
&& StringUtil.hasText(getTokenCacheURLString());
}

public Client getOIDCClient() throws IOException {
return new Client(getOIDCClientID(), getOIDCClientSecret(),
new URL(getOIDCCallbackURI()), new URL(getOIDCRedirectURI()),
getOIDCScope().split(" "), getTokenCacheURLString());
return new Client(
getOIDCClientID(),
getOIDCClientSecret(),
new URL(getOIDCCallbackURI()),
new URL(getOIDCRedirectURI()),
getOIDCScope().split(" "),
getTokenCacheURLString());
}


private enum ApplicationStandards {
PASSWORD_CHANGE(URI.create("ivo://cadc.nrc.ca/passchg")),
PASSWORD_RESET(URI.create("ivo://cadc.nrc.ca/passreset")),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,19 +76,17 @@
import ca.nrc.cadc.rest.InlineContentHandler;
import ca.nrc.cadc.rest.RestAction;
import ca.nrc.cadc.util.StringUtil;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.security.auth.Subject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opencadc.token.Client;

import javax.security.auth.Subject;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.NoSuchElementException;

/**
* Base class to support storing the OIDC Access Token in a cookie.
* This should be replaced with a (<a href="https://bff-patterns.com/patterns/api-token-handler">BFF</a>), but this
Expand All @@ -112,44 +110,50 @@ protected Subject getCurrentSubject(final URL targetURL) throws Exception {
final Subject subject = AuthenticationUtil.getCurrentSubject();

if (StringUtil.hasText(rawCookieHeader)) {
final String[] firstPartyCookies =
Arrays.stream(rawCookieHeader.split(";"))
.map(String::trim)
.filter(cookieString -> cookieString.startsWith(
ApplicationConfiguration.FIRST_PARTY_COOKIE_NAME))
.toArray(String[]::new);
final String[] firstPartyCookies = Arrays.stream(rawCookieHeader.split(";"))
.map(String::trim)
.filter(cookieString -> cookieString.startsWith(ApplicationConfiguration.FIRST_PARTY_COOKIE_NAME))
.toArray(String[]::new);

if (firstPartyCookies.length > 0 && applicationConfiguration.isOIDCConfigured()) {
for (final String cookie : firstPartyCookies) {
// Only split on the first "=" symbol, and trim any wrapping double quotes
final String encryptedCookieValue =
cookie.split("=", 2)[1].replaceAll("\"", "");
final String encryptedCookieValue = cookie.split("=", 2)[1].replaceAll("\"", "");

try {
final String accessToken = getOIDCClient().getAccessToken(encryptedCookieValue);

subject.getPrincipals().add(new AuthorizationTokenPrincipal(AuthenticationUtil.AUTHORIZATION_HEADER,
AuthenticationUtil.CHALLENGE_TYPE_BEARER
+ " " + accessToken));
subject.getPublicCredentials().add(new AuthorizationToken(AuthenticationUtil.CHALLENGE_TYPE_BEARER, accessToken,
Collections.singletonList(targetURL.getHost())));
subject.getPrincipals()
.add(new AuthorizationTokenPrincipal(
AuthenticationUtil.AUTHORIZATION_HEADER,
AuthenticationUtil.CHALLENGE_TYPE_BEARER + " " + accessToken));
subject.getPublicCredentials()
.add(new AuthorizationToken(
AuthenticationUtil.CHALLENGE_TYPE_BEARER,
accessToken,
Collections.singletonList(targetURL.getHost())));
} catch (NoSuchElementException noTokenForKeyInCacheException) {
LOGGER.warn("Cookie found and decrypted but no value in cache. Ignoring cookie...");
}
}

if (!subject.getPrincipals(AuthorizationTokenPrincipal.class).isEmpty()) {
// Ensure it's clean first.
subject.getPublicCredentials(AuthMethod.class)
.forEach(authMethod -> subject.getPublicCredentials().remove(authMethod));
subject.getPublicCredentials(AuthMethod.class).forEach(authMethod -> subject.getPublicCredentials()
.remove(authMethod));
subject.getPublicCredentials().add(AuthMethod.TOKEN);
}
} else if (AuthenticationUtil.getAuthMethod(subject) == AuthMethod.COOKIE) {
final Set<SSOCookieCredential> publicCookieCredentials = subject.getPublicCredentials(SSOCookieCredential.class);
final Set<SSOCookieCredential> publicCookieCredentials =
subject.getPublicCredentials(SSOCookieCredential.class);
if (!publicCookieCredentials.isEmpty()) {
final SSOCookieCredential publicCookieCredential = publicCookieCredentials.toArray(new SSOCookieCredential[0])[0];
subject.getPublicCredentials().add(new SSOCookieCredential(publicCookieCredential.getSsoCookieValue(), targetURL.getHost(),
publicCookieCredential.getExpiryDate()));
final SSOCookieCredential publicCookieCredential =
publicCookieCredentials.toArray(new SSOCookieCredential[0])[0];
subject.getPublicCredentials()
.add(new SSOCookieCredential(
publicCookieCredential.getSsoCookieValue(),
targetURL.getHost(),
publicCookieCredential.getExpiryDate()));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,15 @@

package org.opencadc.scienceportal;

import ca.nrc.cadc.auth.AuthenticationUtil;
import ca.nrc.cadc.net.HttpGet;
import ca.nrc.cadc.rest.InlineContentHandler;
import ca.nrc.cadc.rest.RestAction;
import ca.nrc.cadc.util.StringUtil;

import javax.security.auth.Subject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.PrivilegedExceptionAction;
import java.util.stream.Collectors;
import javax.security.auth.Subject;

public abstract class SciencePortalAuthGetAction extends SciencePortalAuthAction {

Expand All @@ -99,16 +95,14 @@ public void doAction() throws Exception {
if (!syncInput.getParameterNames().isEmpty()) {
query = (StringUtil.hasText(apiEndpointURL.getQuery()) ? "&" : "?")
+ syncInput.getParameterNames().stream()
.map(k -> k + "=" + this.syncInput.getParameter(k))
.collect(Collectors.joining("&"));
.map(k -> k + "=" + this.syncInput.getParameter(k))
.collect(Collectors.joining("&"));
} else {
query = "";
}

Subject.doAs(subject, (PrivilegedExceptionAction<?>) () -> {
final HttpGet httpGet =
new HttpGet(new URL(apiEndpoint + query),
true);
final HttpGet httpGet = new HttpGet(new URL(apiEndpoint + query), true);
httpGet.setRequestProperty("accept", "application/json");
httpGet.prepare();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,10 @@
import ca.nrc.cadc.auth.AuthMethod;
import ca.nrc.cadc.reg.Standards;
import ca.nrc.cadc.reg.client.RegistryClient;
import org.opencadc.scienceportal.ApplicationConfiguration;
import org.opencadc.scienceportal.SciencePortalAuthGetAction;

import java.net.URI;
import java.net.URL;
import org.opencadc.scienceportal.ApplicationConfiguration;
import org.opencadc.scienceportal.SciencePortalAuthGetAction;

public class GetAction extends SciencePortalAuthGetAction {
private static final String CONTEXT_ENDPOINT = "/context";
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/org/opencadc/scienceportal/image/GetAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,10 @@
import ca.nrc.cadc.auth.AuthMethod;
import ca.nrc.cadc.reg.Standards;
import ca.nrc.cadc.reg.client.RegistryClient;
import org.opencadc.scienceportal.ApplicationConfiguration;
import org.opencadc.scienceportal.SciencePortalAuthGetAction;

import java.net.URI;
import java.net.URL;
import org.opencadc.scienceportal.ApplicationConfiguration;
import org.opencadc.scienceportal.SciencePortalAuthGetAction;

public class GetAction extends SciencePortalAuthGetAction {
private static final String IMAGE_ENDPOINT = "/image";
Expand Down
Loading

0 comments on commit 53ae84e

Please sign in to comment.