Make data admin log-in more robust and easier to use.
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / kernel / NodeHttp.java
index 28c569bfdf6ff4908f9a28e10eeb736fe0581a8b..e9219849523eaf0c5bb23cbf21bdd3ad76239ddc 100644 (file)
 package org.argeo.cms.internal.kernel;
 
-import static org.argeo.jackrabbit.servlet.WebdavServlet.INIT_PARAM_RESOURCE_CONFIG;
-
 import java.io.IOException;
-import java.security.cert.X509Certificate;
-import java.util.Enumeration;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.Properties;
-import java.util.StringTokenizer;
 
 import javax.jcr.Repository;
-import javax.servlet.FilterChain;
-import javax.servlet.Servlet;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
 
-import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.jackrabbit.server.SessionProvider;
+import org.apache.jackrabbit.server.remoting.davex.JcrRemotingServlet;
+import org.apache.jackrabbit.webdav.simple.SimpleWebdavServlet;
 import org.argeo.cms.CmsException;
-import org.argeo.jackrabbit.servlet.OpenInViewSessionProvider;
-import org.argeo.jackrabbit.servlet.RemotingServlet;
-import org.argeo.jackrabbit.servlet.WebdavServlet;
-import org.argeo.jcr.ArgeoJcrConstants;
-import org.argeo.security.NodeAuthenticationToken;
-import org.eclipse.equinox.http.servlet.ExtendedHttpService;
+import org.argeo.cms.internal.http.CmsSessionProvider;
+import org.argeo.cms.internal.http.DataHttpContext;
+import org.argeo.cms.internal.http.HttpUtils;
+import org.argeo.cms.internal.http.LinkServlet;
+import org.argeo.cms.internal.http.PrivateHttpContext;
+import org.argeo.cms.internal.http.RobotServlet;
+import org.argeo.node.NodeConstants;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.http.HttpService;
 import org.osgi.service.http.NamespaceException;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContext;
-import org.springframework.security.core.context.SecurityContextHolder;
+import org.osgi.util.tracker.ServiceTracker;
 
 /**
  * Intercepts and enriches http access, mainly focusing on security and
  * transactionality.
  */
