mcanoglu/cwe-class-group huggingface dataset:
def read_config(self, config, **kwargs):
        self.recaptcha_private_key = config.get("recaptcha_private_key")
        self.recaptcha_public_key = config.get("recaptcha_public_key")
        self.enable_registration_captcha = config.get(
            "enable_registration_captcha", False
        )
        self.recaptcha_siteverify_api = config.get(
            "recaptcha_siteverify_api",
            "https://www.recaptcha.net/recaptcha/api/siteverify",
        )
        self.recaptcha_template = self.read_templates(
            ["recaptcha.html"], autoescape=True
        )[0]

// Vulnerability class: CWE-74
it "creates a hostgroup with a parent parameter" do
      post :create, {"hostgroup" => {"name"=>"test_it", "parent_id" => @base.id, :realm_id => realms(:myrealm).id,
                                     :group_parameters_attributes => {"0" => {:name => "x", :value =>"overridden", :_destroy => ""}}}}, set_session_user
      assert_redirected_to hostgroups_url
      hostgroup = Hostgroup.where(:name => "test_it").last
      assert_equal "overridden", hostgroup.parameters["x"]
    end

// Vulnerability class: CWE-200
it 'should return the right response' do
          email_token.update!(created_at: 999.years.ago)

          get "/session/email-login/#{email_token.token}"

          expect(response.status).to eq(200)

          expect(CGI.unescapeHTML(response.body)).to match(
            I18n.t('email_login.invalid_token')
          )
        end

// Vulnerability class: CWE-287
def api_endpoint(uri)
    host = uri.host

    begin
      res = @dns.getresource "_rubygems._tcp.#{host}",
                             Resolv::DNS::Resource::IN::SRV
    rescue Resolv::ResolvError => e
      verbose "Getting SRV record failed: #{e}"
      uri
    else
      target = res.target.to_s.strip

      if /\.#{Regexp.quote(host)}\z/ =~ target
        return URI.parse "#{uri.scheme}://#{target}#{uri.path}"
      end

      uri
    end
  end

// Vulnerability class: CWE-346
def test_update_valid
    AuthSourceLdap.any_instance.stubs(:valid?).returns(true)
    put :update, {:id => AuthSourceLdap.first, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user
    assert_redirected_to auth_source_ldaps_url
  end

// Vulnerability class: CWE-200
def update
    return unless access_granted?(params[:id])

    id = params[:article][:id] || params[:id]
    @article = Article.find(id)

    if params[:article][:draft]
      fetch_fresh_or_existing_draft_for_article
    else
      @article = Article.find(@article.parent_id) unless @article.parent_id.nil?
    end

    update_article_attributes

    if @article.draft
      @article.state = "draft"
    elsif @article.draft?
      @article.publish!
    end

    if @article.save
      Article.where(parent_id: @article.id).map(&:destroy) unless @article.draft
      flash[:success] = I18n.t("admin.content.update.success")
      redirect_to action: "index"
    else
      @article.keywords = Tag.collection_to_string @article.tags
      load_resources
      render "edit"
    end
  end

// Vulnerability class: CWE-732
def update
      if @application.update(application_params)
        flash[:notice] = I18n.t(:notice, scope: i18n_scope(:update))

        respond_to do |format|
          format.html { redirect_to oauth_application_url(@application) }
          format.json { render json: @application }
        end
      else
        respond_to do |format|
          format.html { render :edit }
          format.json do
            errors = @application.errors.full_messages

            render json: { errors: errors }, status: :unprocessable_entity
          end
        end
      end
    end

// Vulnerability class: CWE-862
func (dag *DAG) EnsureService(meta types.NamespacedName, port intstr.IntOrString, cache *KubernetesCache) (*Service, error) {
	svc, svcPort, err := cache.LookupService(meta, port)
	if err != nil {
		return nil, err
	}

	if dagSvc := dag.GetService(k8s.NamespacedNameOf(svc), svcPort.Port); dagSvc != nil {
		return dagSvc, nil
	}

	dagSvc := &Service{
		Weighted: WeightedService{
			ServiceName:      svc.Name,
			ServiceNamespace: svc.Namespace,
			ServicePort:      svcPort,
			Weight:           1,
		},
		Protocol:           upstreamProtocol(svc, svcPort),
		MaxConnections:     annotation.MaxConnections(svc),
		MaxPendingRequests: annotation.MaxPendingRequests(svc),
		MaxRequests:        annotation.MaxRequests(svc),
		MaxRetries:         annotation.MaxRetries(svc),
		ExternalName:       externalName(svc),
	}
	return dagSvc, nil
}

// Vulnerability class: CWE-610
func testExternalNameServiceTLS(namespace string) {
	Specify("external name services work over https", func() {
		t := f.T()

		f.Certs.CreateSelfSignedCert(namespace, "backend-server-cert", "backend-server-cert", "echo")

		f.Fixtures.EchoSecure.Deploy(namespace, "echo-tls")

		externalNameService := &corev1.Service{
			ObjectMeta: metav1.ObjectMeta{
				Namespace: namespace,
				Name:      "external-name-service-tls",
			},
			Spec: corev1.ServiceSpec{
				Type:         corev1.ServiceTypeExternalName,
				ExternalName: "echo-tls." + namespace,
				Ports: []corev1.ServicePort{
					{
						Name:     "https",
						Port:     443,
						Protocol: corev1.ProtocolTCP,
					},
				},
			},
		}
		require.NoError(t, f.Client.Create(context.TODO(), externalNameService))

		p := &contourv1.HTTPProxy{
			ObjectMeta: metav1.ObjectMeta{
				Namespace: namespace,
				Name:      "external-name-proxy-tls",
			},
			Spec: contourv1.HTTPProxySpec{
				VirtualHost: &contourv1.VirtualHost{
					Fqdn: "tls.externalnameservice.projectcontour.io",
				},
				Routes: []contourv1.Route{
					{
						Services: []contourv1.Service{
							{
								Name:     externalNameService.Name,
								Port:     443,
								Protocol: stringPtr("tls"),
							},
						},
						RequestHeadersPolicy: &contourv1.HeadersPolicy{
							Set: []contourv1.HeaderValue{
								{
									Name:  "Host",
									Value: externalNameService.Spec.ExternalName,
								},
							},
						},
					},
				},
			},
		}
		f.CreateHTTPProxyAndWaitFor(p, httpProxyValid)

		res, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{
			Host:      p.Spec.VirtualHost.Fqdn,
			Condition: e2e.HasStatusCode(200),
		})
		require.Truef(t, ok, "expected 200 response code, got %d", res.StatusCode)
	})
}

