// checkPostPolicy - apply policy conditions and validate input values.
// (http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html)
962506
func checkPostPolicy(formValues http.Header, postPolicyForm PostPolicyForm) error {
	// Check if policy document expiry date is still not reached
	if !postPolicyForm.Expiration.After(UTCNow()) {
		return fmt.Errorf("Invalid according to Policy: Policy expired")
	}
	// map to store the metadata
	metaMap := make(map[string]string)
	for cond, v := range postPolicyForm.Conditions.Policies {
		if strings.HasPrefix(cond, "$x-amz-meta-") {
			formCanonicalName := http.CanonicalHeaderKey(strings.TrimPrefix(cond, "$"))
			metaMap[formCanonicalName] = v.Value
		}
	}
	// Check if any extra metadata field is passed as input
	for key := range formValues {
		if strings.HasPrefix(key, "X-Amz-Meta-") {
			if _, ok := metaMap[key]; !ok {
				return fmt.Errorf("Invalid according to Policy: Extra input fields: %s", key)
			}
		}
	}

	// Flag to indicate if all policies conditions are satisfied
	condPassed := true

	// Iterate over policy conditions and check them against received form fields
	for cond, v := range postPolicyForm.Conditions.Policies {
		// Form fields names are in canonical format, convert conditions names
		// to canonical for simplification purpose, so `$key` will become `Key`
		formCanonicalName := http.CanonicalHeaderKey(strings.TrimPrefix(cond, "$"))
		// Operator for the current policy condition
		op := v.Operator
		// If the current policy condition is known
		if startsWithSupported, condFound := startsWithConds[cond]; condFound {
			// Check if the current condition supports starts-with operator
			if op == policyCondStartsWith && !startsWithSupported {
				return fmt.Errorf("Invalid according to Policy: Policy Condition failed")
			}
			// Check if current policy condition is satisfied
			if !condPassed {
				return fmt.Errorf("Invalid according to Policy: Policy Condition failed")
			}
		} else {
			// This covers all conditions X-Amz-Meta-* and X-Amz-*
			if strings.HasPrefix(cond, "$x-amz-meta-") || strings.HasPrefix(cond, "$x-amz-") {
				// Check if policy condition is satisfied
				condPassed = checkPolicyCond(op, formValues.Get(formCanonicalName), v.Value)
				if !condPassed {
					return fmt.Errorf("Invalid according to Policy: Policy Condition failed: [%s, %s, %s]", op, cond, v.Value)
				}
			}
		}
	}

	return nil
}
1217272
func getBucketPolicy(statement Statement, prefix string) (commonFound, readOnly, writeOnly bool) {
	if !(statement.Effect == "Allow" && statement.Principal.AWS.Contains("*")) {
		return commonFound, readOnly, writeOnly
	}

	if statement.Actions.Intersection(commonBucketActions).Equals(commonBucketActions) &&
		statement.Conditions == nil {
		commonFound = true
	}

	if statement.Actions.Intersection(writeOnlyBucketActions).Equals(writeOnlyBucketActions) &&
		statement.Conditions == nil {
		writeOnly = true
	}

	if statement.Actions.Intersection(readOnlyBucketActions).Equals(readOnlyBucketActions) {
		if prefix != "" && statement.Conditions != nil {
			if stringEqualsValue, ok := statement.Conditions["StringEquals"]; ok {
				if s3PrefixValues, ok := stringEqualsValue["s3:prefix"]; ok {
					if s3PrefixValues.Contains(prefix) {
						readOnly = true
					}
				}
			} else if stringNotEqualsValue, ok := statement.Conditions["StringNotEquals"]; ok {
				if s3PrefixValues, ok := stringNotEqualsValue["s3:prefix"]; ok {
					if !s3PrefixValues.Contains(prefix) {
						readOnly = true
					}
				}
			}
		} else if prefix == "" && statement.Conditions == nil {
			readOnly = true
		} else if prefix != "" && statement.Conditions == nil {
			readOnly = true
		}
	}

	return commonFound, readOnly, writeOnly
}
1354813
func (s *CreateHITInput) SetHITReviewPolicy(v *ReviewPolicy) *CreateHITInput {
	s.HITReviewPolicy = v
	return s
}
726337
func httpInspectPolicy(w http.ResponseWriter, r *http.Request, vars map[string]string) (interface{}, error) {
	var obj PolicyInspect
	log.Debugf("Received httpInspectPolicy: %+v", vars)

	key := vars["key"]

	collections.policyMutex.Lock()
	defer collections.policyMutex.Unlock()
	objConfig := collections.policys[key]
	if objConfig == nil {
		log.Errorf("policy %s not found", key)
		return nil, errors.New("policy not found")
	}
	obj.Config = *objConfig

	if err := GetOperPolicy(&obj); err != nil {
		log.Errorf("GetPolicy error for: %+v. Err: %v", obj, err)
		return nil, err
	}

	// Return the obj
	return &obj, nil
}
648507
func (s *Bucket) GetPolicy() (*GetBucketPolicyOutput, error) {
	r, x, err := s.GetPolicyRequest()

	if err != nil {
		return x, err
	}

	err = r.Send()
	if err != nil {
		return nil, err
	}

	requestID := r.HTTPResponse.Header.Get(http.CanonicalHeaderKey("X-QS-Request-ID"))
	x.RequestID = &requestID

	return x, err
}
11366
func (model Model) GetPolicy(sec string, ptype string) [][]string {
	return model[sec][ptype].Policy
}
1315008
func (a *ACL) GetPolicy(args *structs.ACLPolicySpecificRequest, reply *structs.SingleACLPolicyResponse) error {
	if !a.srv.config.ACLEnabled {
		return aclDisabled
	}
	if done, err := a.srv.forward("ACL.GetPolicy", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"nomad", "acl", "get_policy"}, time.Now())

	// Check management level permissions
	acl, err := a.srv.ResolveToken(args.AuthToken)
	if err != nil {
		return err
	} else if acl == nil {
		return structs.ErrPermissionDenied
	}

	// If it is not a management token determine if it can get this policy
	mgt := acl.IsManagement()
	if !mgt {
		snap, err := a.srv.fsm.State().Snapshot()
		if err != nil {
			return err
		}

		token, err := snap.ACLTokenBySecretID(nil, args.AuthToken)
		if err != nil {
			return err
		}
		if token == nil {
			return structs.ErrTokenNotFound
		}

		found := false
		for _, p := range token.Policies {
			if p == args.Name {
				found = true
				break
			}
		}

		if !found {
			return structs.ErrPermissionDenied
		}
	}

	// Setup the blocking query
	opts := blockingOptions{
		queryOpts: &args.QueryOptions,
		queryMeta: &reply.QueryMeta,
		run: func(ws memdb.WatchSet, state *state.StateStore) error {
			// Look for the policy
			out, err := state.ACLPolicyByName(ws, args.Name)
			if err != nil {
				return err
			}

			// Setup the output
			reply.Policy = out
			if out != nil {
				reply.Index = out.ModifyIndex
			} else {
				// Use the last index that affected the policy table
				index, err := state.Index("acl_policy")
				if err != nil {
					return err
				}
				reply.Index = index
			}
			return nil
		}}
	return a.srv.blockingRPC(&opts)
}
398281
func NewPostPolicy() *PostPolicy {
	p := &PostPolicy{}
	p.conditions = make([]policyCondition, 0)
	p.formData = make(map[string]string)
	return p
}
997211
func httpCreatePolicy(w http.ResponseWriter, r *http.Request, vars map[string]string) (interface{}, error) {
	log.Debugf("Received httpGetPolicy: %+v", vars)

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

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

	// set the key
	obj.Key = key

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

	// Return the obj
	return obj, nil
}
853334
func (s *Bucket) PutPolicy(input *PutBucketPolicyInput) (*PutBucketPolicyOutput, error) {
	r, x, err := s.PutPolicyRequest(input)

	if err != nil {
		return x, err
	}

	err = r.Send()
	if err != nil {
		return nil, err
	}

	requestID := r.HTTPResponse.Header.Get(http.CanonicalHeaderKey("X-QS-Request-ID"))
	x.RequestID = &requestID

	return x, err
}
1260011
func (a *Adapter) AddPolicy(sec string, ptype string, rule []string) error {
	return errors.New("not implemented")
}
270092
func (p BucketPolicy) IsValidBucketPolicy() bool {
	switch p {
	case BucketPolicyNone, BucketPolicyReadOnly, BucketPolicyReadWrite, BucketPolicyWriteOnly:
		return true
	}
	return false
}
245119
func parsePostPolicyForm(policy string) (ppf PostPolicyForm, e error) {
	// Convert po into interfaces and
	// perform strict type conversion using reflection.
	var rawPolicy struct {
		Expiration string        `json:"expiration"`
		Conditions []interface{} `json:"conditions"`
	}

	err := json.Unmarshal([]byte(policy), &rawPolicy)
	if err != nil {
		return ppf, err
	}

	parsedPolicy := PostPolicyForm{}

	// Parse expiry time.
	parsedPolicy.Expiration, err = time.Parse(time.RFC3339Nano, rawPolicy.Expiration)
	if err != nil {
		return ppf, err
	}
	parsedPolicy.Conditions.Policies = make(map[string]struct {
		Operator string
		Value    string
	})

	// Parse conditions.
	for _, val := range rawPolicy.Conditions {
		switch condt := val.(type) {
		case map[string]interface{}: // Handle key:value map types.
			for k, v := range condt {
				if !isString(v) { // Pre-check value type.
					// All values must be of type string.
					return parsedPolicy, fmt.Errorf("Unknown type %s of conditional field value %s found in POST policy form", reflect.TypeOf(condt).String(), condt)
				}
				// {"acl": "public-read" } is an alternate way to indicate - [ "eq", "$acl", "public-read" ]
				// In this case we will just collapse this into "eq" for all use cases.
				parsedPolicy.Conditions.Policies["$"+strings.ToLower(k)] = struct {
					Operator string
					Value    string
				}{
					Operator: policyCondEqual,
					Value:    toString(v),
				}
			}
		case []interface{}: // Handle array types.
			if len(condt) != 3 { // Return error if we have insufficient elements.
				return parsedPolicy, fmt.Errorf("Malformed conditional fields %s of type %s found in POST policy form", condt, reflect.TypeOf(condt).String())
			}
			switch toLowerString(condt[0]) {
			case policyCondEqual, policyCondStartsWith:
				for _, v := range condt { // Pre-check all values for type.
					if !isString(v) {
						// All values must be of type string.
						return parsedPolicy, fmt.Errorf("Unknown type %s of conditional field value %s found in POST policy form", reflect.TypeOf(condt).String(), condt)
					}
				}
				operator, matchType, value := toLowerString(condt[0]), toLowerString(condt[1]), toString(condt[2])
				parsedPolicy.Conditions.Policies[matchType] = struct {
					Operator string
					Value    string
				}{
					Operator: operator,
					Value:    value,
				}
			case policyCondContentLength:
				min, err := toInteger(condt[1])
				if err != nil {
					return parsedPolicy, err
				}

				max, err := toInteger(condt[2])
				if err != nil {
					return parsedPolicy, err
				}

				parsedPolicy.Conditions.ContentLengthRange = contentLengthRange{
					Min:   min,
					Max:   max,
					Valid: true,
				}
			default:
				// Condition should be valid.
				return parsedPolicy, fmt.Errorf("Unknown type %s of conditional field value %s found in POST policy form",
					reflect.TypeOf(condt).String(), condt)
			}
		default:
			return parsedPolicy, fmt.Errorf("Unknown field %s of type %s found in POST policy form",
				condt, reflect.TypeOf(condt).String())
		}
	}
	return parsedPolicy, nil
}
414126
func (endpoint *HostComputeEndpoint) ApplyPolicy(endpointPolicy PolicyEndpointRequest) error {
	logrus.Debugf("hcn::HostComputeEndpoint::ApplyPolicy id=%s", endpoint.Id)

	settingsJson, err := json.Marshal(endpointPolicy)
	if err != nil {
		return err
	}
	requestMessage := &ModifyEndpointSettingRequest{
		ResourceType: EndpointResourceTypePolicy,
		RequestType:  RequestTypeUpdate,
		Settings:     settingsJson,
	}

	return ModifyEndpointSettings(endpoint.Id, requestMessage)
}
114315
func (c *ContivClient) RulePost(obj *Rule) error {
	// build key and URL
	keyStr := obj.TenantName + ":" + obj.PolicyName + ":" + obj.RuleID
	url := c.baseURL + "/api/v1/rules/" + keyStr + "/"

	// http post the object
	err := c.httpPost(url, obj)
	if err != nil {
		log.Debugf("Error creating rule %+v. Err: %v", obj, err)
		return err
	}

	return nil
}
648765
func (model Model) PrintPolicy() {
	log.LogPrint("Policy:")
	for key, ast := range model["p"] {
		log.LogPrint(key, ": ", ast.Value, ": ", ast.Policy)
	}

	for key, ast := range model["g"] {
		log.LogPrint(key, ": ", ast.Value, ": ", ast.Policy)
	}
}
304313
func formatKVPolicy(policy *api.ACLPolicy) string {
	output := []string{
		fmt.Sprintf("Name|%s", policy.Name),
		fmt.Sprintf("Description|%s", policy.Description),
		fmt.Sprintf("Rules|%s", policy.Rules),
		fmt.Sprintf("CreateIndex|%v", policy.CreateIndex),
		fmt.Sprintf("ModifyIndex|%v", policy.ModifyIndex),
	}
	return formatKV(output)
}