100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
CORS and BASIC auth improvements/fixes also upgraded to latest version of Undertow
Rich Turnera96668545a66
diff --git a/container/src/main/java/org/openremote/container/security/IdentityService.java b/container/src/main/java/org/openremote/container/security/IdentityService.javaindex 4e4e58c9d..d8a4a7acc 100644--- a/container/src/main/java/org/openremote/container/security/IdentityService.java+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java@@ -19,7 +19,12 @@*/package org.openremote.container.security;+import io.undertow.server.HandlerWrapper;+import io.undertow.server.HttpHandler;+import io.undertow.server.HttpServerExchange;import io.undertow.servlet.api.DeploymentInfo;+import io.undertow.util.HttpString;+import org.jboss.resteasy.spi.CorsHeaders;import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.persistence.PersistenceService;@@ -47,6 +52,7 @@ public abstract class IdentityService implements ContainerService {// The externally visible address of this installationprotected UriBuilder externalServerUri;protected IdentityProvider identityProvider;+ protected boolean devMode;@Overridepublic int getPriority() {@@ -58,6 +64,7 @@ public abstract class IdentityService implements ContainerService {boolean identityNetworkSecure = getBoolean(container.getConfig(), IDENTITY_NETWORK_SECURE, IDENTITY_NETWORK_SECURE_DEFAULT);String identityNetworkHost = getString(container.getConfig(), IDENTITY_NETWORK_HOST, IDENTITY_NETWORK_HOST_DEFAULT);int identityNetworkPort = getInteger(container.getConfig(), IDENTITY_NETWORK_WEBSERVER_PORT, IDENTITY_NETWORK_WEBSERVER_PORT_DEFAULT);+ devMode = container.isDevMode();externalServerUri = UriBuilder.fromUri("").scheme(identityNetworkSecure ? "https" : "http")@@ -94,6 +101,31 @@ public abstract class IdentityService implements ContainerService {deploymentInfo.addOuterHandlerChainWrapper(AuthOverloadHandler::new);deploymentInfo.setSecurityDisabled(false);identityProvider.secureDeployment(deploymentInfo);++ if (devMode) {+ // We need to add an undertow handler wrapper to inject CORS headers on 401/403 responses as the authentication+ // handler doesn't include headers set by deployment filters+ deploymentInfo.addOuterHandlerChainWrapper(new HandlerWrapper() {+ @Override+ public HttpHandler wrap(HttpHandler handler) {+ return new HttpHandler() {+ @Override+ public void handleRequest(HttpServerExchange exchange) throws Exception {++ if (exchange.isInIoThread()) {+ exchange.dispatch(this);+ return;+ }++ String origin = exchange.getRequestHeaders().getFirst(CorsHeaders.ORIGIN);+ exchange.getResponseHeaders().add(HttpString.tryFromString(CorsHeaders.ACCESS_CONTROL_ALLOW_ORIGIN), origin);+ exchange.getResponseHeaders().add(HttpString.tryFromString(CorsHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS), "true");+ handler.handleRequest(exchange);+ }+ };+ }+ });+ }}/**diff --git a/container/src/main/java/org/openremote/container/security/basic/BasicIdentityProvider.java b/container/src/main/java/org/openremote/container/security/basic/BasicIdentityProvider.javaindex 4270098ec..4eed5308d 100644--- a/container/src/main/java/org/openremote/container/security/basic/BasicIdentityProvider.java+++ b/container/src/main/java/org/openremote/container/security/basic/BasicIdentityProvider.java@@ -19,10 +19,18 @@*/package org.openremote.container.security.basic;+import io.undertow.UndertowMessages;+import io.undertow.security.api.AuthenticationMechanism;+import io.undertow.security.api.AuthenticationMechanismFactory;+import io.undertow.security.api.SecurityContext;import io.undertow.security.idm.Account;import io.undertow.security.idm.Credential;import io.undertow.security.idm.IdentityManager;import io.undertow.security.idm.PasswordCredential;+import io.undertow.security.impl.BasicAuthenticationMechanism;+import io.undertow.server.HttpServerExchange;+import io.undertow.server.handlers.form.FormParserFactory;+import io.undertow.servlet.api.AuthMethodConfig;import io.undertow.servlet.api.DeploymentInfo;import io.undertow.servlet.api.LoginConfig;import org.openremote.container.persistence.PersistenceService;@@ -31,14 +39,91 @@ import org.openremote.model.Constants;import javax.persistence.NoResultException;import javax.persistence.NonUniqueResultException;+import java.nio.charset.Charset;+import java.nio.charset.StandardCharsets;import java.security.Principal;+import java.util.Collections;+import java.util.HashMap;+import java.util.Map;import java.util.Set;import java.util.logging.Logger;+import java.util.regex.Pattern;++import static io.undertow.util.Headers.AUTHORIZATION;public abstract class BasicIdentityProvider implements IdentityProvider {- private static final Logger LOG = Logger.getLogger(BasicIdentityProvider.class.getName());+ /**+ * This is a fix for {@link BasicAuthenticationMechanism} which doesn't conform to RFC2617.+ * see: https://issues.redhat.com/browse/UNDERTOW-1727+ * <p>+ * When no {@link io.undertow.util.Headers#AUTHORIZATION} header is supplied then a 401 is returned with+ * {@link io.undertow.util.Headers#WWW_AUTHENTICATE} header unless {@link #silent} is true in which case+ * a 403 will be returned.+ * <p>+ * When an {@link io.undertow.util.Headers#AUTHORIZATION} header is supplied and is valid then the request+ * can proceed otherwise a 403 is returned.+ */+ protected static class BasicFixAuthenticationMechanism extends BasicAuthenticationMechanism {++ protected static class Factory implements AuthenticationMechanismFactory {+ @Override+ public AuthenticationMechanism create(String mechanismName, IdentityManager identityManager, FormParserFactory formParserFactory, Map<String, String> properties) {+ String realm = properties.get(REALM);+ String silent = properties.get(SILENT);+ String charsetString = properties.get(CHARSET);+ Charset charset = charsetString == null ? StandardCharsets.UTF_8 : Charset.forName(charsetString);+ Map<Pattern, Charset> userAgentCharsets = new HashMap<>();+ String userAgentString = properties.get(USER_AGENT_CHARSETS);+ if(userAgentString != null) {+ String[] parts = userAgentString.split(",");+ if(parts.length % 2 != 0) {+ throw UndertowMessages.MESSAGES.userAgentCharsetMustHaveEvenNumberOfItems(userAgentString);+ }+ for(int i = 0; i < parts.length; i += 2) {+ Pattern pattern = Pattern.compile(parts[i]);+ Charset c = Charset.forName(parts[i + 1]);+ userAgentCharsets.put(pattern, c);+ }+ }+ return new BasicFixAuthenticationMechanism(realm, mechanismName, silent != null && silent.equals("true"), identityManager, charset, userAgentCharsets);+ }+ }++ // field is private in super class so need to redefine!!!+ private final boolean silent;+ public static Factory FACTORY = new Factory();++ public BasicFixAuthenticationMechanism(String realmName, String mechanismName, boolean silent, IdentityManager identityManager, Charset charset, Map<Pattern, Charset> userAgentCharsets) {+ super(realmName, mechanismName, false, identityManager, charset, userAgentCharsets);+ this.silent = silent;+ }++ @Override+ public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {+ String authHeader = exchange.getRequestHeaders().getFirst(AUTHORIZATION);+ if (authHeader == null) {+ if (silent) {+ return AuthenticationMechanismOutcome.NOT_ATTEMPTED;+ } else {+ return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;+ }+ }+ return super.authenticate(exchange, securityContext);+ }++ @Override+ public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) {+ String authHeader = exchange.getRequestHeaders().getFirst(AUTHORIZATION);+ if (silent || authHeader != null) {+ return ChallengeResult.NOT_SENT;+ }+ return super.sendChallenge(exchange, securityContext);+ }+ }++ private static final Logger LOG = Logger.getLogger(BasicIdentityProvider.class.getName());final protected PersistenceService persistenceService;public BasicIdentityProvider(PersistenceService persistenceService) {@@ -67,7 +152,10 @@ public abstract class BasicIdentityProvider implements IdentityProvider {@Overridepublic void secureDeployment(DeploymentInfo deploymentInfo) {- LoginConfig loginConfig = new LoginConfig("BASIC", "OpenRemote");+ LoginConfig loginConfig = new LoginConfig("OpenRemote");+ // Make it silent to prevent 401 WWW-Authenticate modal dialog+ deploymentInfo.addAuthenticationMechanism("BASIC-FIX", BasicFixAuthenticationMechanism.FACTORY);+ loginConfig.addFirstAuthMethod(new AuthMethodConfig("BASIC-FIX", Collections.singletonMap("silent", "true")));deploymentInfo.setLoginConfig(loginConfig);deploymentInfo.setIdentityManager(new IdentityManager() {@Overridediff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.javaindex 99f491dee..b854b35ec 100644--- a/container/src/main/java/org/openremote/container/web/WebService.java+++ b/container/src/main/java/org/openremote/container/web/WebService.java@@ -98,7 +98,6 @@ public abstract class WebService implements ContainerService {protected Undertow undertow;protected List<RequestHandler> httpHandlers = new ArrayList<>();protected URI containerHostUri;- protected CORSFilter corsFilter;protected FilterInfo corsFilterInfo;protected static String getLocalIpAddress() throws Exception {@@ -175,7 +174,7 @@ public abstract class WebService implements ContainerService {// This will catch anything not handled by Resteasy/Servlets, such as IOExceptions "at the wrong time"deploymentInfo.setExceptionHandler(new WebServiceExceptions.ServletUndertowExceptionHandler(devMode));-+ // Add CORS filter that works for any servlet deploymentif (corsFilterInfo != null) {deploymentInfo.addFilter(corsFilterInfo);deploymentInfo.addFilterUrlMapping(corsFilterInfo.getName(), "*", DispatcherType.REQUEST);@@ -274,31 +273,31 @@ public abstract class WebService implements ContainerService {return resteasyDeployment;}- protected void createCorsFilter(Container container) {- if (!devMode) {- String allowedOriginsStr = getString(container.getConfig(), WEBSERVER_ALLOWED_ORIGINS, WEBSERVER_ALLOWED_ORIGINS_DEFAULT);- if (allowedOriginsStr != null) {- corsFilter = new CORSFilter();- corsFilter.setAllowCredentials(true);- corsFilter.setAllowedMethods("GET, POST, PUT, DELETE, OPTIONS, HEAD");- corsFilter.setExposedHeaders("*");- corsFilter.setCorsMaxAge(1209600);- String[] allowedOrigins = allowedOriginsStr.split(";");- Arrays.stream(allowedOrigins).forEach(allowedOrigin ->- corsFilter.getAllowedOrigins().add(allowedOrigin)- );- }- } else {- corsFilter = new CORSFilter();- corsFilter.getAllowedOrigins().add("*");+ protected FilterInfo createCorsFilter(Container container) {++ if (corsFilterInfo == null) {++ CORSFilter corsFilter = new CORSFilter();corsFilter.setAllowCredentials(true);- corsFilter.setExposedHeaders("*");corsFilter.setAllowedMethods("GET, POST, PUT, DELETE, OPTIONS, HEAD");+ corsFilter.setExposedHeaders("*");corsFilter.setCorsMaxAge(1209600);- }- if (corsFilter != null) {+ if (!devMode) {+ String allowedOriginsStr = getString(container.getConfig(), WEBSERVER_ALLOWED_ORIGINS, WEBSERVER_ALLOWED_ORIGINS_DEFAULT);+ if (allowedOriginsStr != null) {+ String[] allowedOrigins = allowedOriginsStr.split(";");+ Arrays.stream(allowedOrigins).forEach(allowedOrigin ->+ corsFilter.getAllowedOrigins().add(allowedOrigin)+ );+ }+ } else {+ corsFilter.getAllowedOrigins().add("*");+ }+corsFilterInfo = Servlets.filter("CORS Filter", CORSFilter.class, () -> new ImmediateInstanceHandle<>(corsFilter));}++ return corsFilterInfo;}}diff --git a/deployment/manager/shared/locales/en/or.json b/deployment/manager/shared/locales/en/or.jsonindex 0e0452e8b..eb7cce468 100644--- a/deployment/manager/shared/locales/en/or.json+++ b/deployment/manager/shared/locales/en/or.json@@ -215,11 +215,13 @@"errorOccurred": "An error has occurred","managerError": {"MANAGER_FAILED_TO_LOAD": "Manager failed to load (see console logs)",- "KEYCLOAK_FAILED_TO_LOAD": "Keycloak failed to load (see console logs)",+ "AUTH_FAILED": "Auth failed to load (see console logs)","AUTH_TYPE_UNSUPPORTED": "Requested auth type not supported","CONSOLE_ERROR": "Console error (see console logs)","EVENTS_CONNECTION_ERROR": "Event bus connection error (see console logs)","TRANSLATION_ERROR": "Translations error (see console logs)"},- "couldNotRetrieveAttribute": "Could not retrieve attribute information"+ "couldNotRetrieveAttribute": "Could not retrieve attribute information",+ "submit": "Submit",+ "password": "Password"}diff --git a/gradle.properties b/gradle.propertiesindex 979c2f06e..81b8780fe 100644--- a/gradle.properties+++ b/gradle.properties@@ -8,7 +8,7 @@ javaxPersistenceVersion = 1.0.0.FinaljavaxELVersion = 2.2.6slf4jVersion = 1.7.25guavaVersion = 19.0-undertowVersion = 1.4.12.Final+undertowVersion = 2.1.2.FinalresteasyVersion = 3.0.24.FinalresteasyVersionAsyncHttpServlet = 3.0.19.FinaljbossLoggingAnnotationsVersion = 2.0.2.Finaldiff --git a/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java b/manager/src/main/java/org/openremote/manager/web/ManagerWebService.javaindex 7d6d1a0b0..9f9e2b527 100644--- a/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java+++ b/manager/src/main/java/org/openremote/manager/web/ManagerWebService.java@@ -94,6 +94,7 @@ public class ManagerWebService extends WebService {String defaultApp = getString(container.getConfig(), APP_DEFAULT, APP_DEFAULT_DEFAULT);ResteasyDeployment resteasyDeployment = createResteasyDeployment(container, getApiClasses(), getApiSingletons(), true);+// Serve REST APIHttpHandler apiHandler = createApiHandler(identityService, resteasyDeployment);// Serve JavaScript API