Search in sources :

Example 1 with PermissionDeniedException

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

the class MutableCollection method storeDocument.

@Override
public void storeDocument(final Txn transaction, final DBBroker broker, final XmldbURI name, final InputSource source, @Nullable MimeType mimeType, @Nullable final Date createdDate, @Nullable final Date lastModifiedDate, @Nullable final Permission permission, @Nullable final DocumentType documentType, @Nullable final XMLReader xmlReader) throws EXistException, PermissionDeniedException, SAXException, LockException, IOException {
    if (mimeType == null) {
        mimeType = MimeType.BINARY_TYPE;
    }
    if (mimeType.isXMLType()) {
        // Store XML Document
        final BiConsumer2E<XMLReader, IndexInfo, SAXException, EXistException> validatorFn = (xmlReader1, validateIndexInfo) -> {
            validateIndexInfo.setReader(xmlReader1, null);
            try {
                xmlReader1.parse(source);
            } catch (final SAXException e) {
                throw new SAXException("The XML parser reported a problem: " + e.getMessage(), e);
            } catch (final IOException e) {
                throw new EXistException(e);
            }
        };
        final BiConsumer2E<XMLReader, IndexInfo, SAXException, EXistException> parserFn = (xmlReader1, storeIndexInfo) -> {
            try {
                storeIndexInfo.setReader(xmlReader1, null);
                xmlReader1.parse(source);
            } catch (final IOException e) {
                throw new EXistException(e);
            }
        };
        storeXmlDocument(transaction, broker, name, mimeType, createdDate, lastModifiedDate, permission, documentType, xmlReader, validatorFn, parserFn);
    } else {
        // Store Binary Document
        try (final InputStream is = source.getByteStream()) {
            if (is == null) {
                throw new IOException("storeDocument received a null InputStream when trying to store a Binary Document");
            }
            addBinaryResource(transaction, broker, name, is, mimeType.getName(), -1, createdDate, lastModifiedDate, permission);
        }
    }
}
Also used : CloseShieldReader(org.apache.commons.io.input.CloseShieldReader) java.util(java.util) LockMode(org.exist.storage.lock.Lock.LockMode) Txn(org.exist.storage.txn.Txn) Consumer2E(com.evolvedbinary.j8fu.function.Consumer2E) QName(org.exist.dom.QName) PermissionDeniedException(org.exist.security.PermissionDeniedException) org.exist.dom.persistent(org.exist.dom.persistent) Constants(org.exist.xquery.Constants) VariableByteOutputStream(org.exist.storage.io.VariableByteOutputStream) VALIDATION_SETTING(org.exist.util.XMLReaderObjectFactory.VALIDATION_SETTING) MimeType(org.exist.util.MimeType) Account(org.exist.security.Account) XMLReader(org.xml.sax.XMLReader) org.exist.storage(org.exist.storage) IndexController(org.exist.indexing.IndexController) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream) LockException(org.exist.util.LockException) Subject(org.exist.security.Subject) VariableByteInput(org.exist.storage.io.VariableByteInput) Node(org.w3c.dom.Node) XmldbURI(org.exist.xmldb.XmldbURI) LockType(org.exist.storage.lock.Lock.LockType) BiConsumer2E(com.evolvedbinary.j8fu.function.BiConsumer2E) EXistException(org.exist.EXistException) Indexer(org.exist.Indexer) Permission(org.exist.security.Permission) Nullable(javax.annotation.Nullable) PermissionFactory(org.exist.security.PermissionFactory) InputSource(org.xml.sax.InputSource) Database(org.exist.Database) XMLReaderObjectFactory(org.exist.util.XMLReaderObjectFactory) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) org.exist.storage.lock(org.exist.storage.lock) DOMStreamer(org.exist.util.serializer.DOMStreamer) Sync(org.exist.storage.sync.Sync) NotThreadSafe(net.jcip.annotations.NotThreadSafe) org.exist.collections.triggers(org.exist.collections.triggers) DocumentType(org.w3c.dom.DocumentType) StreamListener(org.exist.indexing.StreamListener) Logger(org.apache.logging.log4j.Logger) java.io(java.io) SAXException(org.xml.sax.SAXException) GuardedBy(net.jcip.annotations.GuardedBy) Configuration(org.exist.util.Configuration) LogManager(org.apache.logging.log4j.LogManager) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) EXistException(org.exist.EXistException) XMLReader(org.xml.sax.XMLReader) SAXException(org.xml.sax.SAXException)

Example 2 with PermissionDeniedException

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

the class MutableCollection method deserialize.