// Vulnerability class: CWE-610
func (svc *Service) ModifyGlobalScheduledQueries(ctx context.Context, id uint, query fleet.ScheduledQueryPayload) (*fleet.ScheduledQuery, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionWrite); err != nil {
		return nil, err
	}

	gp, err := svc.ds.EnsureGlobalPack(ctx)
	if err != nil {
		return nil, err
	}

	query.PackID = ptr.Uint(gp.ID)

	return svc.ModifyScheduledQuery(ctx, id, query)
}

// Vulnerability class: CWE-863
func handleCollectedUplink(ctx context.Context, uplinkFrame gw.UplinkFrame, rxPacket models.RXPacket) error {
	var uplinkIDs []uuid.UUID
	for _, p := range rxPacket.RXInfoSet {
		uplinkIDs = append(uplinkIDs, helpers.GetUplinkID(p))
	}

	log.WithFields(log.Fields{
		"uplink_ids": uplinkIDs,
		"mtype":      rxPacket.PHYPayload.MHDR.MType,
		"ctx_id":     ctx.Value(logging.ContextIDKey),
	}).Info("uplink: frame(s) collected")

	// update the gateway meta-data
	if err := gateway.UpdateMetaDataInRxInfoSet(ctx, storage.DB(), rxPacket.RXInfoSet); err != nil {
		log.WithError(err).Error("uplink: update gateway meta-data in rx-info set error")
	}

	// log the frame for each receiving gateway.
	if err := framelog.LogUplinkFrameForGateways(ctx, ns.UplinkFrameLog{
		PhyPayload: uplinkFrame.PhyPayload,
		TxInfo:     rxPacket.TXInfo,
		RxInfo:     rxPacket.RXInfoSet,
	}); err != nil {
		log.WithFields(log.Fields{
			"ctx_id": ctx.Value(logging.ContextIDKey),
		}).WithError(err).Error("uplink: log uplink frames for gateways error")
	}

	// handle the frame based on message-type
	switch rxPacket.PHYPayload.MHDR.MType {
	case lorawan.JoinRequest:
		return join.Handle(ctx, rxPacket)
	case lorawan.RejoinRequest:
		return rejoin.Handle(ctx, rxPacket)
	case lorawan.UnconfirmedDataUp, lorawan.ConfirmedDataUp:
		return data.Handle(ctx, rxPacket)
	case lorawan.Proprietary:
		return proprietary.Handle(ctx, rxPacket)
	default:
		return nil
	}
}

// Vulnerability class: CWE-20
func (proj AppProject) IsLiveResourcePermitted(un *unstructured.Unstructured, server string, name string) bool {
	if !proj.IsGroupKindPermitted(un.GroupVersionKind().GroupKind(), un.GetNamespace() != "") {
		return false
	}
	if un.GetNamespace() != "" {
		return proj.IsDestinationPermitted(ApplicationDestination{Server: server, Namespace: un.GetNamespace(), Name: name})
	}
	return true
}

// Vulnerability class: CWE-269
func (b *Builder) buildMetricsHTTPConnectionManagerFilter() (*envoy_config_listener_v3.Filter, error) {
	rc, err := b.buildRouteConfiguration("metrics", []*envoy_config_route_v3.VirtualHost{{
		Name:    "metrics",
		Domains: []string{"*"},
		Routes: []*envoy_config_route_v3.Route{{
			Name: "metrics",
			Match: &envoy_config_route_v3.RouteMatch{
				PathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{Prefix: "/"},
			},
			Action: &envoy_config_route_v3.Route_Route{
				Route: &envoy_config_route_v3.RouteAction{
					ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
						Cluster: "pomerium-control-plane-http",
					},
				},
			},
		}},
	}})
	if err != nil {
		return nil, err
	}

	tc := marshalAny(&envoy_http_connection_manager.HttpConnectionManager{
		CodecType:  envoy_http_connection_manager.HttpConnectionManager_AUTO,
		StatPrefix: "metrics",
		RouteSpecifier: &envoy_http_connection_manager.HttpConnectionManager_RouteConfig{
			RouteConfig: rc,
		},
		HttpFilters: []*envoy_http_connection_manager.HttpFilter{{
			Name: "envoy.filters.http.router",
		}},
	})

	return &envoy_config_listener_v3.Filter{
		Name: "envoy.filters.network.http_connection_manager",
		ConfigType: &envoy_config_listener_v3.Filter_TypedConfig{
			TypedConfig: tc,
		},
	}, nil
}

// Vulnerability class: CWE-200
func (svc *Service) MacadminsData(ctx context.Context, id uint) (*fleet.MacadminsData, error) {
	if !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) {
		if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {
			return nil, err
		}

		host, err := svc.ds.HostLite(ctx, id)
		if err != nil {
			return nil, ctxerr.Wrap(ctx, err, "find host for macadmins")
		}

		if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {
			return nil, err
		}
	}

	var munkiInfo *fleet.HostMunkiInfo
	switch version, err := svc.ds.GetMunkiVersion(ctx, id); {
	case err != nil && !fleet.IsNotFound(err):
		return nil, err
	case err == nil:
		munkiInfo = &fleet.HostMunkiInfo{Version: version}
	}

	var mdm *fleet.HostMDM
	switch enrolled, serverURL, installedFromDep, err := svc.ds.GetMDM(ctx, id); {
	case err != nil && !fleet.IsNotFound(err):
		return nil, err
	case err == nil:
		enrollmentStatus := "Unenrolled"
		if enrolled && !installedFromDep {
			enrollmentStatus = "Enrolled (manual)"
		} else if enrolled && installedFromDep {
			enrollmentStatus = "Enrolled (automated)"
		}
		mdm = &fleet.HostMDM{
			EnrollmentStatus: enrollmentStatus,
			ServerURL:        serverURL,
		}
	}

	if munkiInfo == nil && mdm == nil {
		return nil, nil
	}

	data := &fleet.MacadminsData{
		Munki: munkiInfo,
		MDM:   mdm,
	}

	return data, nil
}

// Vulnerability class: CWE-863
func mountNewCgroup(m *configs.Mount) error {
	var (
		data   = m.Data
		source = m.Source
	)
	if data == "systemd" {
		data = cgroups.CgroupNamePrefix + data
		source = "systemd"
	}
	if err := unix.Mount(source, m.Destination, m.Device, uintptr(m.Flags), data); err != nil {
		return err
	}
	return nil
}