-class NodeHttp implements KernelConstants, ArgeoJcrConstants {
+public class NodeHttp implements KernelConstants {
        private final static Log log = LogFactory.getLog(NodeHttp.class);
 
-       private final static String ATTR_AUTH = "auth";
-       private final static String HEADER_AUTHORIZATION = "Authorization";
-       private final static String HEADER_WWW_AUTHENTICATE = "WWW-Authenticate";
-
-       private final AuthenticationManager authenticationManager;
-       private final ExtendedHttpService httpService;
-
-       // FIXME Make it more unique
-       private String httpAuthRealm = "Argeo";
-
-       // Filters
-       private final RootFilter rootFilter;
-       // private final DoSFilter dosFilter;
-       // private final QoSFilter qosFilter;
+       public final static String DEFAULT_SERVICE = "HTTP";
 
-       // WebDav / JCR remoting
-       private OpenInViewSessionProvider sessionProvider;
+       private final BundleContext bc = FrameworkUtil.getBundle(getClass()).getBundleContext();
 
-       NodeHttp(ExtendedHttpService httpService, JackrabbitNode node,
-                       NodeSecurity authenticationManager) {
-               // this.bundleContext = bundleContext;
-               this.authenticationManager = authenticationManager;
+       private ServiceTracker<Repository, Repository> repositories;
+       private final ServiceTracker<HttpService, HttpService> httpServiceTracker;
 
-               this.httpService = httpService;
+       private String httpRealm = "Argeo";
+       private String webDavConfig = HttpUtils.WEBDAV_CONFIG;
+       private final boolean cleanState;
 
-               // Filters
-               rootFilter = new RootFilter();
-               // dosFilter = new CustomDosFilter();
-               // qosFilter = new QoSFilter();
+       public NodeHttp(boolean cleanState) {
+               this.cleanState = cleanState;
+               httpServiceTracker = new PrepareHttpStc();
+               // httpServiceTracker.open();
+               KernelUtils.asyncOpen(httpServiceTracker);
+       }
 
-               // DAV
-               sessionProvider = new OpenInViewSessionProvider();
+       public void destroy() {
+               if (repositories != null)
+                       repositories.close();
+       }
 
-               registerRepositoryServlets(ALIAS_NODE, node);
+       public void registerRepositoryServlets(HttpService httpService, String alias, Repository repository) {
+               if (httpService == null)
+                       throw new CmsException("No HTTP service available");
                try {
-                       httpService.registerFilter("/", rootFilter, null, null);
+                       registerWebdavServlet(httpService, alias, repository);
+                       registerRemotingServlet(httpService, alias, repository);
+                       if (NodeConstants.HOME.equals(alias))
+                               registerFilesServlet(httpService, alias, repository);
+                       if (log.isTraceEnabled())
+                               log.trace("Registered servlets for repository '" + alias + "'");
                } catch (Exception e) {
-                       throw new CmsException(
-                                       "Could not register root filter", e);
+                       throw new CmsException("Could not register servlets for repository '" + alias + "'", e);
                }
        }
 
-       public void destroy() {
-               sessionProvider.destroy();
-               unregisterRepositoryServlets(ALIAS_NODE);
-       }
-
-       void registerRepositoryServlets(String alias, Repository repository) {
+       public static void unregisterRepositoryServlets(HttpService httpService, String alias) {
+               if (httpService == null)
+                       return;
                try {
-                       registerWebdavServlet(alias, repository, true);
-                       registerWebdavServlet(alias, repository, false);
-                       registerRemotingServlet(alias, repository, true);
-                       registerRemotingServlet(alias, repository, false);
+                       httpService.unregister(webdavPath(alias));
+                       httpService.unregister(remotingPath(alias));
+                       if (NodeConstants.HOME.equals(alias))
+                               httpService.unregister(filesPath(alias));
+                       if (log.isTraceEnabled())
+                               log.trace("Unregistered servlets for repository '" + alias + "'");
                } catch (Exception e) {
-                       throw new CmsException(
-                                       "Could not register servlets for repository " + alias, e);
+                       log.error("Could not unregister servlets for repository '" + alias + "'", e);
                }
        }
 
-       void unregisterRepositoryServlets(String alias) {
-               // FIXME unregister servlets
+       void registerWebdavServlet(HttpService httpService, String alias, Repository repository)
+                       throws NamespaceException, ServletException {
+               // WebdavServlet webdavServlet = new WebdavServlet(repository, new
+               // OpenInViewSessionProvider(alias));
+               WebdavServlet webdavServlet = new WebdavServlet(repository, new CmsSessionProvider(alias));
+               String path = webdavPath(alias);
+               Properties ip = new Properties();
+               ip.setProperty(WebdavServlet.INIT_PARAM_RESOURCE_CONFIG, webDavConfig);
+               ip.setProperty(WebdavServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path);
+               httpService.registerServlet(path, webdavServlet, ip, new DataHttpContext(httpRealm));
        }
 
-       void registerWebdavServlet(String alias, Repository repository,
-                       boolean anonymous) throws NamespaceException, ServletException {
-               WebdavServlet webdavServlet = new WebdavServlet(repository,
-                               sessionProvider);
-               String pathPrefix = anonymous ? WEBDAV_PUBLIC : WEBDAV_PRIVATE;
-               String path = pathPrefix + "/" + alias;
+       void registerFilesServlet(HttpService httpService, String alias, Repository repository)
+                       throws NamespaceException, ServletException {
+               WebdavServlet filesServlet = new WebdavServlet(repository, new CmsSessionProvider(alias));
+               String path = filesPath(alias);
                Properties ip = new Properties();
-               ip.setProperty(INIT_PARAM_RESOURCE_CONFIG, WEBDAV_CONFIG);
+               ip.setProperty(WebdavServlet.INIT_PARAM_RESOURCE_CONFIG, webDavConfig);
                ip.setProperty(WebdavServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path);
-               httpService.registerFilter(path, anonymous ? new AnonymousFilter()
-                               : new DavFilter(), null, null);
-               // Cast to servlet because of a weird behaviour in Eclipse
-               httpService.registerServlet(path, (Servlet) webdavServlet, ip, null);
+               httpService.registerServlet(path, filesServlet, ip, new PrivateHttpContext(httpRealm, true));
        }
 
-       void registerRemotingServlet(String alias, Repository repository,
-                       boolean anonymous) throws NamespaceException, ServletException {
-               String pathPrefix = anonymous ? REMOTING_PUBLIC : REMOTING_PRIVATE;
-               RemotingServlet remotingServlet = new RemotingServlet(repository,
-                               sessionProvider);
-               String path = pathPrefix + "/" + alias;
+       void registerRemotingServlet(HttpService httpService, String alias, Repository repository)
+                       throws NamespaceException, ServletException {
+               RemotingServlet remotingServlet = new RemotingServlet(repository, new CmsSessionProvider(alias));
+               String path = remotingPath(alias);
                Properties ip = new Properties();
-               ip.setProperty(RemotingServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path);
+               ip.setProperty(JcrRemotingServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path);
+               ip.setProperty(JcrRemotingServlet.INIT_PARAM_AUTHENTICATE_HEADER, "Negotiate");
 
                // Looks like a bug in Jackrabbit remoting init
-               ip.setProperty(RemotingServlet.INIT_PARAM_HOME,
-                               KernelUtils.getOsgiInstanceDir() + "/tmp/jackrabbit");
-               ip.setProperty(RemotingServlet.INIT_PARAM_TMP_DIRECTORY, "remoting");
-               // Cast to servlet because of a weird behaviour in Eclipse
-               httpService.registerFilter(path, anonymous ? new AnonymousFilter()
-                               : new DavFilter(), null, null);
-               httpService.registerServlet(path, (Servlet) remotingServlet, ip, null);
+               Path tmpDir;
+               try {
+                       tmpDir = Files.createTempDirectory("remoting_" + alias);
+               } catch (IOException e) {
+                       throw new CmsException("Cannot create temp directory for remoting servlet", e);
+               }
+               ip.setProperty(RemotingServlet.INIT_PARAM_HOME, tmpDir.toString());
+               ip.setProperty(RemotingServlet.INIT_PARAM_TMP_DIRECTORY, "remoting_" + alias);
+               ip.setProperty(RemotingServlet.INIT_PARAM_PROTECTED_HANDLERS_CONFIG, HttpUtils.DEFAULT_PROTECTED_HANDLERS);
+               ip.setProperty(RemotingServlet.INIT_PARAM_CREATE_ABSOLUTE_URI, "false");
+               httpService.registerServlet(path, remotingServlet, ip, new PrivateHttpContext(httpRealm));
        }
 
-       private Boolean isSessionAuthenticated(HttpSession httpSession) {
-               SecurityContext contextFromSession = (SecurityContext) httpSession
-                               .getAttribute(SPRING_SECURITY_CONTEXT_KEY);
-               return contextFromSession != null;
+       static String webdavPath(String alias) {
+               return NodeConstants.PATH_DATA + "/" + alias;
        }
 
-       private void requestBasicAuth(HttpSession httpSession,
-                       HttpServletResponse response) {
-               response.setStatus(401);
-               response.setHeader(HEADER_WWW_AUTHENTICATE, "basic realm=\""
-                               + httpAuthRealm + "\"");
-               httpSession.setAttribute(ATTR_AUTH, Boolean.TRUE);
+       static String remotingPath(String alias) {
+               return NodeConstants.PATH_JCR + "/" + alias;
        }
 
-       private NodeAuthenticationToken basicAuth(String authHeader) {
-               if (authHeader != null) {
-                       StringTokenizer st = new StringTokenizer(authHeader);
-                       if (st.hasMoreTokens()) {
-                               String basic = st.nextToken();
-                               if (basic.equalsIgnoreCase("Basic")) {
-                                       try {
-                                               String credentials = new String(Base64.decodeBase64(st
-                                                               .nextToken()), "UTF-8");
-                                               // log.debug("Credentials: " + credentials);
-                                               int p = credentials.indexOf(":");
-                                               if (p != -1) {
-                                                       String login = credentials.substring(0, p).trim();
-                                                       String password = credentials.substring(p + 1)
-                                                                       .trim();
-
-                                                       return new NodeAuthenticationToken(login,
-                                                                       password.toCharArray());
-                                               } else {
-                                                       throw new CmsException(
-                                                                       "Invalid authentication token");
-                                               }
-                                       } catch (Exception e) {
-                                               throw new CmsException(
-                                                               "Couldn't retrieve authentication", e);
-                                       }
-                               }
-                       }
-               }
-               throw new CmsException("Couldn't retrieve authentication");
+       static String filesPath(String alias) {
+               return NodeConstants.PATH_FILES;
        }
 
-       /** Intercepts all requests. Authenticates. */
-       class RootFilter extends HttpFilter {
+       class RepositoriesStc extends ServiceTracker<Repository, Repository> {
+               private final HttpService httpService;
 
-               @Override
-               public void doFilter(HttpSession httpSession,
-                               HttpServletRequest request, HttpServletResponse response,
-                               FilterChain filterChain) throws IOException, ServletException {
-                       if (log.isTraceEnabled())
-                               logRequest(request);
-
-                       String servletPath = request.getServletPath();
+               private final BundleContext bc;
 
-                       // client certificate
-                       X509Certificate clientCert = extractCertificate(request);
-                       if (clientCert != null) {
-                               // TODO authenticate
-                               // if (log.isDebugEnabled())
-                               // log.debug(clientCert.getSubjectX500Principal().getName());
-                       }
+               public RepositoriesStc(BundleContext bc, HttpService httpService) {
+                       super(bc, Repository.class, null);
+                       this.httpService = httpService;
+                       this.bc = bc;
+               }
 
-                       // skip data
-                       if (servletPath.startsWith(PATH_DATA)) {
-                               filterChain.doFilter(request, response);
-                               return;
+               @Override
+               public Repository addingService(ServiceReference<Repository> reference) {
+                       Repository repository = bc.getService(reference);
+                       Object jcrRepoAlias = reference.getProperty(NodeConstants.CN);
+                       if (jcrRepoAlias != null) {
+                               String alias = jcrRepoAlias.toString();
+                               registerRepositoryServlets(httpService, alias, repository);
                        }
+                       return repository;
+               }
 
-                       // skip /ui (workbench) for the time being
-                       if (servletPath.startsWith(PATH_WORKBENCH)) {
-                               filterChain.doFilter(request, response);
-                               return;
-                       }
+               @Override
+               public void modifiedService(ServiceReference<Repository> reference, Repository service) {
+               }
 
-                       // redirect long RWT paths to anchor
-                       String path = request.getRequestURI().substring(
-                                       servletPath.length());
-                       int pathLength = path.length();
-                       if (pathLength != 0 && (path.charAt(0) == '/')
-                                       && !servletPath.endsWith("rwt-resources")
-                                       && !path.equals("/")) {
-                               String newLocation = request.getServletPath() + "#" + path;
-                               response.setHeader("Location", newLocation);
-                               response.setStatus(HttpServletResponse.SC_FOUND);
-                               return;
+               @Override
+               public void removedService(ServiceReference<Repository> reference, Repository service) {
+                       Object jcrRepoAlias = reference.getProperty(NodeConstants.CN);
+                       if (jcrRepoAlias != null) {
+                               String alias = jcrRepoAlias.toString();
+                               unregisterRepositoryServlets(httpService, alias);
                        }
-
-                       // process normally
-                       filterChain.doFilter(request, response);
                }
        }
 
-       private void logRequest(HttpServletRequest request) {
-               log.debug(request.getContextPath());
-               log.debug(request.getServletPath());
-               log.debug(request.getRequestURI());
-               log.debug(request.getQueryString());
-               StringBuilder buf = new StringBuilder();
-               // headers
-               Enumeration<String> en = request.getHeaderNames();
-               while (en.hasMoreElements()) {
-                       String header = en.nextElement();
-                       Enumeration<String> values = request.getHeaders(header);
-                       while (values.hasMoreElements())
-                               buf.append("  " + header + ": " + values.nextElement());
-                       buf.append('\n');
+       private class PrepareHttpStc extends ServiceTracker<HttpService, HttpService> {
+               public PrepareHttpStc() {
+                       super(bc, HttpService.class, null);
                }
 
-               // attributed
-               Enumeration<String> an = request.getAttributeNames();
-               while (an.hasMoreElements()) {
-                       String attr = an.nextElement();
-                       Object value = request.getAttribute(attr);
-                       buf.append("  " + attr + ": " + value);
-                       buf.append('\n');
+               @Override
+               public HttpService addingService(ServiceReference<HttpService> reference) {
+                       long begin = System.currentTimeMillis();
+                       if (log.isTraceEnabled())
+                               log.trace("HTTP prepare starts...");
+                       HttpService httpService = addHttpService(reference);
+                       if (log.isTraceEnabled())
+                               log.trace("HTTP prepare duration: " + (System.currentTimeMillis() - begin) + "ms");
+                       return httpService;
                }
-               log.debug("\n" + buf);
-       }
 
-       private X509Certificate extractCertificate(HttpServletRequest req) {
-               X509Certificate[] certs = (X509Certificate[]) req
-                               .getAttribute("javax.servlet.request.X509Certificate");
-               if (null != certs && certs.length > 0) {
-                       return certs[0];
+               @Override
+               public void removedService(ServiceReference<HttpService> reference, HttpService service) {
+                       repositories.close();
+                       repositories = null;
                }
-               return null;
-       }
 
-       /** Intercepts all requests. Authenticates. */
-       private class AnonymousFilter extends HttpFilter {
-               @Override
-               public void doFilter(HttpSession httpSession,
-                               HttpServletRequest request, HttpServletResponse response,
-                               FilterChain filterChain) throws IOException, ServletException {
-
-                       // Authenticate from session
-                       if (isSessionAuthenticated(httpSession)) {
-                               filterChain.doFilter(request, response);
-                               return;
+               private HttpService addHttpService(ServiceReference<HttpService> sr) {
+                       HttpService httpService = bc.getService(sr);
+                       // TODO find constants
+                       Object httpPort = sr.getProperty("http.port");
+                       Object httpsPort = sr.getProperty("https.port");
+
+                       try {
+                               httpService.registerServlet("/!", new LinkServlet(), null, null);
+                               httpService.registerServlet("/robots.txt", new RobotServlet(), null, null);
+                               // httpService.registerServlet("/html", new HtmlServlet(), null, null);
+                       } catch (Exception e) {
+                               throw new CmsException("Cannot register filters", e);
                        }
+                       // track repositories
+                       if (repositories != null)
+                               throw new CmsException("An http service is already configured");
+                       repositories = new RepositoriesStc(bc, httpService);
+                       // repositories.open();
+                       if (cleanState)
+                               KernelUtils.asyncOpen(repositories);
+                       log.info(httpPortsMsg(httpPort, httpsPort));
+                       // httpAvailable = true;
+                       // checkReadiness();
+
+                       bc.registerService(NodeHttp.class, NodeHttp.this, null);
+                       return httpService;
+               }
 
-                       KernelUtils.anonymousLogin(authenticationManager);
-                       filterChain.doFilter(request, response);
+               private String httpPortsMsg(Object httpPort, Object httpsPort) {
+                       return "HTTP " + httpPort + (httpsPort != null ? " - HTTPS " + httpsPort : "");
                }
        }
 
-       /** Intercepts all requests. Authenticates. */
-       private class DavFilter extends HttpFilter {
+       private static class WebdavServlet extends SimpleWebdavServlet {
+               private static final long serialVersionUID = -4687354117811443881L;
+               private final Repository repository;
+
+               public WebdavServlet(Repository repository, SessionProvider sessionProvider) {
+                       this.repository = repository;
+                       setSessionProvider(sessionProvider);
+               }
+
+               public Repository getRepository() {
+                       return repository;
+               }
 
                @Override
-               public void doFilter(HttpSession httpSession,
-                               HttpServletRequest request, HttpServletResponse response,
-                               FilterChain filterChain) throws IOException, ServletException {
-
-                       // Authenticate from session
-                       // if (isSessionAuthenticated(httpSession)) {
-                       // filterChain.doFilter(request, response);
-                       // return;
+               protected void service(final HttpServletRequest request, final HttpServletResponse response)
+                               throws ServletException, IOException {
+                       WebdavServlet.super.service(request, response);
+                       // try {
+                       // Subject subject = subjectFromRequest(request);
+                       // // TODO make it stronger, with eTags.
+                       // // if (CurrentUser.isAnonymous(subject) &&
+                       // // request.getMethod().equals("GET")) {
+                       // // response.setHeader("Cache-Control", "no-transform, public,
+                       // // max-age=300, s-maxage=900");
+                       // // }
+                       //
+                       // Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
+                       // @Override
+                       // public Void run() throws Exception {
+                       // WebdavServlet.super.service(request, response);
+                       // return null;
+                       // }
+                       // });
+                       // } catch (PrivilegedActionException e) {
+                       // throw new CmsException("Cannot process webdav request",
+                       // e.getException());
                        // }
+               }
 
-                       // Process basic auth
-                       String basicAuth = request.getHeader(HEADER_AUTHORIZATION);
-                       if (basicAuth != null) {
-                               UsernamePasswordAuthenticationToken token = basicAuth(basicAuth);
-                               Authentication auth = authenticationManager.authenticate(token);
-                               SecurityContextHolder.getContext().setAuthentication(auth);
-                               httpSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY,
-                                               SecurityContextHolder.getContext());
-                               httpSession.setAttribute(ATTR_AUTH, Boolean.FALSE);
-                               filterChain.doFilter(request, response);
-                               return;
-                       }
+       }
+
+       private static class RemotingServlet extends JcrRemotingServlet {
+               private final Log log = LogFactory.getLog(RemotingServlet.class);
+               private static final long serialVersionUID = 4605238259548058883L;
+               private final Repository repository;
+               private final SessionProvider sessionProvider;
+
+               public RemotingServlet(Repository repository, SessionProvider sessionProvider) {
+                       this.repository = repository;
+                       this.sessionProvider = sessionProvider;
+               }
+
+               @Override
+               protected Repository getRepository() {
+                       return repository;
+               }
 
-                       requestBasicAuth(httpSession, response);
+               @Override
+               protected SessionProvider getSessionProvider() {
+                       return sessionProvider;
+               }
+
+               @Override
+               protected void service(final HttpServletRequest request, final HttpServletResponse response)
+                               throws ServletException, IOException {
+                       if (log.isTraceEnabled())
+                               HttpUtils.logRequest(log, request);
+                       RemotingServlet.super.service(request, response);
                }
        }
 
-       // class CustomDosFilter extends DoSFilter {
-       // @Override
-       // protected String extractUserId(ServletRequest request) {
-       // HttpSession httpSession = ((HttpServletRequest) request)
-       // .getSession();
-       // if (isSessionAuthenticated(httpSession)) {
-       // String userId = ((SecurityContext) httpSession
-       // .getAttribute(SPRING_SECURITY_CONTEXT_KEY))
-       // .getAuthentication().getName();
-       // return userId;
-       // }
-       // return super.extractUserId(request);
-       //
-       // }
-       // }
 }