Search in sources :

Example 1 with AuthorizationException

use of com.dexels.navajo.script.api.AuthorizationException in project navajo by Dexels.

the class ServiceCommand method handleError.

private void handleError(Navajo result) throws UserException, AuthorizationException, ConditionErrorException {
    Message error = result.getMessage("error");
    if (error != null) {
        String errMsg = error.getProperty("message").getValue();
        String errCode = error.getProperty("code").getValue();
        int errorCode = -1;
        try {
            errorCode = Integer.parseInt(errCode);
        } catch (NumberFormatException e) {
            logger.error("Error: ", e);
        }
        throw new UserException(errorCode, errMsg);
    }
    boolean authenticationError = false;
    Message aaaError = result.getMessage(AuthorizationException.AUTHENTICATION_ERROR_MESSAGE);
    if (aaaError == null) {
        aaaError = result.getMessage(AuthorizationException.AUTHORIZATION_ERROR_MESSAGE);
    } else {
        authenticationError = true;
    }
    if (aaaError != null) {
        throw new AuthorizationException(authenticationError, !authenticationError, aaaError.getProperty("User").getValue(), aaaError.getProperty("Message").getValue());
    }
    if (result.getMessage("ConditionErrors") != null) {
        throw new ConditionErrorException(result);
    }
}
Also used : ConditionErrorException(com.dexels.navajo.server.ConditionErrorException) Message(com.dexels.navajo.document.Message) AuthorizationException(com.dexels.navajo.script.api.AuthorizationException) UserException(com.dexels.navajo.script.api.UserException)

Example 2 with AuthorizationException

use of com.dexels.navajo.script.api.AuthorizationException in project navajo by Dexels.

the class ServiceCommand method performCall.

protected Navajo performCall(ArticleRuntime runtime, String name, Navajo n, String instance) throws APIException {
    try {
        Navajo result = dispatcher.handle(n, instance, true);
        handleError(result);
        return result;
    } catch (UserException | AuthorizationException | FatalException e) {
        throw new APIException(e.getMessage(), e, APIErrorCode.InternalError);
    } catch (ConditionErrorException e) {
        throw new APIException(e.getMessage(), e, APIErrorCode.ConditionError);
    }
}
Also used : ConditionErrorException(com.dexels.navajo.server.ConditionErrorException) APIException(com.dexels.navajo.article.APIException) AuthorizationException(com.dexels.navajo.script.api.AuthorizationException) FatalException(com.dexels.navajo.script.api.FatalException) Navajo(com.dexels.navajo.document.Navajo) UserException(com.dexels.navajo.script.api.UserException)

Example 3 with AuthorizationException

use of com.dexels.navajo.script.api.AuthorizationException in project navajo by Dexels.

the class Dispatcher method generateAuthorizationErrorMessage.

/**
 * Generate a Navajo authorization error response.
 *
 * @param access
 *            Beware, might be null
 * @param ae
 * @return
 * @throws FatalException
 */
private final Navajo generateAuthorizationErrorMessage(Access access, AuthorizationException ae, String rpcName) throws FatalException {
    try {
        Navajo outMessage = NavajoFactory.getInstance().createNavajo();
        // Make sure empty Header is constructed
        Header h = NavajoFactory.getInstance().createHeader(outMessage, "", "", "", -1);
        outMessage.addHeader(h);
        Message errorMessage = NavajoFactory.getInstance().createMessage(outMessage, (ae.isNotAuthorized() ? AuthorizationException.AUTHORIZATION_ERROR_MESSAGE : AuthorizationException.AUTHENTICATION_ERROR_MESSAGE));
        outMessage.addMessage(errorMessage);
        Property prop = NavajoFactory.getInstance().createProperty(outMessage, "Message", Property.STRING_PROPERTY, ae.getMessage(), 0, "Message", Property.DIR_OUT);
        errorMessage.addProperty(prop);
        prop = NavajoFactory.getInstance().createProperty(outMessage, "User", Property.STRING_PROPERTY, ae.getUser(), 0, "User", Property.DIR_OUT);
        errorMessage.addProperty(prop);
        prop = NavajoFactory.getInstance().createProperty(outMessage, "Webservice", Property.STRING_PROPERTY, rpcName, 0, "User", Property.DIR_OUT);
        errorMessage.addProperty(prop);
        if (access != null) {
            access.setException(ae);
            access.setOutputDoc(outMessage);
        }
        return outMessage;
    } catch (Exception e) {
        throw new FatalException(e.getMessage(), e);
    }
}
Also used : Header(com.dexels.navajo.document.Header) Message(com.dexels.navajo.document.Message) FatalException(com.dexels.navajo.script.api.FatalException) Navajo(com.dexels.navajo.document.Navajo) Property(com.dexels.navajo.document.Property) FatalException(com.dexels.navajo.script.api.FatalException) NavajoException(com.dexels.navajo.document.NavajoException) AuthorizationException(com.dexels.navajo.script.api.AuthorizationException) UserException(com.dexels.navajo.script.api.UserException) TriggerException(com.dexels.navajo.server.enterprise.scheduler.TriggerException) IOException(java.io.IOException) SystemException(com.dexels.navajo.script.api.SystemException)

