Search in sources :

Example 71 with PermissionDeniedException

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

the class Deployment method storeRepoXML.

/**
 * Store repo.xml into the db. Adds the time of deployment to the descriptor.
 *
 * @param repoXML
 * @param targetCollection
 * @throws XPathException
 */
private void storeRepoXML(final DBBroker broker, final Txn transaction, final DocumentImpl repoXML, final XmldbURI targetCollection, final Optional<RequestedPerms> requestedPerms) throws PackageException, XPathException {
    // Store repo.xml
    final DateTimeValue time = new DateTimeValue(new Date());
    final MemTreeBuilder builder = new MemTreeBuilder();
    builder.startDocument();
    final UpdatingDocumentReceiver receiver = new UpdatingDocumentReceiver(builder, time.getStringValue());
    try {
        repoXML.copyTo(broker, receiver);
    } catch (final SAXException e) {
        throw new PackageException("Error while updating repo.xml in-memory: " + e.getMessage(), e);
    }
    builder.endDocument();
    final DocumentImpl updatedXML = builder.getDocument();
    try {
        final Collection collection = broker.getOrCreateCollection(transaction, targetCollection);
        final XmldbURI name = XmldbURI.createInternal("repo.xml");
        final Permission permission = PermissionFactory.getDefaultResourcePermission(broker.getBrokerPool().getSecurityManager());
        setPermissions(broker, requestedPerms, false, MimeType.XML_TYPE, permission);
        collection.storeDocument(transaction, broker, name, updatedXML, MimeType.XML_TYPE, null, null, permission, null, null);
    } catch (final PermissionDeniedException | IOException | SAXException | LockException | EXistException e) {
        throw new PackageException("Error while storing updated repo.xml: " + e.getMessage(), e);
    }
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) IOException(java.io.IOException) EXistException(org.exist.EXistException) SAXException(org.xml.sax.SAXException) UnixStylePermission(org.exist.security.UnixStylePermission) Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 72 with PermissionDeniedException

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

the class SecurityManagerImpl method processParameter.