// Vulnerability class: CWE-362
func (b *Backend) rxPacketHandler(c paho.Client, msg paho.Message) {
	b.wg.Add(1)
	defer b.wg.Done()

	var uplinkFrame gw.UplinkFrame
	t, err := marshaler.UnmarshalUplinkFrame(msg.Payload(), &uplinkFrame)
	if err != nil {
		log.WithFields(log.Fields{
			"data_base64": base64.StdEncoding.EncodeToString(msg.Payload()),
		}).WithError(err).Error("gateway/mqtt: unmarshal uplink frame error")
		return
	}

	if uplinkFrame.TxInfo == nil {
		log.WithFields(log.Fields{
			"data_base64": base64.StdEncoding.EncodeToString(msg.Payload()),
		}).Error("gateway/mqtt: tx_info must not be nil")
		return
	}

	if uplinkFrame.RxInfo == nil {
		log.WithFields(log.Fields{
			"data_base64": base64.StdEncoding.EncodeToString(msg.Payload()),
		}).Error("gateway/mqtt: rx_info must not be nil")
		return
	}

	gatewayID := helpers.GetGatewayID(uplinkFrame.RxInfo)
	b.setGatewayMarshaler(gatewayID, t)
	uplinkID := helpers.GetUplinkID(uplinkFrame.RxInfo)

	log.WithFields(log.Fields{
		"uplink_id":  uplinkID,
		"gateway_id": gatewayID,
	}).Info("gateway/mqtt: uplink frame received")

	// Since with MQTT all subscribers will receive the uplink messages sent
	// by all the gateways, the first instance receiving the message must lock it,
	// so that other instances can ignore the same message (from the same gw).
	key := fmt.Sprintf("lora:ns:uplink:lock:%s:%d:%d:%d:%s", gatewayID, uplinkFrame.TxInfo.Frequency, uplinkFrame.RxInfo.Board, uplinkFrame.RxInfo.Antenna, hex.EncodeToString(uplinkFrame.PhyPayload))
	if locked, err := b.isLocked(key); err != nil || locked {
		if err != nil {
			log.WithError(err).WithFields(log.Fields{
				"uplink_id": uplinkID,
				"key":       key,
			}).Error("gateway/mqtt: acquire lock error")
		}
		return
	}

	b.rxPacketChan <- uplinkFrame
}

// Vulnerability class: CWE-20
func (p *GitLabProvider) PrefixAllowedGroups() (groups []string) {

	for _, val := range p.Groups {
		groups = append(groups, fmt.Sprintf("group:%s", val))
	}

	for _, val := range p.Projects {
		groups = append(groups, fmt.Sprintf("project:%s", val.Name))
	}

	return groups
}

// Vulnerability class: CWE-863
func TestBuilder_BuildBootstrapAdmin(t *testing.T) {
	b := New("local-grpc", "local-http", filemgr.NewManager(), nil)
	t.Run("valid", func(t *testing.T) {
		adminCfg, err := b.BuildBootstrapAdmin(&config.Config{
			Options: &config.Options{
				EnvoyAdminAddress: "localhost:9901",
			},
		})
		assert.NoError(t, err)
		testutil.AssertProtoJSONEqual(t, `
			{
				"address": {
					"socketAddress": {
						"address": "127.0.0.1",
						"portValue": 9901
					}
				}
			}
		`, adminCfg)
	})
	t.Run("bad address", func(t *testing.T) {
		_, err := b.BuildBootstrapAdmin(&config.Config{
			Options: &config.Options{
				EnvoyAdminAddress: "xyz1234:zyx4321",
			},
		})
		assert.Error(t, err)
	})
}

// Vulnerability class: CWE-200
func TestDoesPolicySignatureMatch(t *testing.T) {
	credentialTemplate := "%s/%s/%s/s3/aws4_request"
	now := UTCNow()
	accessKey := globalActiveCred.AccessKey

	testCases := []struct {
		form     http.Header
		expected APIErrorCode
	}{
		// (0) It should fail if 'X-Amz-Credential' is missing.
		{
			form:     http.Header{},
			expected: ErrCredMalformed,
		},
		// (1) It should fail if the access key is incorrect.
		{
			form: http.Header{
				"X-Amz-Credential": []string{fmt.Sprintf(credentialTemplate, "EXAMPLEINVALIDEXAMPL", now.Format(yyyymmdd), globalMinioDefaultRegion)},
			},
			expected: ErrInvalidAccessKeyID,
		},
		// (2) It should fail with a bad signature.
		{
			form: http.Header{
				"X-Amz-Credential": []string{fmt.Sprintf(credentialTemplate, accessKey, now.Format(yyyymmdd), globalMinioDefaultRegion)},
				"X-Amz-Date":       []string{now.Format(iso8601Format)},
				"X-Amz-Signature":  []string{"invalidsignature"},
				"Policy":           []string{"policy"},
			},
			expected: ErrSignatureDoesNotMatch,
		},
		// (3) It should succeed if everything is correct.
		{
			form: http.Header{
				"X-Amz-Credential": []string{
					fmt.Sprintf(credentialTemplate, accessKey, now.Format(yyyymmdd), globalMinioDefaultRegion),
				},
				"X-Amz-Date": []string{now.Format(iso8601Format)},
				"X-Amz-Signature": []string{
					getSignature(getSigningKey(globalActiveCred.SecretKey, now,
						globalMinioDefaultRegion, serviceS3), "policy"),
				},
				"Policy": []string{"policy"},
			},
			expected: ErrNone,
		},
	}

	// Run each test case individually.
	for i, testCase := range testCases {
		code := doesPolicySignatureMatch(testCase.form)
		if code != testCase.expected {
			t.Errorf("(%d) expected to get %s, instead got %s", i, niceError(testCase.expected), niceError(code))
		}
	}
}

// Vulnerability class: CWE-285
func (svc *Service) RefetchHost(ctx context.Context, id uint) error {
	if !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) {
		if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {
			return err
		}

		host, err := svc.ds.HostLite(ctx, id)
		if err != nil {
			return ctxerr.Wrap(ctx, err, "find host for refetch")
		}

		// We verify fleet.ActionRead instead of fleet.ActionWrite because we want to allow
		// observers to be able to refetch hosts.
		if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {
			return err
		}
	}

	if err := svc.ds.UpdateHostRefetchRequested(ctx, id, true); err != nil {
		return ctxerr.Wrap(ctx, err, "save host")
	}

	return nil
}

