// validateRequest checks that the request is allowed.
//
// Returns corresponding config rule on success or a grpc error on error.
422100
func (r *MintOAuthTokenGrantRPC) validateRequest(c context.Context, req *minter.MintOAuthTokenGrantRequest, caller identity.Identity) (*Rule, error) {
	// Dump the whole request and relevant auth state to the debug log.
	r.logRequest(c, req, caller)

	// Reject obviously bad requests.
	if err := r.checkRequestFormat(req); err != nil {
		logging.WithError(err).Errorf(c, "Bad request")
		return nil, status.Errorf(codes.InvalidArgument, "bad request - %s", err)
	}

	// TODO(vadimsh): Verify that this user is present by requiring the end user's
	// credentials, e.g make Swarming forward user's OAuth token to the token
	// server, so it can be validated here.

	// Check that requested usage is allowed and grab the corresponding rule.
	return r.checkRules(c, req, caller)
}
1260675
func (m *GrpcJsonTranscoder) Validate() error {
	if m == nil {
		return nil
	}

	if len(m.GetServices()) < 1 {
		return GrpcJsonTranscoderValidationError{
			field:  "Services",
			reason: "value must contain at least 1 item(s)",
		}
	}

	{
		tmp := m.GetPrintOptions()

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

			if err := v.Validate(); err != nil {
				return GrpcJsonTranscoderValidationError{
					field:  "PrintOptions",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	// no validation rules for MatchIncomingRequestRoute

	switch m.DescriptorSet.(type) {

	case *GrpcJsonTranscoder_ProtoDescriptor:
		// no validation rules for ProtoDescriptor

	case *GrpcJsonTranscoder_ProtoDescriptorBin:
		// no validation rules for ProtoDescriptorBin

	default:
		return GrpcJsonTranscoderValidationError{
			field:  "DescriptorSet",
			reason: "value is required",
		}

	}

	return nil
}
203693
func (r QueryRequest) Validate() error {
	if r.Query == "" && r.Spec == nil && r.AST == nil {
		return errors.New(`request body requires either query, spec, or AST`)
	}

	if r.Type != "flux" {
		return fmt.Errorf(`unknown query type: %s`, r.Type)
	}

	if len(r.Dialect.CommentPrefix) > 1 {
		return fmt.Errorf("invalid dialect comment prefix: must be length 0 or 1")
	}

	if len(r.Dialect.Delimiter) != 1 {
		return fmt.Errorf("invalid dialect delimeter: must be length 1")
	}

	rune, size := utf8.DecodeRuneInString(r.Dialect.Delimiter)
	if rune == utf8.RuneError && size == 1 {
		return fmt.Errorf("invalid dialect delimeter character")
	}

	for _, a := range r.Dialect.Annotations {
		switch a {
		case "group", "datatype", "default":
		default:
			return fmt.Errorf(`unknown dialect annotation type: %s`, a)
		}
	}

	switch r.Dialect.DateTimeFormat {
	case "RFC3339", "RFC3339Nano":
	default:
		return fmt.Errorf(`unknown dialect date time format: %s`, r.Dialect.DateTimeFormat)
	}

	return nil
}
699578
func ValidateAndNormalizeRequest(c context.Context, oauthScope []string, durationSecs *int64, auditTags []string) error {
	minDur := time.Duration(*durationSecs) * time.Second
	// Test error cases
	switch {
	case len(oauthScope) <= 0:
		return fmt.Errorf("oauth_scope is required")
	case minDur < 0:
		return fmt.Errorf("min_validity_duration must be positive")
	case minDur > maxAllowedMinValidityDuration:
		return fmt.Errorf("min_validity_duration must not exceed %d", maxAllowedMinValidityDuration/time.Second)
	}
	if err := ValidateTags(auditTags); err != nil {
		return fmt.Errorf("bad audit_tags - %s", err)
	}

	// Perform normalization
	if minDur == 0 {
		*durationSecs = int64(DefaultMinValidityDuration.Seconds())
	}
	return nil
}
563528
func (cerr *ChromeRequestErr) Error() string {
	return "request " + strconv.FormatInt(cerr.Resp.Id, 10) + " failed, code: " + strconv.FormatInt(cerr.Resp.Error.Code, 10) + " msg: " + cerr.Resp.Error.Message
}
1124709
func ParseRequest(contentType string, body io.Reader) (*Request, error) {
	if err := checkContentType(contentType); err != nil {
		return nil, err
	}

	r := &Request{}
	if err := parseReqOrResp(body, r); err != nil {
		return nil, err
	}

	return r, nil
}
728865
func validateResponse(r *http.Response) error {
	if c := r.StatusCode; 200 <= c && c <= 299 {
		return nil
	}

	bodyBytes, _ := ioutil.ReadAll(r.Body)
	bodyString := string(bodyBytes)
	m := &errorJSONResponse{}
	err := json.Unmarshal([]byte(bodyString), &m)
	if err != nil {
		return err
	}

	return m.Error
}
1286485
func (m *HandledConsentRequest) Validate(formats strfmt.Registry) error {
	var res []error

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

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
1083767
func (c *AccessConfig) ValidateRegion(regions ...string) error {
	ec2conn, err := c.NewEC2Connection()
	if err != nil {
		return err
	}

	validRegions, err := listEC2Regions(ec2conn)
	if err != nil {
		return err
	}

	var invalidRegions []string
	for _, region := range regions {
		if region == "" {
			continue
		}
		found := false
		for _, validRegion := range validRegions {
			if region == validRegion {
				found = true
				break
			}
		}
		if !found {
			invalidRegions = append(invalidRegions, region)
		}
	}

	if len(invalidRegions) > 0 {
		return fmt.Errorf("Invalid region(s): %v, available regions: %v", invalidRegions, validRegions)
	}
	return nil
}
132121
func ValidateBindRequest(breq *api.BindRequest) field.ErrorList {
	var allErrs field.ErrorList

	for key := range breq.Parameters {
		if !templatevalidation.ParameterNameRegexp.MatchString(key) {
			allErrs = append(allErrs, field.Invalid(field.NewPath("parameters."+key), key, fmt.Sprintf("does not match %v", templatevalidation.ParameterNameRegexp)))
		}
	}

	return allErrs
}
197480
func (a *Authenticator) AuthenticateRequest(req *http.Request) (*authenticator.Response, bool, error) {
	username, password, found := req.BasicAuth()
	if !found {
		return nil, false, nil
	}

	resp, ok, err := a.auth.AuthenticatePassword(req.Context(), username, password)

	// If the password authenticator didn't error, provide a default error
	if !ok && err == nil {
		err = errInvalidAuth
	}

	return resp, ok, err
}
1072989
func ValidateRoute(route *routeapi.Route) field.ErrorList {
	//ensure meta is set properly
	result := validation.ValidateObjectMeta(&route.ObjectMeta, true, ValidateRouteName, field.NewPath("metadata"))

	specPath := field.NewPath("spec")

	//host is not required but if it is set ensure it meets DNS requirements
	if len(route.Spec.Host) > 0 {
		// TODO: Add a better check that the host name matches up to
		//       DNS requirements. Change to use:
		//         ValidateHostName(route)
		//       Need to check the implications of doing it here in
		//       ValidateRoute - probably needs to be done only on
		//       creation time for new routes.
		if len(kvalidation.IsDNS1123Subdomain(route.Spec.Host)) != 0 {
			result = append(result, field.Invalid(specPath.Child("host"), route.Spec.Host, "host must conform to DNS 952 subdomain conventions"))
		}
	}

	if err := validateWildcardPolicy(route.Spec.Host, route.Spec.WildcardPolicy, specPath.Child("wildcardPolicy")); err != nil {
		result = append(result, err)
	}

	if len(route.Spec.Path) > 0 && !strings.HasPrefix(route.Spec.Path, "/") {
		result = append(result, field.Invalid(specPath.Child("path"), route.Spec.Path, "path must begin with /"))
	}

	if len(route.Spec.Path) > 0 && route.Spec.TLS != nil &&
		route.Spec.TLS.Termination == routeapi.TLSTerminationPassthrough {
		result = append(result, field.Invalid(specPath.Child("path"), route.Spec.Path, "passthrough termination does not support paths"))
	}

	if len(route.Spec.To.Name) == 0 {
		result = append(result, field.Required(specPath.Child("to", "name"), ""))
	}
	if route.Spec.To.Kind != "Service" {
		result = append(result, field.Invalid(specPath.Child("to", "kind"), route.Spec.To.Kind, "must reference a Service"))
	}
	if route.Spec.To.Weight != nil && (*route.Spec.To.Weight < 0 || *route.Spec.To.Weight > 256) {
		result = append(result, field.Invalid(specPath.Child("to", "weight"), route.Spec.To.Weight, "weight must be an integer between 0 and 256"))
	}

	backendPath := specPath.Child("alternateBackends")
	if len(route.Spec.AlternateBackends) > 3 {
		result = append(result, field.Required(backendPath, "cannot specify more than 3 alternate backends"))
	}
	for i, svc := range route.Spec.AlternateBackends {
		if len(svc.Name) == 0 {
			result = append(result, field.Required(backendPath.Index(i).Child("name"), ""))
		}
		if svc.Kind != "Service" {
			result = append(result, field.Invalid(backendPath.Index(i).Child("kind"), svc.Kind, "must reference a Service"))
		}
		if svc.Weight != nil && (*svc.Weight < 0 || *svc.Weight > 256) {
			result = append(result, field.Invalid(backendPath.Index(i).Child("weight"), svc.Weight, "weight must be an integer between 0 and 256"))
		}
	}

	if route.Spec.Port != nil {
		switch target := route.Spec.Port.TargetPort; {
		case target.Type == intstr.Int && target.IntVal == 0,
			target.Type == intstr.String && len(target.StrVal) == 0:
			result = append(result, field.Required(specPath.Child("port", "targetPort"), ""))
		}
	}

	if errs := validateTLS(route, specPath.Child("tls")); len(errs) != 0 {
		result = append(result, errs...)
	}

	return result
}
31516
func HTTPRequestFromContext(ctx context.Context) *http.Request {
	req, _ := ctx.Value(httpRequestContextKey).(*http.Request)
	return req
}
392295
func (r *Request) UseRequest(fn context.HandlerFunc) *Request {
	r.Middleware.UseRequest(fn)
	return r
}
647149
func (m *GrpcService_GoogleGrpc) Validate() error {
	if m == nil {
		return nil
	}

	if len(m.GetTargetUri()) < 1 {
		return GrpcService_GoogleGrpcValidationError{
			field:  "TargetUri",
			reason: "value length must be at least 1 bytes",
		}
	}

	{
		tmp := m.GetChannelCredentials()

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

			if err := v.Validate(); err != nil {
				return GrpcService_GoogleGrpcValidationError{
					field:  "ChannelCredentials",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

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

		{
			tmp := item

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

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

	}

	if len(m.GetStatPrefix()) < 1 {
		return GrpcService_GoogleGrpcValidationError{
			field:  "StatPrefix",
			reason: "value length must be at least 1 bytes",
		}
	}

	// no validation rules for CredentialsFactoryName

	{
		tmp := m.GetConfig()

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

			if err := v.Validate(); err != nil {
				return GrpcService_GoogleGrpcValidationError{
					field:  "Config",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	return nil
}
611304
func Validate(req interface{}) error {
	// validate req message
	if err := v.Struct(req); err != nil {
		if v, ok := err.(validator.ValidationErrors); ok {
			err = v
		}
		return status.Errorf(codes.InvalidArgument, "Request validation failed: %s", err)
	}
	return nil
}
1339620
func ValidateRemote(remote string) error {
	remotes, err := RemoteList()
	if err != nil {
		return err
	}
	for _, r := range remotes {
		if r == remote {
			return nil
		}
	}

	if err = ValidateRemoteURL(remote); err == nil {
		return nil
	}

	return fmt.Errorf("Invalid remote name: %q", remote)
}