]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/internal/runtime/InitUtils.java
Introduce CMS UX
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / runtime / InitUtils.java
1 package org.argeo.cms.internal.runtime;
2
3 import static org.argeo.cms.internal.runtime.KernelUtils.getFrameworkProp;
4
5 import java.io.File;
6 import java.io.FileFilter;
7 import java.io.IOException;
8 import java.io.Reader;
9 import java.net.InetAddress;
10 import java.net.URI;
11 import java.nio.charset.StandardCharsets;
12 import java.nio.file.Files;
13 import java.nio.file.Path;
14 import java.security.KeyStore;
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.Dictionary;
18 import java.util.Hashtable;
19 import java.util.List;
20
21 import javax.security.auth.x500.X500Principal;
22
23 import org.apache.commons.io.FileUtils;
24 import org.argeo.api.cms.CmsConstants;
25 import org.argeo.api.cms.CmsLog;
26 import org.argeo.cms.internal.http.InternalHttpConstants;
27 import org.argeo.osgi.useradmin.UserAdminConf;
28
29 /**
30 * Interprets framework properties in order to generate the initial deploy
31 * configuration.
32 */
33 public class InitUtils {
34 private final static CmsLog log = CmsLog.getLog(InitUtils.class);
35
36 /** Override the provided config with the framework properties */
37 public static Dictionary<String, Object> getHttpServerConfig(Dictionary<String, Object> provided) {
38 String httpPort = getFrameworkProp("org.osgi.service.http.port");
39 String httpsPort = getFrameworkProp("org.osgi.service.http.port.secure");
40 /// TODO make it more generic
41 String httpHost = getFrameworkProp(
42 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.HTTP_HOST);
43 String httpsHost = getFrameworkProp(
44 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.HTTPS_HOST);
45 String webSocketEnabled = getFrameworkProp(
46 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.WEBSOCKET_ENABLED);
47
48 final Hashtable<String, Object> props = new Hashtable<String, Object>();
49 // try {
50 if (httpPort != null || httpsPort != null) {
51 boolean httpEnabled = httpPort != null;
52 props.put(InternalHttpConstants.HTTP_ENABLED, httpEnabled);
53 boolean httpsEnabled = httpsPort != null;
54 props.put(InternalHttpConstants.HTTPS_ENABLED, httpsEnabled);
55
56 if (httpEnabled) {
57 props.put(InternalHttpConstants.HTTP_PORT, httpPort);
58 if (httpHost != null)
59 props.put(InternalHttpConstants.HTTP_HOST, httpHost);
60 }
61
62 if (httpsEnabled) {
63 props.put(InternalHttpConstants.HTTPS_PORT, httpsPort);
64 if (httpsHost != null)
65 props.put(InternalHttpConstants.HTTPS_HOST, httpsHost);
66
67 // server certificate
68 Path keyStorePath = KernelUtils.getOsgiInstancePath(KernelConstants.DEFAULT_KEYSTORE_PATH);
69 Path pemKeyPath = KernelUtils.getOsgiInstancePath(KernelConstants.DEFAULT_PEM_KEY_PATH);
70 Path pemCertPath = KernelUtils.getOsgiInstancePath(KernelConstants.DEFAULT_PEM_CERT_PATH);
71 String keyStorePasswordStr = getFrameworkProp(
72 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.SSL_PASSWORD);
73 char[] keyStorePassword;
74 if (keyStorePasswordStr == null)
75 keyStorePassword = "changeit".toCharArray();
76 else
77 keyStorePassword = keyStorePasswordStr.toCharArray();
78
79 // if PEM files both exists, update the PKCS12 file
80 if (Files.exists(pemCertPath) && Files.exists(pemKeyPath)) {
81 // TODO check certificate update time? monitor changes?
82 KeyStore keyStore = PkiUtils.getKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
83 try (Reader key = Files.newBufferedReader(pemKeyPath, StandardCharsets.US_ASCII);
84 Reader cert = Files.newBufferedReader(pemCertPath, StandardCharsets.US_ASCII);) {
85 PkiUtils.loadPem(keyStore, key, keyStorePassword, cert);
86 PkiUtils.saveKeyStore(keyStorePath, keyStorePassword, keyStore);
87 if (log.isDebugEnabled())
88 log.debug("PEM certificate stored in " + keyStorePath);
89 } catch (IOException e) {
90 log.error("Cannot read PEM files " + pemKeyPath + " and " + pemCertPath, e);
91 }
92 }
93
94 if (!Files.exists(keyStorePath))
95 createSelfSignedKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
96 props.put(InternalHttpConstants.SSL_KEYSTORETYPE, PkiUtils.PKCS12);
97 props.put(InternalHttpConstants.SSL_KEYSTORE, keyStorePath.toString());
98 props.put(InternalHttpConstants.SSL_PASSWORD, new String(keyStorePassword));
99
100 // props.put(InternalHttpConstants.SSL_KEYSTORETYPE, "PKCS11");
101 // props.put(InternalHttpConstants.SSL_KEYSTORE, "../../nssdb");
102 // props.put(InternalHttpConstants.SSL_PASSWORD, keyStorePassword);
103
104 // client certificate authentication
105 String wantClientAuth = getFrameworkProp(
106 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.SSL_WANTCLIENTAUTH);
107 if (wantClientAuth != null)
108 props.put(InternalHttpConstants.SSL_WANTCLIENTAUTH, Boolean.parseBoolean(wantClientAuth));
109 String needClientAuth = getFrameworkProp(
110 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.SSL_NEEDCLIENTAUTH);
111 if (needClientAuth != null)
112 props.put(InternalHttpConstants.SSL_NEEDCLIENTAUTH, Boolean.parseBoolean(needClientAuth));
113 }
114
115 // web socket
116 if (webSocketEnabled != null && webSocketEnabled.equals("true"))
117 props.put(InternalHttpConstants.WEBSOCKET_ENABLED, true);
118
119 props.put(CmsConstants.CN, CmsConstants.DEFAULT);
120 }
121 return props;
122 }
123
124 public static List<Dictionary<String, Object>> getUserDirectoryConfigs() {
125 List<Dictionary<String, Object>> res = new ArrayList<>();
126 File nodeBaseDir = KernelUtils.getOsgiInstancePath(KernelConstants.DIR_NODE).toFile();
127 List<String> uris = new ArrayList<>();
128
129 // node roles
130 String nodeRolesUri = getFrameworkProp(CmsConstants.ROLES_URI);
131 String baseNodeRoleDn = CmsConstants.ROLES_BASEDN;
132 if (nodeRolesUri == null) {
133 nodeRolesUri = baseNodeRoleDn + ".ldif";
134 File nodeRolesFile = new File(nodeBaseDir, nodeRolesUri);
135 if (!nodeRolesFile.exists())
136 try {
137 FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(baseNodeRoleDn + ".ldif"),
138 nodeRolesFile);
139 } catch (IOException e) {
140 throw new RuntimeException("Cannot copy demo resource", e);
141 }
142 // nodeRolesUri = nodeRolesFile.toURI().toString();
143 }
144 uris.add(nodeRolesUri);
145
146 // node tokens
147 String nodeTokensUri = getFrameworkProp(CmsConstants.TOKENS_URI);
148 String baseNodeTokensDn = CmsConstants.TOKENS_BASEDN;
149 if (nodeTokensUri == null) {
150 nodeTokensUri = baseNodeTokensDn + ".ldif";
151 File nodeTokensFile = new File(nodeBaseDir, nodeTokensUri);
152 if (!nodeTokensFile.exists())
153 try {
154 FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(baseNodeTokensDn + ".ldif"),
155 nodeTokensFile);
156 } catch (IOException e) {
157 throw new RuntimeException("Cannot copy demo resource", e);
158 }
159 // nodeRolesUri = nodeRolesFile.toURI().toString();
160 }
161 uris.add(nodeTokensUri);
162
163 // Business roles
164 String userAdminUris = getFrameworkProp(CmsConstants.USERADMIN_URIS);
165 if (userAdminUris == null) {
166 String demoBaseDn = "dc=example,dc=com";
167 userAdminUris = demoBaseDn + ".ldif";
168 File businessRolesFile = new File(nodeBaseDir, userAdminUris);
169 File systemRolesFile = new File(nodeBaseDir, "ou=roles,ou=node.ldif");
170 if (!businessRolesFile.exists())
171 try {
172 FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(demoBaseDn + ".ldif"),
173 businessRolesFile);
174 if (!systemRolesFile.exists())
175 FileUtils.copyInputStreamToFile(
176 InitUtils.class.getResourceAsStream("example-ou=roles,ou=node.ldif"), systemRolesFile);
177 } catch (IOException e) {
178 throw new RuntimeException("Cannot copy demo resources", e);
179 }
180 // userAdminUris = businessRolesFile.toURI().toString();
181 log.warn("## DEV Using dummy base DN " + demoBaseDn);
182 // TODO downgrade security level
183 }
184 for (String userAdminUri : userAdminUris.split(" "))
185 uris.add(userAdminUri);
186
187 // Interprets URIs
188 for (String uri : uris) {
189 URI u;
190 try {
191 u = new URI(uri);
192 if (u.getPath() == null)
193 throw new IllegalArgumentException(
194 "URI " + uri + " must have a path in order to determine base DN");
195 if (u.getScheme() == null) {
196 if (uri.startsWith("/") || uri.startsWith("./") || uri.startsWith("../"))
197 u = new File(uri).getCanonicalFile().toURI();
198 else if (!uri.contains("/")) {
199 // u = KernelUtils.getOsgiInstanceUri(KernelConstants.DIR_NODE + '/' + uri);
200 u = new URI(uri);
201 } else
202 throw new IllegalArgumentException("Cannot interpret " + uri + " as an uri");
203 } else if (u.getScheme().equals(UserAdminConf.SCHEME_FILE)) {
204 u = new File(u).getCanonicalFile().toURI();
205 }
206 } catch (Exception e) {
207 throw new RuntimeException("Cannot interpret " + uri + " as an uri", e);
208 }
209 Dictionary<String, Object> properties = UserAdminConf.uriAsProperties(u.toString());
210 res.add(properties);
211 }
212
213 return res;
214 }
215
216 /**
217 * Called before node initialisation, in order populate OSGi instance are with
218 * some files (typically LDIF, etc).
219 */
220 public static void prepareFirstInitInstanceArea() {
221 String nodeInits = getFrameworkProp(CmsConstants.NODE_INIT);
222 if (nodeInits == null)
223 nodeInits = "../../init";
224
225 for (String nodeInit : nodeInits.split(",")) {
226
227 if (nodeInit.startsWith("http")) {
228 // TODO reconnect it
229 // registerRemoteInit(nodeInit);
230 } else {
231
232 // TODO use java.nio.file
233 File initDir;
234 if (nodeInit.startsWith("."))
235 initDir = KernelUtils.getExecutionDir(nodeInit);
236 else
237 initDir = new File(nodeInit);
238 // TODO also uncompress archives
239 if (initDir.exists())
240 try {
241 FileUtils.copyDirectory(initDir, KernelUtils.getOsgiInstanceDir(), new FileFilter() {
242
243 @Override
244 public boolean accept(File pathname) {
245 if (pathname.getName().equals(".svn") || pathname.getName().equals(".git"))
246 return false;
247 return true;
248 }
249 });
250 log.info("CMS initialized from " + initDir.getCanonicalPath());
251 } catch (IOException e) {
252 throw new RuntimeException("Cannot initialize from " + initDir, e);
253 }
254 }
255 }
256 }
257
258 private static void createSelfSignedKeyStore(Path keyStorePath, char[] keyStorePassword, String keyStoreType) {
259 // for (Provider provider : Security.getProviders())
260 // System.out.println(provider.getName());
261 // File keyStoreFile = keyStorePath.toFile();
262 char[] keyPwd = Arrays.copyOf(keyStorePassword, keyStorePassword.length);
263 if (!Files.exists(keyStorePath)) {
264 try {
265 Files.createDirectories(keyStorePath.getParent());
266 KeyStore keyStore = PkiUtils.getKeyStore(keyStorePath, keyStorePassword, keyStoreType);
267 PkiUtils.generateSelfSignedCertificate(keyStore,
268 new X500Principal("CN=" + InetAddress.getLocalHost().getHostName() + ",OU=UNSECURE,O=UNSECURE"),
269 1024, keyPwd);
270 PkiUtils.saveKeyStore(keyStorePath, keyStorePassword, keyStore);
271 if (log.isDebugEnabled())
272 log.debug("Created self-signed unsecure keystore " + keyStorePath);
273 } catch (Exception e) {
274 try {
275 if (Files.size(keyStorePath) == 0)
276 Files.delete(keyStorePath);
277 } catch (IOException e1) {
278 // silent
279 }
280 log.error("Cannot create keystore " + keyStorePath, e);
281 }
282 } else {
283 throw new IllegalStateException("Keystore " + keyStorePath + " already exists");
284 }
285 }
286
287 }