Search in sources :

Example 21 with PermissionDeniedException

use of org.exist.security.PermissionDeniedException in project exist by eXist-db.

the class ZipFileFunctions method extractEntries.

private Sequence extractEntries(XmldbURI uri) throws XPathException {
    ZipFileSource zipFileSource = new ZipFileFromDb(uri);
    ZipInputStream zis = null;
    Sequence xmlResponse = null;
    context.pushDocumentContext();
    try {
        MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("file", ZipModule.NAMESPACE_URI, ZipModule.PREFIX), null);
        builder.addAttribute(new QName("href", null, null), uri.toString());
        try {
            zis = zipFileSource.getStream();
            ZipEntry zipEntry;
            while ((zipEntry = zis.getNextEntry()) != null) {
                if (zipEntry.isDirectory()) {
                    builder.startElement(new QName("dir", ZipModule.NAMESPACE_URI, ZipModule.PREFIX), null);
                    builder.addAttribute(new QName("name", null, null), zipEntry.toString());
                    builder.endElement();
                } else {
                    logger.debug("file: {}", zipEntry.getName());
                    builder.startElement(new QName("entry", ZipModule.NAMESPACE_URI, ZipModule.PREFIX), null);
                    builder.addAttribute(new QName("name", null, null), zipEntry.toString());
                    builder.endElement();
                }
            }
        } catch (PermissionDeniedException pde) {
            logger.error(pde.getMessage(), pde);
            throw new XPathException("Permission denied to read the source zip");
        } catch (IOException ioe) {
            logger.error(ioe.getMessage(), ioe);
            throw new XPathException("IO exception while reading the source zip");
        }
        builder.endElement();
        xmlResponse = (NodeValue) builder.getDocument().getDocumentElement();
        return (xmlResponse);
    } finally {
        context.popDocumentContext();
    }
}
Also used : ZipInputStream(java.util.zip.ZipInputStream) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) QName(org.exist.dom.QName) ZipEntry(java.util.zip.ZipEntry) PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException)

Example 22 with PermissionDeniedException

use of org.exist.security.PermissionDeniedException in project exist by eXist-db.

the class RestXqServlet method service.

@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    // authenticate
    final Subject user = authenticate(request, response);
    if (user == null) {
        // "Permission denied: unknown user or password");
        return;
    }
    try (final DBBroker broker = getPool().get(Optional.of(user))) {
        final Configuration configuration = broker.getConfiguration();
        final HttpRequest requestAdapter = new HttpServletRequestAdapter(request, () -> (String) configuration.getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY));
        final RestXqService service = getRegistry().findService(requestAdapter);
        if (service != null) {
            if (log.isTraceEnabled()) {
                log.trace("Received {} request for \"{}\" and found Resource Function \"{}\" in  module \"{}\"", requestAdapter.getMethod().name(), requestAdapter.getPath(), service.getResourceFunction().getFunctionSignature(), service.getResourceFunction().getXQueryLocation());
            }
            service.service(requestAdapter, new HttpServletResponseAdapter(response), new ResourceFunctionExecutorImpl(getPool(), request.getContextPath() + request.getServletPath(), request.getRequestURI()), new RestXqServiceSerializerImpl(getPool()));
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Received {} request for \"{}\" but no suitable Resource Function found!", requestAdapter.getMethod().name(), requestAdapter.getPath());
            }
            super.service(request, response);
        }
    } catch (final EXistException e) {
        getLog().error(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    } catch (final RestXqServiceException e) {
        if (e.getCause() instanceof PermissionDeniedException) {
            getAuthenticator().sendChallenge(request, response);
        } else {
            // TODO should probably be caught higher up and returned as a HTTP Response? maybe need two different types of exception to differentiate critical vs processing exception
            getLog().error(e.getMessage(), e);
            throw new ServletException(e.getMessage(), e);
        }
    }
}
Also used : HttpRequest(org.exquery.http.HttpRequest) HttpServletResponseAdapter(org.exist.extensions.exquery.restxq.impl.adapters.HttpServletResponseAdapter) RestXqServiceException(org.exquery.restxq.RestXqServiceException) Configuration(org.exist.util.Configuration) EXistException(org.exist.EXistException) Subject(org.exist.security.Subject) ServletException(javax.servlet.ServletException) RestXqService(org.exquery.restxq.RestXqService) DBBroker(org.exist.storage.DBBroker) HttpServletRequestAdapter(org.exist.extensions.exquery.restxq.impl.adapters.HttpServletRequestAdapter) PermissionDeniedException(org.exist.security.PermissionDeniedException)