// Vulnerability class: CWE-863
func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) {
	params := k.GetParams(ctx)
	expEpochID := k.GetEpochIdentifier(ctx)
	if epochIdentifier != expEpochID {
		return
	}

	// mint coins, update supply
	epochMintProvision, found := k.GetEpochMintProvision(ctx)
	if !found {
		panic("the epochMintProvision was not found")
	}

	mintedCoin := sdk.NewCoin(params.MintDenom, epochMintProvision.TruncateInt())
	if err := k.MintAndAllocateInflation(ctx, mintedCoin); err != nil {
		panic(err)
	}

	// check if a period is over. If it's completed, update period, and epochMintProvision
	period := k.GetPeriod(ctx)
	epochsPerPeriod := k.GetEpochsPerPeriod(ctx)

	newProvision := epochMintProvision

	// current epoch number needs to be within range for the period
	// Given, epochNumber = 1, period = 0, epochPerPeriod = 365
	// 1 - 365 * 0 < 365 --- nothing to do here
	// Given, epochNumber = 731, period = 1, epochPerPeriod = 365
	// 731 - 1 * 365 > 365 --- a period has passed! we change the epochMintProvision and set a new period
	if epochNumber-epochsPerPeriod*int64(period) > epochsPerPeriod {
		period++
		k.SetPeriod(ctx, period)
		period = k.GetPeriod(ctx)
		bondedRatio := k.stakingKeeper.BondedRatio(ctx)
		newProvision = types.CalculateEpochMintProvision(
			params,
			period,
			epochsPerPeriod,
			bondedRatio,
		)
		k.SetEpochMintProvision(ctx, newProvision)
	}

	ctx.EventManager().EmitEvent(
		sdk.NewEvent(
			types.EventTypeMint,
			sdk.NewAttribute(types.AttributeEpochNumber, fmt.Sprintf("%d", epochNumber)),
			sdk.NewAttribute(types.AttributeKeyEpochProvisions, newProvision.String()),
			sdk.NewAttribute(sdk.AttributeKeyAmount, mintedCoin.Amount.String()),
		),
	)
}

// Vulnerability class: CWE-287
func bindMountDeviceNode(dest string, node *devices.Device) error {
	f, err := os.Create(dest)
	if err != nil && !os.IsExist(err) {
		return err
	}
	if f != nil {
		f.Close()
	}
	return unix.Mount(node.Path, dest, "bind", unix.MS_BIND, "")
}

// Vulnerability class: CWE-362
func (svc *Service) GetGlobalScheduledQueries(ctx context.Context, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionRead); err != nil {
		return nil, err
	}

	gp, err := svc.ds.EnsureGlobalPack(ctx)
	if err != nil {
		return nil, err
	}

	return svc.ds.ListScheduledQueriesInPackWithStats(ctx, gp.ID, opts)
}

// Vulnerability class: CWE-863
func testExternalNameServiceInsecure(namespace string) {
	Specify("external name services work over http", func() {
		t := f.T()

		f.Fixtures.Echo.Deploy(namespace, "ingress-conformance-echo")

		externalNameService := &corev1.Service{
			ObjectMeta: metav1.ObjectMeta{
				Namespace: namespace,
				Name:      "external-name-service",
			},
			Spec: corev1.ServiceSpec{
				Type:         corev1.ServiceTypeExternalName,
				ExternalName: "ingress-conformance-echo." + namespace,
				Ports: []corev1.ServicePort{
					{
						Name: "http",
						Port: 80,
					},
				},
			},
		}
		require.NoError(t, f.Client.Create(context.TODO(), externalNameService))

		p := &contourv1.HTTPProxy{
			ObjectMeta: metav1.ObjectMeta{
				Namespace: namespace,
				Name:      "external-name-proxy",
			},
			Spec: contourv1.HTTPProxySpec{
				VirtualHost: &contourv1.VirtualHost{
					Fqdn: "externalnameservice.projectcontour.io",
				},
				Routes: []contourv1.Route{
					{
						Services: []contourv1.Service{
							{
								Name: externalNameService.Name,
								Port: 80,
							},
						},
						RequestHeadersPolicy: &contourv1.HeadersPolicy{
							Set: []contourv1.HeaderValue{
								{
									Name:  "Host",
									Value: externalNameService.Spec.ExternalName,
								},
							},
						},
					},
				},
			},
		}
		f.CreateHTTPProxyAndWaitFor(p, httpProxyValid)

		res, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{
			Host:      p.Spec.VirtualHost.Fqdn,
			Condition: e2e.HasStatusCode(200),
		})
		require.Truef(t, ok, "expected 200 response code, got %d", res.StatusCode)
	})
}

// Vulnerability class: CWE-610
func (b *Builder) buildControlPlanePathRoute(path string, protected bool) (*envoy_config_route_v3.Route, error) {
	r := &envoy_config_route_v3.Route{
		Name: "pomerium-path-" + path,
		Match: &envoy_config_route_v3.RouteMatch{
			PathSpecifier: &envoy_config_route_v3.RouteMatch_Path{Path: path},
		},
		Action: &envoy_config_route_v3.Route_Route{
			Route: &envoy_config_route_v3.RouteAction{
				ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
					Cluster: httpCluster,
				},
			},
		},
	}
	if !protected {
		r.TypedPerFilterConfig = map[string]*any.Any{
			"envoy.filters.http.ext_authz": disableExtAuthz,
		}
	}
	return r, nil
}

// Vulnerability class: CWE-200
func TestDoesPolicySignatureV2Match(t *testing.T) {
	obj, fsDir, err := prepareFS()
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(fsDir)
	if err = newTestConfig(globalMinioDefaultRegion, obj); err != nil {
		t.Fatal(err)
	}

	creds := globalActiveCred
	policy := "policy"
	testCases := []struct {
		accessKey string
		policy    string
		signature string
		errCode   APIErrorCode
	}{
		{"invalidAccessKey", policy, calculateSignatureV2(policy, creds.SecretKey), ErrInvalidAccessKeyID},
		{creds.AccessKey, policy, calculateSignatureV2("random", creds.SecretKey), ErrSignatureDoesNotMatch},
		{creds.AccessKey, policy, calculateSignatureV2(policy, creds.SecretKey), ErrNone},
	}
	for i, test := range testCases {
		formValues := make(http.Header)
		formValues.Set("Awsaccesskeyid", test.accessKey)
		formValues.Set("Signature", test.signature)
		formValues.Set("Policy", test.policy)
		errCode := doesPolicySignatureV2Match(formValues)
		if errCode != test.errCode {
			t.Fatalf("(%d) expected to get %s, instead got %s", i+1, niceError(test.errCode), niceError(errCode))
		}
	}
}