/**
 * Read collection contents from the stream
 *
 * Counterpart method to {@link #serialize(VariableByteOutputStream)}
 *
 * @param broker The database broker
 * @param path The path of the Collection
 * @param istream The input stream to deserialize the Collection from
 */
private static MutableCollection deserialize(final DBBroker broker, final XmldbURI path, final VariableByteInput istream) throws IOException, PermissionDeniedException, LockException {
    final int collectionId = istream.readInt();
    if (collectionId < 0) {
        throw new IOException("Internal error reading collection: invalid collection id");
    }
    final int collLen = istream.readInt();
    // TODO(AR) should we WRITE_LOCK the Collection to stop it being loaded from disk concurrently? see NativeBroker#openCollection line 1030 - already has READ_LOCK ;-)
    // try(final ManagedCollectionLock collectionLock = lockManager.acquireCollectionWriteLock(path, false)) {
    final LinkedHashSet<XmldbURI> subCollections = new LinkedHashSet<>(Math.max(16, collLen));
    for (int i = 0; i < collLen; i++) {
        subCollections.add(XmldbURI.create(istream.readUTF()));
    }
    final Permission permission = PermissionFactory.getDefaultCollectionPermission(broker.getBrokerPool().getSecurityManager());
    permission.read(istream);
    if (!permission.validate(broker.getCurrentSubject(), Permission.EXECUTE)) {
        throw new PermissionDeniedException("Permission denied to open the Collection " + path);
    }
    final long created = istream.readLong();
    final LinkedHashMap<String, DocumentImpl> documents = new LinkedHashMap<>();
    final MutableCollection collection = new MutableCollection(broker, collectionId, path, permission, created, subCollections, documents);
    broker.getCollectionResources(new InternalAccess() {

        @Override
        public void addDocument(final DocumentImpl doc) throws EXistException {
            doc.setCollection(collection);
            if (doc.getDocId() == DocumentImpl.UNKNOWN_DOCUMENT_ID) {
                LOG.error("Document must have ID. [{}]", doc);
                throw new EXistException("Document must have ID.");
            }
            documents.put(doc.getFileURI().lastSegmentString(), doc);
        }

        @Override
        public int getId() {
            return collectionId;
        }
    });
    return collection;
// }
}
Also used : EXistException(org.exist.EXistException) Permission(org.exist.security.Permission) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 3 with PermissionDeniedException

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

the class CollectionConfigurationManager method checkCreateCollection.

/**
 * Check if the collection exists below the system collection. If not,
 * create it.
 *
 * @param broker eXist-db broker
 * @param txn according transaction
 * @param uri to the collection to create
 * @throws EXistException if something goes wrong
 */
private void checkCreateCollection(final DBBroker broker, final Txn txn, final XmldbURI uri) throws EXistException {
    try {
        Collection collection = broker.getCollection(uri);
        if (collection == null) {
            collection = broker.getOrCreateCollection(txn, uri);
            SanityCheck.THROW_ASSERT(collection != null);
            broker.saveCollection(txn, collection);
        }
    } catch (final TriggerException | PermissionDeniedException | IOException e) {
        throw new EXistException("Failed to initialize '" + uri + "' : " + e.getMessage());
    }
}
Also used : PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException) EXistException(org.exist.EXistException) TriggerException(org.exist.collections.triggers.TriggerException)

Example 4 with PermissionDeniedException

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

the class SystemExport method export.

/**
 * Export a collection. Write out the collection metadata and save the resources stored in the collection.
 *
 * @param current    the collection
 * @param output     the output writer
 * @param date
 * @param prevBackup DOCUMENT ME!
 * @param errorList  a list of {@link org.exist.backup.ErrorReport} objects as returned by methods in {@link org.exist.backup.ConsistencyCheck}
 * @param docs       a document set to keep track of all written documents.
 * @throws IOException
 * @throws SAXException
 * @throws TerminatedException DOCUMENT ME!
 */
