]> git.argeo.org Git - lgpl/argeo-commons.git/blobdiff - org.argeo.cms/src/org/argeo/cms/internal/kernel/DataHttp.java
Support anonymous and http session in IPA mode
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / kernel / DataHttp.java
index 469dfd2a70d21c1a5dee4eb3f08612f0566c2321..97ca4bb31fd1aab67466efd3742619020b31cc8d 100644 (file)
@@ -22,7 +22,6 @@ import javax.security.auth.login.LoginException;
 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;
@@ -65,12 +64,8 @@ class DataHttp implements KernelConstants {
        // FIXME Make it more unique
        private String httpAuthRealm = "Argeo";
 
-       // WebDav / JCR remoting
-       private OpenInViewSessionProvider sessionProvider;
-
        DataHttp(HttpService httpService) {
                this.bc = FrameworkUtil.getBundle(getClass()).getBundleContext();
-               sessionProvider = new OpenInViewSessionProvider();
                this.httpService = httpService;
                repositories = new ServiceTracker<>(bc, Repository.class, new RepositoriesStc());
                repositories.open();
@@ -84,8 +79,8 @@ class DataHttp implements KernelConstants {
                try {
                        registerWebdavServlet(alias, repository);
                        // registerWebdavServlet(alias, repository, false);
-                       registerRemotingServlet(alias, repository, true);
-                       registerRemotingServlet(alias, repository, false);
+                       // registerRemotingServlet(alias, repository, true);
+                       registerRemotingServlet(alias, repository);
                        if (log.isDebugEnabled())
                                log.debug("Registered servlets for repository '" + alias + "'");
                } catch (Exception e) {
@@ -97,8 +92,8 @@ class DataHttp implements KernelConstants {
                try {
                        httpService.unregister(webdavPath(alias));
                        // httpService.unregister(webdavPath(alias, false));
-                       httpService.unregister(remotingPath(alias, true));
-                       httpService.unregister(remotingPath(alias, false));
+                       // httpService.unregister(remotingPath(alias, true));
+                       httpService.unregister(remotingPath(alias));
                        if (log.isDebugEnabled())
                                log.debug("Unregistered servlets for repository '" + alias + "'");
                } catch (Exception e) {
@@ -107,7 +102,7 @@ class DataHttp implements KernelConstants {
        }
 
        void registerWebdavServlet(String alias, Repository repository) throws NamespaceException, ServletException {
-               WebdavServlet webdavServlet = new WebdavServlet(repository, sessionProvider);
+               WebdavServlet webdavServlet = new WebdavServlet(repository, new OpenInViewSessionProvider(alias));
                String path = webdavPath(alias);
                Properties ip = new Properties();
                ip.setProperty(WebdavServlet.INIT_PARAM_RESOURCE_CONFIG, WEBDAV_CONFIG);
@@ -115,18 +110,18 @@ class DataHttp implements KernelConstants {
                httpService.registerServlet(path, webdavServlet, ip, new DataHttpContext());
        }
 
-       void registerRemotingServlet(String alias, Repository repository, boolean anonymous)
-                       throws NamespaceException, ServletException {
-               RemotingServlet remotingServlet = new RemotingServlet(repository, sessionProvider);
-               String path = remotingPath(alias, anonymous);
+       void registerRemotingServlet(String alias, Repository repository) throws NamespaceException, ServletException {
+               RemotingServlet remotingServlet = new RemotingServlet(repository, new OpenInViewSessionProvider(alias));
+               String path = remotingPath(alias);
                Properties ip = new Properties();
                ip.setProperty(JcrRemotingServlet.INIT_PARAM_RESOURCE_PATH_PREFIX, path);
 
                // 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");
+               ip.setProperty(RemotingServlet.INIT_PARAM_HOME, KernelUtils.getOsgiInstanceDir() + "/tmp/remoting_" + alias);
+               ip.setProperty(RemotingServlet.INIT_PARAM_TMP_DIRECTORY, "remoting_" + alias);
                ip.setProperty(RemotingServlet.INIT_PARAM_PROTECTED_HANDLERS_CONFIG, DEFAULT_PROTECTED_HANDLERS);
-               httpService.registerServlet(path, remotingServlet, ip, new RemotingHttpContext(anonymous));
+               ip.setProperty(RemotingServlet.INIT_PARAM_CREATE_ABSOLUTE_URI, "false");
+               httpService.registerServlet(path, remotingServlet, ip, new RemotingHttpContext());
        }
 
        private String webdavPath(String alias) {
@@ -135,9 +130,10 @@ class DataHttp implements KernelConstants {
                // return pathPrefix + "/" + alias;
        }
 
-       private String remotingPath(String alias, boolean anonymous) {
-               String pathPrefix = anonymous ? NodeConstants.PATH_JCR_PUB : NodeConstants.PATH_JCR;
-               return pathPrefix + "/" + alias;
+       private String remotingPath(String alias) {
+               return NodeConstants.PATH_JCR + "/" + alias;
+               // String pathPrefix = anonymous ? NodeConstants.PATH_JCR_PUB :
+               // NodeConstants.PATH_JCR;
        }
 
        private Subject subjectFromRequest(HttpServletRequest request) {
@@ -154,6 +150,51 @@ class DataHttp implements KernelConstants {
                }
        }
 
+       private void requestBasicAuth(HttpServletRequest request, HttpServletResponse response) {
+               response.setStatus(401);
+               response.setHeader(HEADER_WWW_AUTHENTICATE, "basic realm=\"" + httpAuthRealm + "\"");
+               // request.getSession().setAttribute(ATTR_AUTH, Boolean.TRUE);
+       }
+
+       private CallbackHandler basicAuth(final HttpServletRequest httpRequest) {
+               String authHeader = httpRequest.getHeader(HEADER_AUTHORIZATION);
+               if (authHeader != null) {
+                       StringTokenizer st = new StringTokenizer(authHeader);
+                       if (st.hasMoreTokens()) {
+                               String basic = st.nextToken();
+                               if (basic.equalsIgnoreCase("Basic")) {
+                                       try {
+                                               // TODO manipulate char[]
+                                               String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
+                                               // log.debug("Credentials: " + credentials);
+                                               int p = credentials.indexOf(":");
+                                               if (p != -1) {
+                                                       final String login = credentials.substring(0, p).trim();
+                                                       final char[] password = credentials.substring(p + 1).trim().toCharArray();
+                                                       return new CallbackHandler() {
+                                                               public void handle(Callback[] callbacks) {
+                                                                       for (Callback cb : callbacks) {
+                                                                               if (cb instanceof NameCallback)
+                                                                                       ((NameCallback) cb).setName(login);
+                                                                               else if (cb instanceof PasswordCallback)
+                                                                                       ((PasswordCallback) cb).setPassword(password);
+                                                                               else if (cb instanceof HttpRequestCallback)
+                                                                                       ((HttpRequestCallback) cb).setRequest(httpRequest);
+                                                                       }
+                                                               }
+                                                       };
+                                               } else {
+                                                       throw new CmsException("Invalid authentication token");
+                                               }
+                                       } catch (Exception e) {
+                                               throw new CmsException("Couldn't retrieve authentication", e);
+                                       }
+                               }
+                       }
+               }
+               return null;
+       }
+
        private class RepositoriesStc implements ServiceTrackerCustomizer<Repository, Repository> {
 
                @Override
@@ -193,14 +234,14 @@ class DataHttp implements KernelConstants {
                                throws IOException {
 
                        // optimization
-                       HttpSession httpSession = request.getSession();
-                       Object remoteUser = httpSession.getAttribute(REMOTE_USER);
-                       Object authorization = httpSession.getAttribute(AUTHORIZATION);
-                       if (remoteUser != null && authorization != null) {
-                               request.setAttribute(REMOTE_USER, remoteUser);
-                               request.setAttribute(AUTHORIZATION, authorization);
-                               return true;
-                       }
+                       // HttpSession httpSession = request.getSession();
+                       // Object remoteUser = httpSession.getAttribute(REMOTE_USER);
+                       // Object authorization = httpSession.getAttribute(AUTHORIZATION);
+                       // if (remoteUser != null && authorization != null) {
+                       // request.setAttribute(REMOTE_USER, remoteUser);
+                       // request.setAttribute(AUTHORIZATION, authorization);
+                       // return true;
+                       // }
 
                        // if (anonymous) {
                        // Subject subject = KernelUtils.anonymousLogin();
@@ -212,18 +253,45 @@ class DataHttp implements KernelConstants {
                        // }
 
                        // if (log.isTraceEnabled())
-                       // KernelUtils.logRequestHeaders(log, request);
+                       KernelUtils.logRequestHeaders(log, request);
+                       LoginContext lc;
                        try {
-                               new LoginContext(NodeConstants.LOGIN_CONTEXT_USER, new HttpRequestCallbackHandler(request)).login();
-                               return true;
+                               lc = new LoginContext(NodeConstants.LOGIN_CONTEXT_USER, new HttpRequestCallbackHandler(request));
+                               lc.login();
+                               // return true;
                        } catch (CredentialNotFoundException e) {
-                               Subject subject = KernelUtils.anonymousLogin();
-                               authorization = subject.getPrivateCredentials(Authorization.class).iterator().next();
-                               request.setAttribute(REMOTE_USER, NodeConstants.ROLE_ANONYMOUS);
-                               request.setAttribute(AUTHORIZATION, authorization);
-                               httpSession.setAttribute(REMOTE_USER, NodeConstants.ROLE_ANONYMOUS);
-                               httpSession.setAttribute(AUTHORIZATION, authorization);
-                               return true;
+                               CallbackHandler token = basicAuth(request);
+                               if (token != null) {
+                                       try {
+                                               lc = new LoginContext(NodeConstants.LOGIN_CONTEXT_USER, token);
+                                               lc.login();
+                                               // Note: this is impossible to reliably clear the
+                                               // authorization header when access from a browser.
+                                               return true;
+                                       } catch (LoginException e1) {
+                                               throw new CmsException("Could not login", e1);
+                                       }
+                               } else {
+                                       // anonymous
+                                       try {
+                                               lc = new LoginContext(NodeConstants.LOGIN_CONTEXT_USER);
+                                               lc.login();
+                                       } catch (LoginException e1) {
+                                               if (log.isDebugEnabled())
+                                                       log.error("Cannot log in anonynous", e1);
+                                               return false;
+                                       }
+                               }
+                               // Subject subject = KernelUtils.anonymousLogin();
+                               // authorization =
+                               // subject.getPrivateCredentials(Authorization.class).iterator().next();
+                               // request.setAttribute(REMOTE_USER,
+                               // NodeConstants.ROLE_ANONYMOUS);
+                               // request.setAttribute(AUTHORIZATION, authorization);
+                               // httpSession.setAttribute(REMOTE_USER,
+                               // NodeConstants.ROLE_ANONYMOUS);
+                               // httpSession.setAttribute(AUTHORIZATION, authorization);
+                               // return true;
                                // CallbackHandler token = basicAuth(request);
                                // if (token != null) {
                                // try {
@@ -245,6 +313,8 @@ class DataHttp implements KernelConstants {
                        } catch (LoginException e) {
                                throw new CmsException("Could not login", e);
                        }
+                       request.setAttribute(NodeConstants.LOGIN_CONTEXT_USER, lc);
+                       return true;
                }
 
                @Override
@@ -260,48 +330,56 @@ class DataHttp implements KernelConstants {
        }
 
        private class RemotingHttpContext implements HttpContext {
-               private final boolean anonymous;
+               // private final boolean anonymous;
 
-               RemotingHttpContext(boolean anonymous) {
-                       this.anonymous = anonymous;
+               RemotingHttpContext() {
+                       // this.anonymous = anonymous;
                }
 
                @Override
                public boolean handleSecurity(final HttpServletRequest request, HttpServletResponse response)
                                throws IOException {
 
-                       if (anonymous) {
-                               Subject subject = KernelUtils.anonymousLogin();
-                               Authorization authorization = subject.getPrivateCredentials(Authorization.class).iterator().next();
-                               request.setAttribute(REMOTE_USER, NodeConstants.ROLE_ANONYMOUS);
-                               request.setAttribute(AUTHORIZATION, authorization);
-                               return true;
-                       }
+                       // if (anonymous) {
+                       // Subject subject = KernelUtils.anonymousLogin();
+                       // Authorization authorization =
+                       // subject.getPrivateCredentials(Authorization.class).iterator().next();
+                       // request.setAttribute(REMOTE_USER, NodeConstants.ROLE_ANONYMOUS);
+                       // request.setAttribute(AUTHORIZATION, authorization);
+                       // return true;
+                       // }
 
                        if (log.isTraceEnabled())
                                KernelUtils.logRequestHeaders(log, request);
+                       LoginContext lc;
                        try {
-                               new LoginContext(NodeConstants.LOGIN_CONTEXT_USER, new HttpRequestCallbackHandler(request)).login();
-                               return true;
+                               lc = new LoginContext(NodeConstants.LOGIN_CONTEXT_USER, new HttpRequestCallbackHandler(request));
+                               lc.login();
                        } catch (CredentialNotFoundException e) {
                                CallbackHandler token = basicAuth(request);
                                if (token != null) {
                                        try {
-                                               LoginContext lc = new LoginContext(NodeConstants.LOGIN_CONTEXT_USER, token);
+                                               lc = new LoginContext(NodeConstants.LOGIN_CONTEXT_USER, token);
                                                lc.login();
                                                // Note: this is impossible to reliably clear the
                                                // authorization header when access from a browser.
-                                               return true;
                                        } catch (LoginException e1) {
                                                throw new CmsException("Could not login", e1);
                                        }
                                } else {
                                        requestBasicAuth(request, response);
-                                       return false;
+                                       lc = null;
                                }
                        } catch (LoginException e) {
                                throw new CmsException("Could not login", e);
                        }
+
+                       if (lc != null) {
+                               request.setAttribute(NodeConstants.LOGIN_CONTEXT_USER, lc);
+                               return true;
+                       } else {
+                               return false;
+                       }
                }
 
                @Override
@@ -314,51 +392,6 @@ class DataHttp implements KernelConstants {
                        return null;
                }
 
-               private void requestBasicAuth(HttpServletRequest request, HttpServletResponse response) {
-                       response.setStatus(401);
-                       response.setHeader(HEADER_WWW_AUTHENTICATE, "basic realm=\"" + httpAuthRealm + "\"");
-                       // request.getSession().setAttribute(ATTR_AUTH, Boolean.TRUE);
-               }
-
-               private CallbackHandler basicAuth(final HttpServletRequest httpRequest) {
-                       String authHeader = httpRequest.getHeader(HEADER_AUTHORIZATION);
-                       if (authHeader != null) {
-                               StringTokenizer st = new StringTokenizer(authHeader);
-                               if (st.hasMoreTokens()) {
-                                       String basic = st.nextToken();
-                                       if (basic.equalsIgnoreCase("Basic")) {
-                                               try {
-                                                       // TODO manipulate char[]
-                                                       String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
-                                                       // log.debug("Credentials: " + credentials);
-                                                       int p = credentials.indexOf(":");
-                                                       if (p != -1) {
-                                                               final String login = credentials.substring(0, p).trim();
-                                                               final char[] password = credentials.substring(p + 1).trim().toCharArray();
-                                                               return new CallbackHandler() {
-                                                                       public void handle(Callback[] callbacks) {
-                                                                               for (Callback cb : callbacks) {
-                                                                                       if (cb instanceof NameCallback)
-                                                                                               ((NameCallback) cb).setName(login);
-                                                                                       else if (cb instanceof PasswordCallback)
-                                                                                               ((PasswordCallback) cb).setPassword(password);
-                                                                                       else if (cb instanceof HttpRequestCallback)
-                                                                                               ((HttpRequestCallback) cb).setRequest(httpRequest);
-                                                                               }
-                                                                       }
-                                                               };
-                                                       } else {
-                                                               throw new CmsException("Invalid authentication token");
-                                                       }
-                                               } catch (Exception e) {
-                                                       throw new CmsException("Couldn't retrieve authentication", e);
-                                               }
-                                       }
-                               }
-                       }
-                       return null;
-               }
-
        }
 
        /**
@@ -367,6 +400,11 @@ class DataHttp implements KernelConstants {
         */
        private class OpenInViewSessionProvider implements SessionProvider, Serializable {
                private static final long serialVersionUID = 2270957712453841368L;
+               private final String alias;
+
+               public OpenInViewSessionProvider(String alias) {
+                       this.alias = alias;
+               }
 
                public Session getSession(HttpServletRequest request, Repository rep, String workspace)
                                throws javax.jcr.LoginException, ServletException, RepositoryException {
@@ -376,9 +414,26 @@ class DataHttp implements KernelConstants {
                protected Session login(HttpServletRequest request, Repository repository, String workspace)
                                throws RepositoryException {
                        if (log.isTraceEnabled())
-                               log.trace("Login to workspace " + (workspace == null ? "<default>" : workspace) + " in web session "
-                                               + request.getSession().getId());
-                       return repository.login(workspace);
+                               log.trace("Repo " + alias + ", login to workspace " + (workspace == null ? "<default>" : workspace)
+                                               + " in web session " + request.getSession().getId());
+                       LoginContext lc = (LoginContext) request.getAttribute(NodeConstants.LOGIN_CONTEXT_USER);
+                       if (lc == null)
+                               throw new CmsException("No login context available");
+                       try {
+                               // LoginContext lc = new
+                               // LoginContext(NodeConstants.LOGIN_CONTEXT_USER,
+                               // new HttpRequestCallbackHandler(request));
+                               // lc.login();
+                               return Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<Session>() {
+                                       @Override
+                                       public Session run() throws Exception {
+                                               return repository.login(workspace);
+                                       }
+                               });
+                       } catch (Exception e) {
+                               throw new CmsException("Cannot log in to JCR", e);
+                       }
+                       // return repository.login(workspace);
                }
 
                public void releaseSession(Session session) {
@@ -404,25 +459,27 @@ class DataHttp implements KernelConstants {
                @Override
                protected void service(final HttpServletRequest request, final HttpServletResponse response)
                                throws ServletException, IOException {
-                       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());
-                       }
+                       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());
+                       // }
                }
        }