// ValidateSAMLResponse validates response returned by SAML identity provider
422582
func (c *Client) ValidateSAMLResponse(re string) (*SAMLAuthResponse, error) {
	out, err := c.PostJSON(c.Endpoint("saml", "requests", "validate"), validateSAMLResponseReq{
		Response: re,
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	var rawResponse *samlAuthRawResponse
	if err := json.Unmarshal(out.Bytes(), &rawResponse); err != nil {
		return nil, trace.Wrap(err)
	}
	response := SAMLAuthResponse{
		Username: rawResponse.Username,
		Identity: rawResponse.Identity,
		Cert:     rawResponse.Cert,
		Req:      rawResponse.Req,
		TLSCert:  rawResponse.TLSCert,
	}
	if len(rawResponse.Session) != 0 {
		session, err := services.GetWebSessionMarshaler().UnmarshalWebSession(rawResponse.Session)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		response.Session = session
	}
	response.HostSigners = make([]services.CertAuthority, len(rawResponse.HostSigners))
	for i, raw := range rawResponse.HostSigners {
		ca, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(raw)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		response.HostSigners[i] = ca
	}
	return &response, nil
}
655410
func (m *StatusResponseControllersItems0Configuration) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateErrorRetryBase(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateInterval(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
17798
func (a *Authenticator) Validate(context.Context, *http.Request) (oauth2.Principal, error) {
	return a.Principal, a.ValidateErr
}
515271
func (m *DeltaDiscoveryResponse) Validate() error {
	if m == nil {
		return nil
	}

	// no validation rules for SystemVersionInfo

	for idx, item := range m.GetResources() {
		_, _ = idx, item

		{
			tmp := item

			if v, ok := interface{}(&tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return DeltaDiscoveryResponseValidationError{
						field:  fmt.Sprintf("Resources[%v]", idx),
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	}

	// no validation rules for Nonce

	return nil
}
524026
func (ctx *Ctx) AuthZResponse(rm ResponseModifier, r *http.Request) error {
	ctx.authReq.ResponseStatusCode = rm.StatusCode()
	ctx.authReq.ResponseHeaders = headers(rm.Header())

	if sendBody(ctx.requestURI, rm.Header()) {
		ctx.authReq.ResponseBody = rm.RawBody()
	}

	for _, plugin := range ctx.plugins {
		logrus.Debugf("AuthZ response using plugin %s", plugin.Name())

		authRes, err := plugin.AuthZResponse(ctx.authReq)
		if err != nil {
			return fmt.Errorf("plugin %s failed with error: %s", plugin.Name(), err)
		}

		if !authRes.Allow {
			return newAuthorizationError(plugin.Name(), authRes.Msg)
		}
	}

	rm.FlushAll()

	return nil
}
1092399
func (m *StatusResponseControllersItems0Status) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateLastFailureTimestamp(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateLastSuccessTimestamp(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
601312
func VerifyResponseSignature(xml string, publicCertPath string) error {
	return verify(xml, publicCertPath, xmlResponseID)
}
1212325
func RestHandleResponse(context *gin.Context, body interface{}, err error) {
	if err == nil {
		context.JSON(200, body)
	} else {
		context.String(400, err.Error())
	}
}
1373956
func (m *RouteAction_HashPolicy_Header) Validate() error {
	if m == nil {
		return nil
	}

	if len(m.GetHeaderName()) < 1 {
		return RouteAction_HashPolicy_HeaderValidationError{
			field:  "HeaderName",
			reason: "value length must be at least 1 bytes",
		}
	}

	return nil
}
184828
func ValidateSignatures(expectedAddress Hash, fragments []Trytes, bundleHash Hash, spongeFunc ...SpongeFunction) (bool, error) {
	normalizedBundleHashFragments := make([][]int8, MaxSecurityLevel)
	normalizeBundleHash := NormalizedBundleHash(bundleHash)

	for i := 0; i < MaxSecurityLevel; i++ {
		normalizedBundleHashFragments[i] = normalizeBundleHash[i*KeySegmentsPerFragment : (i+1)*KeySegmentsPerFragment]
	}

	digests := make(Trits, len(fragments)*HashTrinarySize)
	for i := 0; i < len(fragments); i++ {
		trits, err := TrytesToTrits(fragments[i])
		if err != nil {
			return false, err
		}

		digest, err := Digest(normalizedBundleHashFragments[i%MaxSecurityLevel], trits, spongeFunc...)
		if err != nil {
			return false, err
		}

		copy(digests[i*HashTrinarySize:], digest)
	}

	addressTrits, err := Address(digests, spongeFunc...)
	if err != nil {
		return false, err
	}

	trytes, err := TritsToTrytes(addressTrits)
	if err != nil {
		return false, err
	}

	return expectedAddress == trytes, nil
}
872105
func (req *IdpAuthnRequest) WriteResponse(w http.ResponseWriter) error {
	if req.Response == nil {
		if err := req.MakeResponse(); err != nil {
			return err
		}
	}
	responseBuf, err := xml.Marshal(req.Response)
	if err != nil {
		return err
	}

	// the only supported binding is the HTTP-POST binding
	switch req.ACSEndpoint.Binding {
	case HTTPPostBinding:
		tmpl := template.Must(template.New("saml-post-form").Parse(`<html>` +
			`<form method="post" action="{{.URL}}" id="SAMLResponseForm">` +
			`<input type="hidden" name="SAMLResponse" value="{{.SAMLResponse}}" />` +
			`<input type="hidden" name="RelayState" value="{{.RelayState}}" />` +
			`<input type="submit" value="Continue" />` +
			`</form>` +
			`<script>document.getElementById('SAMLResponseForm').submit();</script>` +
			`</html>`))
		data := struct {
			URL          string
			SAMLResponse string
			RelayState   string
		}{
			URL:          req.ACSEndpoint.Location,
			SAMLResponse: base64.StdEncoding.EncodeToString(responseBuf),
			RelayState:   req.RelayState,
		}

		buf := bytes.NewBuffer(nil)
		if err := tmpl.Execute(buf, data); err != nil {
			return err
		}
		if _, err := io.Copy(w, buf); err != nil {
			return err
		}
		return nil
	case HTTPRedirectBinding:
		acsURL, _ := url.Parse(req.ACSEndpoint.Location)
		q := acsURL.Query()
		q.Set("RelayState", req.RelayState)
		q.Set("SAMLResponse", base64.StdEncoding.EncodeToString(responseBuf))
		acsURL.RawQuery = q.Encode()
		w.Header().Set("Location", acsURL.String())
		w.WriteHeader(307)
		return nil
	default:
		return fmt.Errorf("%s: unsupported binding %s",
			req.ServiceProviderMetadata.EntityID,
			req.ACSEndpoint.Binding)
	}
}
953484
func (parser *EndorserResponseParser) ParseResponse(channel string, res ServiceResponse) error {
	rawResponse := res.Raw()
	if len(rawResponse.Results) == 0 {
		return errors.New("empty results")
	}

	if e := rawResponse.Results[0].GetError(); e != nil {
		return errors.Errorf("server returned: %s", e.Content)
	}

	ccQueryRes := rawResponse.Results[0].GetCcQueryRes()
	if ccQueryRes == nil {
		return errors.Errorf("server returned response of unexpected type: %v", reflect.TypeOf(rawResponse.Results[0]))
	}

	jsonBytes, _ := json.MarshalIndent(parseEndorsementDescriptors(ccQueryRes.Content), "", "\t")
	fmt.Fprintln(parser.Writer, string(jsonBytes))
	return nil
}
709631
func (rm *RegistryMessage) ValidateMessage() bool {
	return rm.RouteServiceURL == "" || strings.HasPrefix(rm.RouteServiceURL, "https")
}
1098192
func (req *IdpAuthnRequest) Validate() error {
	if err := xml.Unmarshal(req.RequestBuffer, &req.Request); err != nil {
		return err
	}

	// TODO(ross): is this supposed to be the metdata URL? or the target URL?
	//   i.e. should idp.SSOURL actually be idp.Metadata().EntityID?
	if req.Request.Destination != req.IDP.SSOURL {
		return fmt.Errorf("expected destination to be %q, not %q",
			req.IDP.SSOURL, req.Request.Destination)
	}
	if req.Request.IssueInstant.Add(MaxIssueDelay).Before(TimeNow()) {
		return fmt.Errorf("request expired at %s",
			req.Request.IssueInstant.Add(MaxIssueDelay))
	}
	if req.Request.Version != "2.0" {
		return fmt.Errorf("expected SAML request version 2, got %q", req.Request.Version)
	}

	// find the service provider
	serviceProvider, serviceProviderFound := req.IDP.ServiceProviders[req.Request.Issuer.Value]
	if !serviceProviderFound {
		return fmt.Errorf("cannot handle request from unknown service provider %s",
			req.Request.Issuer.Value)
	}
	req.ServiceProviderMetadata = serviceProvider

	// Check that the ACS URL matches an ACS endpoint in the SP metadata.
	acsValid := false
	for _, acsEndpoint := range serviceProvider.SPSSODescriptor.AssertionConsumerService {
		if req.Request.AssertionConsumerServiceURL == acsEndpoint.Location {
			req.ACSEndpoint = &acsEndpoint
			acsValid = true
			break
		}
	}
	if !acsValid {
		return fmt.Errorf("invalid ACS url specified in request: %s", req.Request.AssertionConsumerServiceURL)
	}

	return nil
}
699321
func (sp *ServiceProvider) validateSignature(el *etree.Element) error {
	certs, err := sp.getIDPSigningCerts()
	if err != nil {
		return err
	}

	certificateStore := dsig.MemoryX509CertificateStore{
		Roots: certs,
	}

	validationContext := dsig.NewDefaultValidationContext(&certificateStore)
	validationContext.IdAttribute = "ID"
	if Clock != nil {
		validationContext.Clock = Clock
	}

	// Some SAML responses contain a RSAKeyValue element. One of two things is happening here:
	//
	// (1) We're getting something signed by a key we already know about -- the public key
	//     of the signing cert provided in the metadata.
	// (2) We're getting something signed by a key we *don't* know about, and which we have
	//     no ability to verify.
	//
	// The best course of action is to just remove the KeyInfo so that dsig falls back to
	// verifying against the public key provided in the metadata.
	if el.FindElement("./Signature/KeyInfo/X509Data/X509Certificate") == nil {
		if sigEl := el.FindElement("./Signature"); sigEl != nil {
			if keyInfo := sigEl.FindElement("KeyInfo"); keyInfo != nil {
				sigEl.RemoveChild(keyInfo)
			}
		}
	}

	ctx, err := etreeutils.NSBuildParentContext(el)
	if err != nil {
		return err
	}
	ctx, err = ctx.SubContext(el)
	if err != nil {
		return err
	}
	el, err = etreeutils.NSDetatch(ctx, el)
	if err != nil {
		return err
	}

	_, err = validationContext.Validate(el)
	return err
}
747277
func ValidateScheme(name string, apiDef *raml.APIDefinition) bool {
	if name == "" || name == "null" {
		return false
	}
	if ss, ok := apiDef.GetSecurityScheme(name); ok {
		return ss.Type == Oauth2
	}
	return false
}
165097
func (v *CORSRuleType) Validate() error {

	if len(v.AllowedMethods) == 0 {
		return errors.ParameterRequiredError{
			ParameterName: "AllowedMethods",
			ParentName:    "CORSRule",
		}
	}

	if v.AllowedOrigin == nil {
		return errors.ParameterRequiredError{
			ParameterName: "AllowedOrigin",
			ParentName:    "CORSRule",
		}
	}

	return nil
}