Validate the service ticket by extracting the client principal name
172026
public static String validateSecurityContext(Subject subject, final byte[] serviceTicket) throws GSSException {

        // Accept the context and return the client principal name.
        return Subject.doAs(subject, (PrivilegedAction<String>)() -> {
            try {
                // Identify the server that communications are being made
                // to.
                GSSManager manager = GSSManager.getInstance();
                GSSContext context = manager.createContext((GSSCredential) null);
                context.acceptSecContext(serviceTicket, 0, serviceTicket.length);
                return context.getSrcName().toString();
            } catch (Exception e) {
                log.error(Util.getMessage("Krb5TokenKerberosContextProcessingException"),e);
                return null;
            }
        });
    }
1145332
def _validate_client(self, request, data):
        
        client = self.get_client(data.get('client_id'))

        if client is None:
            raise OAuthError({
                'error': 'unauthorized_client',
                'error_description': _("An unauthorized client tried to access"
                    " your resources.")
            })

        form = self.get_request_form(client, data)

        if not form.is_valid():
            raise OAuthError(form.errors)

        return client, form.cleaned_data
973480
def get_shake_info(self, ticket):
        
        res = self._post(
            'shakearound/user/getshakeinfo',
            data={
                'ticket': ticket
            },
            result_processor=lambda x: x['data']
        )
        return res
217124
def validate_proxy_granting_ticket(pgt, target_service):
    
    logger.debug("Proxy ticket request received for %s using %s" % (target_service, pgt))

    pgt = ProxyGrantingTicket.objects.validate_ticket(pgt, target_service)
    pt = ProxyTicket.objects.create_ticket(service=target_service, user=pgt.user, granted_by_pgt=pgt)
    return pt
977014
def verify_ticket(self, ticket):
        
        params = [('ticket', ticket), ('service', self.service_url)]
        url = (urllib_parse.urljoin(self.server_url, 'validate') + '?' +
               urllib_parse.urlencode(params))
        page = requests.get(
            url,
            stream=True,
            verify=self.verify_ssl_certificate
        )
        try:
            page_iterator = page.iter_lines(chunk_size=8192)
            verified = next(page_iterator).strip()
            if verified == 'yes':
                return next(page_iterator).strip(), None, None
            else:
                return None, None, None
        finally:
            page.close()
422150
protected String produceTicketIdentifier(final Service service, final TicketGrantingTicket ticketGrantingTicket,
                                             final boolean credentialProvided) {
        val uniqueTicketIdGenKey = service.getClass().getName();
        var serviceTicketUniqueTicketIdGenerator = (UniqueTicketIdGenerator) null;
        if (this.uniqueTicketIdGeneratorsForService != null && !this.uniqueTicketIdGeneratorsForService.isEmpty()) {
            LOGGER.debug("Looking up service ticket id generator for [{}]", uniqueTicketIdGenKey);
            serviceTicketUniqueTicketIdGenerator = this.uniqueTicketIdGeneratorsForService.get(uniqueTicketIdGenKey);
        }
        if (serviceTicketUniqueTicketIdGenerator == null) {
            serviceTicketUniqueTicketIdGenerator = this.defaultServiceTicketIdGenerator;
            LOGGER.debug("Service ticket id generator not found for [{}]. Using the default generator.", uniqueTicketIdGenKey);
        }

        return serviceTicketUniqueTicketIdGenerator.getNewTicketId(ServiceTicket.PREFIX);
    }
271235
def validate(cls, event_info):
        """"""
        assert 'service_key' in event_info
        assert isinstance(event_info['service_key'], six.string_types)
        assert 'event_type' in event_info
        assert event_info['event_type'] in cls.EVENT_TYPES
        if event_info['event_type'] != cls.EVENT_TYPES[0]:
            assert 'incident_key' in event_info
            assert isinstance(event_info['incident_key'], six.string_types)
        else:
            assert 'description' in event_info

        if 'details' in event_info:
            assert isinstance(event_info['details'], dict)

        if 'contexts' in event_info:
            assert isinstance(event_info['contexts'], (list, tuple,))
389099
def populate(self, ticket=None):
        
        ticket = ticket or AuthTicket.objects.get_any_active('wsfe')
        client = clients.get_client('wsfe', ticket.owner.is_sandboxed)
        service = getattr(client.service, self.__service_name)
        response_xml = service(serializers.serialize_ticket(ticket))

        check_response(response_xml)

        for result in getattr(response_xml.ResultGet, self.__type_name):
            self.get_or_create(
                code=result.Id,
                description=result.Desc,
                valid_from=parsers.parse_date(result.FchDesde),
                valid_to=parsers.parse_date(result.FchHasta),
            )
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;
    }
