code
stringlengths
23
2.05k
label_name
stringlengths
6
7
label
int64
0
37
def test_update_valid Domain.any_instance.stubs(:valid?).returns(true) put :update, {:id => Domain.first.to_param, :domain => {:name => Domain.first.name }}, set_session_user assert_redirected_to domains_url end
CWE-200
10
it "adds the server to the list" do cluster.sync_server server cluster.servers.should include server end
CWE-20
0
def test_update_invalid Subnet.any_instance.stubs(:valid?).returns(false) put :update, {:id => Subnet.first, :subnet => {:network => nil}}, set_session_user assert_template 'edit' end
CWE-200
10
it "should choose :rest when the Settings name isn't 'puppet'" do @request.stubs(:protocol).returns "puppet" @request.stubs(:server).returns "foo" Puppet.settings.stubs(:value).with(:name).returns "foo" @object.select_terminus(@request).should == :rest end
CWE-200
10
it "syncs each seed node" do server = Moped::Server.allocate Moped::Server.should_receive(:new).with("127.0.0.1:27017").and_return(server) cluster.should_receive(:sync_server).with(server).and_return([]) cluster.sync end
CWE-20
0
it "upserts the record matching selector with change" do query.should_receive(:update).with(change, [:upsert]) query.upsert change end
CWE-400
2
def initialize(data = nil, time = nil) if data @data = data elsif time @data = @@generator.generate(time.to_i) else @data = @@generator.next end end
CWE-400
2
it "approves user if invited by staff" do SiteSetting.must_approve_users = true invite = Fabricate(:invite, email: '[email protected]', invited_by: Fabricate(:admin)) user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'test') expect(user.approved).to eq(true) end
CWE-863
11
def deliver!(mail) envelope_from = mail.return_path || mail.sender || mail.from_addrs.first return_path = "-f \"#{envelope_from.to_s.shellescape}\"" if envelope_from arguments = [settings[:arguments], return_path].compact.join(" ") self.class.call(settings[:location], arguments, mail) end
CWE-20
0
it "inserts the documents" do session.should_receive(:execute).with do |insert| insert.documents.should eq [{a: 1}, {b: 2}] end collection.insert([{a: 1}, {b: 2}]) end
CWE-20
0
it "raises a QueryFailure exception" do expect { session.query(query) }.to raise_exception(Moped::Errors::QueryFailure) end
CWE-400
2
def command(command) operation = Protocol::Command.new(name, command) result = session.with(consistency: :strong) do |session| session.simple_query(operation) end raise Errors::OperationFailure.new( operation, result ) unless result["ok"] == 1.0 result end
CWE-400
2
it "memoizes the database" do database = session.current_database session.current_database.should equal(database) end
CWE-400
2
it "drops the collection" do database.should_receive(:command).with(drop: :users) collection.drop end
CWE-400
2
it "returns a random slave connection" do secondaries = [server] cluster.stub(secondaries: secondaries) secondaries.should_receive(:sample).and_return(server) cluster.socket_for(:read).should eq socket end
CWE-400
2
it "article alone should be password protected" do get :redirect, params: { from: from_param } expect(response.body).to have_selector('input[id="article_password"]', count: 1) end
CWE-863
11
it "sets the :database option" do session.use :admin session.options[:database].should eq(:admin) end
CWE-20
0
def primaries servers.select(&:primary?) end
CWE-20
0
def query(operation) reply = session.query operation @get_more_op.limit -= reply.count if limited? @get_more_op.cursor_id = reply.cursor_id @kill_cursor_op.cursor_ids = [reply.cursor_id] reply.documents end
CWE-20
0
it "syncs the cluster" do cluster.should_receive(:sync) do cluster.servers << server end cluster.socket_for :write end
CWE-20
0
it "sets the current database" do session.should_receive(:set_current_database).with(:admin) session.use :admin end
CWE-400
2
def merge(server) previous = servers.find { |other| other == server } primary = server.primary? secondary = server.secondary? if previous previous.merge(server) else servers << server end end
CWE-400
2
def initialize(seeds, direct = false) @seeds = seeds @direct = direct @servers = [] @dynamic_seeds = [] end
CWE-20
0
def command(command) operation = Protocol::Command.new(name, command) result = session.with(consistency: :strong) do |session| session.simple_query(operation) end raise Errors::OperationFailure.new( operation, result ) unless result["ok"] == 1.0 result end
CWE-20
0
it "should allow requests that are whitelisted" do set_cookie("__profilin=stylin") get '/whitelisted' last_response.headers['X-MiniProfiler-Ids'].should_not be_nil end
CWE-200
10
it "returns false" do indexes.drop(other: 1).should be_false end
CWE-400
2
it "returns a new Query" do Moped::Query.should_receive(:new). with(collection, selector).and_return(query) collection.find(selector).should eq query end
CWE-400
2
def known_addresses [].tap do |addresses| addresses.concat seeds addresses.concat dynamic_seeds addresses.concat servers.map { |server| server.address } end.uniq end
CWE-400
2
it "delegates to #with" do session.should_receive(:with).with(new_options).and_return(new_session) session.new(new_options) end
CWE-400
2
it "delegates to the current database" do database = mock(Moped::Database) session.should_receive(:current_database).and_return(database) database.should_receive(:drop) session.drop end
CWE-400
2
def first session.simple_query(operation) end
CWE-400
2
it "returns the index with the provided key" do indexes[name: 1]["name"].should eq "name_1" end
CWE-20
0
it "returns all other known hosts" do cluster.sync_server(server).should =~ ["localhost:61085", "localhost:61086", "localhost:61084"] end
CWE-400
2
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]
CWE-74
1
it "returns a session" do session.with(new_options).should be_a Moped::Session end
CWE-20
0
it "stores the options provided" do session.options.should eq(options) end
CWE-20
0
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
CWE-200
10
it "drops the index that matches the key" do indexes[name: 1].should be_nil end
CWE-400
2
it "stores the selector" do query.selector.should eq selector end
CWE-400
2
it "should should be a subclass of Base" do Puppet::FileServing::Metadata.superclass.should equal(Puppet::FileServing::Base) end
CWE-200
10
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
CWE-287
4
def current_database return @current_database if defined? @current_database if database = options[:database] set_current_database(database) else raise "No database set for session. Call #use or #with before accessing the database" end end
CWE-20
0
it "queries the master node" do session.should_receive(:socket_for).with(:write). and_return(socket) session.query(query) end
CWE-400
2
it "drops all indexes for the collection" do indexes[name: 1].should be_nil indexes[age: -1].should be_nil end
CWE-20
0
it "stores the options provided" do session.options.should eq(options) end
CWE-400
2
it "creates a new cursor" do cursor = mock(Moped::Cursor, next: nil) Moped::Cursor.should_receive(:new). with(session, query.operation).and_return(cursor) query.each end
CWE-20
0
it "adds the server to the list" do cluster.sync_server server cluster.servers.should include server end
CWE-400
2
def initialize(database, command) super database, :$cmd, command, limit: -1 end
CWE-20
0
it "yields the new session" do session.stub(with: new_session) session.new(new_options) do |session| session.should eql new_session end end
CWE-20
0
it 'fails when local logins is disabled' do SiteSetting.enable_local_logins = false get "/session/email-login/#{email_token.token}" expect(response.status).to eq(500) end
CWE-287
4
def limited? @query_op.limit > 0 end
CWE-400
2
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
CWE-346
16
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
CWE-200
10
it "applies the cached authentication" do cluster.stub(:sync) { cluster.servers << server } socket.should_receive(:apply_auth).with(cluster.auth) cluster.socket_for(:write) end
CWE-400
2
it "returns a new session" do session.with(new_options).should_not eql session end
CWE-20
0
it "limits the query" do session.should_receive(:query) do |query| query.limit.should eq(-1) reply end session.simple_query(query) end
CWE-400
2
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
CWE-732
13
it "raises an OperationFailure exception" do session.stub(socket_for: socket) socket.stub(execute: reply) expect { session.execute(operation) }.to raise_exception(Moped::Errors::OperationFailure) end
CWE-20
0
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
CWE-862
8
def setup FactoryGirl.create(:host) end
CWE-200
10
it "sets slave_ok on the query flags" do session.stub(socket_for: socket) socket.should_receive(:execute) do |query| query.flags.should include :slave_ok end session.query(query) end
CWE-400
2
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 }
CWE-610
17
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) }) }
CWE-610
17
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) }
CWE-863
11
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 } }
CWE-20
0
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 }
CWE-269
6
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 }
CWE-200
10
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 }
CWE-863
11
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 }
CWE-362
18
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 }
CWE-20
0
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 }
CWE-863
11
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) }) }
CWE-200
10
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)) } } }
CWE-285
23
func generateHMAC(data []byte, key *[32]byte) []byte { h := hmac.New(sha512.New512_256, key[:]) h.Write(data) return h.Sum(nil) }
CWE-755
21
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 }
CWE-863
11
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()), ), ) }
CWE-287
4
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, "") }
CWE-362
18
if rf, ok := ret.Get(0).(func(string, kube.ResourceKey, func(v1alpha1.ResourceNode, string)) error); ok { r0 = rf(server, key, action) } else { r0 = ret.Error(0) } return r0 }
CWE-269
6
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) }
CWE-863
11
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) }) }
CWE-610
17
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 }
CWE-200
10
func getClaimsFromToken(r *http.Request, token string) (map[string]interface{}, error) {
CWE-285
23
func (AppModuleBasic) ConsensusVersion() uint64 { return 1 }
CWE-287
4
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)) } } }
CWE-285
23
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 }
CWE-400
2
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 }
CWE-269
6
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, }, }) }
CWE-863
11
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) }
CWE-400
2
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 }
CWE-200
10
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() + ">"; },
CWE-287
4
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) }
CWE-755
21
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) }
CWE-863
11
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 }
CWE-400
2
func httpProxyValid(proxy *contourv1.HTTPProxy) bool { return proxy != nil && proxy.Status.CurrentStatus == "valid" }
CWE-610
17
func (p *GitLabProvider) addGroupsToSession(ctx context.Context, s *sessions.SessionState) { // Iterate over projects, check if oauth2-proxy can get project information on behalf of the user for _, group := range p.Groups { s.Groups = append(s.Groups, fmt.Sprintf("group:%s", group)) } }
CWE-863
11
func (AppModule) ConsensusVersion() uint64 { return 1 }
CWE-287
4
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) }
CWE-863
11
func New( localGRPCAddress string, localHTTPAddress string, fileManager *filemgr.Manager, reproxyHandler *reproxy.Handler, ) *Builder { return &Builder{ localGRPCAddress: localGRPCAddress, localHTTPAddress: localHTTPAddress, filemgr: fileManager, reproxy: reproxyHandler, } }
CWE-200
10
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() }
CWE-754
31
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) }
CWE-863
11