// Vulnerability class: CWE-285
func queryMatches(rp *arrayPathResult, value Result) bool {
	rpv := rp.query.value
	if len(rpv) > 0 && rpv[0] == '~' {
		// convert to bool
		rpv = rpv[1:]
		if value.Bool() {
			value = Result{Type: True}
		} else {
			value = Result{Type: False}
		}
	}
	if !value.Exists() {
		return false
	}
	if rp.query.op == "" {
		// the query is only looking for existence, such as:
		//   friends.#(name)
		// which makes sure that the array "friends" has an element of
		// "name" that exists
		return true
	}
	switch value.Type {
	case String:
		switch rp.query.op {
		case "=":
			return value.Str == rpv
		case "!=":
			return value.Str != rpv
		case "<":
			return value.Str < rpv
		case "<=":
			return value.Str <= rpv
		case ">":
			return value.Str > rpv
		case ">=":
			return value.Str >= rpv
		case "%":
			return match.Match(value.Str, rpv)
		case "!%":
			return !match.Match(value.Str, rpv)
		}
	case Number:
		rpvn, _ := strconv.ParseFloat(rpv, 64)
		switch rp.query.op {
		case "=":
			return value.Num == rpvn
		case "!=":
			return value.Num != rpvn
		case "<":
			return value.Num < rpvn
		case "<=":
			return value.Num <= rpvn
		case ">":
			return value.Num > rpvn
		case ">=":
			return value.Num >= rpvn
		}
	case True:
		switch rp.query.op {
		case "=":
			return rpv == "true"
		case "!=":
			return rpv != "true"
		case ">":
			return rpv == "false"
		case ">=":
			return true
		}
	case False:
		switch rp.query.op {
		case "=":
			return rpv == "false"
		case "!=":
			return rpv != "false"
		case "<":
			return rpv == "true"
		case "<=":
			return true
		}
	}
	return false
}

// Vulnerability class: CWE-400
func (c *liveStateCache) IterateHierarchy(server string, key kube.ResourceKey, action func(child appv1.ResourceNode, appName string)) error {
	clusterInfo, err := c.getSyncedCluster(server)
	if err != nil {
		return err
	}
	clusterInfo.IterateHierarchy(key, func(resource *clustercache.Resource, namespaceResources map[kube.ResourceKey]*clustercache.Resource) {
		action(asResourceNode(resource), getApp(resource, namespaceResources))
	})
	return nil
}

// Vulnerability class: CWE-269
func TestAuthorizeTeamPacks(t *testing.T) {
	t.Parallel()

	runTestCases(t, []authTestCase{
		// Team maintainer can read packs of the team.
		{
			user: test.UserTeamMaintainerTeam1,
			object: &fleet.Pack{
				TeamIDs: []uint{1},
			},
			action: read,
			allow:  true,
		},
		// Team observer cannot read packs of the team.
		{
			user: test.UserTeamObserverTeam1TeamAdminTeam2,
			object: &fleet.Pack{
				TeamIDs: []uint{1},
			},
			action: read,
			allow:  false,
		},
		// Team observer cannot write packs of the team.
		{
			user: test.UserTeamObserverTeam1TeamAdminTeam2,
			object: &fleet.Pack{
				TeamIDs: []uint{1},
			},
			action: write,
			allow:  false,
		},
		// Members of a team cannot read packs of another team.
		{
			user: test.UserTeamAdminTeam1,
			object: &fleet.Pack{
				TeamIDs: []uint{2},
			},
			action: read,
			allow:  false,
		},
		// Members of a team cannot read packs of another team.
		{
			user: test.UserTeamAdminTeam1,
			object: &fleet.Pack{
				TeamIDs: []uint{2},
			},
			action: read,
			allow:  false,
		},
		// Team maintainers can read global packs.
		{
			user:   test.UserTeamMaintainerTeam1,
			object: &fleet.Pack{},
			action: read,
			allow:  true,
		},
		// Team admins can read global packs.
		{
			user:   test.UserTeamAdminTeam1,
			object: &fleet.Pack{},
			action: read,
			allow:  true,
		},
		// Team admins cannot write global packs.
		{
			user:   test.UserTeamAdminTeam1,
			object: &fleet.Pack{},
			action: write,
			allow:  false,
		},
	})
}

// Vulnerability class: CWE-863
func (evpool *Pool) flushConsensusBuffer() {
	for _, ev := range evpool.consensusBuffer {
		if err := evpool.addPendingEvidence(ev); err != nil {
			evpool.logger.Error("failed to flush evidence from consensus buffer to pending list: %w", err)
			continue
		}

		evpool.evidenceList.PushBack(ev)
	}
	// reset consensus buffer
	evpool.consensusBuffer = make([]types.Evidence, 0)
}

// Vulnerability class: CWE-400
func (b *Builder) buildControlPlanePrefixRoute(prefix string, protected bool) (*envoy_config_route_v3.Route, error) {
	r := &envoy_config_route_v3.Route{
		Name: "pomerium-prefix-" + prefix,
		Match: &envoy_config_route_v3.RouteMatch{
			PathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{Prefix: prefix},
		},
		Action: &envoy_config_route_v3.Route_Route{
			Route: &envoy_config_route_v3.RouteAction{
				ClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{
					Cluster: httpCluster,
				},
			},
		},
	}
	if !protected {
		r.TypedPerFilterConfig = map[string]*any.Any{
			"envoy.filters.http.ext_authz": disableExtAuthz,
		}
	}
	return r, nil
}

// Vulnerability class: CWE-200
getReturnAddressWithDisplayName(identityId) {
    check(identityId, String);
    const identity = this.getIdentity(identityId);
    const displayName = identity.profile.name + " (via " + this.getServerTitle() + ")";

    // First remove any instances of characters that cause trouble for SimpleSmtp. Ideally,
    // we could escape such characters with a backslash, but that does not seem to help here.
    const sanitized = displayName.replace(/"|<|>|\\|\r/g, "");

    return "\"" + sanitized + "\" <" + this.getReturnAddress() + ">";
  },

// Vulnerability class: CWE-287
func TestWrapHandler(t *testing.T) {
	router := http.NewServeMux()

	router.Handle("/", Handler(DocExpansion("none"), DomID("#swagger-ui")))

	w1 := performRequest("GET", "/index.html", router)
	assert.Equal(t, 200, w1.Code)
	assert.Equal(t, w1.Header()["Content-Type"][0], "text/html; charset=utf-8")

	w2 := performRequest("GET", "/doc.json", router)
	assert.Equal(t, 500, w2.Code)

	swag.Register(swag.Name, &mockedSwag{})
	w2 = performRequest("GET", "/doc.json", router)
	assert.Equal(t, 200, w2.Code)
	assert.Equal(t, "application/json; charset=utf-8", w2.Header().Get("content-type"))

	w3 := performRequest("GET", "/favicon-16x16.png", router)
	assert.Equal(t, 200, w3.Code)
	assert.Equal(t, w3.Header()["Content-Type"][0], "image/png")

	w4 := performRequest("GET", "/swagger-ui.css", router)
	assert.Equal(t, 200, w4.Code)
	assert.Equal(t, w4.Header()["Content-Type"][0], "text/css; charset=utf-8")

	w5 := performRequest("GET", "/swagger-ui-bundle.js", router)
	assert.Equal(t, 200, w5.Code)
	assert.Equal(t, w5.Header()["Content-Type"][0], "application/javascript")

	w6 := performRequest("GET", "/notfound", router)
	assert.Equal(t, 404, w6.Code)

	w7 := performRequest("GET", "/", router)
	assert.Equal(t, 301, w7.Code)
}

// Vulnerability class: CWE-755
func (svc Service) ModifyTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint, query fleet.ScheduledQueryPayload) (*fleet.ScheduledQuery, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {
		return nil, err
	}

	gp, err := svc.ds.EnsureTeamPack(ctx, teamID)
	if err != nil {
		return nil, err
	}

	query.PackID = ptr.Uint(gp.ID)

	return svc.unauthorizedModifyScheduledQuery(ctx, scheduledQueryID, query)
}

