// GetAuthorization is the handler for GET /users/{username}/authorizations/{grantedTo}
// Get the authorization for a specific organization.
765280
func (api UsersAPI) GetAuthorization(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	grantedTo := mux.Vars(r)["grantedTo"]

	userMgr := user.NewManager(r)

	authorization, err := userMgr.GetAuthorization(username, grantedTo)
	if handleServerError(w, "Getting authorization by user", err) {
		return
	}
	if authorization == nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}
	w.Header().Set("Content-type", "application/json")
	json.NewEncoder(w).Encode(authorization)
}
954243
func NewAuthorizationHandler(b *AuthorizationBackend) *AuthorizationHandler {
	h := &AuthorizationHandler{
		Router: NewRouter(),
		Logger: b.Logger,

		AuthorizationService: b.AuthorizationService,
		OrganizationService:  b.OrganizationService,
		UserService:          b.UserService,
		LookupService:        b.LookupService,
	}

	h.HandlerFunc("POST", "/api/v2/authorizations", h.handlePostAuthorization)
	h.HandlerFunc("GET", "/api/v2/authorizations", h.handleGetAuthorizations)
	h.HandlerFunc("GET", "/api/v2/authorizations/:id", h.handleGetAuthorization)
	h.HandlerFunc("PATCH", "/api/v2/authorizations/:id", h.handleUpdateAuthorization)
	h.HandlerFunc("DELETE", "/api/v2/authorizations/:id", h.handleDeleteAuthorization)
	return h
}
1148887
func RoleEscalationAuthorized(ctx context.Context, a authorizer.Authorizer) bool {
	if a == nil {
		return false
	}

	user, ok := genericapirequest.UserFrom(ctx)
	if !ok {
		return false
	}

	requestInfo, ok := genericapirequest.RequestInfoFrom(ctx)
	if !ok {
		return false
	}

	if !requestInfo.IsResourceRequest {
		return false
	}

	requestResource := schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}
	if !roleResources[requestResource] {
		return false
	}

	attrs := authorizer.AttributesRecord{
		User:            user,
		Verb:            "escalate",
		APIGroup:        requestInfo.APIGroup,
		Resource:        requestInfo.Resource,
		Name:            requestInfo.Name,
		Namespace:       requestInfo.Namespace,
		ResourceRequest: true,
	}

	decision, _, err := a.Authorize(attrs)
	if err != nil {
		utilruntime.HandleError(fmt.Errorf(
			"error authorizing user %#v to escalate %#v named %q in namespace %q: %v",
			user, requestResource, requestInfo.Name, requestInfo.Namespace, err,
		))
	}
	return decision == authorizer.DecisionAllow
}
199407
func (t *Template) GetAllAWSConfigAggregationAuthorizationResources() map[string]*resources.AWSConfigAggregationAuthorization {
	results := map[string]*resources.AWSConfigAggregationAuthorization{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSConfigAggregationAuthorization:
			results[name] = resource
		}
	}
	return results
}
386145
func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform.ID) error {
	return s.DeleteAuthorizationFn(ctx, id)
}
1283802
func (s *AuthorizationService) FindAuthorizations(ctx context.Context, filter platform.AuthorizationFilter, opt ...platform.FindOptions) (as []*platform.Authorization, i int, err error) {
	defer func() {
		if err != nil {
			s.Logger.Info("error finding authorizations", zap.Error(err))
		}
	}()

	return s.AuthorizationService.FindAuthorizations(ctx, filter, opt...)
}
1204931
func (controllerAuthorizer) Authorize(authInfo httpcontext.AuthInfo) error {
	if authInfo.Controller {
		return nil
	}
	return errors.Errorf("%s is not a controller", names.ReadableString(authInfo.Entity.Tag()))
}
884071
func (ssa *SQLStorageAuthority) GetPendingAuthorization2(ctx context.Context, req *sapb.GetPendingAuthorizationRequest) (*corepb.Authorization, error) {
	var am authz2Model
	err := ssa.dbMap.WithContext(ctx).SelectOne(
		&am,
		fmt.Sprintf(`SELECT %s FROM authz2 WHERE
			registrationID = :regID AND
			identifierValue = :ident AND
			status = :status AND
			expires > :validUntil
			ORDER BY expires ASC
			LIMIT 1 `, authz2Fields),
		map[string]interface{}{
			"regID":      *req.RegistrationID,
			"ident":      *req.IdentifierValue,
			"status":     statusUint(core.StatusPending),
			"validUntil": time.Unix(0, *req.ValidUntil),
		},
	)
	if err != nil {
		if err == sql.ErrNoRows {
			// there may be an old style pending authorization so look for that
			authz, err := ssa.GetPendingAuthorization(ctx, req)
			if err != nil {
				return nil, err
			}
			return bgrpc.AuthzToPB(*authz)
		}
		return nil, err
	}
	return modelToAuthzPB(&am)
}
312234
func (s *AuthorizationService) FindAuthorizations(ctx context.Context, filter influxdb.AuthorizationFilter, opt ...influxdb.FindOptions) ([]*influxdb.Authorization, int, error) {
	// TODO: we'll likely want to push this operation into the database eventually since fetching the whole list of data
	// will likely be expensive.
	as, _, err := s.s.FindAuthorizations(ctx, filter, opt...)
	if err != nil {
		return nil, 0, err
	}

	// This filters without allocating
	// https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
	authorizations := as[:0]
	for _, a := range as {
		err := authorizeReadAuthorization(ctx, a.UserID)
		if err != nil && influxdb.ErrorCode(err) != influxdb.EUnauthorized {
			return nil, 0, err
		}

		if influxdb.ErrorCode(err) == influxdb.EUnauthorized {
			continue
		}

		authorizations = append(authorizations, a)
	}

	return authorizations, len(authorizations), nil
}
493215
func (c *AuthorizationService) Get(authzURL string) (acme.Authorization, error) {
	if len(authzURL) == 0 {
		return acme.Authorization{}, errors.New("authorization[get]: empty URL")
	}

	var authz acme.Authorization
	_, err := c.core.postAsGet(authzURL, &authz)
	if err != nil {
		return acme.Authorization{}, err
	}
	return authz, nil
}
304290
func (h *AuthorizationHandler) handleGetAuthorization(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodeGetAuthorizationRequest(ctx, r)
	if err != nil {
		h.Logger.Info("failed to decode request", zap.String("handler", "getAuthorization"), zap.Error(err))
		EncodeError(ctx, err, w)
		return
	}

	a, err := h.AuthorizationService.FindAuthorizationByID(ctx, req.ID)
	if err != nil {
		// Don't log here, it should already be handled by the service
		EncodeError(ctx, err, w)
		return
	}

	o, err := h.OrganizationService.FindOrganizationByID(ctx, a.OrgID)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	u, err := h.UserService.FindUserByID(ctx, a.UserID)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	ps, err := newPermissionsResponse(ctx, a.Permissions, h.LookupService)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusOK, newAuthResponse(a, o, u, ps)); err != nil {
		EncodeError(ctx, err, w)
		return
	}
}
1083665
func (s *storage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {
	authorize, err := s.authorizetoken.Get(code, metav1.GetOptions{})
	if kerrors.IsNotFound(err) {
		klog.V(5).Info("Authorization code not found")
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return s.convertFromAuthorizeToken(authorize)
}
192864
func (p *PullRequest) GetAuthorAssociation() string {
	if p == nil || p.AuthorAssociation == nil {
		return ""
	}
	return *p.AuthorAssociation
}
233511
func (ssa *SQLStorageAuthority) GetAuthorizations(
	ctx context.Context,
	req *sapb.GetAuthorizationsRequest) (*sapb.Authorizations, error) {
	authzMap, err := ssa.getAuthorizations(
		ctx,
		authorizationTable,
		string(core.StatusValid),
		*req.RegistrationID,
		req.Domains,
		time.Unix(0, *req.Now),
		*req.RequireV2Authzs,
	)
	if err != nil {
		return nil, err
	}
	if len(authzMap) == len(req.Domains) {
		return authzMapToPB(authzMap)
	}

	// remove names we already have authz for
	remainingNames := []string{}
	for _, name := range req.Domains {
		if _, present := authzMap[name]; !present {
			remainingNames = append(remainingNames, name)
		}
	}
	pendingAuthz, err := ssa.getPendingAuthorizations(
		ctx,
		*req.RegistrationID,
		remainingNames,
		time.Unix(0, *req.Now),
		*req.RequireV2Authzs)
	if err != nil {
		return nil, err
	}
	// merge pending into valid
	for name, a := range pendingAuthz {
		authzMap[name] = a
	}

	// Wildcard domain issuance requires that the authorizations returned by this
	// RPC also include populated challenges such that the caller can know if the
	// challenges meet the wildcard issuance policy (e.g. only 1 DNS-01
	// challenge).
	// Fetch each of the authorizations' associated challenges
	for _, authz := range authzMap {
		authz.Challenges, err = ssa.getChallenges(ssa.dbMap.WithContext(ctx), authz.ID)
		if err != nil {
			return nil, err
		}
	}
	return authzMapToPB(authzMap)
}
897316
func TokenAuthorizedWhereOrg(a *Authorization, org string) func(DocumentIndex, DocumentDecorator) ([]ID, error) {
	return func(idx DocumentIndex, _ DocumentDecorator) ([]ID, error) {
		oid, err := idx.FindOrganizationByName(org)
		if err != nil {
			return nil, err
		}
		return authorizedWhereOrgID(a, oid, idx)
	}
}
454593
func (m *Manager) DeleteAuthorization(username, organization string) (err error) {
	_, err = m.getAuthorizationCollection().RemoveAll(bson.M{"username": username, "grantedto": organization})
	return
}
301457
func (a *preAuthorizer) PreAuthorize(ctx context.Context, ast *ast.Package, auth platform.Authorizer, orgID *platform.ID) error {
	readBuckets, writeBuckets, err := BucketsAccessed(ast, orgID)
	if err != nil {
		return errors.Wrap(err, "could not retrieve buckets for query.Spec")
	}

	for _, readBucketFilter := range readBuckets {
		bucket, err := a.bucketService.FindBucket(ctx, readBucketFilter)
		if err != nil {
			return errors.Wrapf(err, "could not find read bucket with filter: %s", readBucketFilter)
		}

		if bucket == nil {
			return errors.New("bucket service returned nil bucket")
		}

		reqPerm, err := platform.NewPermissionAtID(bucket.ID, platform.ReadAction, platform.BucketsResourceType, bucket.OrgID)
		if err != nil {
			return errors.Wrapf(err, "could not create read bucket permission")
		}

		if !auth.Allowed(*reqPerm) {
			return errors.New("no read permission for bucket: \"" + bucket.Name + "\"")
		}
	}

	for _, writeBucketFilter := range writeBuckets {
		bucket, err := a.bucketService.FindBucket(ctx, writeBucketFilter)
		if err != nil {
			return errors.Wrapf(err, "could not find write bucket with filter: %s", writeBucketFilter)
		}

		reqPerm, err := platform.NewPermissionAtID(bucket.ID, platform.WriteAction, platform.BucketsResourceType, bucket.OrgID)
		if err != nil {
			return errors.Wrapf(err, "could not create write bucket permission")
		}
		if !auth.Allowed(*reqPerm) {
			return errors.New("no write permission for bucket: \"" + bucket.Name + "\"")
		}
	}

	return nil
}