Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Unified x86 Docker images on centos and armhf on raspbian, encapsulated Keycloak identity service

Christian Bauer50bf6ae50b6e
diff --git a/container/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/container/src/main/groovy/org/openremote/test/ContainerTrait.groovy
index 94a452b9a..4c8dda179 100644
--- a/container/src/main/groovy/org/openremote/test/ContainerTrait.groovy
+++ b/container/src/main/groovy/org/openremote/test/ContainerTrait.groovy
@@ -32,6 +32,7 @@ import org.openremote.container.message.MessageBrokerService
import org.openremote.container.message.MessageBrokerSetupService
import org.openremote.container.security.AuthForm
import org.openremote.container.security.IdentityService
+import org.openremote.container.security.keycloak.KeycloakIdentityProvider
import org.openremote.container.web.WebClient
import org.openremote.container.web.WebService
@@ -98,14 +99,14 @@ trait ContainerTrait {
}
static int findEphemeralPort() {
- ServerSocket socket = new ServerSocket(0, 0, Inet4Address.getLocalHost())
+ ServerSocket socket = new ServerSocket(0, 0, Inet4Address.getLoopbackAddress())
int port = socket.getLocalPort()
socket.close()
return port
}
static AccessTokenResponse authenticate(Container container, String realm, String clientId, String username, String password) {
- container.getService(IdentityService.class).getKeycloak()
+ ((KeycloakIdentityProvider)container.getService(IdentityService.class).getIdentityProvider()).getKeycloak()
.getAccessToken(realm, new AuthForm(clientId, username, password))
}
diff --git a/container/src/main/java/org/openremote/container/persistence/EnhancedImportSqlCommandExtractor.java b/container/src/main/java/org/openremote/container/persistence/EnhancedImportSqlCommandExtractor.java
index b292d94aa..bf8ea4ad9 100644
--- a/container/src/main/java/org/openremote/container/persistence/EnhancedImportSqlCommandExtractor.java
+++ b/container/src/main/java/org/openremote/container/persistence/EnhancedImportSqlCommandExtractor.java
@@ -28,9 +28,7 @@ import org.hibernate.tool.hbm2ddl.ImportSqlCommandExtractor;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
-import java.util.Arrays;
import java.util.List;
-import java.util.logging.Logger;
/**
* Load and parse import SQL files, either the whole file as a single statement if its first line
@@ -38,8 +36,6 @@ import java.util.logging.Logger;
*/
public class EnhancedImportSqlCommandExtractor implements ImportSqlCommandExtractor {
- private static final Logger LOG = Logger.getLogger(EnhancedImportSqlCommandExtractor.class.getName());
-
@Override
public String[] extractCommands(Reader reader) {
try {
@@ -65,7 +61,6 @@ public class EnhancedImportSqlCommandExtractor implements ImportSqlCommandExtrac
}
List<String> statementList = parser.getStatementList();
String[] result = statementList.toArray(new String[statementList.size()]);
- LOG.info("Importing multiline SQL: " + Arrays.toString(result));
return result;
}
}
diff --git a/container/src/main/java/org/openremote/container/security/IdentityProvider.java b/container/src/main/java/org/openremote/container/security/IdentityProvider.java
new file mode 100644
index 000000000..4dd8d799f
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/IdentityProvider.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security;
+
+import io.undertow.servlet.api.DeploymentInfo;
+
+/**
+ * SPI for implementations used by {@link IdentityService}.
+ */
+public interface IdentityProvider {
+
+ void start();
+
+ void stop();
+
+ void secureDeployment(DeploymentInfo deploymentInfo);
+}
diff --git a/container/src/main/java/org/openremote/container/security/IdentityService.java b/container/src/main/java/org/openremote/container/security/IdentityService.java
index 40dd07ca2..ed3606168 100644
--- a/container/src/main/java/org/openremote/container/security/IdentityService.java
+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java
@@ -19,43 +19,14 @@
*/
package org.openremote.container.security;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
-import io.undertow.server.handlers.ResponseCodeHandler;
-import io.undertow.server.handlers.proxy.ProxyHandler;
-import io.undertow.server.handlers.proxy.SimpleProxyClientProvider;
-import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
-import org.keycloak.adapters.KeycloakConfigResolver;
-import org.keycloak.adapters.KeycloakDeployment;
-import org.keycloak.adapters.KeycloakDeploymentBuilder;
-import org.keycloak.admin.client.resource.RealmsResource;
-import org.keycloak.common.enums.SslRequired;
-import org.keycloak.representations.adapters.config.AdapterConfig;
-import org.keycloak.representations.idm.ClientRepresentation;
-import org.keycloak.representations.idm.PublishedRealmRepresentation;
-import org.keycloak.representations.idm.RealmRepresentation;
+import io.undertow.servlet.api.DeploymentInfo;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
-import org.openremote.container.web.ProxyWebClientBuilder;
-import org.openremote.container.web.WebClient;
-import org.openremote.container.web.WebService;
-import javax.ws.rs.NotFoundException;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import java.util.logging.Level;
import java.util.logging.Logger;
-import static java.util.concurrent.TimeUnit.MINUTES;
-import static javax.ws.rs.core.Response.Status.Family.REDIRECTION;
-import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL;
import static org.openremote.container.util.MapAccess.*;
-import static org.openremote.container.web.WebClient.getTarget;
public abstract class IdentityService implements ContainerService {
@@ -67,300 +38,49 @@ public abstract class IdentityService implements ContainerService {
public static final String IDENTITY_NETWORK_HOST_DEFAULT = "localhost";
public static final String IDENTITY_NETWORK_WEBSERVER_PORT = "IDENTITY_NETWORK_WEBSERVER_PORT";
public static final int IDENTITY_NETWORK_WEBSERVER_PORT_DEFAULT = 8080;
- public static final String IDENTITY_SESSION_TIMEOUT_SECONDS = "IDENTITY_SESSION_TIMEOUT_SECONDS";
- public static final int IDENTITY_SESSION_TIMEOUT_SECONDS_DEFAULT = 10800; // 3 hours
-
- public static final String KEYCLOAK_HOST = "KEYCLOAK_HOST";
- public static final String KEYCLOAK_HOST_DEFAULT = "localhost";
- public static final String KEYCLOAK_PORT = "KEYCLOAK_PORT";
- public static final int KEYCLOAK_PORT_DEFAULT = 8081;
- public static final String KEYCLOAK_CONNECT_TIMEOUT = "KEYCLOAK_CONNECT_TIMEOUT";
- public static final int KEYCLOAK_CONNECT_TIMEOUT_DEFAULT = 2000;
-
- public static final String KEYCLOAK_REQUEST_TIMEOUT = "KEYCLOAK_REQUEST_TIMEOUT";
- public static final int KEYCLOAK_REQUEST_TIMEOUT_DEFAULT = 10000;
- public static final String KEYCLOAK_CLIENT_POOL_SIZE = "KEYCLOAK_CLIENT_POOL_SIZE";
- public static final int KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT = 20;
// The externally visible address of this installation
protected UriBuilder externalServerUri;
- // Each realm in Keycloak has a client application with this identifier
- final protected String clientId;
-
- // The (internal) URI where Keycloak can be found
- protected UriBuilder keycloakServiceUri;
-
- // The client we use to access Keycloak
- protected Client httpClient;
-
- // Cache Keycloak deployment per realm/client so we don't have to access Keycloak for every token validation
- protected LoadingCache<KeycloakRealmClient, KeycloakDeployment> keycloakDeploymentCache;
-
- // The configuration for the Keycloak servlet extension, looks up the client application per realm
- protected KeycloakConfigResolver keycloakConfigResolver;
-
- // Optional reverse proxy that listens to AUTH_PATH and forwards requests to Keycloak
- protected ProxyHandler authProxyHandler;
-
- // Configuration options for new realms
- protected int sessionTimeoutSeconds;
-
- // This will pass authentication ("NOT ATTEMPTED" state), but later fail any role authorization
- final protected KeycloakDeployment notAuthenticatedKeycloakDeployment = new KeycloakDeployment();
-
- public IdentityService(String clientId) {
- this.clientId = clientId;
- }
-
@Override
public void init(Container container) throws Exception {
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);
- sessionTimeoutSeconds = getInteger(container.getConfig(), IDENTITY_SESSION_TIMEOUT_SECONDS, IDENTITY_SESSION_TIMEOUT_SECONDS_DEFAULT);
externalServerUri = UriBuilder.fromUri("")
.scheme(identityNetworkSecure ? "https" : "http")
.host(identityNetworkHost);
- // Only set the port if it's not the default protocol port. Browsers do this and Keycloak will
- // bake the browsers' redirect URL into the token, so we need a matching config when verifying tokens.
+ // Only set the port if it's not the default protocol port
if (identityNetworkPort != 80 && identityNetworkPort != 443) {
externalServerUri = externalServerUri.port(identityNetworkPort);
}
LOG.info("External system base URL: " + externalServerUri.build());
-
- keycloakServiceUri =
- UriBuilder.fromPath("/")
- .scheme("http")
- .host(getString(container.getConfig(), KEYCLOAK_HOST, KEYCLOAK_HOST_DEFAULT))
- .port(getInteger(container.getConfig(), KEYCLOAK_PORT, KEYCLOAK_PORT_DEFAULT))
- .path(KeycloakResource.KEYCLOAK_CONTEXT_PATH);
-
- LOG.info("Keycloak service URL: " + keycloakServiceUri.build());
-
- // This client sets a custom Host header on outgoing requests, acting like a reverse proxy that "preserves"
- // the Host header. Keycloak will verify token issuer name based on this, so it must match the external host
- // and port that was used to obtain the token.
- ResteasyClientBuilder clientBuilder =
- new ProxyWebClientBuilder(externalServerUri.build().getHost(), externalServerUri.build().getPort())
- .establishConnectionTimeout(
- getInteger(container.getConfig(), KEYCLOAK_CONNECT_TIMEOUT, KEYCLOAK_CONNECT_TIMEOUT_DEFAULT),
- TimeUnit.MILLISECONDS
- )
- .socketTimeout(
- getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT),
- TimeUnit.MILLISECONDS
- )
- .connectionPoolSize(
- getInteger(container.getConfig(), KEYCLOAK_CLIENT_POOL_SIZE, KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT)
- );
-
- httpClient = WebClient.registerDefaults(clientBuilder).build();
-
- keycloakDeploymentCache = createKeycloakDeploymentCache();
-
- keycloakConfigResolver = request -> {
- // The realm we authenticate against must be available as a request header
- String realm = request.getHeader(WebService.REQUEST_HEADER_REALM);
- if (realm == null || realm.length() == 0) {
- LOG.fine("No realm in request, no authentication will be attempted: " + request.getURI());
- return notAuthenticatedKeycloakDeployment;
- }
- KeycloakDeployment keycloakDeployment = getKeycloakDeployment(realm, getClientId());
- if (keycloakDeployment == null) {
- LOG.fine("No Keycloak deployment available for realm, no authentication will be attempted: " + request.getURI());
- return notAuthenticatedKeycloakDeployment;
- }
- return keycloakDeployment;
- };
-
- authProxyHandler = new ProxyHandler(
- new SimpleProxyClientProvider(keycloakServiceUri.clone().replacePath("").build()),
- getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT),
- ResponseCodeHandler.HANDLE_404
- ).setReuseXForwarded(true);
- }
-
- public String getClientId() {
- return clientId;
}
@Override
public void start(Container container) throws Exception {
- // TODO Not a great way to block startup while we wait for other services (Hystrix?)
- waitForKeycloak();
- LOG.info("Keycloak identity provider available: " + keycloakServiceUri.build());
+ getIdentityProvider().start();
}
@Override
public void stop(Container container) throws Exception {
- if (getHttpClient() != null)
- getHttpClient().close();
+ getIdentityProvider().stop();
}
public UriBuilder getExternalServerUri() {
return externalServerUri.clone();
}
- public Client getHttpClient() {
- return httpClient;
- }
-
- public KeycloakConfigResolver getKeycloakConfigResolver() {
- return keycloakConfigResolver;
- }
-
- public void enableAuthProxy(WebService webService) {
- if (authProxyHandler == null)
- throw new IllegalStateException("Initialize this service first");
- LOG.info("Enabling auth reverse proxy (passing requests through to Keycloak) on web context: /" + KeycloakResource.KEYCLOAK_CONTEXT_PATH);
- webService.getPrefixRoutes().put("/" + KeycloakResource.KEYCLOAK_CONTEXT_PATH, authProxyHandler);
- }
-
- public KeycloakResource getKeycloak() {
- return getTarget(getHttpClient(), keycloakServiceUri.build(), null, null, null)
- .proxy(KeycloakResource.class);
- }
-
- /**
- * @param forwardFor Must be the client source address if this is effectively a forwarded request and the
- * access token was obtained by the client (can be null e.g. for Admin CLI calls during setup
- * or tests where the access token was obtained directly). This should not be overloaded because
- * we want to know who is calling this method with "null", as this can lead to subtle runtime
- * problems.
- */
- final public RealmsResource getRealms(String forwardFor, String accessToken) {
- return getTarget(getHttpClient(), keycloakServiceUri.build(), accessToken, forwardFor, forwardFor != null ? externalServerUri.build(): null)
- .proxy(RealmsResource.class);
- }
-
- protected void waitForKeycloak() {
- boolean keycloakAvailable = false;
- while (!keycloakAvailable) {
- LOG.info("Connecting to Keycloak server: " + keycloakServiceUri.build());
- try {
- pingKeycloak();
- keycloakAvailable = true;
- } catch(Exception ex) {
- LOG.info("Keycloak server not available, waiting...");
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
- }
-
- protected void pingKeycloak() throws Exception {
- Response response = null;
- try {
- response = getKeycloak().getWelcomePage();
- if (response != null &&
- (response.getStatusInfo().getFamily() == SUCCESSFUL
- || response.getStatusInfo().getFamily() == REDIRECTION)) {
- return;
- }
- throw new Exception();
- } finally {
- if (response != null)
- response.close();
- }
- }
-
- public KeycloakDeployment getKeycloakDeployment(String realm, String clientId) {
- try {
- return keycloakDeploymentCache.get(new KeycloakRealmClient(realm, clientId));
- } catch (Exception ex) {
- if (ex.getCause() != null && ex.getCause() instanceof NotFoundException) {
- LOG.fine("Client '" + clientId + "' for realm '" + realm + "' not found on identity provider");
- } else {
- LOG.log(
- Level.WARNING,
- "Error loading client '" + clientId + "' for realm '" + realm + "' from identity provider, " +
- "exception from call to identity provider follows",
- ex
- );
- }
- return null;
- }
- }
-
- protected LoadingCache<KeycloakRealmClient, KeycloakDeployment> createKeycloakDeploymentCache() {
- CacheLoader<KeycloakRealmClient, KeycloakDeployment> loader =
- new CacheLoader<KeycloakRealmClient, KeycloakDeployment>() {
- public KeycloakDeployment load(KeycloakRealmClient keycloakRealmClient) {
- LOG.fine("Loading adapter config for client '" + keycloakRealmClient.clientId + "' in realm '" + keycloakRealmClient.realm + "'");
-
- AdapterConfig adapterConfig = getKeycloak().getAdapterConfig(
- keycloakRealmClient.realm, keycloakRealmClient.clientId
- );
-
- // Get the public key for token verification
- PublishedRealmRepresentation realmRepresentation = getKeycloak().getPublishedRealm(keycloakRealmClient.realm);
- adapterConfig.setRealmKey(realmRepresentation.getPublicKeyPem());
-
- // Must rewrite the auth-server URL to our external host and port, which
- // we reverse-proxy back to Keycloak. This is the issuer baked into a token.
- adapterConfig.setAuthServerUrl(
- externalServerUri.clone().replacePath(KeycloakResource.KEYCLOAK_CONTEXT_PATH).build().toString()
- );
-
- // TODO: Some other options should be configurable, e.g. CORS and NotBefore
-
- return KeycloakDeploymentBuilder.build(adapterConfig);
- }
- };
-
- // TODO configurable? Or replace all of this with Observable.cache()?
- return CacheBuilder.newBuilder()
- .maximumSize(500)
- .expireAfterWrite(10, MINUTES)
- .build(loader);
- }
-
- public void configureRealm(RealmRepresentation realmRepresentation, int accessTokenLifespanSeconds) {
- realmRepresentation.setDisplayNameHtml(
- "<span>" + (realmRepresentation.getDisplayName().replaceAll("[^A-Za-z0-9]", "")) + " </span>"
- );
- realmRepresentation.setAccessTokenLifespan(accessTokenLifespanSeconds);
- realmRepresentation.setLoginTheme("openremote");
- realmRepresentation.setAccountTheme("openremote");
- realmRepresentation.setEmailTheme("openremote");
- realmRepresentation.setSsoSessionIdleTimeout(sessionTimeoutSeconds);
-
- realmRepresentation.setSslRequired(SslRequired.NONE.toString());
- }
-
- public ClientRepresentation createClientApplication(String realm, String clientId, String appName, boolean enableDirectAccess) {
- ClientRepresentation client = new ClientRepresentation();
-
- client.setClientId(clientId);
- client.setName(appName);
- client.setPublicClient(true);
-
- if (enableDirectAccess) {
- // We need direct access for integration tests
- LOG.info("### Allowing direct access grants for client app '" + appName + "', this must NOT be used in production! ###");
- client.setDirectAccessGrantsEnabled(true);
- }
-
- List<String> redirectUris = new ArrayList<>();
- addClientRedirectUris(realm, redirectUris);
- client.setRedirectUris(redirectUris);
-
- // Redirect URL for logout etc, go to /<realm>/
- String baseUrl = UriBuilder.fromUri("/").path(realm).build().toString();
- client.setBaseUrl(baseUrl);
-
- return client;
+ public void secureDeployment(DeploymentInfo deploymentInfo) {
+ LOG.info("Securing web deployment: " + deploymentInfo.getContextPath());
+ getIdentityProvider().secureDeployment(deploymentInfo);
}
/**
- * There must be _some_ valid redirect URIs for the application or authentication will not be possible.
+ * To initialize the {@link IdentityProvider}, subclasses should override {@link #init(Container)}.
*/
- abstract protected void addClientRedirectUris(String realm, List<String> redirectUrls);
+ abstract public IdentityProvider getIdentityProvider();
}
\ No newline at end of file
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.java
new file mode 100644
index 000000000..01c2569ce
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/basic/BasicIdentityProvider.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security.basic;
+
+import io.undertow.servlet.api.DeploymentInfo;
+import org.openremote.container.security.IdentityProvider;
+
+// TODO
+public class BasicIdentityProvider implements IdentityProvider{
+
+ @Override
+ public void start() {
+
+ }
+
+ @Override
+ public void stop() {
+
+ }
+
+ @Override
+ public void secureDeployment(DeploymentInfo deploymentInfo) {
+
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/security/AccessTokenAuthContext.java b/container/src/main/java/org/openremote/container/security/keycloak/AccessTokenAuthContext.java
similarity index 94%
rename from container/src/main/java/org/openremote/container/security/AccessTokenAuthContext.java
rename to container/src/main/java/org/openremote/container/security/keycloak/AccessTokenAuthContext.java
index ba9fb9ff8..09f6099f9 100644
--- a/container/src/main/java/org/openremote/container/security/AccessTokenAuthContext.java
+++ b/container/src/main/java/org/openremote/container/security/keycloak/AccessTokenAuthContext.java
@@ -17,9 +17,10 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.container.security;
+package org.openremote.container.security.keycloak;
import org.keycloak.representations.AccessToken;
+import org.openremote.container.security.AuthContext;
/**
* Keycloak-based authorization.
diff --git a/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
new file mode 100644
index 000000000..fb6a33a92
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakIdentityProvider.java
@@ -0,0 +1,351 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.container.security.keycloak;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import io.undertow.server.handlers.ResponseCodeHandler;
+import io.undertow.server.handlers.proxy.ProxyHandler;
+import io.undertow.server.handlers.proxy.SimpleProxyClientProvider;
+import io.undertow.servlet.api.DeploymentInfo;
+import io.undertow.servlet.api.LoginConfig;
+import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
+import org.keycloak.adapters.KeycloakConfigResolver;
+import org.keycloak.adapters.KeycloakDeployment;
+import org.keycloak.adapters.KeycloakDeploymentBuilder;
+import org.keycloak.admin.client.resource.RealmsResource;
+import org.keycloak.common.enums.SslRequired;
+import org.keycloak.representations.adapters.config.AdapterConfig;
+import org.keycloak.representations.idm.ClientRepresentation;
+import org.keycloak.representations.idm.PublishedRealmRepresentation;
+import org.keycloak.representations.idm.RealmRepresentation;
+import org.openremote.container.Container;
+import org.openremote.container.security.AuthOverloadHandler;
+import org.openremote.container.security.IdentityProvider;
+import org.openremote.container.web.ClientRequestInfo;
+import org.openremote.container.web.ProxyWebClientBuilder;
+import org.openremote.container.web.WebClient;
+import org.openremote.container.web.WebService;
+
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import static java.util.concurrent.TimeUnit.MINUTES;
+import static javax.ws.rs.core.Response.Status.Family.REDIRECTION;
+import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL;
+import static org.openremote.container.util.MapAccess.getInteger;
+import static org.openremote.container.util.MapAccess.getString;
+import static org.openremote.container.web.WebClient.getTarget;
+
+public abstract class KeycloakIdentityProvider implements IdentityProvider{
+
+ private static final Logger LOG = Logger.getLogger(KeycloakIdentityProvider.class.getName());
+
+ public static final String KEYCLOAK_HOST = "KEYCLOAK_HOST";
+ public static final String KEYCLOAK_HOST_DEFAULT = "localhost";
+ public static final String KEYCLOAK_PORT = "KEYCLOAK_PORT";
+ public static final int KEYCLOAK_PORT_DEFAULT = 8081;
+ public static final String KEYCLOAK_CONNECT_TIMEOUT = "KEYCLOAK_CONNECT_TIMEOUT";
+ public static final int KEYCLOAK_CONNECT_TIMEOUT_DEFAULT = 2000;
+
+ public static final String KEYCLOAK_REQUEST_TIMEOUT = "KEYCLOAK_REQUEST_TIMEOUT";
+ public static final int KEYCLOAK_REQUEST_TIMEOUT_DEFAULT = 10000;
+ public static final String KEYCLOAK_CLIENT_POOL_SIZE = "KEYCLOAK_CLIENT_POOL_SIZE";
+ public static final int KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT = 20;
+ public static final String KEYCLOAK_SESSION_TIMEOUT_SECONDS = "IDENTITY_SESSION_TIMEOUT_SECONDS";
+ public static final int KEYCLOAK_SESSION_TIMEOUT_SECONDS_DEFAULT = 10800; // 3 hours
+
+ // Each realm in Keycloak has a client application with this identifier
+ final protected String clientId;
+
+ // The externally visible address of this installation
+ final protected UriBuilder externalServerUri;
+
+ // The (internal) URI where Keycloak can be found
+ final protected UriBuilder keycloakServiceUri;
+
+ // The client we use to access Keycloak
+ protected Client httpClient;
+
+ // Cache Keycloak deployment per realm/client so we don't have to access Keycloak for every token validation
+ protected LoadingCache<KeycloakRealmClient, KeycloakDeployment> keycloakDeploymentCache;
+
+ // The configuration for the Keycloak servlet extension, looks up the client application per realm
+ protected KeycloakConfigResolver keycloakConfigResolver;
+
+ // Optional reverse proxy that listens to AUTH_PATH and forwards requests to Keycloak
+ protected ProxyHandler authProxyHandler;
+
+ // Configuration options for new realms
+ final protected int sessionTimeoutSeconds;
+
+ // This will pass authentication ("NOT ATTEMPTED" state), but later fail any role authorization
+ final protected KeycloakDeployment notAuthenticatedKeycloakDeployment = new KeycloakDeployment();
+
+ public KeycloakIdentityProvider(String clientId, UriBuilder externalServerUri, Container container) {
+ this.clientId = clientId;
+ this.externalServerUri = externalServerUri;
+
+ sessionTimeoutSeconds = getInteger(container.getConfig(), KEYCLOAK_SESSION_TIMEOUT_SECONDS, KEYCLOAK_SESSION_TIMEOUT_SECONDS_DEFAULT);
+
+ keycloakServiceUri =
+ UriBuilder.fromPath("/")
+ .scheme("http")
+ .host(getString(container.getConfig(), KEYCLOAK_HOST, KEYCLOAK_HOST_DEFAULT))
+ .port(getInteger(container.getConfig(), KEYCLOAK_PORT, KEYCLOAK_PORT_DEFAULT))
+ .path(KeycloakResource.KEYCLOAK_CONTEXT_PATH);
+
+ LOG.info("Keycloak service URL: " + keycloakServiceUri.build());
+
+ // This client sets a custom Host header on outgoing requests, acting like a reverse proxy that "preserves"
+ // the Host header. Keycloak will verify token issuer name based on this, so it must match the external host
+ // and port that was used to obtain the token.
+ ResteasyClientBuilder clientBuilder =
+ new ProxyWebClientBuilder(externalServerUri.build().getHost(), externalServerUri.build().getPort())
+ .establishConnectionTimeout(
+ getInteger(container.getConfig(), KEYCLOAK_CONNECT_TIMEOUT, KEYCLOAK_CONNECT_TIMEOUT_DEFAULT),
+ TimeUnit.MILLISECONDS
+ )
+ .socketTimeout(
+ getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT),
+ TimeUnit.MILLISECONDS
+ )
+ .connectionPoolSize(
+ getInteger(container.getConfig(), KEYCLOAK_CLIENT_POOL_SIZE, KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT)
+ );
+
+ httpClient = WebClient.registerDefaults(clientBuilder).build();
+
+ keycloakDeploymentCache = createKeycloakDeploymentCache();
+
+ keycloakConfigResolver = request -> {
+ // The realm we authenticate against must be available as a request header
+ String realm = request.getHeader(WebService.REQUEST_HEADER_REALM);
+ if (realm == null || realm.length() == 0) {
+ LOG.fine("No realm in request, no authentication will be attempted: " + request.getURI());
+ return notAuthenticatedKeycloakDeployment;
+ }
+ KeycloakDeployment keycloakDeployment = getKeycloakDeployment(realm, clientId);
+ if (keycloakDeployment == null) {
+ LOG.fine("No Keycloak deployment available for realm, no authentication will be attempted: " + request.getURI());
+ return notAuthenticatedKeycloakDeployment;
+ }
+ return keycloakDeployment;
+ };
+
+ authProxyHandler = new ProxyHandler(
+ new SimpleProxyClientProvider(keycloakServiceUri.clone().replacePath("").build()),
+ getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT),
+ ResponseCodeHandler.HANDLE_404
+ ).setReuseXForwarded(true);
+
+ }
+
+ @Override
+ public void start() {
+ // TODO Not a great way to block startup while we wait for other services (Hystrix?)
+ waitForKeycloak();
+ LOG.info("Keycloak identity provider available: " + keycloakServiceUri.build());
+ }
+
+ @Override
+ public void stop() {
+ if (httpClient != null)
+ httpClient.close();
+ }
+
+ @Override
+ public void secureDeployment(DeploymentInfo deploymentInfo) {
+ deploymentInfo.addOuterHandlerChainWrapper(AuthOverloadHandler::new);
+ deploymentInfo.setSecurityDisabled(false);
+ LoginConfig loginConfig = new LoginConfig(SimpleKeycloakServletExtension.AUTH_MECHANISM, "OpenRemote");
+ deploymentInfo.setLoginConfig(loginConfig);
+ deploymentInfo.addServletExtension(new SimpleKeycloakServletExtension(keycloakConfigResolver));
+ }
+
+ public KeycloakResource getKeycloak() {
+ return getTarget(httpClient, keycloakServiceUri.build(), null, null, null)
+ .proxy(KeycloakResource.class);
+ }
+
+ public RealmsResource getRealms(ClientRequestInfo clientRequestInfo) {
+ return getRealms(clientRequestInfo.getRemoteAddress(), clientRequestInfo.getAccessToken());
+ }
+
+ public RealmsResource getRealms(String accessToken) {
+ return getRealms(null, accessToken);
+ }
+
+ /**
+ * @param forwardFor Must be the client source address if this is effectively a forwarded request and the
+ * access token was obtained by the client (can be null e.g. for Admin CLI calls during setup
+ * or tests where the access token was obtained directly). This should not be overloaded because
+ * we want to know who is calling this method with "null", as this can lead to subtle runtime
+ * problems.
+ */
+ final protected RealmsResource getRealms(String forwardFor, String accessToken) {
+ return getTarget(httpClient, keycloakServiceUri.build(), accessToken, forwardFor, forwardFor != null ? externalServerUri.build(): null)
+ .proxy(RealmsResource.class);
+ }
+
+ public void configureRealm(RealmRepresentation realmRepresentation, int accessTokenLifespanSeconds) {
+ realmRepresentation.setDisplayNameHtml(
+ "<span>" + (realmRepresentation.getDisplayName().replaceAll("[^A-Za-z0-9]", "")) + " </span>"
+ );
+ realmRepresentation.setAccessTokenLifespan(accessTokenLifespanSeconds);
+ realmRepresentation.setLoginTheme("openremote");
+ realmRepresentation.setAccountTheme("openremote");
+ realmRepresentation.setEmailTheme("openremote");
+ realmRepresentation.setSsoSessionIdleTimeout(sessionTimeoutSeconds);
+
+ realmRepresentation.setSslRequired(SslRequired.NONE.toString());
+ }
+
+ protected void waitForKeycloak() {
+ boolean keycloakAvailable = false;
+ while (!keycloakAvailable) {
+ LOG.info("Connecting to Keycloak server: " + keycloakServiceUri.build());
+ try {
+ pingKeycloak();
+ keycloakAvailable = true;
+ } catch(Exception ex) {
+ LOG.info("Keycloak server not available, waiting...");
+ try {
+ Thread.sleep(3000);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+ }
+
+ protected void pingKeycloak() throws Exception {
+ Response response = null;
+ try {
+ response = getKeycloak().getWelcomePage();
+ if (response != null &&
+ (response.getStatusInfo().getFamily() == SUCCESSFUL
+ || response.getStatusInfo().getFamily() == REDIRECTION)) {
+ return;
+ }
+ throw new Exception();
+ } finally {
+ if (response != null)
+ response.close();
+ }
+ }
+
+ public KeycloakDeployment getKeycloakDeployment(String realm, String clientId) {
+ try {
+ return keycloakDeploymentCache.get(new KeycloakRealmClient(realm, clientId));
+ } catch (Exception ex) {
+ if (ex.getCause() != null && ex.getCause() instanceof NotFoundException) {
+ LOG.fine("Client '" + clientId + "' for realm '" + realm + "' not found on identity provider");
+ } else {
+ LOG.log(
+ Level.WARNING,
+ "Error loading client '" + clientId + "' for realm '" + realm + "' from identity provider, " +
+ "exception from call to identity provider follows",
+ ex
+ );
+ }
+ return null;
+ }
+ }
+
+ protected LoadingCache<KeycloakRealmClient, KeycloakDeployment> createKeycloakDeploymentCache() {
+ CacheLoader<KeycloakRealmClient, KeycloakDeployment> loader =
+ new CacheLoader<KeycloakRealmClient, KeycloakDeployment>() {
+ public KeycloakDeployment load(KeycloakRealmClient keycloakRealmClient) {
+ LOG.fine("Loading adapter config for client '" + keycloakRealmClient.clientId + "' in realm '" + keycloakRealmClient.realm + "'");
+
+ AdapterConfig adapterConfig = getKeycloak().getAdapterConfig(
+ keycloakRealmClient.realm, keycloakRealmClient.clientId
+ );
+
+ // Get the public key for token verification
+ PublishedRealmRepresentation realmRepresentation = getKeycloak().getPublishedRealm(keycloakRealmClient.realm);
+ adapterConfig.setRealmKey(realmRepresentation.getPublicKeyPem());
+
+ // Must rewrite the auth-server URL to our external host and port, which
+ // we reverse-proxy back to Keycloak. This is the issuer baked into a token.
+ adapterConfig.setAuthServerUrl(
+ externalServerUri.clone().replacePath(KeycloakResource.KEYCLOAK_CONTEXT_PATH).build().toString()
+ );
+
+ // TODO: Some other options should be configurable, e.g. CORS and NotBefore
+
+ return KeycloakDeploymentBuilder.build(adapterConfig);
+ }
+ };
+
+ // TODO configurable? Or replace all of this with Observable.cache()?
+ return CacheBuilder.newBuilder()
+ .maximumSize(500)
+ .expireAfterWrite(10, MINUTES)
+ .build(loader);
+ }
+
+ protected void enableAuthProxy(WebService webService) {
+ if (authProxyHandler == null)
+ throw new IllegalStateException("Initialize this service first");
+ LOG.info("Enabling auth reverse proxy (passing requests through to Keycloak) on web context: /" + KeycloakResource.KEYCLOAK_CONTEXT_PATH);
+ webService.getPrefixRoutes().put("/" + KeycloakResource.KEYCLOAK_CONTEXT_PATH, authProxyHandler);
+ }
+
+ protected ClientRepresentation createClientApplication(String realm, String clientId, String appName, boolean enableDirectAccess) {
+ ClientRepresentation client = new ClientRepresentation();
+
+ client.setClientId(clientId);
+ client.setName(appName);
+ client.setPublicClient(true);
+
+ if (enableDirectAccess) {
+ // We need direct access for integration tests
+ LOG.info("### Allowing direct access grants for client app '" + appName + "', this must NOT be used in production! ###");
+ client.setDirectAccessGrantsEnabled(true);
+ }
+
+ List<String> redirectUris = new ArrayList<>();
+ addClientRedirectUris(realm, redirectUris);
+ client.setRedirectUris(redirectUris);
+
+ // Redirect URL for logout etc, go to /<realm>/
+ String baseUrl = UriBuilder.fromUri("/").path(realm).build().toString();
+ client.setBaseUrl(baseUrl);
+
+ return client;
+ }
+
+ /**
+ * There must be _some_ valid redirect URIs for the application or authentication will not be possible.
+ */
+ abstract protected void addClientRedirectUris(String realm, List<String> redirectUrls);
+
+}
diff --git a/container/src/main/java/org/openremote/container/security/KeycloakRealmClient.java b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakRealmClient.java
similarity index 96%
rename from container/src/main/java/org/openremote/container/security/KeycloakRealmClient.java
rename to container/src/main/java/org/openremote/container/security/keycloak/KeycloakRealmClient.java
index bd6e194f4..4caa8a4a5 100644
--- a/container/src/main/java/org/openremote/container/security/KeycloakRealmClient.java
+++ b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakRealmClient.java
@@ -17,7 +17,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.container.security;
+package org.openremote.container.security.keycloak;
public class KeycloakRealmClient {
diff --git a/container/src/main/java/org/openremote/container/security/KeycloakResource.java b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakResource.java
similarity index 94%
rename from container/src/main/java/org/openremote/container/security/KeycloakResource.java
rename to container/src/main/java/org/openremote/container/security/keycloak/KeycloakResource.java
index 3eb80b86d..ffc7fcab6 100644
--- a/container/src/main/java/org/openremote/container/security/KeycloakResource.java
+++ b/container/src/main/java/org/openremote/container/security/keycloak/KeycloakResource.java
@@ -17,11 +17,12 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-package org.openremote.container.security;
+package org.openremote.container.security.keycloak;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.adapters.config.AdapterConfig;
import org.keycloak.representations.idm.PublishedRealmRepresentation;
+import org.openremote.container.security.AuthForm;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
diff --git a/container/src/main/java/org/openremote/container/security/SimpleKeycloakServletExtension.java b/container/src/main/java/org/openremote/container/security/keycloak/SimpleKeycloakServletExtension.java
similarity index 99%
rename from container/src/main/java/org/openremote/container/security/SimpleKeycloakServletExtension.java
rename to container/src/main/java/org/openremote/container/security/keycloak/SimpleKeycloakServletExtension.java
index eb05d271f..3475f71c2 100644
--- a/container/src/main/java/org/openremote/container/security/SimpleKeycloakServletExtension.java
+++ b/container/src/main/java/org/openremote/container/security/keycloak/SimpleKeycloakServletExtension.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.openremote.container.security;
+package org.openremote.container.security.keycloak;
import io.undertow.security.api.AuthenticationMechanism;
import io.undertow.security.api.AuthenticationMechanismFactory;
diff --git a/container/src/main/java/org/openremote/container/web/ClientRequestInfo.java b/container/src/main/java/org/openremote/container/web/ClientRequestInfo.java
new file mode 100644
index 000000000..85de208e4
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/ClientRequestInfo.java
@@ -0,0 +1,31 @@
+package org.openremote.container.web;
+
+/**
+ * Details for a client web request, used when forwarding calls through reverse proxy.
+ */
+public class ClientRequestInfo {
+
+ final protected String remoteAddress;
+ final protected String accessToken;
+
+ public ClientRequestInfo(String remoteAddress, String accessToken) {
+ this.remoteAddress = remoteAddress;
+ this.accessToken = accessToken;
+ }
+
+ public String getRemoteAddress() {
+ return remoteAddress;
+ }
+
+ public String getAccessToken() {
+ return accessToken;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "remoteAddress='" + remoteAddress + '\'' +
+ ", authToken='" + accessToken + '\'' +
+ '}';
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
index fe36af6d1..83e6fe62f 100644
--- a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
+++ b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
@@ -29,7 +29,7 @@ import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.openremote.container.message.MessageBrokerSetupService;
-import org.openremote.container.security.AccessTokenAuthContext;
+import org.openremote.container.security.keycloak.AccessTokenAuthContext;
import org.openremote.container.security.IdentityService;
import org.openremote.container.web.socket.WebsocketAdapter;
import org.openremote.container.web.socket.WebsocketCORSFilter;
diff --git a/container/src/main/java/org/openremote/container/web/WebResource.java b/container/src/main/java/org/openremote/container/web/WebResource.java
index 837baf529..34ec68ca9 100644
--- a/container/src/main/java/org/openremote/container/web/WebResource.java
+++ b/container/src/main/java/org/openremote/container/web/WebResource.java
@@ -22,7 +22,7 @@ package org.openremote.container.web;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.openremote.container.Container;
-import org.openremote.container.security.AccessTokenAuthContext;
+import org.openremote.container.security.keycloak.AccessTokenAuthContext;
import org.openremote.container.security.AuthContext;
import javax.servlet.http.HttpServletRequest;
diff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.java
index 3c3da4048..53a8cdc46 100644
--- a/container/src/main/java/org/openremote/container/web/WebService.java
+++ b/container/src/main/java/org/openremote/container/web/WebService.java
@@ -26,21 +26,17 @@ import io.undertow.server.handlers.RequestDumpingHandler;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
-import io.undertow.servlet.api.LoginConfig;
import io.undertow.servlet.api.ServletInfo;
import io.undertow.util.HttpString;
import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import org.jboss.resteasy.spi.ResteasyDeployment;
-import org.keycloak.adapters.KeycloakConfigResolver;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.container.json.JacksonConfig;
import org.openremote.container.json.ModelValueMessageBodyConverter;
-import org.openremote.container.security.AuthOverloadHandler;
import org.openremote.container.security.CORSFilter;
import org.openremote.container.security.IdentityService;
-import org.openremote.container.security.SimpleKeycloakServletExtension;
import org.openremote.container.web.jsapi.JSAPIServlet;
import org.xnio.Options;
@@ -247,8 +243,10 @@ public abstract class WebService implements ContainerService {
.addServlet(restServlet)
.setClassLoader(Container.class.getClassLoader());
- if (identityService != null && identityService.getKeycloakConfigResolver() != null) {
+ if (identityService != null) {
resteasyDeployment.setSecurityEnabled(true);
+ } else {
+ throw new RuntimeException("No identity service deployed, can't enable API security");
}
return addServletDeployment(identityService, deploymentInfo, true);
@@ -292,19 +290,7 @@ public abstract class WebService implements ContainerService {
throw new IllegalStateException(
"No identity service found, make sure " + IdentityService.class.getName() + " is added before this service"
);
-
- KeycloakConfigResolver keycloakConfigResolver = identityService.getKeycloakConfigResolver();
- if (keycloakConfigResolver == null)
- throw new IllegalStateException(
- "No Keycloak config resolver found, make sure " + IdentityService.class.getName() + " is initialized"
- );
-
- LOG.info("Deploying secure web context: " + deploymentInfo.getContextPath());
- deploymentInfo.addOuterHandlerChainWrapper(AuthOverloadHandler::new);
- deploymentInfo.setSecurityDisabled(false);
- LoginConfig loginConfig = new LoginConfig(SimpleKeycloakServletExtension.AUTH_MECHANISM, "OpenRemote");
- deploymentInfo.setLoginConfig(loginConfig);
- deploymentInfo.addServletExtension(new SimpleKeycloakServletExtension(keycloakConfigResolver));
+ identityService.secureDeployment(deploymentInfo);
} else {
LOG.info("Deploying insecure web context: " + deploymentInfo.getContextPath());
}
diff --git a/haproxy/Dockerfile b/haproxy/Dockerfile
index 1a16f3787..de9cc28e6 100644
--- a/haproxy/Dockerfile
+++ b/haproxy/Dockerfile
@@ -1,6 +1,6 @@
FROM centos:7
-RUN yum -y install epel-release && yum -y install rsyslog inotify-tools make gcc pcre-devel openssl-devel readline-devel
+RUN yum update -y && yum -y install epel-release && yum -y install rsyslog inotify-tools make gcc pcre-devel openssl-devel readline-devel && yum clean all
ARG HA_PROXY_MINOR_VERSION=1.7
ARG HA_PROXY_VERSION=1.7.5
diff --git a/haproxy/rpi3.Dockerfile b/haproxy/rpi3.Dockerfile
new file mode 100644
index 000000000..a091e2fd9
--- /dev/null
+++ b/haproxy/rpi3.Dockerfile
@@ -0,0 +1,30 @@
+FROM openremote/rpi-raspbian:latest
+
+ARG ACME_PLUGIN_VERSION=0.1.1
+
+RUN [ "cross-build-start" ]
+
+RUN apt-get update \
+ && apt-get install -y haproxy rsyslog inotify-tools \
+ && rm -rf /var/lib/apt/lists/* \
+ && rm /etc/haproxy/haproxy.cfg
+
+RUN cd /etc/haproxy \
+ && curl -sSL https://github.com/janeczku/haproxy-acme-validation-plugin/archive/${ACME_PLUGIN_VERSION}.tar.gz -o acme-plugin.tar.gz \
+ && tar xvf acme-plugin.tar.gz --strip-components=1 --no-anchored acme-http01-webroot.lua \
+ && rm *.tar.gz && cd
+
+RUN [ "cross-build-end" ]
+
+ADD rsyslog.conf /etc/rsyslog.conf
+ADD haproxy-init.cfg /etc/haproxy/haproxy-init.cfg
+ADD demo /etc/haproxy/demo
+
+VOLUME /etc/letsencrypt
+VOLUME /var/acme-webroot
+
+EXPOSE 80 443
+
+COPY entrypoint.sh /
+RUN chmod +x /entrypoint.sh
+ENTRYPOINT ["/entrypoint.sh"]
\ No newline at end of file
diff --git a/letsencrypt/Dockerfile b/letsencrypt/Dockerfile
index 7d08535c3..472301a85 100644
--- a/letsencrypt/Dockerfile
+++ b/letsencrypt/Dockerfile
@@ -1,7 +1,7 @@
# Adapted from https://github.com/bringnow/docker-letsencrypt-manager
FROM centos:7
-RUN yum -y install epel-release && yum -y install certbot cronie
+RUN yum update -y && yum -y install epel-release && yum -y install certbot cronie && yum clean all
ENV TERM xterm
ENV WEBROOT "/webroot"
diff --git a/manager/Dockerfile b/manager/Dockerfile
index d7001b227..faef0cd08 100644
--- a/manager/Dockerfile
+++ b/manager/Dockerfile
@@ -1,4 +1,7 @@
-FROM openjdk:8
+FROM centos:7
+
+RUN yum update -y && yum -y install java-1.8.0-openjdk-devel && yum clean all
+ENV JAVA_HOME /usr/lib/jvm/java
ENV MANAGER_DOCROOT webapp
ENV CONSOLE_DOCROOT deployment/resources_console
diff --git a/manager/build.gradle b/manager/build.gradle
index 71a647a07..871d0486e 100644
--- a/manager/build.gradle
+++ b/manager/build.gradle
@@ -2,8 +2,9 @@ evaluationDependsOnChildren()
task prepareImage(type: Copy) {
dependsOn resolveTask(":manager:server:installDist"), resolveTask(":manager:client:installDist")
- from "Dockerfile"
+ from "${project.projectDir}"
into "${project.buildDir}/install"
+ include("Dockerfile*")
}
task clean() {
diff --git a/manager/rpi3.Dockerfile b/manager/rpi3.Dockerfile
new file mode 100644
index 000000000..d28f7b157
--- /dev/null
+++ b/manager/rpi3.Dockerfile
@@ -0,0 +1,23 @@
+FROM openremote/rpi-raspbian:latest
+
+ENV LANG C.UTF-8
+
+RUN [ "cross-build-start" ]
+RUN apt-get update && apt-get install -y openjdk-8-jdk-headless --no-install-recommends && rm -rf /var/lib/apt/lists/*
+ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-armhf
+RUN [ "cross-build-end" ]
+
+ENV MANAGER_DOCROOT webapp
+ENV CONSOLE_DOCROOT deployment/resources_console
+ENV LOGGING_CONFIG_FILE deployment/logging.properties
+ENV MAP_TILES_PATH deployment/mapdata.mbtiles
+ENV MAP_SETTINGS_PATH deployment/mapsettings.json
+
+ADD server /opt/app
+ADD client /opt/app
+
+EXPOSE 8080
+
+WORKDIR /opt/app
+
+ENTRYPOINT ["java", "-cp", "/opt/app/lib/*", "org.openremote.manager.server.Main"]
diff --git a/manager/server/src/main/java/org/openremote/manager/server/apps/ConsoleAppService.java b/manager/server/src/main/java/org/openremote/manager/server/apps/ConsoleAppService.java
index 3a24971d0..4686e08fc 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/apps/ConsoleAppService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/apps/ConsoleAppService.java
@@ -64,7 +64,7 @@ public class ConsoleAppService implements ContainerService {
List<ConsoleApp> result = new ArrayList<>();
Files.list(managerWebService.getConsoleDocRoot()).forEach(path -> {
String directoryName = path.getFileName().toString();
- Tenant tenant = identityService.getTenantForRealm(directoryName);
+ Tenant tenant = identityService.getIdentityProvider().getTenantForRealm(directoryName);
if (tenant.isActive(timerService.getCurrentTimeMillis()) && tenant.getDisplayName() != null) {
String appUrl = managerWebService.getConsoleUrl(
identityService.getExternalServerUri(),
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
index 91a484278..d005a28d7 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java
@@ -106,7 +106,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
try {
Tenant tenant = realmId == null || realmId.length() == 0
? getAuthenticatedTenant()
- : identityService.getTenant(realmId);
+ : identityService.getIdentityProvider().getTenantForRealmId(realmId);
if (tenant == null) {
throw new WebApplicationException(NOT_FOUND);
@@ -205,7 +205,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
if (serverAsset == null)
throw new WebApplicationException(NOT_FOUND);
- Tenant tenant = identityService.getTenant(asset.getRealmId());
+ Tenant tenant = identityService.getIdentityProvider().getTenantForRealmId(asset.getRealmId());
if (tenant == null)
throw new WebApplicationException(BAD_REQUEST);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java
index 8fcadf1dc..392eb5de3 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java
@@ -159,7 +159,7 @@ public final class AssetRoute {
}
// Check realm, must be accessible
- if (!identityService.isTenantActiveAndAccessible(authContext, asset)) {
+ if (!identityService.getIdentityProvider().isTenantActiveAndAccessible(authContext, asset)) {
throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
index 00fcc604c..4e85b8671 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java
@@ -107,7 +107,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
(AssetTreeModifiedEvent.TenantFilter) subscription.getFilter();
Tenant authenticatedTenant =
- managerIdentityService.getTenantForRealm(auth.getAuthenticatedRealm());
+ managerIdentityService.getIdentityProvider().getTenantForRealm(auth.getAuthenticatedRealm());
if (authenticatedTenant == null)
return false;
if (filter.getRealmId().equals(authenticatedTenant.getId()))
@@ -303,7 +303,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
// Validate realm
- if (!managerIdentityService.isActiveTenant(asset.getRealmId())) {
+ if (!managerIdentityService.getIdentityProvider().isActiveTenant(asset.getRealmId())) {
throw new IllegalStateException("Realm not found/active: " + asset.getRealmId());
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
index adeabbbee..0427b4574 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
@@ -155,7 +155,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
rulesetStorageService.findEnabledGlobalRulesets().forEach(this::deployGlobalRuleset);
LOG.info("Deploying tenant rulesets");
- activeTenantIds = identityService.getActiveTenantIds();
+ activeTenantIds = identityService.getIdentityProvider().getActiveTenantIds();
rulesetStorageService.findEnabledTenantRulesets()
.stream()
.filter(rd ->
@@ -217,7 +217,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// Check if enabled status has changed
boolean wasEnabled = Arrays.asList(activeTenantIds).contains(tenant.getId());
boolean isEnabled = tenant.getEnabled() && cause != PersistenceEvent.Cause.DELETE;
- activeTenantIds = identityService.getActiveTenantIds();
+ activeTenantIds = identityService.getIdentityProvider().getActiveTenantIds();
if (wasEnabled == isEnabled) {
// Nothing to do here
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesetResourceImpl.java
index 95dc06daa..d04ba9675 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesetResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesetResourceImpl.java
@@ -137,7 +137,7 @@ public class RulesetResourceImpl extends ManagerWebResource implements RulesetRe
@Override
public void createTenantRuleset(@BeanParam RequestParams requestParams, TenantRuleset ruleset) {
- Tenant tenant = identityService.getTenant(ruleset.getRealmId());
+ Tenant tenant = identityService.getIdentityProvider().getTenantForRealmId(ruleset.getRealmId());
if (tenant == null) {
throw new WebApplicationException(BAD_REQUEST);
}
@@ -154,7 +154,7 @@ public class RulesetResourceImpl extends ManagerWebResource implements RulesetRe
if (ruleset == null) {
throw new WebApplicationException(NOT_FOUND);
}
- Tenant tenant = identityService.getTenant(ruleset.getRealmId());
+ Tenant tenant = identityService.getIdentityProvider().getTenantForRealmId(ruleset.getRealmId());
if (tenant == null) {
throw new WebApplicationException(BAD_REQUEST);
}
@@ -171,7 +171,7 @@ public class RulesetResourceImpl extends ManagerWebResource implements RulesetRe
if (existingRuleset == null) {
throw new WebApplicationException(NOT_FOUND);
}
- Tenant tenant = identityService.getTenant(existingRuleset.getRealmId());
+ Tenant tenant = identityService.getIdentityProvider().getTenantForRealmId(existingRuleset.getRealmId());
if (tenant == null) {
throw new WebApplicationException(BAD_REQUEST);
}
@@ -194,7 +194,7 @@ public class RulesetResourceImpl extends ManagerWebResource implements RulesetRe
if (ruleset == null) {
return;
}
- Tenant tenant = identityService.getTenant(ruleset.getRealmId());
+ Tenant tenant = identityService.getIdentityProvider().getTenantForRealmId(ruleset.getRealmId());
if (tenant == null) {
throw new WebApplicationException(BAD_REQUEST);
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityProvider.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityProvider.java
new file mode 100644
index 000000000..66dd4af29
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityProvider.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.server.security;
+
+import org.openremote.container.security.AuthContext;
+import org.openremote.container.security.IdentityProvider;
+import org.openremote.container.web.ClientRequestInfo;
+import org.openremote.manager.shared.security.*;
+import org.openremote.model.asset.Asset;
+
+/**
+ * SPI for implementations used by {@link ManagerIdentityService}, provides CRUD of
+ * {@link User} and {@link Tenant}.
+ */
+public interface ManagerIdentityProvider extends IdentityProvider {
+
+ User[] getUsers(ClientRequestInfo clientRequestInfo, String realm);
+
+ User getUser(ClientRequestInfo clientRequestInfo, String realm, String userId);
+
+ void updateUser(ClientRequestInfo clientRequestInfo, String realm, String userId, User user);
+
+ void createUser(ClientRequestInfo clientRequestInfo, String realm, User user);
+
+ void deleteUser(ClientRequestInfo clientRequestInfo, String realm, String userId);
+
+ void resetPassword(ClientRequestInfo clientRequestInfo, String realm, String userId, Credential credential);
+
+ Role[] getRoles(ClientRequestInfo clientRequestInfo, String realm, String userId);
+
+ void updateRoles(ClientRequestInfo clientRequestInfo, String realm, String userId, Role[] roles);
+
+ boolean isMasterRealmAdmin(ClientRequestInfo clientRequestInfo, String userId);
+
+ Tenant[] getTenants(ClientRequestInfo clientRequestInfo);
+
+ Tenant getTenantForRealm(String realm);
+
+ Tenant getTenantForRealmId(String realmId);
+
+ void updateTenant(ClientRequestInfo clientRequestInfo, String realm, Tenant tenant);
+
+ void createTenant(ClientRequestInfo clientRequestInfo, Tenant tenant);
+
+ void createTenant(ClientRequestInfo clientRequestInfo, Tenant tenant, TenantEmailConfig emailConfig);
+
+ void deleteTenant(ClientRequestInfo clientRequestInfo, String realm);
+
+ boolean isTenantActiveAndAccessible(AuthContext authContext, Tenant tenant);
+
+ boolean isTenantActiveAndAccessible(AuthContext authContext, Asset asset);
+
+ String[] getActiveTenantIds();
+
+ boolean isActiveTenant(String realmId);
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
index 67b59f5c1..c34ee26b9 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java
@@ -19,216 +19,41 @@
*/
package org.openremote.manager.server.security;
-import org.apache.camel.ExchangePattern;
-import org.keycloak.admin.client.resource.ClientResource;
-import org.keycloak.admin.client.resource.ClientsResource;
-import org.keycloak.admin.client.resource.RolesResource;
-import org.keycloak.representations.idm.ClientRepresentation;
-import org.keycloak.representations.idm.RealmRepresentation;
-import org.keycloak.representations.idm.RoleRepresentation;
import org.openremote.container.Container;
-import org.openremote.container.message.MessageBrokerService;
-import org.openremote.container.persistence.PersistenceEvent;
import org.openremote.container.persistence.PersistenceService;
-import org.openremote.container.security.AuthContext;
import org.openremote.container.security.IdentityService;
import org.openremote.container.timer.TimerService;
import org.openremote.container.web.WebService;
-import org.openremote.manager.server.event.ClientEventService;
-import org.openremote.manager.shared.security.ClientRole;
-import org.openremote.manager.shared.security.Tenant;
-import org.openremote.manager.shared.security.TenantEmailConfig;
import org.openremote.manager.shared.security.User;
-import org.openremote.model.Constants;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetTreeModifiedEvent;
-
-import javax.ws.rs.core.UriBuilder;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Logger;
-
-import static org.openremote.model.Constants.*;
-import static org.openremote.manager.server.util.JsonUtil.convert;
public class ManagerIdentityService extends IdentityService {
- private static final Logger LOG = Logger.getLogger(ManagerIdentityService.class.getName());
-
- protected boolean devMode;
- protected TimerService timerService;
protected PersistenceService persistenceService;
- protected MessageBrokerService messageBrokerService;
- protected ClientEventService clientEventService;
-
- public ManagerIdentityService() {
- super(Constants.KEYCLOAK_CLIENT_ID);
- }
+ protected ManagerIdentityProvider identityProvider;
@Override
public void init(Container container) throws Exception {
super.init(container);
- this.devMode = container.isDevMode();
- this.timerService = container.getService(TimerService.class);
this.persistenceService = container.getService(PersistenceService.class);
- this.messageBrokerService = container.getService(MessageBrokerService.class);
- this.clientEventService = container.getService(ClientEventService.class);
-
- enableAuthProxy(container.getService(WebService.class));
container.getService(WebService.class).getApiSingletons().add(
new TenantResourceImpl(container.getService(TimerService.class), this)
);
container.getService(WebService.class).getApiSingletons().add(
- new UserResourceImpl(this)
+ new UserResourceImpl(container.getService(TimerService.class), this)
);
- }
-
- @Override
- protected void addClientRedirectUris(String realm, List<String> redirectUrls) {
- // Callback URL used by Manager web client authentication, any relative path to "ourselves" is fine
- String managerCallbackUrl = UriBuilder.fromUri("/").path(realm).path("*").build().toString();
- redirectUrls.add(managerCallbackUrl);
-
- // Callback URL used by Console web client authentication, any relative path to "ourselves" is fine
- String consoleCallbackUrl = UriBuilder.fromUri("/console/").path(realm).path("*").build().toString();
- redirectUrls.add(consoleCallbackUrl);
- }
-
- public Tenant[] getTenants(String forwardFor, String accessToken) {
- List<RealmRepresentation> realms = getRealms(forwardFor, accessToken).findAll();
-
- // Make sure the master tenant is always on top
- realms.sort((o1, o2) -> {
- if (o1.getRealm().equals(MASTER_REALM))
- return -1;
- if (o2.getRealm().equals(MASTER_REALM))
- return 1;
- return o1.getRealm().compareTo(o2.getRealm());
- });
-
- List<Tenant> tenants = new ArrayList<>();
- for (RealmRepresentation realm : realms) {
- tenants.add(convert(Container.JSON, Tenant.class, realm));
- }
- return tenants.toArray(new Tenant[tenants.size()]);
- }
-
- public Tenant getTenantForRealm(String realm) {
- return persistenceService.doReturningTransaction(em -> {
- List<Tenant> result =
- em.createQuery("select t from Tenant t where t.realm = :realm", Tenant.class)
- .setParameter("realm", realm).getResultList();
- return result.size() > 0 ? result.get(0) : null;
- });
- }
-
- public Tenant getTenant(String realmId) {
- return persistenceService.doReturningTransaction(em -> em.find(Tenant.class, realmId));
- }
-
- public boolean isActiveTenant(String realmId) {
- return persistenceService.doReturningTransaction(em -> {
- Tenant tenant = em.find(Tenant.class, realmId);
- return tenant != null && tenant.isActive(timerService.getCurrentTimeMillis());
- });
- }
-
- public Tenant getAuthenticatedTenant(AuthContext authContext) {
- return getTenantForRealm(authContext.getAuthenticatedRealm());
- }
- /**
- * @return <code>true</code> if the user is the superuser (admin) or if the user is authenticated
- * in the same realm as the tenant and the tenant is active.
- */
- public boolean isTenantActiveAndAccessible(AuthContext authContext, Tenant tenant) {
- return tenant != null && (authContext.isSuperUser()
- || (tenant.isActive(timerService.getCurrentTimeMillis()) && authContext.isRealmAccessibleByUser(tenant.getRealm())));
+ // TODO Configurable provider
+ this.identityProvider = new ManagerKeycloakProvider(getExternalServerUri(), container);
}
- /**
- * @return <code>true</code> if the user is the superuser (admin) or if the user is authenticated
- * in the same realm as the assets' realm and the tenant is active.
- */
- public boolean isTenantActiveAndAccessible(AuthContext authContext, Asset asset) {
- return isTenantActiveAndAccessible(authContext, getTenant(asset.getRealmId()));
- }
-
- public String[] getActiveTenantIds() {
- return persistenceService.doReturningTransaction(entityManager -> {
- @SuppressWarnings("unchecked")
- List<String> results = entityManager.createQuery(
- "select t.id from Tenant t where " +
- "t.enabled = true and (t.notBefore is null or t.notBefore = 0 or to_timestamp(t.notBefore) <= now())"
- ).getResultList();
- return results.toArray(new String[results.size()]);
- });
- }
-
- public void configureRealm(RealmRepresentation realmRepresentation, TenantEmailConfig emailConfig) {
- configureRealm(realmRepresentation, ACCESS_TOKEN_LIFESPAN_SECONDS);
- if (emailConfig != null)
- realmRepresentation.setSmtpServer(emailConfig.asMap());
- }
-
- public void createTenant(String forwardFor, String accessToken, Tenant tenant) throws Exception {
- createTenant(forwardFor, accessToken, tenant, null);
- }
-
- public void createTenant(String forwardFor, String accessToken, Tenant tenant, TenantEmailConfig emailConfig) throws Exception {
- LOG.fine("Create tenant: " + tenant);
- RealmRepresentation realmRepresentation = convert(Container.JSON, RealmRepresentation.class, tenant);
- configureRealm(realmRepresentation, emailConfig);
- getRealms(forwardFor, accessToken).create(realmRepresentation);
- // TODO This is not atomic, write compensation actions
- createClientApplication(forwardFor, accessToken, realmRepresentation.getRealm());
- publishModification(PersistenceEvent.Cause.INSERT, tenant);
- }
-
- public void createClientApplication(String forwardFor, String accessToken, String realm) {
- ClientsResource clientsResource = getRealms(forwardFor, accessToken).realm(realm).clients();
- ClientRepresentation client = createClientApplication(
- realm, KEYCLOAK_CLIENT_ID, "OpenRemote", devMode
- );
- clientsResource.create(client);
- client = clientsResource.findByClientId(client.getClientId()).get(0);
- ClientResource clientResource = clientsResource.get(client.getId());
- addDefaultRoles(clientResource.roles());
- }
-
- public void updateTenant(String forwardFor, String accessToken, String realm, Tenant tenant) throws Exception {
- LOG.fine("Update tenant: " + tenant);
- getRealms(forwardFor, accessToken).realm(realm).update(
- convert(Container.JSON, RealmRepresentation.class, tenant)
- );
- publishModification(PersistenceEvent.Cause.UPDATE, tenant);
- }
-
- public void deleteTenant(String forwardFor, String accessToken, String realm) throws Exception {
- Tenant tenant = getTenantForRealm(realm);
- LOG.fine("Delete tenant: " + realm);
- getRealms(forwardFor, accessToken).realm(realm).remove();
- publishModification(PersistenceEvent.Cause.DELETE, tenant);
+ @Override
+ public ManagerIdentityProvider getIdentityProvider() {
+ return identityProvider;
}
- public void addDefaultRoles(RolesResource rolesResource) {
-
- for (ClientRole clientRole : ClientRole.values()) {
- rolesResource.create(clientRole.getRepresentation());
- }
-
- for (ClientRole clientRole : ClientRole.values()) {
- if (clientRole.getComposites() == null)
- continue;
- List<RoleRepresentation> composites = new ArrayList<>();
- for (ClientRole composite : clientRole.getComposites()) {
- composites.add(rolesResource.get(composite.getValue()).toRepresentation());
- }
- rolesResource.get(clientRole.getValue()).addComposites(composites);
- }
- }
+ // TODO Should all User operations move to ManagerIdentityProvider?
public boolean isRestrictedUser(String userId) {
UserConfiguration userConfiguration = getUserConfiguration(userId);
@@ -241,7 +66,7 @@ public class ManagerIdentityService extends IdentityService {
mergeUserConfiguration(userConfiguration);
}
- public UserConfiguration getUserConfiguration(String userId) {
+ protected UserConfiguration getUserConfiguration(String userId) {
UserConfiguration userConfiguration = persistenceService.doReturningTransaction(em -> em.find(UserConfiguration.class, userId));
if (userConfiguration == null) {
userConfiguration = new UserConfiguration(userId);
@@ -250,7 +75,7 @@ public class ManagerIdentityService extends IdentityService {
return userConfiguration;
}
- public UserConfiguration mergeUserConfiguration(UserConfiguration userConfiguration) {
+ protected UserConfiguration mergeUserConfiguration(UserConfiguration userConfiguration) {
if (userConfiguration.getUserId() == null || userConfiguration.getUserId().length() == 0) {
throw new IllegalArgumentException("User ID must be set on: " + userConfiguration);
}
@@ -264,24 +89,6 @@ public class ManagerIdentityService extends IdentityService {
});
}
- /**
- * Use PERSISTENCE_TOPIC and persistence event
- */
- protected void publishModification(PersistenceEvent.Cause cause, Tenant tenant) {
- PersistenceEvent persistenceEvent = new PersistenceEvent<>(cause, tenant, new String[0], null);
-
- messageBrokerService.getProducerTemplate().sendBodyAndHeader(
- PersistenceEvent.PERSISTENCE_TOPIC,
- ExchangePattern.InOnly,
- persistenceEvent,
- PersistenceEvent.HEADER_ENTITY_TYPE,
- persistenceEvent.getEntity().getClass()
- );
-
- clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), tenant.getId(), null)
- );
- }
@Override
public String toString() {
diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerKeycloakProvider.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerKeycloakProvider.java
new file mode 100644
index 000000000..f967dd2aa
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerKeycloakProvider.java
@@ -0,0 +1,390 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.server.security;
+
+import org.apache.camel.ExchangePattern;
+import org.keycloak.admin.client.resource.ClientResource;
+import org.keycloak.admin.client.resource.ClientsResource;
+import org.keycloak.admin.client.resource.RoleMappingResource;
+import org.keycloak.admin.client.resource.RolesResource;
+import org.keycloak.representations.idm.*;
+import org.openremote.container.Container;
+import org.openremote.container.message.MessageBrokerService;
+import org.openremote.container.persistence.PersistenceEvent;
+import org.openremote.container.persistence.PersistenceService;
+import org.openremote.container.security.AuthContext;
+import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
+import org.openremote.container.timer.TimerService;
+import org.openremote.container.web.ClientRequestInfo;
+import org.openremote.container.web.WebService;
+import org.openremote.manager.server.event.ClientEventService;
+import org.openremote.manager.shared.security.*;
+import org.openremote.model.Constants;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetTreeModifiedEvent;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Logger;
+
+import static org.openremote.manager.server.util.JsonUtil.convert;
+import static org.openremote.model.Constants.*;
+
+public class ManagerKeycloakProvider extends KeycloakIdentityProvider implements ManagerIdentityProvider {
+
+ private static final Logger LOG = Logger.getLogger(ManagerKeycloakProvider.class.getName());
+
+ final boolean devMode;
+ final protected PersistenceService persistenceService;
+ final protected TimerService timerService;
+ final protected MessageBrokerService messageBrokerService;
+ final protected ClientEventService clientEventService;
+
+ public ManagerKeycloakProvider(UriBuilder externalServerUri, Container container) {
+ super(KEYCLOAK_CLIENT_ID, externalServerUri, container);
+
+ this.devMode = container.isDevMode();
+ this.timerService = container.getService(TimerService.class);
+ this.persistenceService = container.getService(PersistenceService.class);
+ this.messageBrokerService = container.getService(MessageBrokerService.class);
+ this.clientEventService = container.getService(ClientEventService.class);
+
+ enableAuthProxy(container.getService(WebService.class));
+ }
+
+ @Override
+ protected void addClientRedirectUris(String realm, List<String> redirectUrls) {
+ // Callback URL used by Manager web client authentication, any relative path to "ourselves" is fine
+ String managerCallbackUrl = UriBuilder.fromUri("/").path(realm).path("*").build().toString();
+ redirectUrls.add(managerCallbackUrl);
+
+ // Callback URL used by Console web client authentication, any relative path to "ourselves" is fine
+ String consoleCallbackUrl = UriBuilder.fromUri("/console/").path(realm).path("*").build().toString();
+ redirectUrls.add(consoleCallbackUrl);
+ }
+
+ @Override
+ public User[] getUsers(ClientRequestInfo clientRequestInfo, String realm) {
+ List<UserRepresentation> userRepresentations =
+ getRealms(clientRequestInfo)
+ .realm(realm).users().search(null, 0, Integer.MAX_VALUE);
+ List<User> users = new ArrayList<>();
+ for (UserRepresentation userRepresentation : userRepresentations) {
+ users.add(convertUser(realm, userRepresentation));
+ }
+ return users.toArray(new User[users.size()]);
+ }
+
+ @Override
+ public User getUser(ClientRequestInfo clientRequestInfo, String realm, String userId) {
+ return convertUser(
+ realm,
+ getRealms(clientRequestInfo)
+ .realm(realm).users().get(userId).toRepresentation()
+ );
+ }
+
+ @Override
+ public void updateUser(ClientRequestInfo clientRequestInfo, String realm, String userId, User user) {
+ getRealms(clientRequestInfo)
+ .realm(realm).users().get(userId).update(
+ convert(Container.JSON, UserRepresentation.class, user)
+ );
+ }
+
+ @Override
+ public void createUser(ClientRequestInfo clientRequestInfo, String realm, User user) {
+ Response response = getRealms(clientRequestInfo)
+ .realm(realm).users().create(
+ convert(Container.JSON, UserRepresentation.class, user)
+ );
+ if (!response.getStatusInfo().equals(Response.Status.CREATED)) {
+ throw new WebApplicationException(
+ Response.status(response.getStatus())
+ .entity(response.getEntity())
+ .build()
+ );
+ }
+ }
+
+ @Override
+ public void deleteUser(ClientRequestInfo clientRequestInfo, String realm, String userId) {
+ Response response = getRealms(clientRequestInfo)
+ .realm(realm).users().delete(userId);
+ if (!response.getStatusInfo().equals(Response.Status.NO_CONTENT)) {
+ throw new WebApplicationException(
+ Response.status(response.getStatus())
+ .entity(response.getEntity())
+ .build()
+ );
+ }
+ }
+
+ @Override
+ public void resetPassword(ClientRequestInfo clientRequestInfo, String realm, String userId, Credential credential) {
+ getRealms(clientRequestInfo)
+ .realm(realm).users().get(userId).resetPassword(
+ convert(Container.JSON, CredentialRepresentation.class, credential)
+ );
+ }
+
+ @Override
+ public Role[] getRoles(ClientRequestInfo clientRequestInfo, String realm, String userId) {
+ RoleMappingResource roleMappingResource = getRealms(clientRequestInfo).realm(realm).users().get(userId).roles();
+ ClientsResource clientsResource = getRealms(clientRequestInfo).realm(realm).clients();
+
+ String clientId = clientsResource.findByClientId(KEYCLOAK_CLIENT_ID).get(0).getId();
+ RolesResource rolesResource = clientsResource.get(clientId).roles();
+
+ List<RoleRepresentation> allRoles = rolesResource.list();
+ List<RoleRepresentation> effectiveRoles = roleMappingResource.clientLevel(clientId).listEffective();
+
+ List<Role> roles = new ArrayList<>();
+ for (RoleRepresentation roleRepresentation : allRoles) {
+ boolean isAssigned = false;
+
+ for (RoleRepresentation effectiveRole : effectiveRoles) {
+ if (effectiveRole.getId().equals(roleRepresentation.getId()))
+ isAssigned = true;
+ }
+
+ roles.add(new Role(
+ roleRepresentation.getId(),
+ roleRepresentation.getName(),
+ roleRepresentation.isComposite(),
+ isAssigned
+ ));
+ }
+
+ return roles.toArray(new Role[roles.size()]);
+ }
+
+ @Override
+ public void updateRoles(ClientRequestInfo clientRequestInfo, String realm, String userId, Role[] roles) {
+ RoleMappingResource roleMappingResource = getRealms(clientRequestInfo).realm(realm).users().get(userId).roles();
+ ClientsResource clientsResource = getRealms(clientRequestInfo).realm(realm).clients();
+
+ String clientId = clientsResource.findByClientId(KEYCLOAK_CLIENT_ID).get(0).getId();
+
+ List<RoleRepresentation> rolesToAdd = new ArrayList<>();
+ List<RoleRepresentation> rolesToRemove = new ArrayList<>();
+
+ for (Role role : roles) {
+ RoleRepresentation roleRepresentation = new RoleRepresentation();
+ roleRepresentation.setId(role.getId());
+ roleRepresentation.setName(role.getName());
+ if (role.isAssigned()) {
+ rolesToAdd.add(roleRepresentation);
+ } else {
+ rolesToRemove.add(roleRepresentation);
+ }
+ }
+
+ roleMappingResource.clientLevel(clientId).add(rolesToAdd);
+ roleMappingResource.clientLevel(clientId).remove(rolesToRemove);
+ }
+
+ @Override
+ public boolean isMasterRealmAdmin(ClientRequestInfo clientRequestInfo, String userId) {
+ List<UserRepresentation> adminUsers =
+ // TODO Why null here in getRealms()?
+ getRealms(null, clientRequestInfo.getAccessToken()).realm(MASTER_REALM)
+ .users().search(MASTER_REALM_ADMIN_USER, null, null);
+ if (adminUsers.size() == 0) {
+ throw new IllegalStateException("Can't load master realm admin user");
+ } else if (adminUsers.size() > 1) {
+ throw new IllegalStateException("Several master realm admin users, this should not be possible.");
+ }
+ return adminUsers.get(0).getId().equals(userId);
+ }
+
+ @Override
+ public Tenant[] getTenants(ClientRequestInfo clientRequestInfo) {
+ List<RealmRepresentation> realms = getRealms(clientRequestInfo).findAll();
+
+ // Make sure the master tenant is always on top
+ realms.sort((o1, o2) -> {
+ if (o1.getRealm().equals(MASTER_REALM))
+ return -1;
+ if (o2.getRealm().equals(MASTER_REALM))
+ return 1;
+ return o1.getRealm().compareTo(o2.getRealm());
+ });
+
+ List<Tenant> tenants = new ArrayList<>();
+ for (RealmRepresentation realm : realms) {
+ tenants.add(convert(Container.JSON, Tenant.class, realm));
+ }
+ return tenants.toArray(new Tenant[tenants.size()]);
+ }
+
+ @Override
+ public Tenant getTenantForRealm(String realm) {
+ return persistenceService.doReturningTransaction(em -> {
+ List<Tenant> result =
+ em.createQuery("select t from Tenant t where t.realm = :realm", Tenant.class)
+ .setParameter("realm", realm).getResultList();
+ return result.size() > 0 ? result.get(0) : null;
+ });
+ }
+
+ @Override
+ public Tenant getTenantForRealmId(String realmId) {
+ return persistenceService.doReturningTransaction(em -> em.find(Tenant.class, realmId));
+ }
+
+ @Override
+ public void updateTenant(ClientRequestInfo clientRequestInfo, String realm, Tenant tenant) {
+ LOG.fine("Update tenant: " + tenant);
+ getRealms(clientRequestInfo).realm(realm).update(
+ convert(Container.JSON, RealmRepresentation.class, tenant)
+ );
+ publishModification(PersistenceEvent.Cause.UPDATE, tenant);
+ }
+
+ @Override
+ public void createTenant(ClientRequestInfo clientRequestInfo, Tenant tenant) {
+ createTenant(clientRequestInfo, tenant, null);
+ }
+
+ @Override
+ public void createTenant(ClientRequestInfo clientRequestInfo, Tenant tenant, TenantEmailConfig emailConfig) {
+ LOG.fine("Create tenant: " + tenant);
+ RealmRepresentation realmRepresentation = convert(Container.JSON, RealmRepresentation.class, tenant);
+ configureRealm(realmRepresentation, emailConfig);
+
+ // TODO This is not atomic, write compensation actions
+ getRealms(clientRequestInfo).create(realmRepresentation);
+ createClientApplication(clientRequestInfo, realmRepresentation.getRealm());
+
+ publishModification(PersistenceEvent.Cause.INSERT, tenant);
+ }
+
+ @Override
+ public void deleteTenant(ClientRequestInfo clientRequestInfo, String realm) {
+ Tenant tenant = getTenantForRealm(realm);
+ if (tenant != null) {
+ LOG.fine("Delete tenant: " + realm);
+ getRealms(clientRequestInfo).realm(realm).remove();
+ publishModification(PersistenceEvent.Cause.DELETE, tenant);
+ }
+ }
+
+ /**
+ * @return <code>true</code> if the user is the superuser (admin) or if the user is authenticated
+ * in the same realm as the tenant and the tenant is active.
+ */
+ @Override
+ public boolean isTenantActiveAndAccessible(AuthContext authContext, Tenant tenant) {
+ return tenant != null && (authContext.isSuperUser()
+ || (tenant.isActive(timerService.getCurrentTimeMillis()) && authContext.isRealmAccessibleByUser(tenant.getRealm())));
+ }
+
+ /**
+ * @return <code>true</code> if the user is the superuser (admin) or if the user is authenticated
+ * in the same realm as the assets' realm and the tenant is active.
+ */
+ @Override
+ public boolean isTenantActiveAndAccessible(AuthContext authContext, Asset asset) {
+ return isTenantActiveAndAccessible(authContext, getTenantForRealmId(asset.getRealmId()));
+ }
+
+ @Override
+ public String[] getActiveTenantIds() {
+ return persistenceService.doReturningTransaction(entityManager -> {
+ @SuppressWarnings("unchecked")
+ List<String> results = entityManager.createQuery(
+ "select t.id from Tenant t where " +
+ "t.enabled = true and (t.notBefore is null or t.notBefore = 0 or to_timestamp(t.notBefore) <= now())"
+ ).getResultList();
+ return results.toArray(new String[results.size()]);
+ });
+ }
+
+ @Override
+ public boolean isActiveTenant(String realmId) {
+ return persistenceService.doReturningTransaction(em -> {
+ Tenant tenant = em.find(Tenant.class, realmId);
+ return tenant != null && tenant.isActive(timerService.getCurrentTimeMillis());
+ });
+ }
+
+
+ public void configureRealm(RealmRepresentation realmRepresentation, TenantEmailConfig emailConfig) {
+ configureRealm(realmRepresentation, Constants.ACCESS_TOKEN_LIFESPAN_SECONDS);
+ if (emailConfig != null)
+ realmRepresentation.setSmtpServer(emailConfig.asMap());
+ }
+
+ public void createClientApplication(ClientRequestInfo clientRequestInfo, String realm) {
+ ClientsResource clientsResource = getRealms(clientRequestInfo).realm(realm).clients();
+ ClientRepresentation client = createClientApplication(
+ realm, KEYCLOAK_CLIENT_ID, "OpenRemote", devMode
+ );
+ clientsResource.create(client);
+ client = clientsResource.findByClientId(client.getClientId()).get(0);
+ ClientResource clientResource = clientsResource.get(client.getId());
+ addDefaultRoles(clientResource.roles());
+ }
+
+ protected void addDefaultRoles(RolesResource rolesResource) {
+
+ for (ClientRole clientRole : ClientRole.values()) {
+ rolesResource.create(clientRole.getRepresentation());
+ }
+
+ for (ClientRole clientRole : ClientRole.values()) {
+ if (clientRole.getComposites() == null)
+ continue;
+ List<RoleRepresentation> composites = new ArrayList<>();
+ for (ClientRole composite : clientRole.getComposites()) {
+ composites.add(rolesResource.get(composite.getValue()).toRepresentation());
+ }
+ rolesResource.get(clientRole.getValue()).addComposites(composites);
+ }
+ }
+
+ protected User convertUser(String realm, UserRepresentation userRepresentation) {
+ User user = convert(Container.JSON, User.class, userRepresentation);
+ user.setRealm(realm);
+ return user;
+ }
+
+ protected void publishModification(PersistenceEvent.Cause cause, Tenant tenant) {
+ // Fire persistence event although we don't use database for Tenant CUD but call Keycloak API
+ PersistenceEvent persistenceEvent = new PersistenceEvent<>(cause, tenant, new String[0], null);
+
+ messageBrokerService.getProducerTemplate().sendBodyAndHeader(
+ PersistenceEvent.PERSISTENCE_TOPIC,
+ ExchangePattern.InOnly,
+ persistenceEvent,
+ PersistenceEvent.HEADER_ENTITY_TYPE,
+ persistenceEvent.getEntity().getClass()
+ );
+
+ clientEventService.publishEvent(
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), tenant.getId(), null)
+ );
+ }
+
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/TenantResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/security/TenantResourceImpl.java
index 971659a77..a4cdac24f 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/security/TenantResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/security/TenantResourceImpl.java
@@ -20,6 +20,7 @@
package org.openremote.manager.server.security;
import org.openremote.container.timer.TimerService;
+import org.openremote.container.web.ClientRequestInfo;
import org.openremote.manager.server.i18n.I18NService;
import org.openremote.manager.server.web.ManagerWebResource;
import org.openremote.manager.shared.http.RequestParams;
@@ -55,7 +56,9 @@ public class TenantResourceImpl extends ManagerWebResource implements TenantReso
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
try {
- return identityService.getTenants(getClientRemoteAddress(), requestParams.getBearerAuth());
+ return identityService.getIdentityProvider().getTenants(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth())
+ );
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (Exception ex) {
@@ -65,7 +68,7 @@ public class TenantResourceImpl extends ManagerWebResource implements TenantReso
@Override
public Tenant get(RequestParams requestParams, String realm) {
- Tenant tenant = identityService.getTenantForRealm(realm);
+ Tenant tenant = identityService.getIdentityProvider().getTenantForRealm(realm);
if (tenant == null)
throw new WebApplicationException(NOT_FOUND);
if (!isTenantActiveAndAccessible(tenant)) {
@@ -77,7 +80,7 @@ public class TenantResourceImpl extends ManagerWebResource implements TenantReso
@Override
public Tenant getForRealmId(RequestParams requestParams, String realmId) {
- Tenant tenant = identityService.getTenant(realmId);
+ Tenant tenant = identityService.getIdentityProvider().getTenantForRealmId(realmId);
if (tenant == null)
throw new WebApplicationException(NOT_FOUND);
if (!isTenantActiveAndAccessible(tenant)) {
@@ -92,7 +95,6 @@ public class TenantResourceImpl extends ManagerWebResource implements TenantReso
if (!isSuperUser()) {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
- // TODO If the realm name changes, what happens to all the assets?
ConstraintViolationReport violationReport;
if ((violationReport = isIllegalMasterRealmMutation(realm, tenant)) != null) {
throw new WebApplicationException(
@@ -103,7 +105,9 @@ public class TenantResourceImpl extends ManagerWebResource implements TenantReso
);
}
try {
- identityService.updateTenant(getClientRemoteAddress(), requestParams.getBearerAuth(), realm, tenant);
+ identityService.getIdentityProvider().updateTenant(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm, tenant
+ );
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (Exception ex) {
@@ -117,7 +121,9 @@ public class TenantResourceImpl extends ManagerWebResource implements TenantReso
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
try {
- identityService.createTenant(getClientRemoteAddress(), requestParams.getBearerAuth(), tenant);
+ identityService.getIdentityProvider().createTenant(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), tenant
+ );
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (Exception ex) {
@@ -141,7 +147,9 @@ public class TenantResourceImpl extends ManagerWebResource implements TenantReso
);
}
try {
- identityService.deleteTenant(getClientRemoteAddress(), requestParams.getBearerAuth(), realm);
+ identityService.getIdentityProvider().deleteTenant(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm
+ );
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (Exception ex) {
diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java
index d1cb2eb49..8c331f016 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java
@@ -19,15 +19,10 @@
*/
package org.openremote.manager.server.security;
-import org.keycloak.admin.client.resource.ClientsResource;
-import org.keycloak.admin.client.resource.RoleMappingResource;
-import org.keycloak.admin.client.resource.RolesResource;
-import org.keycloak.representations.idm.CredentialRepresentation;
-import org.keycloak.representations.idm.RoleRepresentation;
-import org.keycloak.representations.idm.UserRepresentation;
-import org.openremote.container.Container;
-import org.openremote.container.web.WebResource;
+import org.openremote.container.timer.TimerService;
+import org.openremote.container.web.ClientRequestInfo;
import org.openremote.manager.server.i18n.I18NService;
+import org.openremote.manager.server.web.ManagerWebResource;
import org.openremote.manager.shared.http.RequestParams;
import org.openremote.manager.shared.security.Credential;
import org.openremote.manager.shared.security.Role;
@@ -45,16 +40,13 @@ import java.util.List;
import java.util.ResourceBundle;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
-import static org.openremote.manager.server.util.JsonUtil.convert;
import static org.openremote.manager.shared.validation.ConstraintViolationReport.VIOLATION_EXCEPTION_HEADER;
-import static org.openremote.model.Constants.*;
+import static org.openremote.model.Constants.MASTER_REALM;
-public class UserResourceImpl extends WebResource implements UserResource {
+public class UserResourceImpl extends ManagerWebResource implements UserResource {
- protected final ManagerIdentityService identityService;
-
- public UserResourceImpl(ManagerIdentityService identityService) {
- this.identityService = identityService;
+ public UserResourceImpl(TimerService timerService, ManagerIdentityService identityService) {
+ super(timerService, identityService);
}
@Override
@@ -63,14 +55,9 @@ public class UserResourceImpl extends WebResource implements UserResource {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
try {
- List<UserRepresentation> userRepresentations =
- identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
- .realm(realm).users().search(null, 0, Integer.MAX_VALUE);
- List<User> users = new ArrayList<>();
- for (UserRepresentation userRepresentation : userRepresentations) {
- users.add(convertUser(realm, userRepresentation));
- }
- return users.toArray(new User[users.size()]);
+ return identityService.getIdentityProvider().getUsers(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm
+ );
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (Exception ex) {
@@ -84,10 +71,8 @@ public class UserResourceImpl extends WebResource implements UserResource {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
try {
- return convertUser(
- realm,
- identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
- .realm(realm).users().get(userId).toRepresentation()
+ return identityService.getIdentityProvider().getUser(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm, userId
);
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
@@ -111,9 +96,8 @@ public class UserResourceImpl extends WebResource implements UserResource {
);
}
try {
- identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
- .realm(realm).users().get(userId).update(
- convert(Container.JSON, UserRepresentation.class, user)
+ identityService.getIdentityProvider().updateUser(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm, userId, user
);
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
@@ -128,17 +112,9 @@ public class UserResourceImpl extends WebResource implements UserResource {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
try {
- Response response = identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
- .realm(realm).users().create(
- convert(Container.JSON, UserRepresentation.class, user)
+ identityService.getIdentityProvider().createUser(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm, user
);
- if (!response.getStatusInfo().equals(Response.Status.CREATED)) {
- throw new WebApplicationException(
- Response.status(response.getStatus())
- .entity(response.getEntity())
- .build()
- );
- }
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (WebApplicationException ex) {
@@ -163,15 +139,9 @@ public class UserResourceImpl extends WebResource implements UserResource {
);
}
try {
- Response response = identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
- .realm(realm).users().delete(userId);
- if (!response.getStatusInfo().equals(Response.Status.NO_CONTENT)) {
- throw new WebApplicationException(
- Response.status(response.getStatus())
- .entity(response.getEntity())
- .build()
- );
- }
+ identityService.getIdentityProvider().deleteUser(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm, userId
+ );
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (WebApplicationException ex) {
@@ -187,9 +157,8 @@ public class UserResourceImpl extends WebResource implements UserResource {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
try {
- identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
- .realm(realm).users().get(userId).resetPassword(
- convert(Container.JSON, CredentialRepresentation.class, credential)
+ identityService.getIdentityProvider().resetPassword(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm, userId, credential
);
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
@@ -204,37 +173,9 @@ public class UserResourceImpl extends WebResource implements UserResource {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
try {
- RoleMappingResource roleMappingResource =
- identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
- .realm(realm).users().get(userId).roles();
- ClientsResource clientsResource =
- identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
- .realm(realm).clients();
- String clientId = clientsResource.findByClientId(KEYCLOAK_CLIENT_ID).get(0).getId();
- RolesResource rolesResource = clientsResource.get(clientId).roles();
-
- List<RoleRepresentation> allRoles = rolesResource.list();
- List<RoleRepresentation> effectiveRoles = roleMappingResource.clientLevel(clientId).listEffective();
-
- List<Role> roles = new ArrayList<>();
- for (RoleRepresentation roleRepresentation : allRoles) {
- boolean isAssigned = false;
-
- for (RoleRepresentation effectiveRole : effectiveRoles) {
- if (effectiveRole.getId().equals(roleRepresentation.getId()))
- isAssigned = true;
- }
-
- roles.add(new Role(
- roleRepresentation.getId(),
- roleRepresentation.getName(),
- roleRepresentation.isComposite(),
- isAssigned
- ));
- }
-
- return roles.toArray(new Role[roles.size()]);
-
+ return identityService.getIdentityProvider().getRoles(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm, userId
+ );
} catch (ClientErrorException ex) {
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
} catch (Exception ex) {
@@ -248,31 +189,9 @@ public class UserResourceImpl extends WebResource implements UserResource {
throw new WebApplicationException(Response.Status.FORBIDDEN);
}
try {
- RoleMappingResource roleMappingResource =
- identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
- .realm(realm).users().get(userId).roles();
- ClientsResource clientsResource =
- identityService.getRealms(getClientRemoteAddress(), requestParams.getBearerAuth())
- .realm(realm).clients();
- String clientId = clientsResource.findByClientId(KEYCLOAK_CLIENT_ID).get(0).getId();
-
- List<RoleRepresentation> rolesToAdd = new ArrayList<>();
- List<RoleRepresentation> rolesToRemove = new ArrayList<>();
-
- for (Role role : roles) {
- RoleRepresentation roleRepresentation = new RoleRepresentation();
- roleRepresentation.setId(role.getId());
- roleRepresentation.setName(role.getName());
- if (role.isAssigned()) {
- rolesToAdd.add(roleRepresentation);
- } else {
- rolesToRemove.add(roleRepresentation);
- }
- }
-
- roleMappingResource.clientLevel(clientId).add(rolesToAdd);
- roleMappingResource.clientLevel(clientId).remove(rolesToRemove);
-
+ identityService.getIdentityProvider().updateRoles(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), realm, userId, roles
+ );
} catch (ClientErrorException ex) {
ex.printStackTrace(System.out);
throw new WebApplicationException(ex.getCause(), ex.getResponse().getStatus());
@@ -281,19 +200,13 @@ public class UserResourceImpl extends WebResource implements UserResource {
}
}
- protected User convertUser(String realm, UserRepresentation userRepresentation) {
- User user = convert(Container.JSON, User.class, userRepresentation);
- user.setRealm(realm);
- return user;
- }
-
protected ConstraintViolationReport isIllegalMasterAdminUserDeletion(RequestParams requestParams, String realm, String userId) {
if (!realm.equals(MASTER_REALM))
return null;
- UserRepresentation masterAdminUser = getMasterRealmAdminUser(requestParams);
- if (!masterAdminUser.getId().equals(userId))
- return null;
+ if (!identityService.getIdentityProvider().isMasterRealmAdmin(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), userId
+ )) return null;
ResourceBundle validationMessages = getContainer().getService(I18NService.class).getValidationMessages();
List<ConstraintViolation> violations = new ArrayList<>();
@@ -310,9 +223,9 @@ public class UserResourceImpl extends WebResource implements UserResource {
if (!realm.equals(MASTER_REALM))
return null;
- UserRepresentation masterAdminUser = getMasterRealmAdminUser(requestParams);
- if (!masterAdminUser.getId().equals(user.getId()))
- return null;
+ if (!identityService.getIdentityProvider().isMasterRealmAdmin(
+ new ClientRequestInfo(getClientRemoteAddress(), requestParams.getBearerAuth()), user.getId()
+ )) return null;
ResourceBundle validationMessages = getContainer().getService(I18NService.class).getValidationMessages();
@@ -333,16 +246,5 @@ public class UserResourceImpl extends WebResource implements UserResource {
return null;
}
- protected UserRepresentation getMasterRealmAdminUser(RequestParams requestParams) {
- List<UserRepresentation> adminUsers = identityService
- .getRealms(null, requestParams.getBearerAuth()).realm(MASTER_REALM)
- .users().search(MASTER_REALM_ADMIN_USER, null, null);
- if (adminUsers.size() == 0) {
- throw new IllegalStateException("Can't load master realm admin user");
- } else if (adminUsers.size() > 1) {
- throw new IllegalStateException("Several master realm admin users, this should not be possible.");
- }
- return adminUsers.get(0);
- }
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractKeycloakSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractKeycloakSetup.java
index 74a8f4cf7..9fdfd329b 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractKeycloakSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractKeycloakSetup.java
@@ -25,8 +25,8 @@ import org.keycloak.admin.client.resource.UsersResource;
import org.keycloak.representations.idm.ClientRepresentation;
import org.openremote.container.Container;
import org.openremote.container.security.AuthForm;
-import org.openremote.container.util.MapAccess;
import org.openremote.manager.server.security.ManagerIdentityService;
+import org.openremote.manager.server.security.ManagerKeycloakProvider;
import org.openremote.manager.shared.security.TenantEmailConfig;
import static org.openremote.container.util.MapAccess.getBoolean;
@@ -58,6 +58,7 @@ public abstract class AbstractKeycloakSetup implements Setup {
public static final String SETUP_KEYCLOAK_EMAIL_FROM_DEFAULT = "[email protected]";
final protected ManagerIdentityService identityService;
+ final protected ManagerKeycloakProvider keycloakProvider;
final protected SetupService setupService;
final protected String accessToken;
final protected RealmResource masterRealmResource;
@@ -67,17 +68,19 @@ public abstract class AbstractKeycloakSetup implements Setup {
public AbstractKeycloakSetup(Container container) {
this.identityService = container.getService(ManagerIdentityService.class);
+ this.keycloakProvider = ((ManagerKeycloakProvider)identityService.getIdentityProvider());
this.setupService = container.getService(SetupService.class);
+
// Use direct access grant feature of Keycloak Admin CLI to get superuser access token
String demoAdminPassword = container.getConfig().getOrDefault(SETUP_KEYCLOAK_ADMIN_PASSWORD, SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT);
- this.accessToken = identityService.getKeycloak().getAccessToken(
+ this.accessToken = keycloakProvider.getKeycloak().getAccessToken(
MASTER_REALM, new AuthForm(ADMIN_CLI_CLIENT_ID, MASTER_REALM_ADMIN_USER, demoAdminPassword)
).getToken();
- masterRealmResource = identityService.getRealms(null, accessToken).realm(MASTER_REALM);
- masterClientsResource = identityService.getRealms(null, accessToken).realm(MASTER_REALM).clients();
- masterUsersResource = identityService.getRealms(null, accessToken).realm(MASTER_REALM).users();
+ masterRealmResource = keycloakProvider.getRealms(accessToken).realm(MASTER_REALM);
+ masterClientsResource = keycloakProvider.getRealms(accessToken).realm(MASTER_REALM).clients();
+ masterUsersResource = keycloakProvider.getRealms(accessToken).realm(MASTER_REALM).users();
// Configure SMTP
if (container.getConfig().containsKey(SETUP_KEYCLOAK_EMAIL_HOST)) {
@@ -94,6 +97,10 @@ public abstract class AbstractKeycloakSetup implements Setup {
}
}
+ public ManagerKeycloakProvider getKeycloakProvider() {
+ return keycloakProvider;
+ }
+
protected String getClientObjectId(ClientsResource clientsResource) {
return clientsResource.findByClientId(KEYCLOAK_CLIENT_ID)
.stream()
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakCleanSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakCleanSetup.java
index 70eaff1d9..d5cf6f9f8 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakCleanSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakCleanSetup.java
@@ -43,11 +43,11 @@ public class KeycloakCleanSetup extends AbstractKeycloakSetup {
// Delete all realms that are not the master realm
LOG.info("Deleting all non-master realms");
- RealmsResource realmsResource = identityService.getRealms(null, accessToken);
+ RealmsResource realmsResource = keycloakProvider.getRealms(accessToken);
List<RealmRepresentation> realms = realmsResource.findAll();
for (RealmRepresentation realmRepresentation : realms) {
if (!realmRepresentation.getRealm().equals(MASTER_REALM)) {
- identityService.getRealms(null, accessToken).realm(realmRepresentation.getRealm()).remove();
+ keycloakProvider.getRealms(accessToken).realm(realmRepresentation.getRealm()).remove();
}
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java
index 69e06f397..7be67c450 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java
@@ -25,6 +25,7 @@ import org.keycloak.admin.client.resource.UsersResource;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.openremote.container.Container;
+import org.openremote.container.web.ClientRequestInfo;
import org.openremote.manager.server.setup.AbstractKeycloakSetup;
import org.openremote.manager.shared.security.ClientRole;
import org.openremote.manager.shared.security.Tenant;
@@ -62,28 +63,28 @@ public class KeycloakDemoSetup extends AbstractKeycloakSetup {
public void execute() throws Exception {
// Tenants
- masterTenant = identityService.getTenantForRealm(Constants.MASTER_REALM);
+ masterTenant = identityService.getIdentityProvider().getTenantForRealm(Constants.MASTER_REALM);
Tenant customerA = new Tenant();
customerA.setRealm("customerA");
customerA.setDisplayName("Customer A");
customerA.setEnabled(true);
- identityService.createTenant(null, accessToken, customerA, emailConfig);
- customerATenant = identityService.getTenantForRealm(customerA.getRealm());
+ keycloakProvider.createTenant(new ClientRequestInfo(null, accessToken), customerA, emailConfig);
+ customerATenant = keycloakProvider.getTenantForRealm(customerA.getRealm());
Tenant customerB = new Tenant();
customerB.setRealm("customerB");
customerB.setDisplayName("Customer B");
customerB.setEnabled(true);
- identityService.createTenant(null, accessToken, customerB, emailConfig);
- customerBTenant = identityService.getTenantForRealm(customerB.getRealm());
+ keycloakProvider.createTenant(new ClientRequestInfo(null, accessToken), customerB, emailConfig);
+ customerBTenant = keycloakProvider.getTenantForRealm(customerB.getRealm());
Tenant customerC = new Tenant();
customerC.setRealm("customerC");
customerC.setDisplayName("Customer C");
customerC.setEnabled(true);
- identityService.createTenant(null, accessToken, customerC, emailConfig);
- customerCTenant = identityService.getTenantForRealm(customerC.getRealm());
+ keycloakProvider.createTenant(new ClientRequestInfo(null, accessToken), customerC, emailConfig);
+ customerCTenant = keycloakProvider.getTenantForRealm(customerC.getRealm());
// Users
@@ -113,8 +114,8 @@ public class KeycloakDemoSetup extends AbstractKeycloakSetup {
));
LOG.info("Added demo user '" + testuser1.getUsername() + "' with password '" + testuser1Credentials.getValue() + "'");
- UsersResource customerAUsersResource = identityService.getRealms(null, accessToken).realm("customerA").users();
- ClientsResource customerAClientsResource = identityService.getRealms(null, accessToken).realm("customerA").clients();
+ UsersResource customerAUsersResource = keycloakProvider.getRealms(accessToken).realm("customerA").users();
+ ClientsResource customerAClientsResource = keycloakProvider.getRealms(accessToken).realm("customerA").clients();
String customerAClientObjectId = getClientObjectId(customerAClientsResource);
RolesResource customerARolesResource = customerAClientsResource.get(customerAClientObjectId).roles();
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakInitSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakInitSetup.java
index 1edbe6596..67253e76f 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakInitSetup.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakInitSetup.java
@@ -25,6 +25,7 @@ import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.openremote.container.Container;
+import org.openremote.container.web.ClientRequestInfo;
import org.openremote.manager.server.setup.AbstractKeycloakSetup;
import org.openremote.manager.shared.security.ClientRole;
@@ -49,12 +50,12 @@ public class KeycloakInitSetup extends AbstractKeycloakSetup {
masterRealm.setDisplayName("Master");
// Set SMTP server, theme, timeouts, etc.
- identityService.configureRealm(masterRealm, emailConfig);
+ keycloakProvider.configureRealm(masterRealm, emailConfig);
masterRealmResource.update(masterRealm);
// Create our client application with its default roles
- identityService.createClientApplication(null, accessToken, masterRealm.getRealm());
+ keycloakProvider.createClientApplication(new ClientRequestInfo(null, accessToken), masterRealm.getRealm());
// Get the client application ID so we can assign roles to users at the client
// level (we can only check realm _or_ client application roles in @RolesAllowed!)
diff --git a/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java b/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java
index 945d5ff50..506264198 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/web/ManagerWebResource.java
@@ -40,15 +40,15 @@ public class ManagerWebResource extends WebResource {
}
public Tenant getAuthenticatedTenant() {
- return identityService.getTenantForRealm(getAuthenticatedRealm());
+ return identityService.getIdentityProvider().getTenantForRealm(getAuthenticatedRealm());
}
public boolean isTenantActiveAndAccessible(Asset asset) {
- return identityService.isTenantActiveAndAccessible(this, asset);
+ return identityService.getIdentityProvider().isTenantActiveAndAccessible(this, asset);
}
public boolean isTenantActiveAndAccessible(Tenant tenant) {
- return identityService.isTenantActiveAndAccessible(this, tenant);
+ return identityService.getIdentityProvider().isTenantActiveAndAccessible(this, tenant);
}
}
diff --git a/manager/server/src/main/resources/Extensions.sql b/manager/server/src/main/resources/Extensions.sql
new file mode 100644
index 000000000..469c5cbd3
--- /dev/null
+++ b/manager/server/src/main/resources/Extensions.sql
@@ -0,0 +1,3 @@
+create extension if not exists postgis;
+create extension if not exists postgis_topology;
+create extension if not exists fuzzystrmatch;
diff --git a/manager/server/src/main/resources/META-INF/persistence.xml b/manager/server/src/main/resources/META-INF/persistence.xml
index a96383266..81547bf7b 100644
--- a/manager/server/src/main/resources/META-INF/persistence.xml
+++ b/manager/server/src/main/resources/META-INF/persistence.xml
@@ -31,7 +31,11 @@
<property name="hibernate.archive.autodetection" value="none"/>
<property name="hibernate.current_session_context_class" value="thread"/>
<property name="hibernate.hbm2ddl.import_files_sql_extractor" value="org.openremote.container.persistence.EnhancedImportSqlCommandExtractor"/>
- <property name="hibernate.hbm2ddl.import_files" value="GetAssetTreePath.sql, LoadScript.sql"/>
+ <property name="javax.persistence.schema-generation.create-source" value="script-then-metadata"/>
+ <!-- Before the schema is created -->
+ <property name="javax.persistence.schema-generation.create-script-source" value="Extensions.sql"/>
+ <!-- After the schema is created -->
+ <property name="hibernate.hbm2ddl.import_files" value="GetAssetTreePath.sql, Constraints.sql"/>
</properties>
</persistence-unit>
diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/security/UserResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/security/UserResource.java
index 62bf82df3..a53317e85 100644
--- a/manager/shared/src/main/java/org/openremote/manager/shared/security/UserResource.java
+++ b/manager/shared/src/main/java/org/openremote/manager/shared/security/UserResource.java
@@ -28,7 +28,6 @@ import javax.validation.Valid;
import javax.ws.rs.*;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
-import static javax.ws.rs.core.MediaType.TEXT_PLAIN;
/**
* Manage users in realms.
diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
index 5b5b2d88a..4f1c2b79e 100644
--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
@@ -9,6 +9,7 @@ import org.openremote.container.message.MessageBrokerService
import org.openremote.container.message.MessageBrokerSetupService
import org.openremote.container.persistence.PersistenceService
import org.openremote.container.security.IdentityService
+import org.openremote.container.security.keycloak.KeycloakIdentityProvider
import org.openremote.container.timer.TimerService
import org.openremote.manager.server.agent.AgentService
import org.openremote.manager.server.apps.ConsoleAppService
@@ -43,8 +44,8 @@ trait ManagerContainerTrait extends ContainerTrait {
static Map<String, String> defaultConfig(int serverPort) {
[
(WEBSERVER_LISTEN_PORT) : Integer.toString(serverPort),
- (IDENTITY_NETWORK_HOST) : IdentityService.KEYCLOAK_HOST_DEFAULT,
- (IDENTITY_NETWORK_WEBSERVER_PORT) : Integer.toString(IdentityService.KEYCLOAK_PORT_DEFAULT),
+ (IDENTITY_NETWORK_HOST) : KeycloakIdentityProvider.KEYCLOAK_HOST_DEFAULT,
+ (IDENTITY_NETWORK_WEBSERVER_PORT) : Integer.toString(KeycloakIdentityProvider.KEYCLOAK_PORT_DEFAULT),
(SETUP_IMPORT_DEMO_SCENES) : "false",
(SETUP_IMPORT_DEMO_RULES) : "false"
]
diff --git a/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy
index bae4f8e72..9ecb41caa 100644
--- a/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy
@@ -21,7 +21,8 @@ import org.openremote.manager.client.i18n.ManagerMessages
import org.openremote.manager.client.service.EventService
import org.openremote.manager.client.service.RequestServiceImpl
import org.openremote.manager.client.style.WidgetStyle
-import org.openremote.manager.server.security.ManagerIdentityService
+import org.openremote.manager.server.setup.AbstractKeycloakSetup
+import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.shared.http.EntityReader
import org.openremote.manager.shared.security.Tenant
import org.openremote.manager.shared.security.TenantResource
@@ -47,7 +48,7 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainer
given: "The server container is started"
def serverPort = findEphemeralPort()
def container = startContainerNoDemoAssets(defaultConfig(serverPort), defaultServices())
- def identityService = container.getService(ManagerIdentityService.class)
+ def keycloakProvider = container.getService(SetupService.class).getTaskOfType(AbstractKeycloakSetup.class).keycloakProvider
and: "expected results"
def conditions = new PollingConditions(timeout: 10)
@@ -66,7 +67,7 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainer
getString(container.getConfig(), SETUP_KEYCLOAK_ADMIN_PASSWORD, SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT)
).token
}
- def securityService = new ClientSecurityService(identityService.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), accessToken)
+ def securityService = new ClientSecurityService(keycloakProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), accessToken)
and: "A client request service and target"
def constraintViolationReader = new ClientObjectMapper(container.JSON, ConstraintViolationReport.class) as EntityReader<ConstraintViolationReport>
diff --git a/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy
index e23d84333..240f473dc 100644
--- a/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy
@@ -18,7 +18,8 @@ import org.openremote.manager.client.i18n.ManagerMessages
import org.openremote.manager.client.service.EventService
import org.openremote.manager.client.service.RequestServiceImpl
import org.openremote.manager.client.style.WidgetStyle
-import org.openremote.manager.server.security.ManagerIdentityService
+import org.openremote.manager.server.setup.AbstractKeycloakSetup
+import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.shared.http.EntityReader
import org.openremote.manager.shared.security.*
import org.openremote.manager.shared.validation.ConstraintViolationReport
@@ -44,7 +45,7 @@ class AdminUsersActivityTest extends Specification implements ManagerContainerTr
given: "The server container is started"
def serverPort = findEphemeralPort()
def container = startContainerNoDemoAssets(defaultConfig(serverPort), defaultServices())
- def identityService = container.getService(ManagerIdentityService.class)
+ def keycloakProvider = container.getService(SetupService.class).getTaskOfType(AbstractKeycloakSetup.class).keycloakProvider
and: "expected results"
def conditions = new PollingConditions(timeout: 10)
@@ -66,7 +67,7 @@ class AdminUsersActivityTest extends Specification implements ManagerContainerTr
getString(container.getConfig(), SETUP_KEYCLOAK_ADMIN_PASSWORD, SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT)
).token
}
- def securityService = new ClientSecurityService(identityService.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), accessToken)
+ def securityService = new ClientSecurityService(keycloakProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), accessToken)
and: "A client request service and target"
def constraintViolationReader = new ClientObjectMapper(container.JSON, ConstraintViolationReport.class) as EntityReader<ConstraintViolationReport>
diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy
index ab361dcc8..06c0f8470 100644
--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy
@@ -16,6 +16,7 @@ import org.openremote.manager.client.service.RequestServiceImpl
import org.openremote.manager.client.style.WidgetStyle
import org.openremote.manager.server.asset.AssetStorageService
import org.openremote.manager.server.security.ManagerIdentityService
+import org.openremote.manager.server.setup.AbstractKeycloakSetup
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.KeycloakDemoSetup
import org.openremote.manager.server.setup.builtin.ManagerDemoSetup
@@ -45,6 +46,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaine
def serverPort = findEphemeralPort()
def container = startContainer(defaultConfig(serverPort), defaultServices())
def identityService = container.getService(ManagerIdentityService.class)
+ def keycloakProvider = container.getService(SetupService.class).getTaskOfType(AbstractKeycloakSetup.class).keycloakProvider
def assetStorageService = container.getService(AssetStorageService.class)
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
@@ -60,8 +62,8 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaine
getString(container.getConfig(), SETUP_KEYCLOAK_ADMIN_PASSWORD, SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT)
).token
}
- def securityService = new ClientSecurityService(identityService.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), accessToken)
- def currentTenant = identityService.getTenantForRealm(realm)
+ def securityService = new ClientSecurityService(keycloakProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), accessToken)
+ def currentTenant = identityService.identityProvider.getTenantForRealm(realm)
and: "a client request service and target"
def constraintViolationReader = new ClientObjectMapper(container.JSON, ConstraintViolationReport.class) as EntityReader<ConstraintViolationReport>
@@ -217,6 +219,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaine
def serverPort = findEphemeralPort()
def container = startContainer(defaultConfig(serverPort), defaultServices())
def identityService = container.getService(ManagerIdentityService.class)
+ def keycloakProvider = container.getService(SetupService.class).getTaskOfType(AbstractKeycloakSetup.class).keycloakProvider
def assetStorageService = container.getService(AssetStorageService.class)
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
@@ -232,8 +235,8 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaine
"testuser1"
).token
}
- def securityService = new ClientSecurityService(identityService.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), accessToken)
- def currentTenant = identityService.getTenantForRealm(realm)
+ def securityService = new ClientSecurityService(keycloakProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), accessToken)
+ def currentTenant = identityService.identityProvider.getTenantForRealm(realm)
and: "a client request service and target"
def constraintViolationReader = new ClientObjectMapper(container.JSON, ConstraintViolationReport.class) as EntityReader<ConstraintViolationReport>
@@ -395,8 +398,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaine
def serverPort = findEphemeralPort()
def container = startContainer(defaultConfig(serverPort), defaultServices())
def identityService = container.getService(ManagerIdentityService.class)
- def assetStorageService = container.getService(AssetStorageService.class)
- def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
+ def keycloakProvider = container.getService(SetupService.class).getTaskOfType(AbstractKeycloakSetup.class).keycloakProvider
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
and: "An authenticated user and client security service"
@@ -410,8 +412,8 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaine
"testuser3"
).token
}
- def securityService = new ClientSecurityService(identityService.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), accessToken)
- def currentTenant = identityService.getTenantForRealm(realm)
+ def securityService = new ClientSecurityService(keycloakProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID), accessToken)
+ def currentTenant = identityService.identityProvider.getTenantForRealm(realm)
and: "a client request service and target"
def constraintViolationReader = new ClientObjectMapper(container.JSON, ConstraintViolationReport.class) as EntityReader<ConstraintViolationReport>
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
index bb85a121e..c2018ddc6 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
@@ -1,5 +1,6 @@
package org.openremote.test.rules
+import org.openremote.container.web.ClientRequestInfo
import org.openremote.manager.server.rules.RulesService
import org.openremote.manager.server.rules.RulesetStorageService
import org.openremote.manager.server.security.ManagerIdentityService
@@ -209,7 +210,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
def apartment3Engine = rulesService.assetEngines.get(managerDemoSetup.apartment3Id)
def customerATenant = keycloakDemoSetup.customerATenant
customerATenant.setEnabled(false)
- identityService.updateTenant(null, accessToken, customerATenant.getRealm(), customerATenant)
+ identityService.identityProvider.updateTenant(new ClientRequestInfo(null, accessToken), customerATenant.getRealm(), customerATenant)
then: "the tenants rule engine should stop and all asset rule engines in this realm should also stop"
conditions.eventually {
@@ -235,7 +236,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
when: "the disabled tenant is re-enabled"
customerATenant.setEnabled(true)
- identityService.updateTenant(null, accessToken, customerATenant.getRealm(), customerATenant)
+ identityService.identityProvider.updateTenant(new ClientRequestInfo(null, accessToken), customerATenant.getRealm(), customerATenant)
then: "the tenants rule engine should start and all asset rule engines from this realm should also start"
conditions.eventually {
diff --git a/platform/rpi3/README.md b/platform/rpi3/README.md
index 58b12d777..e34fb480e 100644
--- a/platform/rpi3/README.md
+++ b/platform/rpi3/README.md
@@ -13,13 +13,13 @@ DOCKER_MACHINE_NAME=openremote1 \
DOCKER_MACHINE_IP=10.0.0.123 \
WIFI_SSID=MyWifiNetwork \
WIFI_PASSWORD=MyWifiPassword \
-SSH_PUBKEY=$HOME/.ssh/id_dsa.pub \
+SSH_PUBKEY=$HOME/.ssh/id_rsa.pub \
platform/rpi3/machine/openremote-setup.sh
```
Note that `DOCKER_MACHINE_NAME` is used for the name of the Docker Machine configuration on your workstation, as well as the host name of the Raspberry Pi.
-The `DOCKER_MACHINE_IP` should be the IP address you expect your Raspberry Pi to have when it connects to your LAN. We recommend you lease a static IP address to the machine in your LAN router's DHCP setup. If you don't use Wifi, edit the file `build/boot/device-init.yaml` after generation.
+The network setup of the Raspberry Pi will request an IP on interface `wlan0` with DHCP. Make sure your LAN router provides the configured the `DOCKER_MACHINE_IP`. If another IP is assigned, you must edit the generated `config.json` Docker Machine settings. If you don't use Wifi, edit the file `build/boot/device-init.yaml` after generation.
The provided `SSH_PUBKEY` will be the only authorized key for SSH connections to your Raspberry Pi, password authentication is disabled. You can connect with the user `openremote` on port 22 or simply use `docker-machine ssh openremote1`.
@@ -32,10 +32,44 @@ eval $(docker-machine env openremote1)
docker version
```
+TODO: Alternative OS with aarch64 support and better OpenJDK JIT, but currently no Docker CE packages exist: https://github.com/bamarni/pi64
+TODO: Alternative OS: https://project31.github.io/
+
## Customizing Docker authentication
By default a dummy CA and self-signed certificates are generated for the Docker client connection and authentication on the Docker host. The same key is used on the server and client. See the comments in `platform/rpi3/machine/openremote-setup.sh` for customization options.
## Deploying OpenRemote containers
-TBC
\ No newline at end of file
+TODO: This doesn't work yet, still have to write a replacement for Keycloak identity service!
+
+The Docker images for OpenRemote can be build on your x86 workstation with the QEMU emulator for the ARM environment. After building the images, you can export and load them onto the Raspberry Pi.
+
+First build the base image:
+
+```
+docker build -t openremote/rpi-raspbian platform/rpi3/rpi-raspbian
+```
+
+Next build the OpenRemote service images from source with:
+
+```
+./gradlew clean prepareImage
+docker build -t openremote/rpi-haproxy:latest -f haproxy/rpi3.Dockerfile haproxy
+docker build -t openremote/rpi-postgresql:latest -f postgresql/rpi3.Dockerfile postgresql
+docker build -t openremote/rpi-manager:latest -f manager/build/install/rpi3.Dockerfile manager/build/install
+```
+
+Copy them to your Raspberry Pi (replace `openremote1` with your `DOCKER_MACHINE_NAME`):
+
+```
+docker save openremote/rpi-haproxy | (eval $(docker-machine env openremote1) && docker load)
+docker save openremote/rpi-manager | (eval $(docker-machine env openremote1) && docker load)
+docker save openremote/rpi-postgresql | (eval $(docker-machine env openremote1) && docker load)
+```
+
+Deploy the containers, providing the IP/hostname of your Raspberry Pi:
+
+```
+IDENTITY_NETWORK_HOST=10.0.0.123 docker-compose -p openremote -f profile/demo_rpi.yml up
+```
\ No newline at end of file
diff --git a/platform/rpi3/machine/src/config.txt b/platform/rpi3/machine/src/config.txt
new file mode 100644
index 000000000..f0ce74b96
--- /dev/null
+++ b/platform/rpi3/machine/src/config.txt
@@ -0,0 +1,14 @@
+# Enable serial port
+enable_uart=1
+
+# Disable camera
+start_x=0
+
+# Use minimum of GPU memory
+gpu_mem=16
+
+# Use HDMI mode even if no HDMI monitor is detected
+hdmi_force_hotplug=1
+
+# Enable audio
+dtparam=audio=on
diff --git a/platform/rpi3/machine/src/openremote-boot.sh b/platform/rpi3/machine/src/openremote-boot.sh
index 34e269dd4..e112c195f 100755
--- a/platform/rpi3/machine/src/openremote-boot.sh
+++ b/platform/rpi3/machine/src/openremote-boot.sh
@@ -9,7 +9,9 @@ if ! [ $(getent group openremote) ]; then
rm /home/openremote/.bash_prompt
rm /etc/sudoers.d/user-pirate
echo 'openremote ALL=NOPASSWD: ALL' > /etc/sudoers.d/user-openremote
-
+ mkdir -p /data/manager /data/postgresql
+ chown 5432:5432 /data/postgresql
+
if [ -f /boot/openremote-ssh.pub ]; then
echo "Disabling password authentication, using provided SSH public key"
mkdir /home/openremote/.ssh
diff --git a/platform/rpi3/rpi-raspbian/Dockerfile b/platform/rpi3/rpi-raspbian/Dockerfile
new file mode 100755
index 000000000..ebc1efc82
--- /dev/null
+++ b/platform/rpi3/rpi-raspbian/Dockerfile
@@ -0,0 +1,4 @@
+FROM resin/rpi-raspbian:stretch
+
+ENV QEMU_EXECVE 1
+COPY . /usr/bin
diff --git a/platform/rpi3/rpi-raspbian/LICENCE b/platform/rpi3/rpi-raspbian/LICENCE
new file mode 100755
index 000000000..705bf76fb
--- /dev/null
+++ b/platform/rpi3/rpi-raspbian/LICENCE
@@ -0,0 +1,204 @@
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don`t include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2016 Resin, Inc
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/platform/rpi3/rpi-raspbian/cross-build-end b/platform/rpi3/rpi-raspbian/cross-build-end
new file mode 100755
index 000000000..e33bff58c
--- /dev/null
+++ b/platform/rpi3/rpi-raspbian/cross-build-end
@@ -0,0 +1,3 @@
+#!/usr/bin/qemu-arm-static /bin/sh.real
+
+mv /bin/sh.real /bin/sh
diff --git a/platform/rpi3/rpi-raspbian/cross-build-start b/platform/rpi3/rpi-raspbian/cross-build-start
new file mode 100755
index 000000000..8a09176c1
--- /dev/null
+++ b/platform/rpi3/rpi-raspbian/cross-build-start
@@ -0,0 +1,4 @@
+#!/usr/bin/qemu-arm-static /bin/sh
+
+mv /bin/sh /bin/sh.real
+cp /usr/bin/sh-shim /bin/sh
diff --git a/platform/rpi3/rpi-raspbian/qemu-arm-static b/platform/rpi3/rpi-raspbian/qemu-arm-static
new file mode 100755
index 000000000..6264ef917
Binary files /dev/null and b/platform/rpi3/rpi-raspbian/qemu-arm-static differ
diff --git a/platform/rpi3/rpi-raspbian/sh-shim b/platform/rpi3/rpi-raspbian/sh-shim
new file mode 100755
index 000000000..fdb1afcda
--- /dev/null
+++ b/platform/rpi3/rpi-raspbian/sh-shim
@@ -0,0 +1,9 @@
+#!/usr/bin/qemu-arm-static /bin/sh.real
+
+set -o errexit
+
+cp /bin/sh.real /bin/sh
+
+/bin/sh "$@"
+
+cp /usr/bin/sh-shim /bin/sh
diff --git a/postgresql/Dockerfile b/postgresql/Dockerfile
index b9c202e8d..94d7ac13d 100644
--- a/postgresql/Dockerfile
+++ b/postgresql/Dockerfile
@@ -1,28 +1,46 @@
-# Copyright (c) 2014, Docker PostGIS Authors (See AUTHORS)
+FROM centos:7
-# Permission is hereby granted, free of charge, to any person
-# obtaining a copy of this software and associated documentation
-# files (the "Software"), to deal in the Software without
-# restriction, including without limitation the rights to use,
-# copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the
-# Software is furnished to do so, subject to the following
-# conditions:
+ENV CENTOS_VERSION=7 \
+ PG_VERSION=9.6 \
+ PG_VERSION_MINOR=3 \
+ PG_NODOT=96 \
+ POSTGIS_VERSION=23 \
+ GOSU_VERSION=1.10
-# The above copyright notice and this permission notice shall be
-# included in all copies or substantial portions of the Software.
+# Use fixed UID/GID
+RUN groupadd -r postgres --gid=5432 && useradd -N -r -g postgres --uid=5432 postgres
-FROM postgres:9.6.1
+# Install from Postgres website
+RUN cd /tmp && \
+ yum install -y epel-release && \
+ curl -L -o pgdg.rpm https://yum.postgresql.org/${PG_VERSION}/redhat/rhel-${CENTOS_VERSION}-x86_64/pgdg-redhat${PG_NODOT}-${PG_VERSION}-${PG_VERSION_MINOR}.noarch.rpm && \
+ yum localinstall -y pgdg.rpm && \
+ yum upgrade -y && \
+ yum install -y \
+ postgis${POSTGIS_VERSION}_${PG_NODOT} \
+ postgis${POSTGIS_VERSION}_${PG_NODOT}-client \
+ postgis${POSTGIS_VERSION}_${PG_NODOT}-utils \
+ pgrouting_${PG_NODOT} \
+ postgresql${PG_NODOT}-contrib \
+ postgresql${PG_NODOT}-server
-ENV POSTGIS_MAJOR 2.3
+# Need gosu
+RUN curl -L -o /usr/local/bin/gosu https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-amd64 \
+ && chmod +x /usr/local/bin/gosu \
+ && gosu nobody true
-RUN apt-get update \
- && apt-get install -y --no-install-recommends \
- postgresql-$PG_MAJOR-postgis-$POSTGIS_MAJOR \
- postgresql-$PG_MAJOR-postgis-$POSTGIS_MAJOR-scripts \
- && rm -rf /var/lib/apt/lists/*
+# Prepare data directory
+ENV PGDATA /var/lib/postgresql/data/
+RUN mkdir -p "$PGDATA" && chown -R postgres:postgres "$PGDATA"
+VOLUME ${PGDATA}
-ENV POSTGRES_USER postgres
+# Some defaults
+ENV PG_BIN=/usr/pgsql-${PG_VERSION}/bin
+ENV PATH $PATH:$PG_BIN
+ENV LANG en_US.utf8
-ADD scripts /docker-entrypoint-initdb.d/
-RUN chmod +x /docker-entrypoint-initdb.d/*.sh
\ No newline at end of file
+EXPOSE 5432
+
+COPY entrypoint.sh /
+RUN chmod +x /entrypoint.sh
+ENTRYPOINT ["/entrypoint.sh"]
diff --git a/postgresql/entrypoint.sh b/postgresql/entrypoint.sh
new file mode 100644
index 000000000..899fb4126
--- /dev/null
+++ b/postgresql/entrypoint.sh
@@ -0,0 +1,48 @@
+#!/bin/bash
+set -e
+
+DB_NAME=${POSTGRES_DB:-}
+DB_USER=${POSTGRES_USER:-}
+DB_PASS=${POSTGRES_PASSWORD:-}
+
+EXECUTE_SINGLE_COMMAND="gosu postgres ${PG_BIN}/postgres --single -c config_file=${PGDATA}/postgresql.conf -D ${PGDATA}"
+
+# If there is no config file, assume initdb must be called
+if ! [ -f $PGDATA/postgresql.conf ]; then
+ echo "Init database directory (mount a volume on your host to keep data): $PGDATA"
+
+ # Create initial database files
+ gosu postgres ${PG_BIN}/initdb --auth='ident' -E UTF8
+ chown -R postgres:postgres ${PGDATA}
+
+ # Allow IPv4 authenticated remote connections
+ echo "host all all 0.0.0.0/0 md5" >> ${PGDATA}/pg_hba.conf
+ echo "listen_addresses = '0.0.0.0'" >> ${PGDATA}/postgresql.conf
+
+ # Log to stderr
+ sed -i 's/^logging_collector = on/logging_collector = off/g' ${PGDATA}/postgresql.conf
+fi
+
+# If POSTGRES_USER is set, create a superuser with POSTGRES_PASSWORD
+if [ -n "${DB_USER}" ]; then
+ if [ -z "${DB_PASS}" ]; then
+ echo "No password specified for user: \"${DB_USER}\""
+ exit 1
+ fi
+ echo "Creating user \"${DB_USER}\"..."
+ echo "CREATE ROLE ${DB_USER} with superuser login PASSWORD '${DB_PASS}';" | ${EXECUTE_SINGLE_COMMAND} >/dev/null
+fi
+
+# If POSTGRES_DB is set and not 'postgres', create the database and give POSTGRES_USER full access
+if [ -n "${DB_NAME}" ] && [ "${DB_NAME}" != 'postgres' ]; then
+ echo "Creating database \"${DB_NAME}\"..."
+ echo "CREATE DATABASE ${DB_NAME};" | ${EXECUTE_SINGLE_COMMAND} >/dev/null
+
+ if [ -n "${DB_USER}" ]; then
+ echo "Granting access to database \"${DB_NAME}\" for user \"${DB_USER}\"..."
+ echo "GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} to ${DB_USER};" | ${EXECUTE_SINGLE_COMMAND} >/dev/null
+ fi
+fi
+
+echo "Starting database server..."
+gosu postgres ${PG_BIN}/postgres "$@"
\ No newline at end of file
diff --git a/postgresql/rpi3.Dockerfile b/postgresql/rpi3.Dockerfile
new file mode 100644
index 000000000..1c6a5f7ba
--- /dev/null
+++ b/postgresql/rpi3.Dockerfile
@@ -0,0 +1,45 @@
+FROM openremote/rpi-raspbian:latest
+
+ENV PG_VERSION=9.6 \
+ PG_VERSION_INSTALL=9.6* \
+ POSTGIS_VERSION=2.3 \
+ GOSU_VERSION=1.10
+
+RUN [ "cross-build-start" ]
+
+# Use fixed UID/GID
+RUN groupadd -r postgres --gid=5432 && useradd -N -r -g postgres --uid=5432 postgres
+
+# Install from repo
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends postgresql-common \
+ && sed -ri 's/#(create_main_cluster) .*$/\1 = false/' /etc/postgresql-common/createcluster.conf \
+ && apt-get install -y --no-install-recommends \
+ postgresql=$PG_VERSION_INSTALL \
+ postgresql-contrib=$PG_VERSION_INSTALL \
+ postgresql-$PG_VERSION-postgis-$POSTGIS_VERSION \
+ postgresql-$PG_VERSION-postgis-$POSTGIS_VERSION-scripts \
+ && rm -rf /var/lib/apt/lists/*
+
+# Need gosu
+RUN curl -L -o /usr/local/bin/gosu https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-armhf \
+ && chmod +x /usr/local/bin/gosu \
+ && gosu nobody true
+
+RUN [ "cross-build-end" ]
+
+# Prepare data directory
+ENV PGDATA /var/lib/postgresql/data/
+RUN mkdir -p "$PGDATA" && chown -R postgres:postgres "$PGDATA"
+VOLUME ${PGDATA}
+
+# Some defaults
+ENV PG_BIN=/usr/lib/postgresql/${PG_VERSION}/bin
+ENV PATH $PATH:$PG_BIN
+
+EXPOSE 5432
+VOLUME /var/lib/postgresql/data
+
+COPY entrypoint.sh /
+RUN chmod +x /entrypoint.sh
+ENTRYPOINT ["/entrypoint.sh"]
diff --git a/postgresql/scripts/01-init-user.sh b/postgresql/scripts/01-init-user.sh
deleted file mode 100644
index 933991a6e..000000000
--- a/postgresql/scripts/01-init-user.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/bin/bash
-set -e
-psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
- CREATE USER $OPENREMOTE_USERNAME PASSWORD '$OPENREMOTE_PASSWORD';
- GRANT ALL PRIVILEGES ON DATABASE $POSTGRES_DB TO $OPENREMOTE_USERNAME;
-EOSQL
diff --git a/postgresql/scripts/02-init-postgis.sh b/postgresql/scripts/02-init-postgis.sh
deleted file mode 100644
index 0a736421c..000000000
--- a/postgresql/scripts/02-init-postgis.sh
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/bin/bash
-set -e
-psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname="$POSTGRES_DB" <<-EOSQL
- CREATE EXTENSION IF NOT EXISTS postgis;
- CREATE EXTENSION IF NOT EXISTS postgis_topology;
- CREATE EXTENSION IF NOT EXISTS fuzzystrmatch;
- CREATE EXTENSION IF NOT EXISTS postgis_tiger_geocoder;
-EOSQL
diff --git a/profile/demo.yml b/profile/demo.yml
index 8ac325f78..35de05daa 100644
--- a/profile/demo.yml
+++ b/profile/demo.yml
@@ -148,19 +148,17 @@ services:
image: openremote/postgresql:latest
environment:
TZ: Europe/Zurich
- # This is the DBMS superuser and password. You should change this, especially if you
- # expose the DBMS port and make it accessible externally!
- POSTGRES_USER: postgres
- POSTGRES_PASSWORD: CHANGE_ME_DB_SUPERUSER_PASSWORD
- # The database and service connection user, passwords should be changed in production!
+ # Create transient database and user. For production, run this once
+ # with your volume mapping for the data directory, then remove the
+ # variables and restart to preserve the stored data
POSTGRES_DB: openremote
- OPENREMOTE_USERNAME: openremote
- OPENREMOTE_PASSWORD: CHANGE_ME_DB_USER_PASSWORD
+ POSTGRES_USER: openremote
+ POSTGRES_PASSWORD: CHANGE_ME_DB_USER_PASSWORD
# Durable data requires a volume mapping on your Docker host
# volumes:
- # - /path/to/data/on/my/host/postgresql:/var/lib/postgresql/data
+ # - /path/to/data/on/my/host:/var/lib/pgsql/data
# Configure logging of the container
logging:
diff --git a/profile/demo_rpi.yml b/profile/demo_rpi.yml
new file mode 100644
index 000000000..b42660878
--- /dev/null
+++ b/profile/demo_rpi.yml
@@ -0,0 +1,123 @@
+# Demo setup of OpenRemote v3 on Rasperry Pi 3
+#
+# TODO Not finished, doesn't work
+#
+version: '2'
+services:
+
+ # The frontend proxy, terminates SSL/TLS connections and forwards them to the Manager backend.
+ # TODO Document how to install sidecar letsencrypt container for production certificates, with shared volume mapping.
+ haproxy:
+
+ # Use installed or pull the latest image from Docker Hub.
+ image: openremote/rpi-haproxy:latest
+
+ environment:
+
+ # It is important that all services have the same timezone and are time synchronized.
+ # Bearer tokens are only valid for minutes, and authentication fails if Keycloak drifts.
+ TZ: Europe/Zurich
+
+ # This is a demo configuration with a self-signed dummy SSL certificate, baked into the image.
+ HAPROXY_CONFIG: /etc/haproxy/demo/haproxy-demo.cfg
+
+ # This service needs access to other services on the Docker network.
+ links:
+ - manager
+
+ # Expose a public web service mapped to ports on the host.
+ ports:
+ - "80:80"
+ - "443:443"
+
+ # Configure logging of the container
+ logging:
+ options:
+ max-size: 10m
+
+ # The API gateway and Manager web application.
+ manager:
+
+ # Use installed or pull the latest image from Docker Hub.
+ image: openremote/rpi-manager:latest
+
+ environment:
+
+ TZ: Europe/Zurich
+
+ # If developer mode is enabled, all setup tasks will be executed on application startup.
+ # This will clean all data in Keycloak and the Manager database, and then import demo/test
+ # data. Some caching and other runtime performance-optimizations will also be disabled.
+ DEV_MODE: 'false'
+
+ # If you are not running in developer mode, and this is the first time you are starting
+ # the application, you can configure which setup tasks you want to execute. Careful,
+ # these tasks will clean and populate Keycloak and the Manager database with demo data!
+ SETUP_INIT_CLEAN_DATABASE: 'true'
+ SETUP_KEYCLOAK_ADMIN_PASSWORD: secret
+ SETUP_IMPORT_DEMO_USERS: 'true'
+ SETUP_IMPORT_DEMO_ASSETS: 'true'
+ SETUP_IMPORT_DEMO_RULES: 'true'
+
+ # The public host name of this OpenRemote installation. This name is used in bearer tokens
+ # and must be the name you access the web services under.
+ IDENTITY_NETWORK_HOST: localhost
+
+ # Set if SSL is enabled on the frontend reverse proxy and all internal proxies should assume https
+ IDENTITY_NETWORK_SECURE: 'true'
+
+ # The public port of this OpenRemote installation.
+ IDENTITY_NETWORK_WEBSERVER_PORT: 443
+
+ # The service-internal JDBC connection URL for the database service.
+ DATABASE_CONNECTION_URL: jdbc:postgresql://postgresql/openremote
+
+ # The database connection settings, passwords should be changed in production!
+ DATABASE_USERNAME: openremote
+ DATABASE_PASSWORD: CHANGE_ME_DB_USER_PASSWORD
+ DATABASE_MIN_POOL_SIZE: 5
+ DATABASE_MAX_POOL_SIZE: 20
+ DATABASE_CONNECTION_TIMEOUT_SECONDS: 300
+
+ # The service-internal host name and port of the identity provider.
+ KEYCLOAK_HOST: keycloak
+ KEYCLOAK_PORT: 8080
+
+ # Optional: Console applications can register for push notifications through FCM.
+ # NOTIFICATION_FIREBASE_URL: https://fcm.googleapis.com/fcm/send
+ # NOTIFICATION_FIREBASE_API_KEY = '...'
+
+ # Optional: Override built-in logging.properties with a file of your choice
+ # LOGGING_CONFIG_FILE: /my/manager/logging.properties
+
+ # This service needs access to other services on the Docker network.
+ links:
+ - postgresql
+# TODO Replace keycloak service
+# - keycloak
+
+ # Configure logging of the container, see config/logging.properties
+ logging:
+ options:
+ max-size: 10m
+
+ # PostgreSQL DBMS
+ postgresql:
+ image: openremote/rpi-postgresql:latest
+ environment:
+ TZ: Europe/Zurich
+
+ # Create transient database and user. For production, run this once
+ # with your volume mapping, then remove the variables and restart
+ POSTGRES_DB: openremote
+ POSTGRES_USER: openremote
+ POSTGRES_PASSWORD: CHANGE_ME_DB_USER_PASSWORD
+
+ # Durable data requires a volume mapping on your Docker host
+ # volumes:
+ # - /path/to/data/on/my/host:/var/lib/pgsql/data
+
+ # Configure logging of the container
+ logging:
+ options:
+ max-size: 10m
diff --git a/profile/postgresql_dev.yml b/profile/postgresql_dev.yml
index 775f4f60c..17c48447b 100644
--- a/profile/postgresql_dev.yml
+++ b/profile/postgresql_dev.yml
@@ -9,11 +9,9 @@ services:
context: ../postgresql
environment:
TZ: Europe/Zurich
- # This is the database superuser
- POSTGRES_PASSWORD: CHANGE_ME_DB_SUPERUSER_PASSWORD
- # Create default database when started (see scripts)
+ # Create transient database and user
POSTGRES_DB: openremote
- OPENREMOTE_USERNAME: openremote
- OPENREMOTE_PASSWORD: CHANGE_ME_DB_USER_PASSWORD
+ POSTGRES_USER: openremote
+ POSTGRES_PASSWORD: CHANGE_ME_DB_USER_PASSWORD
ports:
- "5432:5432"
\ No newline at end of file