@Override
public void processParameter(final DBBroker broker, final DocumentImpl document) throws ConfigurationException {
    XmldbURI uri = document.getCollection().getURI();
    final boolean isRemoved = uri.endsWith(SecurityManager.REMOVED_COLLECTION_URI);
    if (isRemoved) {
        uri = uri.removeLastSegment();
    }
    final boolean isAccount = uri.endsWith(SecurityManager.ACCOUNTS_COLLECTION_URI);
    final boolean isGroup = uri.endsWith(SecurityManager.GROUPS_COLLECTION_URI);
    if (isAccount || isGroup) {
        uri = uri.removeLastSegment();
        final String realmId = uri.lastSegment().toString();
        final AbstractRealm realm = (AbstractRealm) findRealmForRealmId(realmId);
        final Configuration conf = Configurator.parse(broker.getBrokerPool(), document);
        Integer id = -1;
        if (isRemoved) {
            id = conf.getPropertyInteger("id");
        }
        final String name = conf.getProperty("name");
        if (isAccount) {
            if (isRemoved && id > 2 && !hasUser(id)) {
                final AccountImpl account = new AccountImpl(realm, conf);
                account.removed = true;
                registerAccount(account);
            } else if (name != null) {
                if (realm.hasAccount(name)) {
                    final Integer oldId = saving.get(document.getURI());
                    final Integer newId = conf.getPropertyInteger("id");
                    if (!newId.equals(oldId)) {
                        final Account current = realm.getAccount(name);
                        try (final ManagedLock<ReadWriteLock> lock = ManagedLock.acquire(accountLocks.getLock(current), LockMode.WRITE_LOCK)) {
                            usersById.write(principalDb -> {
                                principalDb.remove(oldId);
                                principalDb.put(newId, current);
                            });
                        }
                    }
                } else {
                    final Account account = new AccountImpl(realm, conf);
                    if (account.getGroups().length == 0) {
                        try {
                            account.setPrimaryGroup(realm.getGroup(SecurityManager.UNKNOWN_GROUP));
                            LOG.warn("Account '{}' has no groups, but every account must have at least 1 group. Assigned group: " + SecurityManager.UNKNOWN_GROUP, account.getName());
                        } catch (final PermissionDeniedException e) {
                            throw new ConfigurationException("Account has no group, unable to default to " + SecurityManager.UNKNOWN_GROUP + ": " + e.getMessage(), e);
                        }
                    }
                    registerAccount(account);
                    realm.registerAccount(account);
                }
            } else {
                // this can't be! log any way
                LOG.error("Account '{}' already exists in realm: '{}', but received notification that a new one was created.", name, realmId);
            }
        } else if (isGroup) {
            if (isRemoved && id > 2 && !hasGroup(id)) {
                final GroupImpl group = new GroupImpl(realm, conf);
                group.removed = true;
                registerGroup(group);
            } else if (name != null && !realm.hasGroup(name)) {
                final GroupImpl group = new GroupImpl(realm, conf);
                registerGroup(group);
                realm.registerGroup(group);
            } else {
                // this can't be! log any way
                LOG.error("Group '{}' already exists in realm: '{}', but received notification that a new one was created.", name, realmId);
            }
        }
        saving.remove(document.getURI());
    }
}
Also used : LockMode(org.exist.storage.lock.Lock.LockMode) Txn(org.exist.storage.txn.Txn) BrokerPool(org.exist.storage.BrokerPool) ConfigurationException(org.exist.config.ConfigurationException) BiFunction(java.util.function.BiFunction) JobDescription(org.exist.scheduler.JobDescription) PermissionDeniedException(org.exist.security.PermissionDeniedException) ConcurrentValueWrapper(org.exist.util.ConcurrentValueWrapper) Configuration(org.exist.config.Configuration) Configurator(org.exist.config.Configurator) Map(java.util.Map) SchemaType(org.exist.security.SchemaType) Collection(org.exist.collections.Collection) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) JobExecutionContext(org.quartz.JobExecutionContext) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) AbstractRealm(org.exist.security.AbstractRealm) AuthenticationException(org.exist.security.AuthenticationException) GroupAider(org.exist.security.internal.aider.GroupAider) Session(org.exist.security.Session) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AtomicLazyVal(com.evolvedbinary.j8fu.lazy.AtomicLazyVal) Collectors(java.util.stream.Collectors) SecurityManager(org.exist.security.SecurityManager) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Principal(org.exist.security.Principal) ManagedLock(org.exist.storage.lock.ManagedLock) JobDataMap(org.quartz.JobDataMap) Realm(org.exist.security.realm.Realm) WeakLazyStripes(org.exist.util.WeakLazyStripes) ThreadSafe(net.jcip.annotations.ThreadSafe) HashMap(java.util.HashMap) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ArrayList(java.util.ArrayList) Account(org.exist.security.Account) Subject(org.exist.security.Subject) BrokerPoolServiceException(org.exist.storage.BrokerPoolServiceException) XmldbURI(org.exist.xmldb.XmldbURI) SimpleTrigger(org.quartz.SimpleTrigger) DocumentImpl(org.exist.dom.persistent.DocumentImpl) EXistException(org.exist.EXistException) Permission(org.exist.security.Permission) Database(org.exist.Database) Properties(java.util.Properties) Group(org.exist.security.Group) BrokerPoolService(org.exist.storage.BrokerPoolService) org.exist.config.annotation(org.exist.config.annotation) DBBroker(org.exist.storage.DBBroker) Int2ObjectMap(it.unimi.dsi.fastutil.ints.Int2ObjectMap) LogManager(org.apache.logging.log4j.LogManager) Account(org.exist.security.Account) Configuration(org.exist.config.Configuration) AbstractRealm(org.exist.security.AbstractRealm) ManagedLock(org.exist.storage.lock.ManagedLock) ConfigurationException(org.exist.config.ConfigurationException) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 73 with PermissionDeniedException

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