608085
private function validate()
    {
        if (isset($this->_values[self::OPTION_HOST]) && !is_string($this->_values[self::OPTION_HOST])) {
            throw new ClientException('host should be a string');
        }

        if (isset($this->_values[self::OPTION_PORT]) && !is_int($this->_values[self::OPTION_PORT])) {
            throw new ClientException('port should be an integer');
        }

        // can use either endpoint or host/port
        if (isset($this->_values[self::OPTION_HOST], $this->_values[self::OPTION_ENDPOINT])) {
            throw new ClientException('must not specify both host and endpoint');
        }

        if (isset($this->_values[self::OPTION_HOST]) && !isset($this->_values[self::OPTION_ENDPOINT])) {
            // upgrade host/port to an endpoint
            $this->_values[self::OPTION_ENDPOINT] = [ 'tcp://' . $this->_values[self::OPTION_HOST] . ':' . $this->_values[self::OPTION_PORT] ];
            unset($this->_values[self::OPTION_HOST]);
        }
        
        if (!is_array($this->_values[self::OPTION_ENDPOINT])) {
            // make sure that we always have an array of endpoints
            $this->_values[self::OPTION_ENDPOINT] = [ $this->_values[self::OPTION_ENDPOINT] ];
        }
        
        assert(is_array($this->_values[self::OPTION_ENDPOINT]));
        foreach ($this->_values[self::OPTION_ENDPOINT] as $key => $value) {
            $this->_values[self::OPTION_ENDPOINT][$key] = Endpoint::normalize($value);
        }
        
        if (count($this->_values[self::OPTION_ENDPOINT]) > 1) {
            // when we have more than a single endpoint, we must always use the reconnect option
            $this->_values[ConnectionOptions::OPTION_RECONNECT] = true;
        }

        // validate endpoint
        $ep = $this->getCurrentEndpoint();
        if (!Endpoint::isValid($ep)) {
            throw new ClientException(sprintf("invalid endpoint specification '%s'", $ep));
        }

        $type = Endpoint::getType($ep);
        if ($type === Endpoint::TYPE_UNIX) {
            // must set port to 0 for UNIX domain sockets
            $this->_values[self::OPTION_PORT] = 0;
        } elseif ($type === Endpoint::TYPE_SSL) {
            // must set port to 0 for SSL connections
            $this->_values[self::OPTION_PORT] = 0;
        } else {
          if (preg_match("/:(\d+)$/", $ep, $match)) {
            // get port number from endpoint, to not confuse developers when dumping
            // connection details
            $this->_values[self::OPTION_PORT] = (int) $match[1];
          }
        }
        
        if (isset($this->_values[self::OPTION_AUTH_TYPE]) && !in_array(
                $this->_values[self::OPTION_AUTH_TYPE],
                self::getSupportedAuthTypes(), true
            )
        ) {
            throw new ClientException('unsupported authorization method');
        }

        if (isset($this->_values[self::OPTION_CONNECTION]) && !in_array(
                $this->_values[self::OPTION_CONNECTION],
                self::getSupportedConnectionTypes(), true
            )
        ) {
            throw new ClientException(
                sprintf(
                    "unsupported connection value '%s'",
                    $this->_values[self::OPTION_CONNECTION]
                )
            );
        }

        UpdatePolicy::validate($this->_values[self::OPTION_UPDATE_POLICY]);
        UpdatePolicy::validate($this->_values[self::OPTION_REPLACE_POLICY]);
        UpdatePolicy::validate($this->_values[self::OPTION_DELETE_POLICY]);
    }
2223
def validate_callback(self, service, pgturl, pgtid, pgtiou):
        """"""
        if not proxy_allowed(service):
            raise UnauthorizedServiceProxy("%s is not authorized to use proxy authentication" % service)

        if not is_scheme_https(pgturl):
            raise InvalidProxyCallback("Proxy callback %s is not HTTPS" % pgturl)

        if not proxy_callback_allowed(service, pgturl):
            raise InvalidProxyCallback("%s is not an authorized proxy callback URL" % pgturl)

        # Verify that the SSL certificate is valid
        verify = os.environ.get('REQUESTS_CA_BUNDLE', True)
        try:
            requests.get(pgturl, verify=verify, timeout=5)
        except requests.exceptions.SSLError:
            raise InvalidProxyCallback("SSL certificate validation failed for proxy callback %s" % pgturl)
        except requests.exceptions.RequestException as e:
            raise InvalidProxyCallback(e)

        # Callback certificate appears valid, so send the ticket strings
        pgturl = add_query_params(pgturl, {'pgtId': pgtid, 'pgtIou': pgtiou})
        try:
            response = requests.get(pgturl, verify=verify, timeout=5)
        except requests.exceptions.RequestException as e:
            raise InvalidProxyCallback(e)

        try:
            response.raise_for_status()
        except requests.exceptions.HTTPError as e:
            raise InvalidProxyCallback("Proxy callback %s returned %s" % (pgturl, e))
