code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def check_owner return if params[:id].nil? or params[:id].empty? or @login_user.nil? email = Email.find(params[:id]) if !@login_user.admin?(User::AUTH_MAIL) and email.user_id != @login_user.id Log.add_check(request, '[check_owner]'+request.to_s) flash[:notice] = t('msg.need_to_be_owner') ...
Base
1
def send_password Log.add_info(request, params.inspect) mail_addr = params[:thetisBoxEdit] SqlHelper.validate_token([mail_addr]) begin users = User.where("email='#{mail_addr}'").to_a rescue => evar end if users.nil? or users.empty? Log.add_error(request, evar) flash[:no...
Base
1
it "returns the right category group permission for a staff user ordered by ascending group name" do json = described_class.new(category, scope: Guardian.new(admin), root: false).as_json expect(json[:group_permissions]).to eq([ { permission_type: CategoryGroup.permission_types[:readonly...
Base
1
def sanitize_value(value) case value when Array then value.collect { |i| i.to_s.shellescape } when NilClass then value else value.to_s.shellescape end
Base
1
it 'removes existing content types' do subject.content_type :xls, 'application/vnd.ms-excel' subject.get :excel do 'some binary content' end get '/excel.json' expect(last_response.status).to eq(406) expect(last_response.body).to eq("The requested format 'txt' is not suppo...
Base
1
def new_ally_request_link(uniqueid, data) link = "/profile?uid=#{data[:uid]}" link_html = "<a href=\"#{link}\">#{data[:user]}</a>" # rubocop:disable Layout/LineLength "<div id=\"#{uniqueid}\"><div>#{t('notifications.ally.sent_html', link_to_user: link_html)}</div>#{request_actions(data[:user_id])}</di...
Base
1
def initialize(data = nil, time = nil) if data @data = data elsif time @data = @@generator.generate(time.to_i) else @data = @@generator.next end end
Class
2
def self.search_by_puppetclass(key, operator, value) conditions = "puppetclasses.name #{operator} '#{value_to_sql(operator, value)}'" hosts = Host.my_hosts.all(:conditions => conditions, :joins => :puppetclasses, :select => 'DISTINCT hosts.id').map(&:id) host_groups = Hostgr...
Base
1
it "returns the document" do session.simple_query(query).should eq(a: 1) end
Class
2
it "syncs the cluster" do cluster.should_receive(:sync) do cluster.servers << server end cluster.socket_for :write end
Class
2
def self.get_for_user(user) return [] if user.nil? toys = Toy.where("user_id=#{user.id}").to_a deleted_ary = [] return [] if toys.nil? toys.each do |toy| case toy.xtype when Toy::XTYPE_ITEM item = Item.find_by_id(toy.target_id) if item.nil? deleted...
Base
1
def self.normalize_key_names(options) options = options.dup if options.key?(:key_prefix) && !options.key?(:namespace) options[:namespace] = options.delete(:key_prefix) # RailsSessionStore end options[:raw] = !options[:marshalling] options end
Base
1
def write!(headers) if @orig_disable_profiling != @disable_profiling || @orig_backtrace_level != @backtrace_level || @cookie.nil? settings = {"p" => "t" } settings["dp"] = "t" if @disable_profiling settings["bt"] = @backtrace_level if @backtrace_level ...
Class
2
def forwarded_for @env[FORWARDED_FOR] end
Class
2
def base_api_url computed_api_endpoint = "https://#{get_data_center_from_api_key(self.api_key)}api.mailchimp.com" raise Gibbon::GibbonError, "SSRF attempt" unless URI(computed_api_endpoint).host.include?("api.mailchimp.com") "#{self.api_endpoint || computed_api_endpoint}/3.0/" end
Base
1
def set_configs(params, request, session) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end return JSON.generate({'status' => 'bad_json'}) if not params['configs'] begin configs_json = JSON.parse(params['configs']) rescue JSON::ParserError return JSON...
Compound
4
def private_messages_for(user, type) options = @options options.reverse_merge!(per_page: per_page_setting) result = Topic.includes(:allowed_users) result = result.includes(:tags) if SiteSetting.tagging_enabled if type == :group result = result.joins( "INNER JOIN top...
Class
2
it "removes the stored credentials" do cluster.logout :admin cluster.auth.should be_empty end
Class
2
it "executes a distinct command" do database.should_receive(:command).with( distinct: collection.name, key: "name", query: selector ).and_return("values" => [ "durran", "bernerd" ]) query.distinct(:name) end
Class
2
def _marshal(val, options) yield marshal?(options) ? Marshal.dump(val) : val end
Base
1
def remove_all delete = Protocol::Delete.new( operation.database, operation.collection, operation.selector ) session.with(consistency: :strong) do |session| session.execute delete end end
Class
2
it "has an empty list of secondaries" do cluster.secondaries.should be_empty end
Class
2
it "updates the selector to mongo's advanced selector" do query.sort(a: 1) query.operation.selector.should eq( "$query" => selector, "$orderby" => { a: 1 } ) end
Class
2
def verify_active_session if !request.post? && params[:status].blank? && User.exists?(session[:user].presence) warning _("You have already logged in") redirect_back_or_to hosts_path return end end
Class
2
def test_create_valid AuthSourceLdap.any_instance.stubs(:valid?).returns(true) post :create, {:auth_source_ldap => {:name => AuthSourceLdap.first.name}}, set_session_user assert_redirected_to auth_source_ldaps_url end
Class
2
def remove_acl_usergroup(session, role_id, usergroup_id) stdout, stderror, retval = run_cmd( session, PCS, "acl", "role", "unassign", role_id.to_s, usergroup_id.to_s, "--autodelete" ) if retval != 0 if stderror.empty? return "Error removing user / group" else return stderror.join("\n")...
Compound
4
it "handles Symbol keys with underscore" do cl = subject.build_command_line("true", :abc_def => "ghi") expect(cl).to eq "true --abc-def ghi" end
Base
1
def get_permissions_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::GRANT) return 403, 'Permission denied' end pcs_config = PCSConfig.new(Cfgsync::PcsdSettings.from_file('{}').text()) data = { 'user_types' => Permissions::get_user_types(), 'permission_types' ...
Compound
4
def decode_compact_serialized(input, public_key_or_secret, algorithms = nil, allow_blank_payload = false) unless input.count('.') + 1 == NUM_OF_SEGMENTS raise InvalidFormat.new("Invalid JWS Format. JWS should include #{NUM_OF_SEGMENTS} segments.") end header, claims, signature = ...
Class
2
def initialize(file) @file = file.is_a?(String) ? StringIO.new(file) : file end
Base
1
def send(force=false) nodes_txt = @nodes.join(', ') @configs.each { |cfg| $logger.info( "Sending config '#{cfg.class.name}' version #{cfg.version} #{cfg.hash}"\ + " to nodes: #{nodes_txt}" ) } data = self.prepare_request_data(@configs, @cluster_name, forc...
Compound
4
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
Class
2
def test_private_address assert_raises PrivateAddressCheck::PrivateConnectionAttemptedError do PrivateAddressCheck.only_public_connections do TCPSocket.new("localhost", 80) end end end
Class
2
def initialize(seeds, direct = false) @seeds = seeds @direct = direct @servers = [] @dynamic_seeds = [] end
Class
2
def fence_device_metadata(params, request, session) if not allowed_for_local_cluster(session, Permissions::READ) return 403, 'Permission denied' end return 200 if not params[:resourcename] or params[:resourcename] == "" @fenceagent = FenceAgent.new(params[:resourcename]) @fenceagent.required_options, @fen...
Compound
4
def handle_meta(message, local, &callback) method = Channel.parse(message['channel'])[1] unless META_METHODS.include?(method) response = make_response(message) response['error'] = Faye::Error.channel_forbidden(message['channel']) response['successful'] = false return cal...
Class
2
def node_unstandby(params, request, session) if params[:name] code, response = send_request_with_token( session, params[:name], 'node_unstandby', true, {"node"=>params[:name]} ) # data={"node"=>params[:name]} for backward compatibility with older versions of pcs/pcsd else if not allowed_for_lo...
Compound
4
def add_fence_level(session, level, devices, node, remove = false) if not remove stdout, stderr, retval = run_cmd( session, PCS, "stonith", "level", "add", level, node, devices ) return retval,stdout, stderr else stdout, stderr, retval = run_cmd( session, PCS, "stonith", "level", "remove...
Compound
4
def get_group_users Log.add_info(request, params.inspect) @group_id = nil if !params[:thetisBoxSelKeeper].nil? @group_id = params[:thetisBoxSelKeeper].split(':').last elsif !params[:group_id].nil? and !params[:group_id].empty? @group_id = params[:group_id] end submit_url = url_fo...
Base
1
def wizard_submit(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end wizard = PCSDWizard.getWizard(params["wizard"]) if wizard != nil return erb wizard.process_responses(params) else return "Error finding Wizard - #{params["w...
Compound
4
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
Class
2
it 'should return a second factor prompt' do get "/session/email-login/#{email_token.token}" expect(response.status).to eq(200) response_body = CGI.unescapeHTML(response.body) expect(response_body).to include(I18n.t( "login.second_factor_title" ...
Class
2
def get_cluster_properties_definition(params, request, session) unless allowed_for_local_cluster(session, Permissions::READ) return 403, 'Permission denied' end stdout, _, retval = run_cmd( session, PCS, 'property', 'get_cluster_properties_definition' ) if retval == 0 return [200, stdout] end ...
Compound
4
it "returns a hex string representation of the id" do Moped::BSON::ObjectId.new(bytes).to_s.should eq "4e4d66343b39b68407000001" end
Class
2
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
Class
2
it "yields the new session" do session.stub(with: new_session) session.new(new_options) do |session| session.should eql new_session end end
Class
2
it "converts to Punycode URI" do expect(subject.process_uri(uri).to_s).to eq 'http://xn--eckwd4c7cu47r2wf.jp/test.jpg' end
Base
1
def getAllSettings(session, cib_dom=nil) unless cib_dom cib_dom = get_cib_dom(session) end ret = {} if cib_dom cib_dom.elements.each('/cib/configuration/crm_config//nvpair') { |e| ret[e.attributes['name']] = e.attributes['value'] } end return ret end
Compound
4
it 'should not overwrite an existing file if overwrite_stored_key is not set' do @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1') @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd') @plugin.stubs(:lookup_config_option).with('over...
Class
2
it "executes a simple query" do session.should_receive(:simple_query).with(query.operation) query.one end
Class
2
it "adds the credentials to the auth cache" do cluster.login("admin", "username", "password") cluster.auth.should eq("admin" => ["username", "password"]) end
Class
2
def check_action_permission!(skip_source = nil) super(skip_source) # only perform the following check, if we are called from # BsRequest.permission_check_change_state! (that is, if # skip_source is set to true). Always executing this check # would be a regression, because this code is also execute...
Class
2
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
Class
2
def show_owners name response = rubygems_api_request :get, "api/v1/gems/#{name}/owners.yaml" do |request| request.add_field "Authorization", api_key end with_response response do |resp| owners = YAML.load resp.body say "Owners for gem: #{name}" owners.each do |owner| say ...
Base
1
def self.get_for(user, mail_account_id, xtype) return nil if user.nil? or mail_account_id.blank? if user.kind_of?(User) user_id = user.id else user_id = user.to_s end SqlHelper.validate_token([user_id, mail_account_id, xtype]) con = [] con << "(user_id=#{user_id})" con ...
Base
1
def initialize(seeds, direct = false) @seeds = seeds @direct = direct @servers = [] @dynamic_seeds = [] end
Class
2
it "returns a session" do session.with(new_options).should be_a Moped::Session end
Class
2
def order_by order_option = '' if self.order_column direction = self.order_direction || 'ASC' order_option = "#{self.order_column} #{direction}" end order_option.present? ? order_option : @@default_order end
Base
1
it "should get the script it asks for" do def @bus.is_admin_lookup proc { |_| true } end get "/message-bus/_diagnostics/assets/message-bus.js" last_response.status.must_equal 200 last_response.content_type.must_equal "application/javascript;charset=UTF-8" end
Base
1
it "returns all other known hosts" do cluster.sync_server(server).should =~ ["localhost:61085", "localhost:61086", "localhost:61084"] end
Class
2
def index html = <<~HTML <!DOCTYPE html> <html> <head> </head> <body> <div id="app"></div> #{js_asset "jquery-1.8.2.js"} #{js_asset "react.js"} #{js_asset "react-dom.js"} #{js_asset "babel.min.js"} #{js_asset "message-...
Base
1
it "stores the selector" do query.selector.should eq selector end
Class
2
def set_auth_teams Log.add_info(request, params.inspect) @folder = Folder.find(params[:id]) if Folder.check_user_auth(@folder.id, @login_user, 'w', true) read_teams = [] write_teams = [] teams_auth = params[:teams_auth] unless teams_auth.nil? teams_auth.each do |auth_para...
Base
1
def setup_cluster(params, request, session) if not allowed_for_superuser(session) return 403, 'Permission denied' end $logger.info("Setting up cluster: " + params.inspect) nodes_rrp = params[:nodes].split(';') options = [] myoptions = JSON.parse(params[:options]) transport_udp = false options_udp = ...
Compound
4
def quote_column_name(name) #:nodoc: @quoted_column_names[name] ||= "`#{name}`" end
Base
1
def remove delete = Protocol::Delete.new( operation.database, operation.collection, operation.selector, flags: [:remove_first] ) session.with(consistency: :strong) do |session| session.execute delete end end
Class
2
def get_folders_order Log.add_info(request, params.inspect) @folder_id = params[:id] if @folder_id == '0' @folders = MailFolder.get_account_roots_for(@login_user) else mail_folder = MailFolder.find(@folder_id) if mail_folder.user_id == @login_user.id @folders = MailFolder.g...
Base
1
def get_auth_teams Log.add_info(request, params.inspect) begin @folder = Folder.find(params[:id]) rescue @folder = nil end target_user_id = (@login_user.admin?(User::AUTH_TEAM))?(nil):(@login_user.id) @teams = Team.get_for(target_user_id, true) session[:folder_id] = params[:...
Base
1
def initialize(data = nil, time = nil) if data @data = data elsif time @data = @@generator.generate(time.to_i) else @data = @@generator.next end end
Class
2
it 'should overwrite the existing public key if overwrite_stored_key is set' do @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1') @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd') @plugin.stubs(:lookup_config_option).with('overw...
Class
2
def self.map_library_name(lib) # Mangle the library name to reflect the native library naming conventions lib = lib.to_s unless lib.kind_of?(String) lib = Library::LIBC if lib == 'c' if lib && File.basename(lib) == lib lib = Platform::LIBPREFIX + lib unless lib =~ /^#{Platform::LIBPREFIX}/ ...
Base
1
def cama_current_user return @cama_current_user if defined?(@cama_current_user) # api current user... @cama_current_user = cama_calc_api_current_user return @cama_current_user if @cama_current_user return nil unless cookies[:auth_token].present? c = cookies[:auth_token].split("&") return ...
Base
1
def show filename = Rails.root.join("attachments", @attachment.filename) unless File.exist?(filename) COURSE_LOGGER.log("Cannot find the file '#{@attachment.filename}' for"\ " attachment #{@attachment.name}") flash[:error] = "Error loading #{@attachment.name} from #{@attac...
Base
1
it "returns a new session" do session.with(new_options).should_not eql session end
Class
2
def get_mail_attachment Log.add_info(request, params.inspect) attached_id = params[:id].to_i mail_attach = MailAttachment.find_by_id(attached_id) if mail_attach.nil? redirect_to(THETIS_RELATIVE_URL_ROOT + '/404.html') return end email = Email.find_by_id(mail_attach.email_id) ...
Base
1
def munge_name(name) # LAK:NOTE http://snurl.com/21zf8 [groups_google_com] # Change to name.downcase.split(".",-1).reverse for FQDN support name.downcase.split(".").reverse end
Class
2
def get_group_users Log.add_info(request, params.inspect) @group_id = nil if !params[:thetisBoxSelKeeper].nil? @group_id = params[:thetisBoxSelKeeper].split(':').last elsif !params[:group_id].nil? and !params[:group_id].empty? @group_id = params[:group_id] end submit_url = url_fo...
Base
1
def known_addresses [].tap do |addresses| addresses.concat seeds addresses.concat dynamic_seeds addresses.concat servers.map { |server| server.address } end.uniq end
Class
2
def initialize(database, command) super database, :$cmd, command, limit: -1 end
Class
2
def authorize_params super.tap do |params| %w[display state scope].each do |v| if request.params[v] params[v.to_sym] = request.params[v] # to support omniauth-oauth2's auto csrf protection session['omniauth.state'] = params[:state] if v == '...
Compound
4
it "returns the master connection" do cluster.socket_for(:read).should eq socket end
Class
2
def more? @get_more_op.cursor_id != 0 end
Class
2
def self.getSuperuserSession() return { :username => SUPERUSER, :usergroups => [], } end
Compound
4
def ffi_lib(*names) raise LoadError.new("library names list must not be empty") if names.empty? lib_flags = defined?(@ffi_lib_flags) ? @ffi_lib_flags : FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL ffi_libs = names.map do |name| if name == FFI::CURRENT_PROCESS ...
Base
1
def legal?(str) !!str.match(/^[0-9a-f]{24}$/i) end
Class
2
it "removes the first matching document" do session.should_receive(:with, :consistency => :strong). and_yield(session) session.should_receive(:execute).with do |delete| delete.flags.should eq [:remove_first] delete.selector.should eq query.operation.selector end que...
Class
2
def self.on_desktop?(user, xtype, target_id) return false if user.nil? or xtype.nil? or target_id.nil? SqlHelper.validate_token([xtype, target_id]) con = "(user_id=#{user.id}) and (xtype='#{xtype}') and (target_id=#{target_id})" begin toy = Toy.where(con).first rescue => evar Log.a...
Base
1
def include_allowed?(target, reader) doc = reader.document return false if doc.safe >= ::Asciidoctor::SafeMode::SECURE return false if doc.attributes.fetch('max-include-depth', 64).to_i < 1 return false if target_uri?(target) && !doc.attributes.key?('allow-uri-read') true end
Base
1
def add_acl_usergroup(session, acl_role_id, user_group, name) if (user_group == "user") or (user_group == "group") stdout, stderr, retval = run_cmd( session, PCS, "acl", user_group, "create", name.to_s, acl_role_id.to_s ) if retval == 0 return "" end if not /^error: (user|group) #{name...
Compound
4
def check_image_content_type!(new_file) if image?(new_file) magic_type = mime_magic_content_type(new_file) if magic_type != new_file.content_type raise CarrierWave::IntegrityError, "has MIME type mismatch" end end end
Base
1
it "converts the comment markup to HTML" do expect(comment.generate_html(:body)).to match(%r{<em>italic</em>}) expect(comment.generate_html(:body)).to match(%r{<strong>bold</strong>}) end
Base
1
it "updates to a mongo advanced selector" do query.explain query.operation.selector.should eq( "$query" => selector, "$explain" => true, "$orderby" => { _id: 1 } ) end
Class
2
def remote_node_available(params, request, session) if (not ISRHEL6 and File.exist?(Cfgsync::CorosyncConf.file_path)) or (ISRHEL6 and File.exist?(Cfgsync::ClusterConf.file_path)) or File.exist?("/var/lib/pacemaker/cib/cib.xml") return JSON.generate({:node_available => false}) end return JSON.generate({:node_a...
Compound
4
def self.taxonomy_conditions org = Organization.expand(Organization.current) if SETTINGS[:organizations_enabled] loc = Location.expand(Location.current) if SETTINGS[:locations_enabled] conditions = {} conditions[:organization_id] = Array(org).map { |o| o.subtree_ids }.flatten.uniq if org.pre...
Class
2
it "should redeem the invite if invited by staff" do SiteSetting.must_approve_users = true inviter = invite.invited_by inviter.admin = true user = invite_redeemer.redeem invite.reload expect(user.name).to eq(name) expect(user.username).to eq(username) expect(user.inv...
Class
2
def add_node(session, new_nodename, all=false, auto_start=true) if all command = [PCS, "cluster", "node", "add", new_nodename] if auto_start command << '--start' command << '--enable' end out, stderror, retval = run_cmd(session, *command) else out, stderror, retval = run_cmd( s...
Compound
4
it "raises with a valid SSRF attack" do @api_key = "-attacker.net/test/?" @gibbon.api_key = @api_key expect {@gibbon.try.retrieve}.to raise_error(Gibbon::MailChimpError, /SSRF attempt/) end
Base
1
it "can set the password and ip_address" do password = 's3cure5tpasSw0rD' ip_address = '192.168.1.1' invite = Fabricate(:invite, email: 'walter.white@email.com') user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White', passw...
Class
2
it "returns true" do Moped::BSON::ObjectId.new(bytes).should == Moped::BSON::ObjectId.new(bytes) end
Class
2
def team Log.add_info(request, params.inspect) date_s = params[:date] if date_s.nil? or date_s.empty? @date = Date.today else @date = Date.parse(date_s) end begin team = Team.find(params[:id]) team_users = team.get_users_a rescue => evar Log.add_error(reques...
Base
1