Example 23 with PermissionDeniedException

use of org.exist.security.PermissionDeniedException in project exist by eXist-db.

the class Deployment method scanDirectory.

private List<String> scanDirectory(final DBBroker broker, final Txn transaction, final Path directory, final XmldbURI target, final InMemoryNodeSet resources, final boolean inRootDir, final boolean isResourcesDir, final Optional<RequestedPerms> requestedPerms, final List<String> errors) {
    Collection collection = null;
    try {
        collection = broker.getOrCreateCollection(transaction, target);
        setPermissions(broker, requestedPerms, true, null, collection.getPermissionsNoLock());
        broker.saveCollection(transaction, collection);
    } catch (final PermissionDeniedException | TriggerException | IOException e) {
        LOG.warn(e);
        errors.add(e.getMessage());
    }
    final boolean isResources = isResourcesDir || isResourceDir(target, resources);
    // the root dir is not allowed to be a resources directory
    if (!inRootDir && isResources) {
        try {
            storeBinaryResources(broker, transaction, directory, collection, requestedPerms, errors);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    } else {
        storeFiles(broker, transaction, directory, collection, inRootDir, requestedPerms, errors);
    }
    // scan sub directories
    try (final Stream<Path> subDirs = Files.find(directory, 1, (path, attrs) -> (!path.equals(directory)) && attrs.isDirectory())) {
        subDirs.forEach(path -> scanDirectory(broker, transaction, path, target.append(FileUtils.fileName(path)), resources, false, isResources, requestedPerms, errors));
    } catch (final IOException ioe) {
        LOG.warn("Unable to scan sub-directories", ioe);
    }
    return errors;
}
Also used : Path(java.nio.file.Path) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException) TriggerException(org.exist.collections.triggers.TriggerException) PermissionDeniedException(org.exist.security.PermissionDeniedException) EXistException(org.exist.EXistException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) TriggerException(org.exist.collections.triggers.TriggerException)

Example 24 with PermissionDeniedException

use of org.exist.security.PermissionDeniedException in project exist by eXist-db.

the class Deployment method checkUserSettings.

private void checkUserSettings(final DBBroker broker, final RequestedPerms requestedPerms) throws PackageException {
    final org.exist.security.SecurityManager secman = broker.getBrokerPool().getSecurityManager();
    try {
        if (requestedPerms.group.filter(g -> !secman.hasGroup(g)).isPresent()) {
            secman.addGroup(broker, new GroupAider(requestedPerms.group.get()));
        }
        if (!secman.hasAccount(requestedPerms.user)) {
            final UserAider aider = new UserAider(requestedPerms.user);
            aider.setPassword(requestedPerms.password);
            requestedPerms.group.ifPresent(aider::addGroup);
            secman.addAccount(broker, aider);
        }
    } catch (final PermissionDeniedException | EXistException e) {
        throw new PackageException("Failed to create user: " + requestedPerms.user, e);
    }
}
Also used : DependencyVersion(org.expath.pkg.repo.deps.DependencyVersion) Txn(org.exist.storage.txn.Txn) java.util(java.util) BufferedInputStream(java.io.BufferedInputStream) QName(org.exist.dom.QName) SequenceIterator(org.exist.xquery.value.SequenceIterator) PermissionDeniedException(org.exist.security.PermissionDeniedException) org.exist.xquery(org.exist.xquery) DirectoryStream(java.nio.file.DirectoryStream) JarEntry(java.util.jar.JarEntry) org.exist.dom.memtree(org.exist.dom.memtree) Collection(org.exist.collections.Collection) UnixStylePermission(org.exist.security.UnixStylePermission) XmldbURI(org.exist.xmldb.XmldbURI) Attributes(org.xml.sax.Attributes) JarInputStream(java.util.jar.JarInputStream) EXistException(org.exist.EXistException) DocUtils(org.exist.xquery.util.DocUtils) DateTimeValue(org.exist.xquery.value.DateTimeValue) SystemProperties(org.exist.SystemProperties) Path(java.nio.file.Path) Permission(org.exist.security.Permission) Nullable(javax.annotation.Nullable) BatchUserInteraction(org.expath.pkg.repo.tui.BatchUserInteraction) PermissionFactory(org.exist.security.PermissionFactory) InputSource(org.xml.sax.InputSource) Files(java.nio.file.Files) GroupAider(org.exist.security.internal.aider.GroupAider) Type(org.exist.xquery.value.Type) FileSource(org.exist.source.FileSource) IOException(java.io.IOException) UserAider(org.exist.security.internal.aider.UserAider) Either(com.evolvedbinary.j8fu.Either) org.expath.pkg.repo(org.expath.pkg.repo) Logger(org.apache.logging.log4j.Logger) Element(org.w3c.dom.Element) Stream(java.util.stream.Stream) DBBroker(org.exist.storage.DBBroker) SAXException(org.xml.sax.SAXException) org.exist.util(org.exist.util) Sequence(org.exist.xquery.value.Sequence) TriggerException(org.exist.collections.triggers.TriggerException) LogManager(org.apache.logging.log4j.LogManager) Package(org.expath.pkg.repo.Package) AttrList(org.exist.util.serializer.AttrList) InputStream(java.io.InputStream) PermissionDeniedException(org.exist.security.PermissionDeniedException) EXistException(org.exist.EXistException) GroupAider(org.exist.security.internal.aider.GroupAider) UserAider(org.exist.security.internal.aider.UserAider)

