// ContextRequiredScopes extracts the security scopes from the given context.
// This should be used in auth handlers to validate that the required scopes are present in the
// JWT or OAuth2 token.
498910
func ContextRequiredScopes(ctx context.Context) []string {
	if s := ctx.Value(securityScopesKey); s != nil {
		return s.([]string)
	}
	return nil
}
381598
func NewOauth2Scopes(in interface{}, context *compiler.Context) (*Oauth2Scopes, error) {
	errors := make([]error, 0)
	x := &Oauth2Scopes{}
	m, ok := compiler.UnpackMap(in)
	if !ok {
		message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in)
		errors = append(errors, compiler.NewError(context, message))
	} else {
		// repeated NamedString additional_properties = 1;
		// MAP: string
		x.AdditionalProperties = make([]*NamedString, 0)
		for _, item := range m {
			k, ok := compiler.StringValue(item.Key)
			if ok {
				v := item.Value
				pair := &NamedString{}
				pair.Name = k
				pair.Value = v.(string)
				x.AdditionalProperties = append(x.AdditionalProperties, pair)
			}
		}
	}
	return x, compiler.NewErrorGroupOrNil(errors)
}
502721
func GetContext(sp *Spider, req *request.Request) *Context {
	ctx := contextPool.Get().(*Context)
	ctx.spider = sp
	ctx.Request = req
	return ctx
}
108834
func (w *Wallet) defaultScopeManagers() (
	map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager, error) {

	scopedMgrs := make(map[waddrmgr.KeyScope]*waddrmgr.ScopedKeyManager)
	for _, scope := range waddrmgr.DefaultKeyScopes {
		scopedMgr, err := w.Manager.FetchScopedKeyManager(scope)
		if err != nil {
			return nil, err
		}

		scopedMgrs[scope] = scopedMgr
	}

	return scopedMgrs, nil
}
729019
func validateScopedResourceSelectorRequirement(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}
	hardLimits := sets.NewString()
	for k := range resourceQuotaSpec.Hard {
		hardLimits.Insert(string(k))
	}
	fldPath := fld.Child("matchExpressions")
	scopeSet := sets.NewString()
	for _, req := range resourceQuotaSpec.ScopeSelector.MatchExpressions {
		if !helper.IsStandardResourceQuotaScope(string(req.ScopeName)) {
			allErrs = append(allErrs, field.Invalid(fldPath.Child("scopeName"), req.ScopeName, "unsupported scope"))
		}
		for _, k := range hardLimits.List() {
			if helper.IsStandardQuotaResourceName(k) && !helper.IsResourceQuotaScopeValidForResource(req.ScopeName, k) {
				allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.ScopeSelector, "unsupported scope applied to resource"))
			}
		}
		switch req.ScopeName {
		case core.ResourceQuotaScopeBestEffort, core.ResourceQuotaScopeNotBestEffort, core.ResourceQuotaScopeTerminating, core.ResourceQuotaScopeNotTerminating:
			if req.Operator != core.ScopeSelectorOpExists {
				allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), req.Operator,
					"must be 'Exist' only operator when scope is any of ResourceQuotaScopeTerminating, ResourceQuotaScopeNotTerminating, ResourceQuotaScopeBestEffort and ResourceQuotaScopeNotBestEffort"))
			}
		}

		switch req.Operator {
		case core.ScopeSelectorOpIn, core.ScopeSelectorOpNotIn:
			if len(req.Values) == 0 {
				allErrs = append(allErrs, field.Required(fldPath.Child("values"),
					"must be at least one value when `operator` is 'In' or 'NotIn' for scope selector"))
			}
		case core.ScopeSelectorOpExists, core.ScopeSelectorOpDoesNotExist:
			if len(req.Values) != 0 {
				allErrs = append(allErrs, field.Invalid(fldPath.Child("values"), req.Values,
					"must be no value when `operator` is 'Exist' or 'DoesNotExist' for scope selector"))
			}
		default:
			allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), req.Operator, "not a valid selector operator"))
		}
		scopeSet.Insert(string(req.ScopeName))
	}
	invalidScopePairs := []sets.String{
		sets.NewString(string(core.ResourceQuotaScopeBestEffort), string(core.ResourceQuotaScopeNotBestEffort)),
		sets.NewString(string(core.ResourceQuotaScopeTerminating), string(core.ResourceQuotaScopeNotTerminating)),
	}
	for _, invalidScopePair := range invalidScopePairs {
		if scopeSet.HasAll(invalidScopePair.List()...) {
			allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "conflicting scopes"))
		}
	}

	return allErrs
}
1100834
func contextWithRepositoryScope(ctx context.Context, refspec reference.Spec, push bool) (context.Context, error) {
	s, err := repositoryScope(refspec, push)
	if err != nil {
		return nil, err
	}
	return context.WithValue(ctx, tokenScopesKey{}, []string{s}), nil
}
998376
func Context(r *http.Request) *RequestContext {
	contextMutex.RLock()
	defer contextMutex.RUnlock()
	return requestContextMap[r]
}
133180
func GetOAuthTokenContext(ctx context.Context, client httpClient, clientID, clientSecret, code, redirectURI string) (accessToken string, scope string, err error) {
	response, err := GetOAuthResponseContext(ctx, client, clientID, clientSecret, code, redirectURI)
	if err != nil {
		return "", "", err
	}
	return response.AccessToken, response.Scope, nil
}
1101401
func (mr *MockRequesterMockRecorder) GetRequestedScopes() *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRequestedScopes", reflect.TypeOf((*MockRequester)(nil).GetRequestedScopes))
}
183022
func (nc *Conn) AuthRequired() bool {
	nc.mu.RLock()
	defer nc.mu.RUnlock()
	return nc.info.AuthRequired
}
15698
func CheckSecurityRequirements(obj *Object, getScopes func(b *ucon.Bubble) ([]string, error)) ucon.MiddlewareFunc {

	return func(b *ucon.Bubble) error {
		op, ok := b.RequestHandler.Value(swaggerOperationKey{}).(*Operation)
		if !ok {
			return b.Next()
		}

		var secReqs []SecurityRequirement
		if op.Security != nil {
			// If len(op.Security) == 0, It overwrite top-level definition.
			// check by != nil.
			secReqs = op.Security

		} else {
			secReqs = obj.Security
		}

		// check security. It is ok if any one of the security passes.
		passed := false
		for _, req := range secReqs {
		sec_type:
			for name, oauth2ReqScopes := range req {
				if obj.SecurityDefinitions == nil {
					return ErrSecurityDefinitionsIsRequired
				}

				scheme, ok := obj.SecurityDefinitions[name]
				if !ok {
					return ErrSecurityDefinitionsIsRequired
				}

				switch scheme.Type {
				case "oauth2":
					scopes, err := getScopes(b)
					if err != nil {
						return err
					}

					// all scopes are required.
				outer:
					for _, reqScope := range oauth2ReqScopes {
						for _, scope := range scopes {
							if scope == reqScope {
								continue outer
							}
						}

						continue sec_type
					}

					passed = true

				case "basic":
					fallthrough
				case "apiKey":
					fallthrough
				default:
					if len(oauth2ReqScopes) != 0 {
						return ErrSecuritySettingsAreWrong
					}

					return ErrNotImplemented
				}
			}
		}
		if passed {
			return b.Next()
		}

		return ErrAccessDenied
	}
}
649962
func ContextError(ctx context.Context) error {
	if err := ctx.Value(errKey); err != nil {
		return err.(error)
	}
	return nil
}
131399
func LoginRequired() negroni.HandlerFunc {
	return func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		token := GetToken(r)
		if token == nil || !token.Valid() {
			// Set token to null to avoid redirection loop
			SetToken(r, nil)
			next := url.QueryEscape(r.URL.RequestURI())
			http.Redirect(rw, r, PathLogin+"?"+keyNextPage+"="+next, http.StatusFound)
		} else {
			next(rw, r)
		}
	}
}
479090
func verifyScopes(scopeString string, username string, clientID string, orgMgr *organization.Manager) (string, error) {
	scopes := strings.Split(scopeString, ",")
	for i, scope := range scopes {
		// If the scope is memberof:clientid, where clientid is the globalid of the
		// organization requesting authorization, verify if we really have this scope
		// or if we have the scope on one or more children. In case of the latter, replace
		// the scopes by the appropriate ones
		if scope == "user:memberof:"+clientID {
			inOrg, err := orgMgr.IsInOrgs(username, clientID)
			if err != nil {
				return scopeString, err
			}
			// Should only have 1 result, and result MUST be clientID
			if len(inOrg) == 1 && inOrg[0] == clientID {
				return scopeString, nil
			}

			log.Debugf("Access token contains scope %v, but user is not a member of %v - parse suborganizations",
				scope, clientID)
			// Remove the memberof:parentOrg scope
			scopes = append(scopes[:i], scopes[i+1:]...)
			var subOrgScopes []string
			subOrgScopes, err = findSuborgScopes(clientID, username, orgMgr)
			if err != nil {
				return scope, err
			}
			// Add the correct memberof scopes
			scopes = append(scopes, subOrgScopes...)
			scopeString = strings.Join(scopes, ",")
		}
	}
	return scopeString, nil
}
384547
func ValidateSecurityContext(sc *api.SecurityContext, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}
	//this should only be true for testing since SecurityContext is defaulted by the api
	if sc == nil {
		return allErrs
	}

	if sc.Privileged != nil {
		if *sc.Privileged && !capabilities.Get().AllowPrivileged {
			allErrs = append(allErrs, field.Forbidden(fldPath.Child("privileged"), "disallowed by policy"))
		}
	}

	if sc.RunAsUser != nil {
		if *sc.RunAsUser < 0 {
			allErrs = append(allErrs, field.Invalid(fldPath.Child("runAsUser"), *sc.RunAsUser, isNegativeErrorMsg))
		}
	}
	return allErrs
}
533585
func (s *Spec) SecurityRequirementsFor(operation *spec.Operation) [][]SecurityRequirement {
	if s.spec.Security == nil && operation.Security == nil {
		return nil
	}

	schemes := s.spec.Security
	if operation.Security != nil {
		schemes = operation.Security
	}

	result := [][]SecurityRequirement{}
	for _, scheme := range schemes {
		if len(scheme) == 0 {
			// append a zero object for anonymous
			result = append(result, []SecurityRequirement{{}})
			continue
		}
		var reqs []SecurityRequirement
		for k, v := range scheme {
			if v == nil {
				v = []string{}
			}
			reqs = append(reqs, SecurityRequirement{Name: k, Scopes: v})
		}
		result = append(result, reqs)
	}
	return result
}
934901
func (m *Manager) DeleteRequiredScope(globalId string, requiredScope string) error {
	return m.collection.Update(bson.M{"globalid": globalId},
		bson.M{"$pull": bson.M{"requiredscopes": bson.M{"scope": requiredScope}}})
}