the class Serializer method parse.

public void parse(String systemId) throws IOException, SAXException {
    try {
        // try to load document from eXist
        // TODO: this systemId came from exist, so should be an unchecked create, right?
        final DocumentImpl doc = broker.getResource(XmldbURI.create(systemId), Permission.READ);
        if (doc == null) {
            throw new SAXException("document " + systemId + " not found in database");
        } else {
            LOG.debug("serializing {}", doc.getFileURI());
        }
        toSAX(doc);
    } catch (final PermissionDeniedException e) {
        throw new SAXException("permission denied");
    }
}
Also used : PermissionDeniedException(org.exist.security.PermissionDeniedException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) SAXException(org.xml.sax.SAXException)

Example 74 with PermissionDeniedException

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

the class Serializer method setStylesheet.

/**
 *  Plug an XSL stylesheet into the processing pipeline.
 *  All output will be passed to this stylesheet.
 *
 * @param doc the document
 * @param stylesheet the stylesheet
 *
 * @throws TransformerConfigurationException if the stylesheet cannot be set
 */
public void setStylesheet(Document doc, String stylesheet) throws TransformerConfigurationException {
    if (stylesheet == null) {
        templates = null;
        return;
    }
    final long start = System.currentTimeMillis();
    xslHandler = null;
    XmldbURI stylesheetUri = null;
    URI externalUri = null;
    try {
        stylesheetUri = XmldbURI.xmldbUriFor(stylesheet);
        if (!stylesheetUri.toCollectionPathURI().equals(stylesheetUri)) {
            externalUri = stylesheetUri.getXmldbURI();
        }
    } catch (final URISyntaxException e) {
        // could be an external URI!
        try {
            externalUri = new URI(stylesheet);
        } catch (final URISyntaxException ee) {
            throw new IllegalArgumentException("Stylesheet URI could not be parsed: " + ee.getMessage());
        }
    }
    // does stylesheet point to an external resource?
    if (externalUri != null) {
        final StreamSource source = new StreamSource(externalUri.toString());
        this.templates = factory.get().newTemplates(source);
    // read stylesheet from the database
    } else {
        // current collection and normalize
        if (doc != null && doc instanceof DocumentImpl) {
            stylesheetUri = ((DocumentImpl) doc).getCollection().getURI().resolveCollectionPath(stylesheetUri).normalizeCollectionPath();
        }
        // load stylesheet from eXist
        DocumentImpl xsl = null;
        try {
            xsl = broker.getResource(stylesheetUri, Permission.READ);
        } catch (final PermissionDeniedException e) {
            throw new TransformerConfigurationException("permission denied to read " + stylesheetUri);
        }
        if (xsl == null) {
            throw new TransformerConfigurationException("stylesheet not found: " + stylesheetUri);
        }
        // TODO: use xmldbURI
        if (xsl.getCollection() != null) {
            factory.get().setURIResolver(new InternalURIResolver(xsl.getCollection().getURI().toString()));
        }
        // save handlers
        Receiver oldReceiver = receiver;
        // compile stylesheet
        factory.get().setErrorListener(new ErrorListener());
        final TemplatesHandler handler = factory.get().newTemplatesHandler();
        receiver = new ReceiverToSAX(handler);
        try {
            this.serializeToReceiver(xsl, true);
            templates = handler.getTemplates();
        } catch (final SAXException e) {
            throw new TransformerConfigurationException(e.getMessage(), e);
        }
        // restore handlers
        receiver = oldReceiver;
        factory.get().setURIResolver(null);
    }
    LOG.debug("compiling stylesheet took {}", System.currentTimeMillis() - start);
    if (templates != null) {
        xslHandler = factory.get().newTransformerHandler(templates);
        try {
            xslHandler.startDocument();
            documentStarted = true;
        } catch (final SAXException e) {
            throw new TransformerConfigurationException(e.getMessage(), e);
        }
    }
    // xslHandler.getTransformer().setOutputProperties(outputProperties);
    checkStylesheetParams();
}
Also used : TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) ReceiverToSAX(org.exist.util.serializer.ReceiverToSAX) StreamSource(javax.xml.transform.stream.StreamSource) Receiver(org.exist.util.serializer.Receiver) TemplatesHandler(javax.xml.transform.sax.TemplatesHandler) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) XmldbURI(org.exist.xmldb.XmldbURI) DocumentImpl(org.exist.dom.persistent.DocumentImpl) SAXException(org.xml.sax.SAXException) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 75 with PermissionDeniedException

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