private void export(final BackupHandler bh, final Collection current, final BackupWriter output, final Date date, final BackupDescriptor prevBackup, final List<ErrorReport> errorList, final MutableDocumentSet docs) throws IOException, SAXException, TerminatedException, PermissionDeniedException {
    if ((monitor != null) && !monitor.proceed()) {
        throw (new TerminatedException("system export terminated by db"));
    }
    // if( !current.getURI().equalsInternal( XmldbURI.ROOT_COLLECTION_URI ) ) {
    output.newCollection(Backup.encode(URIUtils.urlDecodeUtf8(current.getURI())));
    // }
    final SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
    try {
        final Writer contents = output.newContents();
        // serializer writes to __contents__.xml
        serializer.setOutput(contents, contentsOutputProps);
        final Permission perm = current.getPermissionsNoLock();
        serializer.startDocument();
        serializer.startPrefixMapping("", Namespaces.EXIST_NS);
        final XmldbURI uri = current.getURI();
        final AttributesImpl attr = new AttributesImpl();
        attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", uri.toString());
        attr.addAttribute(Namespaces.EXIST_NS, "version", "version", "CDATA", String.valueOf(currVersion));
        Backup.writeUnixStylePermissionAttributes(attr, perm);
        try {
            attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", new DateTimeValue(new Date(current.getCreated())).getStringValue());
        } catch (final XPathException e) {
            e.printStackTrace();
        }
        bh.backup(current, attr);
        serializer.startElement(Namespaces.EXIST_NS, "collection", "collection", attr);
        if (perm instanceof ACLPermission) {
            Backup.writeACLPermission(serializer, (ACLPermission) perm);
        }
        bh.backup(current, serializer);
        final int docsCount = current.getDocumentCountNoLock(broker);
        int count = 0;
        for (final Iterator<DocumentImpl> i = current.iteratorNoLock(broker); i.hasNext(); count++) {
            final DocumentImpl doc = i.next();
            if (isDamaged(doc, errorList)) {
                reportError("Skipping damaged document " + doc.getFileURI(), null);
                continue;
            }
            if (doc.getFileURI().equalsInternal(CONTENTS_URI) || doc.getFileURI().equalsInternal(LOST_URI)) {
                // skip __contents__.xml documents
                continue;
            }
            exportDocument(bh, output, date, prevBackup, serializer, docsCount, count, doc);
            docs.add(doc, false);
        }
        for (final Iterator<XmldbURI> i = current.collectionIteratorNoLock(broker); i.hasNext(); ) {
            final XmldbURI childUri = i.next();
            if (childUri.equalsInternal(TEMP_COLLECTION)) {
                continue;
            }
            if (isDamagedChild(childUri, errorList)) {
                reportError("Skipping damaged child collection " + childUri, null);
                continue;
            }
            attr.clear();
            attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", childUri.toString());
            attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", Backup.encode(URIUtils.urlDecodeUtf8(childUri.toString())));
            serializer.startElement(Namespaces.EXIST_NS, "subcollection", "subcollection", attr);
            serializer.endElement(Namespaces.EXIST_NS, "subcollection", "subcollection");
        }
        if (prevBackup != null) {
            // Check which collections and resources have been deleted since
            // the
            // last backup
            final CheckDeletedHandler check = new CheckDeletedHandler(current, serializer);
            try {
                prevBackup.parse(broker.getBrokerPool().getParserPool(), check);
            } catch (final Exception e) {
                LOG.error("Caught exception while trying to parse previous backup descriptor: {}", prevBackup.getSymbolicPath(), e);
            }
        }
        // close <collection>
        serializer.endElement(Namespaces.EXIST_NS, "collection", "collection");
        serializer.endPrefixMapping("");
        serializer.endDocument();
        output.closeContents();
    } finally {
        SerializerPool.getInstance().returnObject(serializer);
        // if( !current.getURI().equalsInternal( XmldbURI.ROOT_COLLECTION_URI ) ) {
        output.closeCollection();
    // }
    }
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) ACLPermission(org.exist.security.ACLPermission) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockException(org.exist.util.LockException) TerminatedException(org.exist.xquery.TerminatedException) XMLStreamException(javax.xml.stream.XMLStreamException) SAXException(org.xml.sax.SAXException) XPathException(org.exist.xquery.XPathException) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) SAXSerializer(org.exist.util.serializer.SAXSerializer) TerminatedException(org.exist.xquery.TerminatedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 5 with PermissionDeniedException

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

the class CollectionDeferredPermission method apply.

@Override
public void apply(final DBBroker broker, final Txn transaction) {
    try (final Collection collection = broker.openCollection(getTarget(), Lock.LockMode.WRITE_LOCK)) {
        final Permission permission = collection.getPermissions();
        PermissionFactory.chown(broker, permission, Optional.ofNullable(getOwner()), Optional.ofNullable(getGroup()));
        PermissionFactory.chmod(broker, permission, Optional.of(getMode()), Optional.ofNullable(permission instanceof ACLPermission ? getAces() : null));
        broker.saveCollection(transaction, collection);
    } catch (final PermissionDeniedException | IOException e) {
        final String msg = "ERROR: Failed to set permissions on Collection '" + getTarget() + "'.";
        LOG.error(msg, e);
        getListener().warn(msg);
    }
}
Also used : ACLPermission(org.exist.security.ACLPermission) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException)

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