// EnforceSafe calls Enforce in a safe way, returns error instead of causing panic.
512630
func (e *SyncedEnforcer) EnforceSafe(rvals ...interface{}) (result bool, err error) {
	e.m.RLock()
	defer e.m.RUnlock()
	return e.Enforcer.EnforceSafe(rvals...)
}
1276459
func (mr *MockTriremeControllerMockRecorder) Enforce(ctx, puID, policy, runtime interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Enforce", reflect.TypeOf((*MockTriremeController)(nil).Enforce), ctx, puID, policy, runtime)
}
498482
func (isolators Isolators) assertValid() error {
	typesMap := make(map[ACIdentifier]bool)
	for _, i := range isolators {
		v := i.Value()
		if v == nil {
			return ErrInvalidIsolator
		}
		if err := v.AssertValid(); err != nil {
			return err
		}
		if _, ok := typesMap[i.Name]; ok {
			if !v.multipleAllowed() {
				return fmt.Errorf(`isolators set contains too many instances of type %s"`, i.Name)
			}
		}
		for _, c := range v.Conflicts() {
			if _, found := typesMap[c]; found {
				return ErrIncompatibleIsolator
			}
		}
		typesMap[i.Name] = true
	}
	return nil
}
976219
func (e *Enforcer) Enforce(rvals ...interface{}) bool {
	if !e.enabled {
		return true
	}

	functions := make(map[string]govaluate.ExpressionFunction)
	for key, function := range e.fm {
		functions[key] = function
	}
	if _, ok := e.model["g"]; ok {
		for key, ast := range e.model["g"] {
			rm := ast.RM
			functions[key] = util.GenerateGFunction(rm)
		}
	}

	expString := e.model["m"]["m"].Value
	expression, err := govaluate.NewEvaluableExpressionWithFunctions(expString, functions)
	if err != nil {
		panic(err)
	}

	var policyEffects []effect.Effect
	var matcherResults []float64
	if policyLen := len(e.model["p"]["p"].Policy); policyLen != 0 {
		policyEffects = make([]effect.Effect, policyLen)
		matcherResults = make([]float64, policyLen)
		if len(e.model["r"]["r"].Tokens) != len(rvals) {
			panic(
				fmt.Sprintf(
					"Invalid Request Definition size: expected %d got %d rvals: %v",
					len(e.model["r"]["r"].Tokens),
					len(rvals),
					rvals))
		}
		for i, pvals := range e.model["p"]["p"].Policy {
			// log.LogPrint("Policy Rule: ", pvals)
			if len(e.model["p"]["p"].Tokens) != len(pvals) {
				panic(
					fmt.Sprintf(
						"Invalid Policy Rule size: expected %d got %d pvals: %v",
						len(e.model["p"]["p"].Tokens),
						len(pvals),
						pvals))
			}
			parameters := make(map[string]interface{}, 8)
			for j, token := range e.model["r"]["r"].Tokens {
				parameters[token] = rvals[j]
			}
			for j, token := range e.model["p"]["p"].Tokens {
				parameters[token] = pvals[j]
			}

			result, err := expression.Evaluate(parameters)
			// log.LogPrint("Result: ", result)

			if err != nil {
				policyEffects[i] = effect.Indeterminate
				panic(err)
			}

			switch result := result.(type) {
			case bool:
				if !result {
					policyEffects[i] = effect.Indeterminate
					continue
				}
			case float64:
				if result == 0 {
					policyEffects[i] = effect.Indeterminate
					continue
				} else {
					matcherResults[i] = result
				}
			default:
				panic(errors.New("matcher result should be bool, int or float"))
			}

			if eft, ok := parameters["p_eft"]; ok {
				if eft == "allow" {
					policyEffects[i] = effect.Allow
				} else if eft == "deny" {
					policyEffects[i] = effect.Deny
				} else {
					policyEffects[i] = effect.Indeterminate
				}
			} else {
				policyEffects[i] = effect.Allow
			}

			if e.model["e"]["e"].Value == "priority(p_eft) || deny" {
				break
			}

		}
	} else {
		policyEffects = make([]effect.Effect, 1)
		matcherResults = make([]float64, 1)

		parameters := make(map[string]interface{}, 8)
		for j, token := range e.model["r"]["r"].Tokens {
			parameters[token] = rvals[j]
		}
		for _, token := range e.model["p"]["p"].Tokens {
			parameters[token] = ""
		}

		result, err := expression.Evaluate(parameters)
		// log.LogPrint("Result: ", result)

		if err != nil {
			policyEffects[0] = effect.Indeterminate
			panic(err)
		}

		if result.(bool) {
			policyEffects[0] = effect.Allow
		} else {
			policyEffects[0] = effect.Indeterminate
		}
	}

	// log.LogPrint("Rule Results: ", policyEffects)

	result, err := e.eft.MergeEffects(e.model["e"]["e"].Value, policyEffects, matcherResults)
	if err != nil {
		panic(err)
	}

	// Log request.
	if log.GetLogger().IsEnabled() {
		reqStr := "Request: "
		for i, rval := range rvals {
			if i != len(rvals)-1 {
				reqStr += fmt.Sprintf("%v, ", rval)
			} else {
				reqStr += fmt.Sprintf("%v", rval)
			}
		}
		reqStr += fmt.Sprintf(" ---> %t", result)
		log.LogPrint(reqStr)
	}

	return result
}
1185827
func (e *Enforcer) RemoveGroupingPolicySafe(params ...interface{}) (result bool, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("%v", r)
			result = false
		}
	}()

	result = e.RemoveGroupingPolicy(params...)
	err = nil
	return
}
184671
func (s *Store) EnsureCheck(idx uint64, hc *structs.HealthCheck) error {
	tx := s.db.Txn(true)
	defer tx.Abort()

	// Call the check registration
	if err := s.ensureCheckTxn(tx, idx, hc); err != nil {
		return err
	}

	tx.Commit()
	return nil
}
281286
func EnforceVersionPolicies(versionGetter VersionGetter, newK8sVersionStr string, newK8sVersion *version.Version, allowExperimentalUpgrades, allowRCUpgrades bool) *VersionSkewPolicyErrors {

	skewErrors := &VersionSkewPolicyErrors{
		Mandatory: []error{},
		Skippable: []error{},
	}

	clusterVersionStr, clusterVersion, err := versionGetter.ClusterVersion()
	if err != nil {
		// This case can't be forced: kubeadm has to be able to lookup cluster version for upgrades to work
		skewErrors.Mandatory = append(skewErrors.Mandatory, errors.Wrap(err, "Unable to fetch cluster version"))
		return skewErrors
	}

	kubeadmVersionStr, kubeadmVersion, err := versionGetter.KubeadmVersion()
	if err != nil {
		// This case can't be forced: kubeadm has to be able to lookup its version for upgrades to work
		skewErrors.Mandatory = append(skewErrors.Mandatory, errors.Wrap(err, "Unable to fetch kubeadm version"))
		return skewErrors
	}

	kubeletVersions, err := versionGetter.KubeletVersions()
	if err != nil {
		// This is a non-critical error; continue although kubeadm couldn't look this up
		skewErrors.Skippable = append(skewErrors.Skippable, errors.Wrap(err, "Unable to fetch kubelet version"))
	}

	// Make sure the new version is a supported version (higher than the minimum one supported)
	if constants.MinimumControlPlaneVersion.AtLeast(newK8sVersion) {
		// This must not happen, kubeadm always supports a minimum version; and we can't go below that
		skewErrors.Mandatory = append(skewErrors.Mandatory, errors.Errorf("Specified version to upgrade to %q is equal to or lower than the minimum supported version %q. Please specify a higher version to upgrade to", newK8sVersionStr, clusterVersionStr))
	}

	// kubeadm doesn't support upgrades between two minor versions; e.g. a v1.7 -> v1.9 upgrade is not supported right away
	if newK8sVersion.Minor() > clusterVersion.Minor()+MaximumAllowedMinorVersionUpgradeSkew {
		tooLargeUpgradeSkewErr := errors.Errorf("Specified version to upgrade to %q is too high; kubeadm can upgrade only %d minor version at a time", newK8sVersionStr, MaximumAllowedMinorVersionUpgradeSkew)
		// If the version that we're about to upgrade to is a released version, we should fully enforce this policy
		// If the version is a CI/dev/experimental version, it's okay to jump two minor version steps, but then require the -f flag
		if len(newK8sVersion.PreRelease()) == 0 {
			skewErrors.Mandatory = append(skewErrors.Mandatory, tooLargeUpgradeSkewErr)
		} else {
			skewErrors.Skippable = append(skewErrors.Skippable, tooLargeUpgradeSkewErr)
		}
	}

	// kubeadm doesn't support downgrades between two minor versions; e.g. a v1.9 -> v1.7 downgrade is not supported right away
	if newK8sVersion.Minor() < clusterVersion.Minor()-MaximumAllowedMinorVersionDowngradeSkew {
		tooLargeDowngradeSkewErr := errors.Errorf("Specified version to downgrade to %q is too low; kubeadm can downgrade only %d minor version at a time", newK8sVersionStr, MaximumAllowedMinorVersionDowngradeSkew)
		// If the version that we're about to downgrade to is a released version, we should fully enforce this policy
		// If the version is a CI/dev/experimental version, it's okay to jump two minor version steps, but then require the -f flag
		if len(newK8sVersion.PreRelease()) == 0 {
			skewErrors.Mandatory = append(skewErrors.Mandatory, tooLargeDowngradeSkewErr)
		} else {
			skewErrors.Skippable = append(skewErrors.Skippable, tooLargeDowngradeSkewErr)
		}
	}

	// If the kubeadm version is lower than what we want to upgrade to; error
	if kubeadmVersion.LessThan(newK8sVersion) {
		if newK8sVersion.Minor() > kubeadmVersion.Minor() {
			tooLargeKubeadmSkew := errors.Errorf("Specified version to upgrade to %q is at least one minor release higher than the kubeadm minor release (%d > %d). Such an upgrade is not supported", newK8sVersionStr, newK8sVersion.Minor(), kubeadmVersion.Minor())
			// This is unsupported; kubeadm has no idea how it should handle a newer minor release than itself
			// If the version is a CI/dev/experimental version though, lower the severity of this check, but then require the -f flag
			if len(newK8sVersion.PreRelease()) == 0 {
				skewErrors.Mandatory = append(skewErrors.Mandatory, tooLargeKubeadmSkew)
			} else {
				skewErrors.Skippable = append(skewErrors.Skippable, tooLargeKubeadmSkew)
			}
		} else {
			// Upgrading to a higher patch version than kubeadm is ok if the user specifies --force. Not recommended, but possible.
			skewErrors.Skippable = append(skewErrors.Skippable, errors.Errorf("Specified version to upgrade to %q is higher than the kubeadm version %q. Upgrade kubeadm first using the tool you used to install kubeadm", newK8sVersionStr, kubeadmVersionStr))
		}
	}

	if kubeadmVersion.Major() > newK8sVersion.Major() ||
		kubeadmVersion.Minor() > newK8sVersion.Minor() {
		skewErrors.Skippable = append(skewErrors.Skippable, errors.Errorf("Kubeadm version %s can only be used to upgrade to Kubernetes version %d.%d", kubeadmVersionStr, kubeadmVersion.Major(), kubeadmVersion.Minor()))
	}

	// Detect if the version is unstable and the user didn't allow that
	if err = detectUnstableVersionError(newK8sVersion, newK8sVersionStr, allowExperimentalUpgrades, allowRCUpgrades); err != nil {
		skewErrors.Skippable = append(skewErrors.Skippable, err)
	}

	// Detect if there are too old kubelets in the cluster
	// Check for nil here since this is the only case where kubeletVersions can be nil; if KubeletVersions() returned an error
	// However, it's okay to skip that check
	if kubeletVersions != nil {
		if err = detectTooOldKubelets(newK8sVersion, kubeletVersions); err != nil {
			skewErrors.Skippable = append(skewErrors.Skippable, err)
		}
	}

	// If we did not see any errors, return nil
	if len(skewErrors.Skippable) == 0 && len(skewErrors.Mandatory) == 0 {
		return nil
	}

	// Uh oh, we encountered one or more errors, return them
	return skewErrors
}
648553
func (e *Enforcer) Enforce(rvals ...interface{}) bool {
	return enforce(e.Enforcer, e.defaultRole, e.claimsEnforcerFunc, rvals...)
}
1294837
func NewSyncedEnforcerSafe(params ...interface{}) (enforcer *SyncedEnforcer, err error) {
	e := &SyncedEnforcer{}
	e.Enforcer, err = NewEnforcerSafe(params...)

	if err != nil {
		return nil, err
	}

	e.autoLoad = false
	return e, nil
}
38442
func (s *Sanitizer) KeepAlive(ctx context.Context, lease Lease, expires time.Time) error {
	if !isKeySafe(lease.Key) {
		return trace.BadParameter(errorMessage)
	}
	return s.backend.KeepAlive(ctx, lease, expires)
}
928949
func (p *GoTemplatePrinter) safeExecute(w io.Writer, obj interface{}) error {
	var panicErr error
	// Sorry for the double anonymous function. There's probably a clever way
	// to do this that has the defer'd func setting the value to be returned, but
	// that would be even less obvious.
	retErr := func() error {
		defer func() {
			if x := recover(); x != nil {
				panicErr = fmt.Errorf("caught panic: %+v", x)
			}
		}()
		return p.template.Execute(w, obj)
	}()
	if panicErr != nil {
		return panicErr
	}
	return retErr
}
303785
func (e *Enforcer) EnforceErr(rvals ...interface{}) error {
	if !e.Enforce(rvals...) {
		errMsg := "permission denied"
		if len(rvals) > 0 {
			rvalsStrs := make([]string, len(rvals)-1)
			for i, rval := range rvals[1:] {
				rvalsStrs[i] = fmt.Sprintf("%s", rval)
			}
			errMsg = fmt.Sprintf("%s: %s", errMsg, strings.Join(rvalsStrs, ", "))
		}
		return status.Error(codes.PermissionDenied, errMsg)
	}
	return nil
}
1288474
func (c *Cache) enforceCapacity() {
	// Check maxItems.
	if c.config.MaxItems > 0 {
		for c.l.Len() > c.config.MaxItems {
			if !c.dropTail() {
				break
			}
		}
	}
	// Check maxBytes.
	if c.config.MaxBytes > 0 {
		for c.size > c.config.MaxBytes {
			if !c.dropTail() {
				break
			}
		}
	}
}
906001
func (*Config) Ensure(c context.Context, req *config.EnsureRequest) (*config.Config, error) {
	if req.GetId() == "" {
		return nil, status.Errorf(codes.InvalidArgument, "ID is required")
	}
	cfg := &model.Config{
		ID:     req.Id,
		Config: *req.Config,
	}
	if err := datastore.Put(c, cfg); err != nil {
		return nil, errors.Annotate(err, "failed to store config").Err()
	}
	return &cfg.Config, nil
}
1120650
func (t *Tree) findUnsafe(ctx context.Context, h Hash) (ret interface{}, root Hash, err error) {
	return t.findTyped(ctx, h, true)
}
430389
func (t *trireme) Enforce(ctx context.Context, puID string, policy *policy.PUPolicy, runtime *policy.PURuntime) error {
	lock, _ := t.locks.LoadOrStore(puID, &sync.Mutex{})
	lock.(*sync.Mutex).Lock()
	defer lock.(*sync.Mutex).Unlock()
	return t.doHandleCreate(puID, policy, runtime)
}
675645
func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) bool {
	if h, ok := a.t.(tHelper); ok {
		h.Helper()
	}
	return Failf(a.t, failureMessage, msg, args...)
}