// Vulnerability class: CWE-863
func (evpool *Pool) CheckEvidence(evList types.EvidenceList) error {
	hashes := make([][]byte, len(evList))
	for idx, ev := range evList {

		ok := evpool.fastCheck(ev)

		if !ok {
			// check that the evidence isn't already committed
			if evpool.isCommitted(ev) {
				return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("evidence was already committed")}
			}

			err := evpool.verify(ev)
			if err != nil {
				return &types.ErrInvalidEvidence{Evidence: ev, Reason: err}
			}

			if err := evpool.addPendingEvidence(ev); err != nil {
				// Something went wrong with adding the evidence but we already know it is valid
				// hence we log an error and continue
				evpool.logger.Error("Can't add evidence to pending list", "err", err, "ev", ev)
			}

			evpool.logger.Info("Verified new evidence of byzantine behavior", "evidence", ev)
		}

		// check for duplicate evidence. We cache hashes so we don't have to work them out again.
		hashes[idx] = ev.Hash()
		for i := idx - 1; i >= 0; i-- {
			if bytes.Equal(hashes[i], hashes[idx]) {
				return &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New("duplicate evidence")}
			}
		}
	}

	return nil
}

// Vulnerability class: CWE-400
func (svc *Service) GlobalScheduleQuery(ctx context.Context, sq *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionRead); err != nil {
		return nil, err
	}

	gp, err := svc.ds.EnsureGlobalPack(ctx)
	if err != nil {
		return nil, err
	}
	sq.PackID = gp.ID

	return svc.ScheduleQuery(ctx, sq)
}

// Vulnerability class: CWE-863
func New(
	localGRPCAddress string,
	localHTTPAddress string,
	fileManager *filemgr.Manager,
	reproxyHandler *reproxy.Handler,
) *Builder {
	return &Builder{
		localGRPCAddress: localGRPCAddress,
		localHTTPAddress: localHTTPAddress,
		filemgr:          fileManager,
		reproxy:          reproxyHandler,
	}
}

// Vulnerability class: CWE-200
func (g Grant) ValidateBasic() error {
	if g.Expiration.Unix() < time.Now().Unix() {
		return sdkerrors.Wrap(ErrInvalidExpirationTime, "Time can't be in the past")
	}

	av := g.Authorization.GetCachedValue()
	a, ok := av.(Authorization)
	if !ok {
		return sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expected %T, got %T", (Authorization)(nil), av)
	}
	return a.ValidateBasic()
}

// Vulnerability class: CWE-754
func (svc Service) ListSoftware(ctx context.Context, opt fleet.SoftwareListOptions) ([]fleet.Software, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Software{}, fleet.ActionRead); err != nil {
		return nil, err
	}

	// default sort order to hosts_count descending
	if opt.OrderKey == "" {
		opt.OrderKey = "hosts_count"
		opt.OrderDirection = fleet.OrderDescending
	}
	opt.WithHostCounts = true
	return svc.ds.ListSoftware(ctx, opt)
}

// Vulnerability class: CWE-863
func (svc *Service) GetHost(ctx context.Context, id uint) (*fleet.HostDetail, error) {
	alreadyAuthd := svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken)
	if !alreadyAuthd {
		// First ensure the user has access to list hosts, then check the specific
		// host once team_id is loaded.
		if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {
			return nil, err
		}
	}

	host, err := svc.ds.Host(ctx, id, false)
	if err != nil {
		return nil, ctxerr.Wrap(ctx, err, "get host")
	}

	if !alreadyAuthd {
		// Authorize again with team loaded now that we have team_id
		if err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {
			return nil, err
		}
	}

	return svc.getHostDetails(ctx, host)
}

// Vulnerability class: CWE-863
func (app *Configurable) Encrypt(parameters map[string]string) interfaces.AppFunction {
	algorithm, ok := parameters[Algorithm]
	if !ok {
		app.lc.Errorf("Could not find '%s' parameter for Encrypt", Algorithm)
		return nil
	}

	secretPath := parameters[SecretPath]
	secretName := parameters[SecretName]
	encryptionKey := parameters[EncryptionKey]

	// SecretPath & SecretName are optional if EncryptionKey specified
	// EncryptionKey is optional if SecretPath & SecretName are specified

	// If EncryptionKey not specified, then SecretPath & SecretName must be specified
	if len(encryptionKey) == 0 && (len(secretPath) == 0 || len(secretName) == 0) {
		app.lc.Errorf("Could not find '%s' or '%s' and '%s' in configuration", EncryptionKey, SecretPath, SecretName)
		return nil
	}

	// SecretPath & SecretName both must be specified it one of them is.
	if (len(secretPath) != 0 && len(secretName) == 0) || (len(secretPath) == 0 && len(secretName) != 0) {
		app.lc.Errorf("'%s' and '%s' both must be set in configuration", SecretPath, SecretName)
		return nil
	}

	initVector, ok := parameters[InitVector]
	if !ok {
		app.lc.Error("Could not find " + InitVector)
		return nil
	}

	transform := transforms.Encryption{
		EncryptionKey:        encryptionKey,
		InitializationVector: initVector,
		SecretPath:           secretPath,
		SecretName:           secretName,
	}

	switch strings.ToLower(algorithm) {
	case EncryptAES:
		return transform.EncryptWithAES
	default:
		app.lc.Errorf(
			"Invalid encryption algorithm '%s'. Must be '%s'",
			algorithm,
			EncryptAES)
		return nil
	}
}

// Vulnerability class: CWE-327
func getGateway(ctx *statsContext) error {
	gatewayID := helpers.GetGatewayID(&ctx.gatewayStats)
	gw, err := storage.GetAndCacheGateway(ctx.ctx, storage.DB(), gatewayID)
	if err != nil {
		return errors.Wrap(err, "get gateway error")
	}

	ctx.gateway = gw
	return nil
}