Example 25 with PermissionDeniedException

use of org.exist.security.PermissionDeniedException in project exist by eXist-db.

the class Deployment method runQuery.

private Sequence runQuery(final DBBroker broker, final XmldbURI targetCollection, final Path tempDir, final String fileName, final String pkgName, final QueryPurpose purpose) throws PackageException, IOException, XPathException {
    final Path xquery = tempDir.resolve(fileName);
    if (!Files.isReadable(xquery)) {
        LOG.warn("The XQuery resource specified in the {} was not found for EXPath Package: '{}'", purpose.getPurposeString(), pkgName);
        return Sequence.EMPTY_SEQUENCE;
    }
    final XQuery xqs = broker.getBrokerPool().getXQueryService();
    final XQueryContext ctx = new XQueryContext(broker.getBrokerPool());
    ctx.declareVariable("dir", tempDir.toAbsolutePath().toString());
    final Optional<Path> home = broker.getConfiguration().getExistHome();
    if (home.isPresent()) {
        ctx.declareVariable("home", home.get().toAbsolutePath().toString());
    }
    if (targetCollection != null) {
        ctx.declareVariable("target", targetCollection.toString());
        ctx.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI + targetCollection.toString());
    } else {
        ctx.declareVariable("target", Sequence.EMPTY_SEQUENCE);
    }
    if (QueryPurpose.PREINSTALL == purpose) {
        // when running pre-setup scripts, base path should point to directory
        // because the target collection does not yet exist
        ctx.setModuleLoadPath(tempDir.toAbsolutePath().toString());
    }
    CompiledXQuery compiled;
    try {
        compiled = xqs.compile(ctx, new FileSource(xquery, false));
        return xqs.execute(broker, compiled, null);
    } catch (final PermissionDeniedException e) {
        throw new PackageException(e.getMessage(), e);
    }
}
Also used : Path(java.nio.file.Path) FileSource(org.exist.source.FileSource) PermissionDeniedException(org.exist.security.PermissionDeniedException)

Aggregations

PermissionDeniedException (org.exist.security.PermissionDeniedException)182 EXistException (org.exist.EXistException)82 XmldbURI (org.exist.xmldb.XmldbURI)70 IOException (java.io.IOException)58 DocumentImpl (org.exist.dom.persistent.DocumentImpl)48 Collection (org.exist.collections.Collection)44 DBBroker (org.exist.storage.DBBroker)41 Txn (org.exist.storage.txn.Txn)38 LockException (org.exist.util.LockException)35 SAXException (org.xml.sax.SAXException)35 LockedDocument (org.exist.dom.persistent.LockedDocument)31 XPathException (org.exist.xquery.XPathException)31 Permission (org.exist.security.Permission)23 URISyntaxException (java.net.URISyntaxException)22 TriggerException (org.exist.collections.triggers.TriggerException)22 Source (org.exist.source.Source)20 Path (java.nio.file.Path)19 Account (org.exist.security.Account)18 InputSource (org.xml.sax.InputSource)18 Sequence (org.exist.xquery.value.Sequence)17