Example 4 with AuthorizationException

use of com.dexels.navajo.script.api.AuthorizationException in project navajo by Dexels.

the class Dispatcher method processNavajo.

/**
 * Handle a webservice.
 *
 * @param inMessage
 * @param userCertificate
 * @param clientInfo
 * @param origRunnable
 * @param skipAuth
 *            , always skip authorization part.
 * @return
 * @throws FatalException
 */
private final Navajo processNavajo(Navajo inMessage, String instance, Object userCertificate, ClientInfo clientInfo, boolean skipAuth, TmlRunnable origRunnable, AfterWebServiceEmitter emit) throws FatalException {
    Access access = null;
    Navajo outMessage = null;
    String rpcName = "";
    String rpcUser = "";
    String rpcPassword = "";
    Throwable myException = null;
    String origThreadName = null;
    boolean scheduledWebservice = false;
    boolean afterWebServiceActivated = false;
    int accessSetSize = accessSet.size();
    setRequestRate(clientInfo, accessSetSize);
    Navajo result = handleCallbackPointers(inMessage, instance);
    if (result != null) {
        return result;
    }
    Header header = inMessage.getHeader();
    rpcName = header.getRPCName();
    rpcUser = header.getRPCUser();
    rpcPassword = header.getRPCPassword();
    boolean preventFinalize = false;
    try {
        /**
         * Phase II: Authorisation/Authentication of the user. Is the user
         * known and valid and may it use the specified service? Also log
         * the access.
         */
        long startAuth = System.currentTimeMillis();
        if (rpcName == null) {
            throw new FatalException("No script defined");
        }
        if (rpcName.equals("navajo_ping")) {
            // Ping!
            outMessage = NavajoFactory.getInstance().createNavajo();
            Header h = NavajoFactory.getInstance().createHeader(outMessage, "", "", "", -1);
            outMessage.addHeader(h);
            return outMessage;
        }
        access = new Access(1, 1, rpcUser, rpcName, "", "", "", userCertificate, false, null);
        access.setTenant(instance);
        access.rpcPwd = rpcPassword;
        access.setInDoc(inMessage);
        access.setClientDescription(header.getHeaderAttribute("clientdescription"));
        access.setApplication(header.getHeaderAttribute("application"));
        access.setOrganization(header.getHeaderAttribute("organization"));
        if (clientInfo != null) {
            access.ipAddress = clientInfo.getIP();
            access.hostName = clientInfo.getHost();
        }
        NavajoEventRegistry.getInstance().publishEvent(new NavajoRequestEvent(access));
        appendGlobals(inMessage, instance);
        if (useAuthorisation && !skipAuth) {
            try {
                if (navajoConfig == null) {
                    throw new FatalException("EMPTY NAVAJOCONFIG, INVALID STATE OF DISPATCHER!");
                }
                // if (instance == null) {
                // throw new SystemException(-1, "No tenant set -cannot authenticate!");
                // }
                // Determine authenticator
                final AuthenticationMethod authenticator;
                if (clientInfo == null) {
                    authenticator = authMethodBuilder.getInstanceForRequest(null);
                } else {
                    authenticator = authMethodBuilder.getInstanceForRequest(clientInfo.getAuthHeader());
                }
                if (authenticator == null) {
                    throw new FatalException("Missing authenticator");
                }
                authenticator.process(access);
            } catch (AuthorizationException ex) {
                outMessage = generateAuthorizationErrorMessage(access, ex, rpcName);
                AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + ex.getMessage(), Level.WARNING);
                access.setExitCode(Access.EXIT_AUTH_EXECPTION);
                return outMessage;
            }/*catch (SystemException se) { //
                    logger.error("SystemException on authenticateUser  {} for {}: ", rpcUser, rpcName, se);
                    outMessage = generateErrorMessage(access, se.getMessage(), SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
                    AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + se.getMessage(),
                            Level.WARNING);
                    access.setExitCode(Access.EXIT_AUTH_EXECPTION);
                    return outMessage;
                }*/
             catch (Throwable t) {
                logger.error("Unexpected exception on authenticateUser  {} for {}: ", rpcUser, rpcName, t);
                outMessage = generateErrorMessage(access, t.getMessage(), SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
                access.setExitCode(Access.EXIT_AUTH_EXECPTION);
                access.setException(t);
                return outMessage;
            }
        }
        if (clientInfo != null) {
            access.ipAddress = clientInfo.getIP();
            access.hostName = clientInfo.getHost();
            access.parseTime = clientInfo.getParseTime();
            access.queueTime = clientInfo.getQueueTime();
            access.requestEncoding = clientInfo.getEncoding();
            access.compressedReceive = clientInfo.isCompressedRecv();
            access.compressedSend = clientInfo.isCompressedSend();
            access.contentLength = clientInfo.getContentLength();
            access.created = clientInfo.getCreated();
            access.queueId = clientInfo.getQueueId();
            access.queueSize = clientInfo.getQueueSize();
            // Set the name of this thread.
            origThreadName = Thread.currentThread().getName();
            Thread.currentThread().setName(getThreadName(access));
        }
        final GlobalManager gm;
        if (instance != null) {
            gm = globalManagers.get(instance);
        } else {
            gm = globalManagers.get("default");
        }
        if (gm != null) {
            gm.initGlobals(inMessage);
        }
        if (origRunnable != null) {
            access.setOriginalRunnable(origRunnable);
            // and vice versa, for the endTransaction
            origRunnable.setAttribute("access", access);
        }
        String fullLog = inMessage.getHeader().getHeaderAttribute("fullLog");
        if ("true".equals(fullLog)) {
            logger.info("Full debug detected. Accesshash: {}", access.hashCode());
            access.setDebugAll(true);
        }
        if ((access.userID == -1) || (access.serviceID == -1)) {
            // ACCESS NOTGRANTED.
            String errorMessage = "";
            if (access.userID == -1) {
                errorMessage = "Cannot authenticate user: " + rpcUser;
            } else {
                errorMessage = "Cannot authorise use of: " + rpcName;
            }
            outMessage = generateErrorMessage(access, errorMessage, SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
            return outMessage;
        } else {
            // ACCESS GRANTED.
            access.authorisationTime = (int) (System.currentTimeMillis() - startAuth);
            accessSet.add(access);
            // username might've changed as the username might've been a placeholder while we're authenticating using a bearer token
            rpcUser = access.getRpcUser();
            // Be very defensive not to add null values to the MDC, as they will fail at unexpected moments
            if (access.accessID != null) {
                MDC.put("accessId", access.accessID);
            }
            if (access.getRpcName() != null) {
                MDC.put("rpcName", access.getRpcName());
            }
            if (access.getRpcUser() != null) {
                MDC.put("rpcUser", access.getRpcUser());
            }
            if (access.getTenant() != null) {
                MDC.put("tenant", access.getTenant());
            }
            if (getNavajoConfig().getRootPath() != null) {
                MDC.put("rootPath", getNavajoConfig().getRootPath());
            }
            if (getNavajoConfig().getInstanceName() != null) {
                MDC.put("instanceName", getNavajoConfig().getInstanceName());
            }
            if (getNavajoConfig().getInstanceGroup() != null) {
                MDC.put("instanceGroup", getNavajoConfig().getInstanceGroup());
            }
            if (inMessage.getHeader().getSchedule() != null && !inMessage.getHeader().getSchedule().equals("")) {
                if (validTimeSpecification(inMessage.getHeader().getSchedule())) {
                    scheduledWebservice = true;
                    logger.info("Scheduling webservice: {}  on {} ", inMessage.getHeader().getRPCName(), inMessage.getHeader().getSchedule());
                    TaskRunnerInterface trf = TaskRunnerFactory.getInstance();
                    TaskInterface ti = trf.createTask();
                    try {
                        ti.setTrigger(inMessage.getHeader().getSchedule());
                        ti.setNavajo(inMessage);
                        // Make sure task gets persisted in tasks.xml
                        ti.setPersisted(true);
                        if (inMessage.getHeader().getHeaderAttribute("keeprequestresponse") != null && inMessage.getHeader().getHeaderAttribute("keeprequestresponse").equals("true")) {
                            ti.setKeepRequestResponse(true);
                        }
                        trf.addTask(ti);
                        outMessage = generateScheduledMessage(inMessage.getHeader(), ti.getId(), false);
                    } catch (TriggerException e) {
                        logger.info("WARNING: Invalid trigger specified for task {}: {}", ti.getId(), inMessage.getHeader().getSchedule());
                        trf.removeTask(ti);
                        outMessage = generateErrorMessage(access, "Could not schedule task:" + e.getMessage(), -1, -1, e);
                    }
                } else {
                    // obsolete time specification
                    outMessage = generateScheduledMessage(inMessage.getHeader(), null, true);
                }
            } else {
                /**
                 * Phase VI: Dispatch to proper servlet.
                 */
                // Create beforeWebservice event.
                access.setInDoc(inMessage);
                long bstart = System.currentTimeMillis();
                Navajo useProxy = (WebserviceListenerFactory.getInstance() != null ? WebserviceListenerFactory.getInstance().beforeWebservice(rpcName, access) : null);
                access.setBeforeServiceTime((int) (System.currentTimeMillis() - bstart));
                if (useAuthorisation) {
                    if (useProxy == null) {
                        outMessage = dispatch(access);
                    } else {
                        rpcName = access.rpcName;
                        outMessage = useProxy;
                    }
                } else {
                    throw new UnsupportedOperationException("I've removed this code because I assumed it wasn't used any more");
                }
            }
        }
    } catch (AuthorizationException aee) {
        outMessage = generateAuthorizationErrorMessage(access, aee, rpcName);
        AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + aee.getMessage() + ")", Level.WARNING);
        myException = aee;
        access.setExitCode(Access.EXIT_AUTH_EXECPTION);
        return outMessage;
    } catch (UserException ue) {
        try {
            outMessage = generateErrorMessage(access, ue.getMessage(), ue.code, 1, (ue.getCause() != null ? ue.getCause() : ue));
            myException = ue;
            return outMessage;
        } catch (Exception ee) {
            logger.error("Error: ", ee);
            myException = ee;
            return errorHandler(access, ee, inMessage);
        }
    } catch (SystemException se) {
        logger.error("Error: ", se);
        myException = se;
        try {
            outMessage = generateErrorMessage(access, se.getMessage(), se.code, 1, (se.getCause() != null ? se.getCause() : se));
            return outMessage;
        } catch (Exception ee) {
            logger.error("Error: ", ee);
            return errorHandler(access, ee, inMessage);
        }
    } catch (Throwable e) {
        logger.error("Error: ", e);
        myException = e;
        return errorHandler(access, e, inMessage);
    } finally {
        if (!preventFinalize) {
            finalizeService(inMessage, access, rpcName, rpcUser, myException, origThreadName, scheduledWebservice, afterWebServiceActivated, emit);
        }
    }
    return access.getOutputDoc();
}
Also used : FatalException(com.dexels.navajo.script.api.FatalException) AuthorizationException(com.dexels.navajo.script.api.AuthorizationException) Access(com.dexels.navajo.script.api.Access) Navajo(com.dexels.navajo.document.Navajo) AuthenticationMethod(com.dexels.navajo.authentication.api.AuthenticationMethod) NavajoRequestEvent(com.dexels.navajo.events.types.NavajoRequestEvent) FatalException(com.dexels.navajo.script.api.FatalException) NavajoException(com.dexels.navajo.document.NavajoException) AuthorizationException(com.dexels.navajo.script.api.AuthorizationException) UserException(com.dexels.navajo.script.api.UserException) TriggerException(com.dexels.navajo.server.enterprise.scheduler.TriggerException) IOException(java.io.IOException) SystemException(com.dexels.navajo.script.api.SystemException) Header(com.dexels.navajo.document.Header) GlobalManager(com.dexels.navajo.server.global.GlobalManager) SystemException(com.dexels.navajo.script.api.SystemException) TaskRunnerInterface(com.dexels.navajo.server.enterprise.scheduler.TaskRunnerInterface) TaskInterface(com.dexels.navajo.server.enterprise.scheduler.TaskInterface) UserException(com.dexels.navajo.script.api.UserException) TriggerException(com.dexels.navajo.server.enterprise.scheduler.TriggerException)