466687
function(ledName) {
      var result = this.isValidLEDName(ledName) ? tessel.port[this.validLEDNames.indexOf(ledName)] : null;

      return result;
    }
77622
def validate_account_id(sts_client, account_id):
    """"""
    resp = sts_client.get_caller_identity()
    if 'Account' in resp:
        if resp['Account'] == account_id:
            LOGGER.info('Verified current AWS account matches required '
                        'account id %s.',
                        account_id)
        else:
            LOGGER.error('Current AWS account %s does not match '
                         'required account %s in Runway config.',
                         resp['Account'],
                         account_id)
            sys.exit(1)
    else:
        LOGGER.error('Error checking current account ID')
        sys.exit(1)
1190882
def validate_service(self, request, uid):
        """"""

        result = get_record_value(request, uid, 'result')
        if not result:
            # No result set for this service, dismiss
            return None

        if not api.is_floatable(result):
            return "Expected result value must be numeric"

        spec_min = get_record_value(request, uid, "min", result)
        spec_max = get_record_value(request, uid, "max", result)
        error = get_record_value(request, uid, "error", "0")
        if not api.is_floatable(spec_min):
            return "'Min' value must be numeric"
        if not api.is_floatable(spec_max):
            return "'Max' value must be numeric"
        if api.to_float(spec_min) > api.to_float(result):
            return "'Min' value must be below the expected result"
        if api.to_float(spec_max) < api.to_float(result):
            return "'Max' value must be above the expected result"
        if not api.is_floatable(error) or 0.0 < api.to_float(error) > 100:
            return "% Error must be between 0 and 100"
        return None
794676
def get_assertion(self, ticket, attributes):
        
        assertion = etree.Element('Assertion')
        assertion.set('xmlns', 'urn:oasis:names:tc:SAML:1.0:assertion')
        assertion.set('AssertionID', self.generate_id())
        assertion.set('IssueInstant', self.instant())
        assertion.set('Issuer', 'localhost')
        assertion.set('MajorVersion', '1')
        assertion.set('MinorVersion', '1')
        assertion.append(self.get_conditions(ticket.service))
        subject = self.get_subject(ticket.user.get_username())
        if attributes:
            assertion.append(self.get_attribute_statement(subject, attributes))
        assertion.append(self.get_authentication_statement(subject, ticket))

        return assertion
1077061
def validate_name(ctx, param, value):
    """"""
    if not value:
        value = os.path.basename(ctx.params['directory'].rstrip(os.path.sep))
    return value
1259930
def validate_headers(self):
        

        pc = getToolByName(self, 'portal_catalog')
        pu = getToolByName(self, "plone_utils")

        client = self.aq_parent

        # Verify Client Name
        if self.getClientName() != client.Title():
            self.error("%s: value is invalid (%s)." % (
                'Client name', self.getClientName()))

        # Verify Client ID
        if self.getClientID() != client.getClientID():
            self.error("%s: value is invalid (%s)." % (
                'Client ID', self.getClientID()))

        existing_arimports = pc(portal_type='ARImport',
                                review_state=['valid', 'imported'])
        # Verify Client Order Number
        for arimport in existing_arimports:
            if arimport.UID == self.UID() \
                    or not arimport.getClientOrderNumber():
                continue
            arimport = arimport.getObject()

            if arimport.getClientOrderNumber() == self.getClientOrderNumber():
                self.error('%s: already used by existing ARImport.' %
                           'ClientOrderNumber')
                break

        # Verify Client Reference
        for arimport in existing_arimports:
            if arimport.UID == self.UID() \
                    or not arimport.getClientReference():
                continue
            arimport = arimport.getObject()
            if arimport.getClientReference() == self.getClientReference():
                self.error('%s: already used by existing ARImport.' %
                           'ClientReference')
                break

        # getCCContacts has no value if object is not complete (eg during test)
        if self.getCCContacts():
            cc_contacts = self.getCCContacts()[0]
            contacts = [x for x in client.objectValues('Contact')]
            contact_names = [c.Title() for c in contacts]
            # validate Contact existence in this Client
            for k in ['CCNamesReport', 'CCNamesInvoice']:
                for val in cc_contacts[k]:
                    if val and val not in contact_names:
                        self.error('%s: value is invalid (%s)' % (k, val))
        else:
            cc_contacts = {'CCNamesReport': [],
                           'CCEmailsReport': [],
                           'CCNamesInvoice': [],
                           'CCEmailsInvoice': []
                           }
            # validate Contact existence in this Client
            for k in ['CCEmailsReport', 'CCEmailsInvoice']:
                for val in cc_contacts.get(k, []):
                    if val and not pu.validateSingleNormalizedEmailAddress(val):
                        self.error('%s: value is invalid (%s)' % (k, val))