Validate assertion.

@param request         the request
@param serviceTicketId the service ticket id
@param assertion       the assertion
@param service         the service
@return true/false
549651
private boolean validateAssertion(final HttpServletRequest request, final String serviceTicketId, final Assertion assertion, final Service service) {
        for (val spec : serviceValidateConfigurationContext.getValidationSpecifications()) {
            spec.reset();
            val binder = new ServletRequestDataBinder(spec, "validationSpecification");
            initBinder(request, binder);
            binder.bind(request);
            if (!spec.isSatisfiedBy(assertion, request)) {
                LOGGER.warn("Service ticket [{}] does not satisfy validation specification.", serviceTicketId);
                return false;
            }
        }
        enforceTicketValidationAuthorizationFor(request, service, assertion);
        return true;
    }
188810
public static ErrorCode validateProvidedServiceInstance(ProvidedServiceInstance serviceInstance) {

        ErrorCode retstr = isIdValid(serviceInstance.getProviderId());
        if (retstr != ErrorCode.OK) {
            return retstr;
        }

        retstr = isNameValid(serviceInstance.getServiceName());
        if (retstr != ErrorCode.OK) {
            return retstr;
        }

        retstr = isUriValid(serviceInstance.getUri());
        if (retstr != ErrorCode.OK) {
            return retstr;
        }

        retstr = isPortValid(serviceInstance.getPort());
        if (retstr != ErrorCode.OK) {
            return retstr;
        }

        /**
        * Skip the ip validation.
        retstr = isAddressValid(serviceInstance.getAddress());
        if (retstr != ErrorCode.OK) {
            return retstr;
        }
        **/

        Map<String, String> metadata = serviceInstance.getMetadata();
        if (metadata != null && metadata.size() > 0) {
            Iterator<Entry<String, String>> itor = metadata.entrySet().iterator();
            while (itor.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry<String, String>) itor
                        .next();
                if (!isOptionalFieldValid(entry.getKey(), metaKeyRegEx)) {
                    return ErrorCode.SERVICE_INSTANCE_METAKEY_FORMAT_ERROR;
                }
            }
        }
        return ErrorCode.OK;
    }
938689
def validate_service_ticket(service, ticket, pgturl=None, renew=False, require_https=False):
    
    logger.debug("Service validation request received for %s" % ticket)

    # Check for proxy tickets passed to /serviceValidate
    if ticket and ticket.startswith(ProxyTicket.TICKET_PREFIX):
        raise InvalidTicketSpec('Proxy tickets cannot be validated with /serviceValidate')

    st = ServiceTicket.objects.validate_ticket(ticket, service, renew=renew, require_https=require_https)
    attributes = get_attributes(st.user, st.service)

    if pgturl is not None:
        logger.debug("Proxy-granting ticket request received for %s" % pgturl)
        pgt = ProxyGrantingTicket.objects.create_ticket(service, pgturl, user=st.user, granted_by_st=st)
    else:
        pgt = None
    return st, attributes, pgt
479411
def perform_service_validate(
        self,
        ticket=None,
        service_url=None,
        headers=None,
        ):
        '''
        
        '''
        url = self._get_service_validate_url(ticket, service_url=service_url)
        logging.debug('[CAS] ServiceValidate URL: {}'.format(url))
        return self._perform_cas_call(url, ticket=ticket, headers=headers)
511291
@Override
	public void serviceRequest(final Request request) {

		// Get trigger id
		String triggerId = request.getParameter(WServlet.AJAX_TRIGGER_PARAM_NAME);
		if (triggerId == null) {
			throw new SystemException("No AJAX trigger id to on request");
		}

		// Find the Component for this trigger
		ComponentWithContext trigger = WebUtilities.getComponentById(triggerId,
				true);
		if (trigger == null) {
			throw new SystemException("No component found for AJAX trigger " + triggerId + ".");
		}
		WComponent triggerComponent = trigger.getComponent();

		// Check for an internal AJAX request (if client has flagged it as internal)
		boolean internal = request.getParameter(WServlet.AJAX_TRIGGER_INTERNAL_PARAM_NAME) != null;

		AjaxOperation ajaxOperation = null;
		if (internal) {
			if (!(triggerComponent instanceof AjaxInternalTrigger)) {
				throw new SystemException("AJAX trigger [" + triggerId + "] does not support internal actions.");
			}
			// Create internal operation
			ajaxOperation = new AjaxOperation(triggerId);
		} else {
			// Check for a registered AJAX operation
			ajaxOperation = AjaxHelper.getAjaxOperation(triggerId);

			// Override registered operation if it is a GET and trigger supports Internal AJAX
			// TODO This is only required until all components start using the Internal param flag
			if (ajaxOperation != null && "GET".equals(request.getMethod()) && triggerComponent instanceof AjaxInternalTrigger) {
				// Create internal operation
				ajaxOperation = new AjaxOperation(triggerId);
			}
		}

		// If no operation registered, check if the trigger supports internal AJAX then assume it is an Internal Action
		if (ajaxOperation == null && trigger.getComponent() instanceof AjaxInternalTrigger) {
			// Create internal operation
			ajaxOperation = new AjaxOperation(triggerId);
		}

		// No Valid operation
		if (ajaxOperation == null) {
			throw new SystemException("No AJAX operation has been registered for trigger " + triggerId + ".");
		}

		// Set current operation
		AjaxHelper.setCurrentOperationDetails(ajaxOperation, trigger);

		// Process Service Request
		super.serviceRequest(request);
	}