Example 5 with AuthorizationException

use of com.dexels.navajo.script.api.AuthorizationException in project navajo by Dexels.

the class NavajoMap method continueAfterRun.

public void continueAfterRun() throws UserException, ConditionErrorException, AuthorizationException {
    try {
        // Get task if if trigger was specified.
        if (trigger != null) {
            taskId = inDoc.getHeader().getSchedule();
            logger.info("************************************************* TASKID: {}", taskId);
        }
        // Call sorted.
        if (performOrderBy) {
            inDoc.performOrdering();
        }
        Message error = inDoc.getMessage("error");
        if (error != null && breakOnException) {
            String errMsg = error.getProperty("message").getValue();
            String errCode = error.getProperty("code").getValue();
            int errorCode = -1;
            try {
                errorCode = Integer.parseInt(errCode);
            } catch (NumberFormatException e) {
                e.printStackTrace(Access.getConsoleWriter(access));
            }
            throw new UserException(errorCode, errMsg);
        } else if (error != null) {
            logger.debug("EXCEPTIONERROR OCCURED, BUT WAS EXCEPTION HANDLING WAS SET TO FALSE, RETURNING....");
            return;
        }
        boolean authenticationError = false;
        Message aaaError = inDoc.getMessage(AuthorizationException.AUTHENTICATION_ERROR_MESSAGE);
        if (aaaError == null) {
            aaaError = inDoc.getMessage(AuthorizationException.AUTHORIZATION_ERROR_MESSAGE);
        } else {
            authenticationError = true;
        }
        if (aaaError != null) {
            AuditLog.log("NavajoMap", "THROWING AUTHORIZATIONEXCEPTION IN NAVAJOMAP" + aaaError.getProperty("User").getValue(), Level.WARNING, access.accessID);
            throw new AuthorizationException(authenticationError, !authenticationError, aaaError.getProperty("User").getValue(), aaaError.getProperty("Message").getValue());
        }
        if (breakOnConditionError && inDoc.getMessage("ConditionErrors") != null) {
            logger.debug("BREAKONCONDITIONERROR WAS SET TO TRUE, RETURNING CONDITION ERROR");
            throw new ConditionErrorException(inDoc);
        } else if (inDoc.getMessage("ConditionErrors") != null) {
            logger.debug("BREAKONCONDITIONERROR WAS SET TO FALSE, RETURNING....");
            return;
        }
        // Set property directions.
        processPropertyDirections(inDoc);
        // Suppress properties.
        processSuppressedProperties(inDoc);
        // Show properties.
        processShowProperties(inDoc);
        // Reset property directives
        this.suppressProperties = null;
        this.inputProperties = null;
        this.outputProperties = null;
        this.showProperties = null;
        if (!compare.equals("")) {
            Message other = inMessage.getMessage(compare);
            Message rec = inDoc.getMessage(compare);
            if (other == null || rec == null) {
                isEqual = false;
            } else {
                isEqual = other.isEqual(rec, this.skipProperties);
            }
        } else {
            outDoc = inDoc;
        }
    } finally {
        synchronized (waitForResult) {
            waitForResult.notify();
        }
        if (myResponseListener != null) {
            myResponseListener.onNavajoResponse(this);
        }
    }
}
Also used : ConditionErrorException(com.dexels.navajo.server.ConditionErrorException) Message(com.dexels.navajo.document.Message) AuthorizationException(com.dexels.navajo.script.api.AuthorizationException) UserException(com.dexels.navajo.script.api.UserException)

