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: 'test@example.com', invited_by: Fabricate(:admin)) user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'test') expect(user.approved).to...
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) en...
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.reca...
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_u...
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') ...
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 ...
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 ...
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 ...
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 dagSv...
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{ ...
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 ...
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.PHY...
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...
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_...
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 e...
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()), ...
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) ...
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.Heade...
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.Wr...
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(...
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 s...
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: "externa...
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_c...
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 st...
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 == "" { ...
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[k...
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...
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 b...
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}, }, Ac...
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...
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 := performReq...
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.E...
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, Rea...
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....
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",...
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_c...
CWE-863
11