the class ExtCollection method eval.

@Override
public Sequence eval(final Sequence contextSequence, final Item contextItem) throws XPathException {
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().start(this);
        context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
        if (contextSequence != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
        }
        if (contextItem != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
        }
    }
    final List<String> args = getParameterValues(contextSequence, contextItem);
    final Sequence result;
    try {
        if (args.isEmpty()) {
            final Sequence docs = toSequence(context.getStaticallyKnownDocuments());
            final Sequence dynamicCollection = context.getDynamicallyAvailableCollection("");
            if (dynamicCollection != null) {
                result = new ValueSequence();
                result.addAll(docs);
                result.addAll(dynamicCollection);
            } else {
                result = docs;
            }
        } else {
            final Sequence dynamicCollection = context.getDynamicallyAvailableCollection(asUri(args.get(0)).toString());
            if (dynamicCollection != null) {
                result = dynamicCollection;
            } else {
                final MutableDocumentSet ndocs = new DefaultDocumentSet();
                for (final String next : args) {
                    final XmldbURI uri = new AnyURIValue(next).toXmldbURI();
                    try (final Collection coll = context.getBroker().openCollection(uri, Lock.LockMode.READ_LOCK)) {
                        if (coll == null) {
                            if (context.isRaiseErrorOnFailedRetrieval()) {
                                throw new XPathException(this, ErrorCodes.FODC0002, "Can not access collection '" + uri + "'");
                            }
                        } else {
                            if (context.inProtectedMode()) {
                                context.getProtectedDocs().getDocsByCollection(coll, ndocs);
                            } else {
                                coll.allDocs(context.getBroker(), ndocs, includeSubCollections, context.getProtectedDocs());
                            }
                        }
                    }
                }
                result = toSequence(ndocs);
            }
        }
    } catch (final XPathException e) {
        // From AnyURIValue constructor
        e.setLocation(line, column);
        Sequence flattenedArgs = Sequence.EMPTY_SEQUENCE;
        try {
            flattenedArgs = argsToSeq(contextSequence, contextItem);
        } catch (final XPathException xe) {
            LOG.warn(e.getMessage(), xe);
        }
        throw new XPathException(this, ErrorCodes.FODC0002, e.getMessage(), flattenedArgs, e);
    } catch (final PermissionDeniedException e) {
        Sequence flattenedArgs = Sequence.EMPTY_SEQUENCE;
        try {
            flattenedArgs = argsToSeq(contextSequence, contextItem);
        } catch (final XPathException xe) {
            LOG.warn(e.getMessage(), xe);
        }
        throw new XPathException(this, ErrorCodes.FODC0002, "Can not access collection '" + e.getMessage() + "'", flattenedArgs, e);
    } catch (final LockException e) {
        Sequence flattenedArgs = Sequence.EMPTY_SEQUENCE;
        try {
            flattenedArgs = argsToSeq(contextSequence, contextItem);
        } catch (final XPathException xe) {
            LOG.warn(e.getMessage(), xe);
        }
        throw new XPathException(this, ErrorCodes.FODC0002, e.getMessage(), flattenedArgs, e);
    }
    // iterate through all docs and create the node set
    registerUpdateListener();
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", result);
    }
    return result;
}
Also used : LockException(org.exist.util.LockException) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

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