Aggregations

AuthorizationException (com.dexels.navajo.script.api.AuthorizationException)5 UserException (com.dexels.navajo.script.api.UserException)5 Message (com.dexels.navajo.document.Message)3 Navajo (com.dexels.navajo.document.Navajo)3 FatalException (com.dexels.navajo.script.api.FatalException)3 ConditionErrorException (com.dexels.navajo.server.ConditionErrorException)3 Header (com.dexels.navajo.document.Header)2 NavajoException (com.dexels.navajo.document.NavajoException)2 SystemException (com.dexels.navajo.script.api.SystemException)2 TriggerException (com.dexels.navajo.server.enterprise.scheduler.TriggerException)2 IOException (java.io.IOException)2 APIException (com.dexels.navajo.article.APIException)1 AuthenticationMethod (com.dexels.navajo.authentication.api.AuthenticationMethod)1 Property (com.dexels.navajo.document.Property)1 NavajoRequestEvent (com.dexels.navajo.events.types.NavajoRequestEvent)1 Access (com.dexels.navajo.script.api.Access)1 TaskInterface (com.dexels.navajo.server.enterprise.scheduler.TaskInterface)1 TaskRunnerInterface (com.dexels.navajo.server.enterprise.scheduler.TaskRunnerInterface)1 GlobalManager (com.dexels.navajo.server.global.GlobalManager)1