// Vulnerability class: CWE-20
func Handler(configFns ...func(*Config)) http.HandlerFunc {
	var once sync.Once

	config := &Config{
		URL:          "doc.json",
		DeepLinking:  true,
		DocExpansion: "list",
		DomID:        "#swagger-ui",
	}
	for _, configFn := range configFns {
		configFn(config)
	}

	// create a template with name
	t := template.New("swagger_index.html")
	index, _ := t.Parse(indexTempl)

	var re = regexp.MustCompile(`^(.*/)([^?].*)?[?|.]*$`)

	return func(w http.ResponseWriter, r *http.Request) {
		matches := re.FindStringSubmatch(r.RequestURI)
		path := matches[2]

		h := swaggerFiles.Handler
		once.Do(func() {
			h.Prefix = matches[1]
		})

		switch filepath.Ext(path) {
		case ".html":
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
		case ".css":
			w.Header().Set("Content-Type", "text/css; charset=utf-8")
		case ".js":
			w.Header().Set("Content-Type", "application/javascript")
		case ".png":
			w.Header().Set("Content-Type", "image/png")
		case ".json":
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
		}

		switch path {
		case "index.html":
			_ = index.Execute(w, config)
		case "doc.json":
			doc, err := swag.ReadDoc()
			if err != nil {
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)

				return
			}
			_, _ = w.Write([]byte(doc))
		case "":
			http.Redirect(w, r, h.Prefix+"index.html", 301)
		default:
			h.ServeHTTP(w, r)
		}
	}
}

// Vulnerability class: CWE-755
func TestMaxDepthValidation(t *testing.T) {
	s, err := schema.ParseSchema(interfaceSimple, false)
	if err != nil {
		t.Fatal(err)
	}

	for _, tc := range []struct {
		name     string
		query    string
		maxDepth int
		expected bool
	}{
		{
			name: "off",
			query: `query Fine {        # depth 0
				characters {         # depth 1
				  id                 # depth 2
				  name               # depth 2
				  friends {          # depth 2
					  id               # depth 3
					  name             # depth 3
				  }
				}
			}`,
			maxDepth: 0,
		}, {
			name: "fields",
			query: `query Fine {        # depth 0
				characters {         # depth 1
				  id                 # depth 2
				  name               # depth 2
				  friends {          # depth 2
					  id               # depth 3
					  name             # depth 3
				  }
				}
			}`,
			maxDepth: 2,
			expected: true,
		}, {
			name: "fragment",
			query: `fragment friend on Character {
				id # depth 6
				name
				friends {
					name # depth 7
				}
			}
			query {        # depth 0
				characters {         # depth 1
				  id                 # depth 2
				  name               # depth 2
				  friends {          # depth 2
					friends {        # depth 3
						friends {    # depth 4
						  friends {  # depth 5
							...friend # depth 6
						  }
						}
					}
				  }
				}
			}`,
			maxDepth: 5,
			expected: true,
		}, {
			name: "inlinefragment",
			query: `query { # depth 0
				characters { # depth 1
				  ... on Droid { # depth 2
					primaryFunction # depth 2
				  }
				}
			  }`,
			maxDepth: 1,
			expected: true,
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			doc, err := query.Parse(tc.query)
			if err != nil {
				t.Fatal(err)
			}

			context := newContext(s, doc, tc.maxDepth)
			op := doc.Operations[0]

			opc := &opContext{context: context, ops: doc.Operations}

			actual := validateMaxDepth(opc, op.Selections, 1)
			if actual != tc.expected {
				t.Errorf("expected %t, actual %t", tc.expected, actual)
			}
		})
	}
}

// Vulnerability class: CWE-400
func (p *GitLabProvider) addProjectsToSession(ctx context.Context, s *sessions.SessionState) {
	// Iterate over projects, check if oauth2-proxy can get project information on behalf of the user
	for _, project := range p.Projects {
		projectInfo, err := p.getProjectInfo(ctx, s, project.Name)

		if err != nil {
			logger.Errorf("Warning: project info request failed: %v", err)
			continue
		}

		if !projectInfo.Archived {
			perms := projectInfo.Permissions.ProjectAccess
			if perms == nil {
				// use group project access as fallback
				perms = projectInfo.Permissions.GroupAccess
				// group project access is not set for this user then we give up
				if perms == nil {
					logger.Errorf("Warning: user %q has no project level access to %s", s.Email, project.Name)
					continue
				}
			}

			if perms != nil && perms.AccessLevel >= project.AccessLevel {
				s.Groups = append(s.Groups, fmt.Sprintf("project:%s", project.Name))
			} else {
				logger.Errorf("Warning: user %q does not have the minimum required access level for project %q", s.Email, project.Name)
			}
		} else {
			logger.Errorf("Warning: project %s is archived", project.Name)
		}

	}

}

// Vulnerability class: CWE-863
func Test_buildControlPlanePathRoute(t *testing.T) {
	b := &Builder{filemgr: filemgr.NewManager()}
	route, err := b.buildControlPlanePathRoute("/hello/world", false)
	require.NoError(t, err)
	testutil.AssertProtoJSONEqual(t, `
		{
			"name": "pomerium-path-/hello/world",
			"match": {
				"path": "/hello/world"
			},
			"route": {
				"cluster": "pomerium-control-plane-http"
			},
			"typedPerFilterConfig": {
				"envoy.filters.http.ext_authz": {
					"@type": "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute",
					"disabled": true
				}
			}
		}
	`, route)
}

// Vulnerability class: CWE-200
func (svc Service) DeleteTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint) error {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {
		return err
	}
	return svc.ds.DeleteScheduledQuery(ctx, scheduledQueryID)
}

// Vulnerability class: CWE-863
func (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string) (*AuthenticatorOAuth2IntrospectionResult, bool) {
	if !config.Cache.Enabled {
		return nil, false
	}

	item, found := a.tokenCache.Get(token)
	if !found {
		return nil, false
	}

	i := item.(*AuthenticatorOAuth2IntrospectionResult)
	expires := time.Unix(i.Expires, 0)
	if expires.Before(time.Now()) {
		a.tokenCache.Del(token)
		return nil, false
	}

	return i, true
}