915948
function validateService(res, url, callback) {
  if (debug) {
    console.log('Sending request to: "' + url + '" to validate ticket.');
  }

  fetch(url).then(function(res) {
      if (res.status == 200) {
        return res.text();
      } else {
        console.log('Receive response from cas when validating ticket, but request failed with status code: ' + casRes.statusCode + '!');
        res.status(401).send({
          message: 'Receive response from cas when validating ticket, but request failed with status code: ' + casRes.statusCode + '.'
        });
      }
    })
    .then(function(casBody) {
      if (casBody) {
        if (debug) {
          console.log('Receive response from CAS when validating ticket with status code 200, casBody: ', casBody);
        }

        callback(casBody);
      }
    })
    .catch(function(err) {
      console.log('Receive response from cas when validating ticket, but request failed!');
      console.error(err);
      return res.status(401).send({
        message: 'Receive response from cas when validating ticket, but request failed!',
        error: err
      });
    });

}
743826
protected void verifyAuthenticationContextSignature(final MessageContext ctx,
                                                        final HttpServletRequest request,
                                                        final RequestAbstractType authnRequest,
                                                        final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws Exception {
        if (!SAMLBindingSupport.isMessageSigned(ctx)) {
            LOGGER.debug("The authentication context is not signed");
            if (adaptor.isAuthnRequestsSigned()) {
                LOGGER.error("Metadata for [{}] says authentication requests are signed, yet authentication request is not", adaptor.getEntityId());
                throw new SAMLException("AuthN request is not signed but should be");
            }
            LOGGER.debug("Authentication request is not signed, so there is no need to verify its signature.");
        } else {
            LOGGER.debug("The authentication context is signed; Proceeding to validate signatures...");
            samlProfileHandlerConfigurationContext.getSamlObjectSignatureValidator().verifySamlProfileRequestIfNeeded(authnRequest, adaptor, request, ctx);
        }
    }
835257
private static boolean keyIsValid(final BinaryRequest request) {
        if (request.keyBytes() == null || request.keyBytes().length < MIN_KEY_BYTES) {
            request.observable().onError(new IllegalArgumentException("The Document ID must not be null or empty."));
            return false;
        }

        if (request.keyBytes().length > MAX_KEY_BYTES) {
            request.observable().onError(new IllegalArgumentException(
                "The Document ID must not be longer than 250 bytes."));
            return false;
        }

        return true;
    }
1156996
@Override
	public void serviceRequest(final Request request) {
		LOG.debug("Before Service Request - Clearing targetable index.");
		UIContext uic = UIContextHolder.getCurrent();

		super.serviceRequest(request);
		// Clear phase scope scratch map
		LOG.debug("After Service Request - Clearing scratch map with phase scope.");
		uic.clearScratchMap();
	}
276836
function AssertionError(actual, expected, phrase, base) {
  this.name = 'AssertionError';
  this.actual = actual;
  this.expected = expected;
  this.message = 'expected ' + objectDisplay(actual) + ' ' +
      phrase + ' ' +
    objectDisplay(expected);

  if (typeof actual === 'object' || typeof expected === 'object') {
    this.showDiff = true;
  }

  Error.captureStackTrace(this, base);
}
877872
@Override
	public void serviceRequest(final Request request) {

		// Get expected step count
		UIContext uic = UIContextHolder.getCurrent();
		int expected = uic.getEnvironment().getStep();

		// Get step count from the request
		int got = StepCountUtil.getRequestStep(request);

		// Match (first time, both are zero)
		// or no Step count and processing a GET
		if (expected == got || (!StepCountUtil.isStepOnRequest(request) && "GET".equals(request.
				getMethod()))) {
			// Process Service Request
			getBackingComponent().serviceRequest(request);
		} else { // Invalid step
			LOG.warn(
					"SERVER: Wrong step detected. Expected step " + expected + " but got step " + got);

			// Redirect to error page
			if (StepCountUtil.isErrorRedirect()) {
				String url = StepCountUtil.getErrorUrl();
				LOG.warn("User will be redirected to an error page. URL: " + url);
				try {
					getResponse().sendRedirect(url);
				} catch (IOException e) {
					LOG.warn("Error trying to redirect for wrong step indicator.");
				}

				// Make sure the render phase is not processed
				throw new ActionEscape();
			} else {  // Warp to the future
				// Call handle step error
				WComponent application = getUI();
				if (application instanceof WApplication) {
					LOG.warn("The handleStepError method will be called on WApplication.");
					((WApplication) application).handleStepError();
				}

				LOG.warn("The render phase will warp the user back to the future.");
			}
		}
	}
1111031
public void assertCorrectResonse(JSONObject response) throws JSONException {
		Integer lastHTTPResponseCode = getLastHTTPResponseCode();
		if(lastHTTPResponseCode != null) {
			//if a response code is set, check it. Selenium requests do not let you query this which is why we can't check this in case of a selenium API call
			assertEquals("The https response code should be 200 (OK)", new Integer(HttpURLConnection.HTTP_OK), lastHTTPResponseCode);
		}
		assertNotNull("The request should result in a response", response);	
	}
719939
@Override
	public void serviceRequest(final Request request) {
		// Get trigger id
		triggerId = request.getParameter(WServlet.AJAX_TRIGGER_PARAM_NAME);
		if (triggerId == null) {
			throw new SystemException("No AJAX trigger id to check step count");
		}

		// Get trigger and its context
		ComponentWithContext trigger = AjaxHelper.getCurrentTriggerAndContext();
		if (trigger == null) {
			throw new IllegalStateException(
					"No component/context available for AJAX trigger " + triggerId + ".");
		}

		// Get expected step count
		UIContext uic = UIContextHolder.getCurrent();
		int expected = uic.getEnvironment().getStep();

		// Step should already be set on the session
		if (expected == 0) {
			throw new SystemException(
					"Step count should already be set on the session before AJAX request.");
		}

		// Get step count on the request
		int got = StepCountUtil.getRequestStep(request);

		// Check we are on the current step
		if (expected == got) {
			// Process Service Request
			getBackingComponent().serviceRequest(request);
		} else { // Invalid step
			LOG.warn("AJAX: Wrong step detected. Expected step " + expected + " but got step " + got);
			// "GET" Ajax requests are just ignored and return an error code
			if ("GET".equals(request.getMethod())) {
				LOG.warn("Error code will be sent in the response for AJAX GET Request.");
				handleErrorCode();
				// Make sure the render phase is not processed
				throw new ActionEscape();
			} else if (StepCountUtil.isErrorRedirect()) { // Redirect to error page
				LOG.warn("User will be redirected to an error page.");
				redirectUrl = StepCountUtil.getErrorUrl();
			} else {  // Warp to the future by refreshing the page
				LOG.warn("Warp the user back to the future by refreshing the page.");
				handleWarpToTheFuture(uic);
				redirectUrl = buildApplicationUrl(uic);
			}
		}
	}
406196
function AssertionError( message, startFunc ) {
		var self = this;

		self.name = 'Assertion Error';
		self.message = message;

		if ( Error.captureStackTrace ) {
			Error.captureStackTrace( self, startFunc );
		}
	}
827916
private void validateRestServiceConfiguration() {
        boolean isRestEnabled = voldemortConfig.isRestServiceEnabled();
        boolean isRestPortDefined = (identityNode.getRestPort() != -1) ? true : false;
        if(isRestEnabled != isRestPortDefined) {
            if(isRestEnabled) {
                String errorMessage = "Rest Service is enabled without defining \"rest-port\" in cluster.xml .  "
                                      + this.identityNode.getStateString();
                logger.error(errorMessage);
                throw new VoldemortApplicationException(errorMessage);
            } else {
                logger.warn("\"rest-port\" is defined in cluster.xml but Rest service is not enabled.");
            }
        }
    }
162800
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity ssoStatus(final HttpServletRequest request) {
        val tgtId = this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request);
        if (StringUtils.isNotBlank(tgtId)) {
            val auth = this.ticketRegistrySupport.getAuthenticationFrom(tgtId);
            if (auth != null) {
                val ticketState = this.ticketRegistrySupport.getTicketState(tgtId);
                val body = CollectionUtils.wrap("principal", auth.getPrincipal().getId(),
                    "authenticationDate", auth.getAuthenticationDate(),
                    "ticketGrantingTicketCreationTime", ticketState.getCreationTime(),
                    "ticketGrantingTicketPreviousTimeUsed", ticketState.getPreviousTimeUsed(),
                    "ticketGrantingTicketLastTimeUsed", ticketState.getLastTimeUsed());
                return ResponseEntity.ok(body);
            }
        }
        return ResponseEntity.badRequest().build();
    }
240800
@Override
    public void verify() throws SniffyAssertionError {
        checkOpened();
        SniffyAssertionError assertionError = getSniffyAssertionError();
        if (null != assertionError) {
            throw assertionError;
        }
    }