// Rule API
// NewRaiseRule creates a rule that runs action when a raised alerts matche filter.
// Action happens before incoming alert is raised.
333826
func NewRaiseRule(name string, filter Filter, action Action) Rule {
	return &rule{name: name, event: raiseEvent, filter: filter, action: action}
}
910397
func makeRule(c context.Context, ruleProto *admin.ServiceAccountRule, defaults *admin.ServiceAccountRuleDefaults, rev string) (*Rule, error) {
	ctx := &validation.Context{Context: c}
	validateRule(ctx, ruleProto.Name, ruleProto)
	if err := ctx.Finalize(); err != nil {
		return nil, err
	}

	allowedScopes := stringset.New(len(ruleProto.AllowedScope) + len(defaults.AllowedScope))
	for _, scope := range ruleProto.AllowedScope {
		allowedScopes.Add(scope)
	}
	for _, scope := range defaults.AllowedScope {
		allowedScopes.Add(scope)
	}

	endUsers, err := identityset.FromStrings(ruleProto.EndUser, nil)
	if err != nil {
		return nil, fmt.Errorf("bad 'end_user' set - %s", err)
	}

	proxies, err := identityset.FromStrings(ruleProto.Proxy, nil)
	if err != nil {
		return nil, fmt.Errorf("bad 'proxy' set - %s", err)
	}

	trustedProxies, err := identityset.FromStrings(ruleProto.TrustedProxy, nil)
	if err != nil {
		return nil, fmt.Errorf("bad 'trusted_proxy' set - %s", err)
	}

	if ruleProto.MaxGrantValidityDuration == 0 {
		ruleProto.MaxGrantValidityDuration = defaults.MaxGrantValidityDuration
	}

	return &Rule{
		Rule:           ruleProto,
		Revision:       rev,
		AllowedScopes:  allowedScopes,
		EndUsers:       endUsers,
		Proxies:        proxies,
		TrustedProxies: trustedProxies,
		AllProxies:     identityset.Union(proxies, trustedProxies),
	}, nil
}
745071
func (api *API) CreatePageRule(zoneID string, rule PageRule) (*PageRule, error) {
	uri := "/zones/" + zoneID + "/pagerules"
	res, err := api.makeRequest("POST", uri, rule)
	if err != nil {
		return nil, errors.Wrap(err, errMakeRequestError)
	}
	var r PageRuleDetailResponse
	err = json.Unmarshal(res, &r)
	if err != nil {
		return nil, errors.Wrap(err, errUnmarshalError)
	}
	return &r.Result, nil
}
618296
func (q Queue) ToRulesMap() RulesMap {
	pattern := q.Filter.RuleList.Pattern()
	return NewRulesMap(q.Events, pattern, q.ARN.TargetID)
}
933978
func NewOpenIngressRule(protocol string, from, to int) IngressRule {
	rule, _ := NewIngressRule(protocol, from, to)
	return rule
}
1258928
func httpCreateRule(w http.ResponseWriter, r *http.Request, vars map[string]string) (interface{}, error) {
	log.Debugf("Received httpGetRule: %+v", vars)

	var obj Rule
	key := vars["key"]

	// Get object from the request
	err := json.NewDecoder(r.Body).Decode(&obj)
	if err != nil {
		log.Errorf("Error decoding rule create request. Err %v", err)
		return nil, err
	}

	// set the key
	obj.Key = key

	// Create the object
	err = CreateRule(&obj)
	if err != nil {
		log.Errorf("CreateRule error for: %+v. Err: %v", obj, err)
		return nil, err
	}

	// Return the obj
	return obj, nil
}
1295716
func (r *Rules) parseRule(rule string) error {
	rule = strings.TrimSpace(rule)

	// Ignore blank lines
	if rule == "" {
		return nil
	}
	// Comment
	if strings.HasPrefix(rule, "#") {
		return nil
	}

	// Fail any rules that contain **
	if strings.Contains(rule, "**") {
		return errors.New("double-star (**) syntax is not supported")
	}

	// Fail any patterns that can't compile. A non-empty string must be
	// given to Match() to avoid optimization that skips rule evaluation.
	if _, err := filepath.Match(rule, "abc"); err != nil {
		return err
	}

	p := &pattern{raw: rule}

	// Negation is handled at a higher level, so strip the leading ! from the
	// string.
	if strings.HasPrefix(rule, "!") {
		p.negate = true
		rule = rule[1:]
	}

	// Directory verification is handled by a higher level, so the trailing /
	// is removed from the rule. That way, a directory named "foo" matches,
	// even if the supplied string does not contain a literal slash character.
	if strings.HasSuffix(rule, "/") {
		p.mustDir = true
		rule = strings.TrimSuffix(rule, "/")
	}

	if strings.HasPrefix(rule, "/") {
		// Require path matches the root path.
		p.match = func(n string, fi os.FileInfo) bool {
			rule = strings.TrimPrefix(rule, "/")
			ok, err := filepath.Match(rule, n)
			if err != nil {
				log.Printf("Failed to compile %q: %s", rule, err)
				return false
			}
			return ok
		}
	} else if strings.Contains(rule, "/") {
		// require structural match.
		p.match = func(n string, fi os.FileInfo) bool {
			ok, err := filepath.Match(rule, n)
			if err != nil {
				log.Printf("Failed to compile %q: %s", rule, err)
				return false
			}
			return ok
		}
	} else {
		p.match = func(n string, fi os.FileInfo) bool {
			// When there is no slash in the pattern, we evaluate ONLY the
			// filename.
			n = filepath.Base(n)
			ok, err := filepath.Match(rule, n)
			if err != nil {
				log.Printf("Failed to compile %q: %s", rule, err)
				return false
			}
			return ok
		}
	}

	r.patterns = append(r.patterns, p)
	return nil
}
570300
func (r *Registry) AddExternalHTTPRule(qualifiedMethodName string, rule *annotations.HttpRule) {
	r.externalHTTPRules[qualifiedMethodName] = append(r.externalHTTPRules[qualifiedMethodName], rule)
}
138580
func NewRules() *rules {
	rules := &rules{namesKeys: nameToKey, phoneDevices: phoneDevices, tabletDevices: tabletDevices, operatingSystems: operatingSystems, browsers: browsers}
	rules.setMobileDetectionRules(nameToKey)
	return rules
}
648895
func MarshalAlertRule(r *ScopedAlert) ([]byte, error) {
	j, err := json.Marshal(r.AlertRule)
	if err != nil {
		return nil, err
	}
	return proto.Marshal(&AlertRule{
		ID:     r.ID,
		SrcID:  int64(r.SrcID),
		KapaID: int64(r.KapaID),
		JSON:   string(j),
	})
}
461864
func (inliner *Inliner) handleQualifiedRule(rule *css.Rule) {
	for _, selector := range rule.Selectors {
		if Inlinable(selector) {
			inliner.doc.Find(selector).Each(func(i int, s *goquery.Selection) {
				// get marker
				eltMarker, exists := s.Attr(eltMarkerAttr)
				if !exists {
					// mark element
					eltMarker = strconv.Itoa(inliner.eltMarker)
					s.SetAttr(eltMarkerAttr, eltMarker)
					inliner.eltMarker++

					// add new element
					inliner.elements[eltMarker] = NewElement(s)
				}

				// add style rule for element
				inliner.elements[eltMarker].addStyleRule(NewStyleRule(selector, rule.Declarations))
			})
		} else {
			// Keep it 'as is'
			inliner.rawRules = append(inliner.rawRules, NewStyleRule(selector, rule.Declarations))
		}
	}
}
1132345
func NewRule(scope, namePrefix, connector string) (*Rule, error) {
	if namePrefix == "" {
		return nil, errors.New("namePrefix could not be empty, should be defined in yaml file")
	}

	if scope == "" {
		return nil, errors.New("scope could not be empty, should be defined in yaml file")
	}

	if strings.HasPrefix(namePrefix, "*") && len(namePrefix) != 1 {
		// we don't support name like '*.service.v1'
		return nil, errors.Errorf(
			"namePrefix like %v is not supported, cannot put * at the beginning of namePrefix.", namePrefix)
	}

	globMatch := glob.MustCompile(namePrefix)

	return &Rule{NamePrefix: namePrefix, Scope: scope, Connector: connector, GlobMatch: globMatch}, nil
}
975740
func (s *GetRateBasedRuleOutput) SetRule(v *RateBasedRule) *GetRateBasedRuleOutput {
	s.Rule = v
	return s
}
847045
func (rule *Rule) MergeChildRule(childRule *Rule) {
	for key, existingChildRule := range rule.Children {
		if existingChildRule.Name == childRule.Name {
			for _, behavior := range childRule.Behaviors {
				rule.Children[key].MergeBehavior(behavior)
			}

			for _, criteria := range childRule.Criteria {
				rule.Children[key].MergeCriteria(criteria)
			}

			for _, child := range childRule.Children {
				rule.Children[key].MergeChildRule(child)
			}

			return
		}
	}

	rule.Children = append(rule.Children, childRule)
}
1218855
func (i *Index) SearchRules(query string, opts ...interface{}) (res SearchRulesRes, err error) {
	body := newSearchRulesParams(query, opts...)
	path := i.path("/rules/search")
	err = i.transport.Request(&res, http.MethodPost, path, body, call.Read, opts...)
	return
}
142887
func ValidateRule(obj *Rule) error {
	collections.ruleMutex.Lock()
	defer collections.ruleMutex.Unlock()

	// Validate key is correct
	keyStr := obj.TenantName + ":" + obj.PolicyName + ":" + obj.RuleID
	if obj.Key != keyStr {
		log.Errorf("Expecting Rule Key: %s. Got: %s", keyStr, obj.Key)
		return errors.New("Invalid Key")
	}

	// Validate each field

	actionMatch := regexp.MustCompile("^(allow|deny)$")
	if actionMatch.MatchString(obj.Action) == false {
		return errors.New("action string invalid format")
	}

	directionMatch := regexp.MustCompile("^(in|out)$")
	if directionMatch.MatchString(obj.Direction) == false {
		return errors.New("direction string invalid format")
	}

	if len(obj.FromEndpointGroup) > 64 {
		return errors.New("fromEndpointGroup string too long")
	}

	fromEndpointGroupMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])?$")
	if fromEndpointGroupMatch.MatchString(obj.FromEndpointGroup) == false {
		return errors.New("fromEndpointGroup string invalid format")
	}

	fromIpAddressMatch := regexp.MustCompile("^(((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})(\\-(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]))?(/(3[0-1]|2[0-9]|1[0-9]|[1-9]))?)?$")
	if fromIpAddressMatch.MatchString(obj.FromIpAddress) == false {
		return errors.New("fromIpAddress string invalid format")
	}

	if len(obj.FromNetwork) > 64 {
		return errors.New("fromNetwork string too long")
	}

	fromNetworkMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])?$")
	if fromNetworkMatch.MatchString(obj.FromNetwork) == false {
		return errors.New("fromNetwork string invalid format")
	}

	if len(obj.PolicyName) > 64 {
		return errors.New("policyName string too long")
	}

	policyNameMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$")
	if policyNameMatch.MatchString(obj.PolicyName) == false {
		return errors.New("policyName string invalid format")
	}

	if obj.Port > 65535 {
		return errors.New("port Value Out of bound")
	}

	if obj.Priority == 0 {
		obj.Priority = 1
	}

	if obj.Priority < 1 {
		return errors.New("priority Value Out of bound")
	}

	if obj.Priority > 100 {
		return errors.New("priority Value Out of bound")
	}

	protocolMatch := regexp.MustCompile("^(tcp|udp|icmp||[0-9]{1,3}?)$")
	if protocolMatch.MatchString(obj.Protocol) == false {
		return errors.New("protocol string invalid format")
	}

	if len(obj.RuleID) > 64 {
		return errors.New("ruleId string too long")
	}

	ruleIdMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$")
	if ruleIdMatch.MatchString(obj.RuleID) == false {
		return errors.New("ruleId string invalid format")
	}

	if len(obj.TenantName) > 64 {
		return errors.New("tenantName string too long")
	}

	tenantNameMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$")
	if tenantNameMatch.MatchString(obj.TenantName) == false {
		return errors.New("tenantName string invalid format")
	}

	if len(obj.ToEndpointGroup) > 64 {
		return errors.New("toEndpointGroup string too long")
	}

	toEndpointGroupMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])?$")
	if toEndpointGroupMatch.MatchString(obj.ToEndpointGroup) == false {
		return errors.New("toEndpointGroup string invalid format")
	}

	toIpAddressMatch := regexp.MustCompile("^(((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})(\\-(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]))?(/(3[0-1]|2[0-9]|1[0-9]|[1-9]))?)?$")
	if toIpAddressMatch.MatchString(obj.ToIpAddress) == false {
		return errors.New("toIpAddress string invalid format")
	}

	if len(obj.ToNetwork) > 64 {
		return errors.New("toNetwork string too long")
	}

	toNetworkMatch := regexp.MustCompile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])?$")
	if toNetworkMatch.MatchString(obj.ToNetwork) == false {
		return errors.New("toNetwork string invalid format")
	}

	return nil
}
309431
func (s *ObjectLockConfiguration) SetRule(v *ObjectLockRule) *ObjectLockConfiguration {
	s.Rule = v
	return s
}