// Vulnerability class: CWE-863
func Test_bindConfig(t *testing.T) {
	ctx, clearTimeout := context.WithTimeout(context.Background(), time.Second*10)
	defer clearTimeout()

	b := New("local-grpc", "local-http", filemgr.NewManager(), nil)
	t.Run("no bind config", func(t *testing.T) {
		cluster, err := b.buildPolicyCluster(ctx, &config.Options{}, &config.Policy{
			From: "https://from.example.com",
			To:   mustParseWeightedURLs(t, "https://to.example.com"),
		})
		assert.NoError(t, err)
		assert.Nil(t, cluster.UpstreamBindConfig)
	})
	t.Run("freebind", func(t *testing.T) {
		cluster, err := b.buildPolicyCluster(ctx, &config.Options{
			EnvoyBindConfigFreebind: null.BoolFrom(true),
		}, &config.Policy{
			From: "https://from.example.com",
			To:   mustParseWeightedURLs(t, "https://to.example.com"),
		})
		assert.NoError(t, err)
		testutil.AssertProtoJSONEqual(t, `
			{
				"freebind": true,
				"sourceAddress": {
					"address": "0.0.0.0",
					"portValue": 0
				}
			}
		`, cluster.UpstreamBindConfig)
	})
	t.Run("source address", func(t *testing.T) {
		cluster, err := b.buildPolicyCluster(ctx, &config.Options{
			EnvoyBindConfigSourceAddress: "192.168.0.1",
		}, &config.Policy{
			From: "https://from.example.com",
			To:   mustParseWeightedURLs(t, "https://to.example.com"),
		})
		assert.NoError(t, err)
		testutil.AssertProtoJSONEqual(t, `
			{
				"sourceAddress": {
					"address": "192.168.0.1",
					"portValue": 0
				}
			}
		`, cluster.UpstreamBindConfig)
	})
}

// Vulnerability class: CWE-200
func (evpool *Pool) removePendingEvidence(evidence types.Evidence) {
	key := keyPending(evidence)
	if err := evpool.evidenceStore.Delete(key); err != nil {
		evpool.logger.Error("Unable to delete pending evidence", "err", err)
	} else {
		atomic.AddUint32(&evpool.evidenceSize, ^uint32(0))
		evpool.logger.Info("Deleted pending evidence", "evidence", evidence)
	}
}

// Vulnerability class: CWE-400
func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) {
	added, err := cs.addVote(vote, peerID)
	if err != nil {
		// If the vote height is off, we'll just ignore it,
		// But if it's a conflicting sig, add it to the cs.evpool.
		// If it's otherwise invalid, punish peer.
		// nolint: gocritic
		if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
			if cs.privValidatorPubKey == nil {
				return false, errPubKeyIsNotSet
			}

			if bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) {
				cs.Logger.Error(
					"Found conflicting vote from ourselves. Did you unsafe_reset a validator?",
					"height",
					vote.Height,
					"round",
					vote.Round,
					"type",
					vote.Type)
				return added, err
			}
			var timestamp time.Time
			if voteErr.VoteA.Height == cs.state.InitialHeight {
				timestamp = cs.state.LastBlockTime // genesis time
			} else {
				timestamp = sm.MedianTime(cs.LastCommit.MakeCommit(), cs.LastValidators)
			}
			// form duplicate vote evidence from the conflicting votes and send it across to the
			// evidence pool
			ev := types.NewDuplicateVoteEvidence(voteErr.VoteA, voteErr.VoteB, timestamp, cs.Validators)
			evidenceErr := cs.evpool.AddEvidenceFromConsensus(ev)
			if evidenceErr != nil {
				cs.Logger.Error("Failed to add evidence to the evidence pool", "err", evidenceErr)
			} else {
				cs.Logger.Debug("Added evidence to the evidence pool", "ev", ev)
			}
			return added, err
		} else if err == types.ErrVoteNonDeterministicSignature {
			cs.Logger.Debug("Vote has non-deterministic signature", "err", err)
		} else {
			// Either
			// 1) bad peer OR
			// 2) not a bad peer? this can also err sometimes with "Unexpected step" OR
			// 3) tmkms use with multiple validators connecting to a single tmkms instance
			// 		(https://github.com/tendermint/tendermint/issues/3839).
			cs.Logger.Info("Error attempting to add vote", "err", err)
			return added, ErrAddingVote
		}
	}
	return added, nil
}

// Vulnerability class: CWE-400
func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error {
	var (
		dest  = m.Destination
		data  = label.FormatMountLabel(m.Data, mountLabel)
		flags = m.Flags
	)
	if libcontainerUtils.CleanPath(dest) == "/dev" {
		flags &= ^unix.MS_RDONLY
	}

	// Mount it rw to allow chmod operation. A remount will be performed
	// later to make it ro if set.
	if m.Device == "tmpfs" {
		flags &= ^unix.MS_RDONLY
	}

	copyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP
	if !(copyUp || strings.HasPrefix(dest, rootfs)) {
		dest = filepath.Join(rootfs, dest)
	}

	if err := unix.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil {
		return err
	}

	for _, pflag := range m.PropagationFlags {
		if err := unix.Mount("", dest, "", uintptr(pflag), ""); err != nil {
			return err
		}
	}
	return nil
}

// Vulnerability class: CWE-362
func (cn *clusterNode) resurrect() {
	gRPCServer, err := comm_utils.NewGRPCServer(cn.bindAddress, cn.serverConfig)
	if err != nil {
		panic(fmt.Errorf("failed starting gRPC server: %v", err))
	}
	cn.srv = gRPCServer
	orderer.RegisterClusterServer(gRPCServer.Server(), cn)
	go cn.srv.Start()
}

// Vulnerability class: CWE-20
func (r *schemaResolver) UpdateSavedSearch(ctx context.Context, args *struct {
	ID          graphql.ID
	Description string
	Query       string
	NotifyOwner bool
	NotifySlack bool
	OrgID       *graphql.ID
	UserID      *graphql.ID
}) (*savedSearchResolver, error) {
	var userID, orgID *int32
	// 🚨 SECURITY: Make sure the current user has permission to update a saved search for the specified user or org.
	if args.UserID != nil {
		u, err := unmarshalSavedSearchID(*args.UserID)
		if err != nil {
			return nil, err
		}
		userID = &u
		if err := backend.CheckSiteAdminOrSameUser(ctx, r.db, u); err != nil {
			return nil, err
		}
	} else if args.OrgID != nil {
		o, err := unmarshalSavedSearchID(*args.OrgID)
		if err != nil {
			return nil, err
		}
		orgID = &o
		if err := backend.CheckOrgAccessOrSiteAdmin(ctx, r.db, o); err != nil {
			return nil, err
		}
	} else {
		return nil, errors.New("failed to update saved search: no Org ID or User ID associated with saved search")
	}

	id, err := unmarshalSavedSearchID(args.ID)
	if err != nil {
		return nil, err
	}

	if !queryHasPatternType(args.Query) {
		return nil, errMissingPatternType
	}

	ss, err := r.db.SavedSearches().Update(ctx, &types.SavedSearch{
		ID:          id,
		Description: args.Description,
		Query:       args.Query,
		Notify:      args.NotifyOwner,
		NotifySlack: args.NotifySlack,
		UserID:      userID,
		OrgID:       orgID,
	})
	if err != nil {
		return nil, err
	}

	return r.toSavedSearchResolver(*ss), nil
}

// Vulnerability class: CWE-863