code
stringlengths 12
2.05k
| label_name
stringlengths 6
8
| label
int64 0
95
|
---|---|---|
def edit_timecard
Log.add_info(request, params.inspect)
date_s = params[:date]
if date_s.nil? or date_s.empty?
@date = Date.today
date_s = @date.strftime(Schedule::SYS_DATE_FORM)
else
@date = Date.parse(date_s)
end
@timecard = Timecard.get_for(@login_user.id, date_s)
render(:partial => 'timecard', :layout => false)
end | CWE-89 | 0 |
def process
# We don't want any tracking back in the fs. Unlikely, but there
# you go.
client = self.host.gsub("..",".")
dir = File.join(Puppet[:reportdir], client)
if ! FileTest.exists?(dir)
FileUtils.mkdir_p(dir)
FileUtils.chmod_R(0750, dir)
end
# Now store the report.
now = Time.now.gmtime
name = %w{year month day hour min}.collect do |method|
# Make sure we're at least two digits everywhere
"%02d" % now.send(method).to_s
end.join("") + ".yaml"
file = File.join(dir, name)
f = Tempfile.new(name, dir)
begin
begin
f.chmod(0640)
f.print to_yaml
ensure
f.close
end
FileUtils.mv(f.path, file)
rescue => detail
puts detail.backtrace if Puppet[:trace]
Puppet.warning "Could not write report for #{client} at #{file}: #{detail}"
end
# Only testing cares about the return value
file
end | CWE-22 | 2 |
def self.dump(object)
MultiJson.dump object,
mode: :compat, escape_mode: :xss_safe, time_format: :ruby
end | CWE-79 | 1 |
it "sanitizes Pathname param key" do
cl = subject.build_command_line("true", Pathname.new("/usr/bin/ruby") => nil)
expect(cl).to eq "true /usr/bin/ruby"
end | CWE-78 | 6 |
def verify_signature(string, signature)
if signature.nil?
fail InvalidSignature, "missing \"signature\" param"
elsif signature != generate_signature(string)
fail InvalidSignature, "provided signature does not match the calculated signature"
end
end | CWE-208 | 91 |
def calculated_content_type
@calculated_content_type ||= type_from_file_command.chomp
end | CWE-79 | 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 << "(mail_account_id=#{mail_account_id})"
con << "(xtype='#{xtype}')"
return MailFolder.where(con.join(' and ')).first
end | CWE-89 | 0 |
def self.extract_events(post)
cooked = PrettyText.cook(post.raw, topic_id: post.topic_id, user_id: post.user_id)
valid_options = VALID_OPTIONS.map { |o| "data-#{o}" }
valid_custom_fields = []
SiteSetting.discourse_post_event_allowed_custom_fields.split('|').each do |setting|
valid_custom_fields << {
original: "data-#{setting}",
normalized: "data-#{setting.gsub(/_/, '-')}"
}
end
Nokogiri::HTML(cooked).css('div.discourse-post-event').map do |doc|
event = nil
doc.attributes.values.each do |attribute|
name = attribute.name
value = attribute.value
if value && valid_options.include?(name)
event ||= {}
event[name.sub('data-', '').to_sym] = CGI.escapeHTML(value)
end
valid_custom_fields.each do |valid_custom_field|
if value && valid_custom_field[:normalized] == name
event ||= {}
event[valid_custom_field[:original].sub('data-', '').to_sym] = CGI.escapeHTML(value)
end
end
end
event
end.compact
end | CWE-79 | 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 #{@attachment.filename}"
redirect_to([@course, :attachments]) && return
end
send_file(filename, disposition: "inline",
type: @attachment.mime_type, filename: @attachment.filename) && return
end | CWE-79 | 1 |
def self.get_next_revision(user_id, source_id)
copied_items = Item.where("user_id=#{user_id} and source_id=#{source_id}").order('created_at DESC').to_a
rev = 0
copied_items.each do |item|
rev_ary = item.title.scan(/[#](\d\d\d)$/)
next if rev_ary.nil?
rev = rev_ary.first.to_a.first.to_i
break
end
return '#' + sprintf('%03d', rev+1)
end | CWE-89 | 0 |
def update_folders_order
Log.add_info(request, params.inspect)
order_ary = params[:folders_order]
folders = MailFolder.get_childs(params[:id], false, false)
# folders must be ordered by xorder ASC.
folders.sort! { |id_a, id_b|
idx_a = order_ary.index(id_a)
idx_b = order_ary.index(id_b)
if idx_a.nil? or idx_b.nil?
idx_a = folders.index(id_a)
idx_b = folders.index(id_b)
end
idx_a - idx_b
}
idx = 1
folders.each do |folder_id|
begin
folder = MailFolder.find(folder_id)
next if folder.user_id != @login_user.id
folder.update_attribute(:xorder, idx)
if folder.xtype == MailFolder::XTYPE_ACCOUNT_ROOT
mail_account = MailAccount.find_by_id(folder.mail_account_id)
unless mail_account.nil?
mail_account.update_attribute(:xorder, idx)
end
end
idx += 1
rescue => evar
Log.add_error(request, evar)
end
end
render(:text => '')
end | CWE-89 | 0 |
def self.trim_by_capacity(user_id, mail_account_id, capacity_mb)
# FEATURE_MAIL_STRICT_CAPACITY >>>
=begin
# max_size = capacity_mb * 1024 * 1024
# cur_size = MailAccount.get_using_size(mail_account_id)
#
# if cur_size > max_size
# over_size = cur_size - max_size
# emails = []
#
# # First, empty Trashbox
# user = User.find(user_id)
# trashbox = MailFolder.get_for(user, mail_account_id, MailFolder::XTYPE_TRASH)
# trash_nodes = [trashbox.id.to_s]
# trash_nodes += MailFolder.get_childs(trash_nodes.first, true, false)
# con = "mail_folder_id in (#{trash_nodes.join(',')})"
# emails = Email.where(con).order('updated_at ASC').to_a
# emails.each do |email|
# next if email.size.nil?
#
# email.destroy
# over_size -= email.size
# break if over_size <= 0
# end
#
# # Now, remove others
# if over_size > 0
# emails = Email.where("mail_account_id=#{mail_account_id}").order('updated_at ASC').to_a
# emails.each do |email|
# next if email.size.nil?
#
# email.destroy
# over_size -= email.size
# break if over_size <= 0
# end
# end
# end
=end
# FEATURE_MAIL_STRICT_CAPACITY <<<
end | CWE-89 | 0 |
def column_content(column, item)
value = column.value_object(item)
if value.is_a?(Array)
value.collect {|v| column_value(column, item, v)}.compact.join(', ').html_safe
else
column_value(column, item, value)
end
end | CWE-79 | 1 |
def set_auth_users
Log.add_info(request, params.inspect)
@folder = Folder.find(params[:id])
if Folder.check_user_auth(@folder.id, @login_user, 'w', true)
read_users = []
write_users = []
users_auth = params[:users_auth]
unless users_auth.nil?
users_auth.each do |auth_param|
user_id = auth_param.split(':').first
auths = auth_param.split(':').last.split('+')
if auths.include?('r')
read_users << user_id
end
if auths.include?('w')
write_users << user_id
end
end
end
user_id = @folder.get_my_folder_owner
if !user_id.nil? and (!read_users.include?(user_id.to_s) or !write_users.include?(user_id.to_s))
flash[:notice] = 'ERROR:' + t('folder.my_folder_without_auth_owner')
else
@folder.set_read_users read_users
@folder.set_write_users write_users
@folder.save
flash[:notice] = t('msg.register_success')
end
else
flash[:notice] = 'ERROR:' + t('folder.need_auth_to_modify')
end
@group_id = params[:group_id]
if @group_id.nil? or @group_id.empty?
@users = []
else
@users = Group.get_users(@group_id)
end
render(:partial => 'ajax_auth_users', :layout => false)
rescue => evar
Log.add_error(request, evar)
render(:partial => 'ajax_auth_users', :layout => false)
end | CWE-89 | 0 |
def login_success
if params[:ref].blank?
redirect_to default_logged_in_path
elsif params[:ref] =~ /^\//
redirect_to params[:ref]
else
render "sns/login/redirect"
end
end | CWE-601 | 11 |
def self.validate_token(tokens, extra_chars=nil)
extra_chars = Regexp.escape((extra_chars || []).join())
regexp = Regexp.new("^[ ]*[a-zA-Z0-9_.#{extra_chars}]+[ ]*$")
[tokens].flatten.each do |token|
next if token.blank?
if token.to_s.match(regexp).nil?
raise("[ERROR] SqlHelper.validate_token failed: #{token}")
end
end
end | CWE-89 | 0 |
it "passes the initial directory" do
expect(File.cleanpath('C/../../D')).to eq "../D"
end | CWE-22 | 2 |
def self.get_for(user_id, category=nil)
SqlHelper.validate_token([user_id, category])
con = []
con << "(user_id=#{user_id})"
con << "(category='#{category}')" unless category.nil?
settings = Setting.where(con.join(' and ')).to_a
return nil if settings.nil? or settings.empty?
hash = Hash.new
settings.each do |setting|
hash[setting.xkey] = setting.xvalue
end
return hash
end | CWE-89 | 0 |
def self.search_by_params(key, operator, value)
key_name = key.sub(/^.*\./,'')
opts = {:conditions => "name = '#{key_name}' and value #{operator} '#{value_to_sql(operator, value)}'", :order => :priority}
p = Parameter.all(opts)
return {:conditions => '1 = 0'} if p.blank?
max = p.first.priority
negate_opts = {:conditions => "name = '#{key_name}' and NOT(value #{operator} '#{value_to_sql(operator, value)}') and priority > #{max}", :order => :priority}
n = Parameter.all(negate_opts)
conditions = param_conditions(p)
negate = param_conditions(n)
conditions += " AND " unless conditions.blank? || negate.blank?
conditions += " NOT(#{negate})" unless negate.blank?
return {:conditions => conditions}
end | CWE-89 | 0 |
def original_filename
filename = filename_from_header || filename_from_uri
mime_type = MiniMime.lookup_by_content_type(file.content_type)
unless File.extname(filename).present? || mime_type.blank?
filename = "#{filename}.#{mime_type.extension}"
end
filename
end | CWE-918 | 16 |
def timeline
unless params[:type].empty?
model = params[:type].camelize.constantize
item = model.find(params[:id])
item.update_attribute(:state, params[:state])
else
comments, emails = params[:id].split("+")
Comment.update_all("state = '#{params[:state]}'", "id IN (#{comments})") unless comments.blank?
Email.update_all("state = '#{params[:state]}'", "id IN (#{emails})") unless emails.blank?
end
render :nothing => true
end | CWE-89 | 0 |
def self.destroy(host)
client = host.gsub("..",".")
dir = File.join(Puppet[:reportdir], client)
if File.exists?(dir)
Dir.entries(dir).each do |file|
next if ['.','..'].include?(file)
file = File.join(dir, file)
File.unlink(file) if File.file?(file)
end
Dir.rmdir(dir)
end
end | CWE-22 | 2 |
def set_attachment
Log.add_info(request, params.inspect)
created = false
if params[:id].nil? or params[:id].empty?
@item = Item.new_info(0)
@item.attributes = params[:item]
@item.user_id = @login_user.id
@item.title = t('paren.no_title')
[:attachment0, :attachment1].each do |attach|
next if params[attach].nil? or params[attach][:file].nil? or params[attach][:file].size == 0
@item.save!
created = true
break
end
else
@item = Item.find(params[:id])
end
modified = false
item_attachments = @item.attachments_without_content
[:attachment0, :attachment1].each do |attach|
next if params[attach].nil? or params[attach][:file].nil? or params[attach][:file].size == 0
attachment = Attachment.create(params[attach], @item, item_attachments.length)
modified = true
item_attachments << attachment
end
if modified and !created
@item.update_attribute(:updated_at, Time.now)
end
render(:partial => 'ajax_item_attachment', :layout => false)
rescue => evar
Log.add_error(request, evar)
@attachment = Attachment.new
@attachment.errors.add_to_base(evar.to_s[0, 256])
render(:partial => 'ajax_item_attachment', :layout => false)
end | CWE-89 | 0 |
def self.get_sql_like(attr_names, keyword)
key = ActiveRecord::Base.connection.quote("%#{SqlHelper.escape_for_like(keyword)}%")
con = []
attr_names.each do |attr_name|
con << "(#{attr_name} like #{key})"
end
sql = con.join(' or ')
sql = '(' + sql + ')' if con.length > 1
return sql
end | CWE-89 | 0 |
def self.add_statistics_group(group_id)
yaml = Research.get_config_yaml
yaml = Hash.new if yaml.nil?
if yaml[:statistics].nil?
yaml[:statistics] = Hash.new
end
groups = yaml[:statistics][:groups]
if groups.nil?
yaml[:statistics][:groups] = group_id
ary = [group_id.to_s]
else
ary = groups.split('|')
ary << group_id
ary.compact!
ary.delete ''
yaml[:statistics][:groups] = ary.join('|')
end
Research.save_config_yaml yaml
return ary
end | CWE-89 | 0 |
def delete_statistics_group
Log.add_info(request, params.inspect)
group_id = params[:group_id]
if group_id.nil? or group_id.empty?
@group_ids = Research.get_statistics_groups
render(:partial => 'ajax_statistics_groups', :layout => false)
return
end
@group_ids = Research.delete_statistics_group group_id
render(:partial => 'ajax_statistics_groups', :layout => false)
end | CWE-89 | 0 |
def initialize(file)
@file = file.is_a?(String) ? StringIO.new(file) : file
end | CWE-918 | 16 |
def ajax_move_mails
Log.add_info(request, params.inspect)
folder_id = params[:thetisBoxSelKeeper].split(':').last
mail_folder = MailFolder.find_by_id(folder_id)
if folder_id == '0' \
or mail_folder.nil? \
or mail_folder.user_id != @login_user.id
flash[:notice] = 'ERROR:' + t('msg.cannot_save_in_folder')
get_mails
return
end
unless params[:check_mail].blank?
count = 0
params[:check_mail].each do |email_id, value|
if value == '1'
begin
email = Email.find(email_id)
next if email.user_id != @login_user.id
email.update_attribute(:mail_folder_id, folder_id)
rescue => evar
Log.add_error(request, evar)
end
count += 1
end
end
flash[:notice] = t('mail.moved', :count => count)
end
get_mails
end | CWE-89 | 0 |
def spree_current_user
@spree_current_user ||= Spree.user_class.find_by(id: doorkeeper_token.resource_owner_id) if doorkeeper_token
end | CWE-613 | 7 |
def self.up
add_column :items, :source_id, :integer
add_column :addresses, :groups, :text
add_column :addresses, :teams, :text
add_column :workflows, :groups, :text
add_column :users, :figure, :string
add_column :groups, :xtype, :string
add_column :teams, :req_to_del_at, :datetime
change_table :teams do |t|
t.timestamps
end
teams = Team.all
unless teams.nil?
teams.each do |team|
begin
item = Item.find(team.item_id)
rescue
end
next if item.nil?
attrs = ActionController::Parameters.new({created_at: item.created_at, updated_at: item.updated_at})
attrs.permit!
team.update_attributes(attrs)
end
end
end | CWE-89 | 0 |
def rename
Log.add_info(request, params.inspect)
@mail_folder = MailFolder.find(params[:id])
unless params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?
@mail_folder.name = params[:thetisBoxEdit]
@mail_folder.save
end
render(:partial => 'ajax_folder_name', :layout => false)
end | CWE-89 | 0 |
it "does not remove multiple '../' at the beginning" do
expect(File.cleanpath('../../A/B')).to eq '../../A/B'
end | CWE-22 | 2 |
def edit
Log.add_info(request, params.inspect)
date_s = params[:date]
if date_s.nil? or date_s.empty?
@date = Date.today
date_s = @date.strftime(Schedule::SYS_DATE_FORM)
else
@date = Date.parse(date_s)
end
if params[:user_id].nil?
@selected_user = @login_user
else
@selected_user = User.find(params[:user_id])
end
@timecard = Timecard.get_for(@selected_user.id, date_s)
if @selected_user == @login_user
@schedules = Schedule.get_user_day(@login_user, @date)
end
if !params[:display].nil? and params[:display].split('_').first == 'group'
@group_id = params[:display].split('_').last
end
end | CWE-89 | 0 |
def edit
Log.add_info(request, params.inspect)
@group_id = params[:group_id]
official_title_id = params[:id]
unless official_title_id.nil? or official_title_id.empty?
@official_title = OfficialTitle.find(official_title_id)
end
render(:partial => 'ajax_official_title_form', :layout => (!request.xhr?))
end | CWE-89 | 0 |
def reset_users
Log.add_info(request, params.inspect)
count = 0
unless params[:check_user].nil?
params[:check_user].each do |user_id, value|
if value == '1'
begin
Research.destroy_all('user_id=' + user_id.to_s)
count += 1
rescue => evar
Log.add_error(request, evar)
end
end
end
end
if count > 0
flash[:notice] = t('msg.status_of')+ count.to_s + t('user.status_reset')
end
redirect_to(:controller => 'researches', :action => 'users')
rescue => evar
Log.add_error(request, evar)
render(:text => evar.to_s)
end | CWE-89 | 0 |
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.get_childs(@folder_id, false, true)
end
end
render(:partial => 'ajax_folders_order', :layout => false)
rescue => evar
Log.add_error(request, evar)
render(:partial => 'ajax_folders_order', :layout => false)
end | CWE-89 | 0 |
def self.validate_token(tokens, extra_chars=nil)
if extra_chars.nil?
extra_chars = ''
else
extra_chars = Regexp.escape(extra_chars.join())
end
regexp = Regexp.new("^[ ]*[a-zA-Z0-9_.@\\-#{extra_chars}]+[ ]*$")
[tokens].flatten.each do |token|
next if token.blank?
if token.to_s.match(regexp).nil?
raise("[ERROR] SqlHelper.validate_token failed: #{token}")
end
end
end | CWE-89 | 0 |
def new
@item = Item.new
if params[:folder_id].nil? or params[:folder_id].empty?
my_folder = @login_user.get_my_folder
if my_folder.nil?
@item.folder_id = 0
else
@item.folder_id = my_folder.id
end
else
@item.folder_id = params[:folder_id].to_i
end
@item.xtype= Item::XTYPE_INFO
@item.layout = 'C'
render(:action => 'edit')
end | CWE-89 | 0 |
def bbs
Log.add_info(request, params.inspect)
if !params[:select_sorting].nil?
sort_a = params[:select_sorting].split(' ')
params[:sort_col] = sort_a.first
params[:sort_type] = sort_a.last
end
list
render(:action => 'bbs')
end | CWE-89 | 0 |
def update_config
Log.add_info(request, params.inspect)
@yaml = ApplicationHelper.get_config_yaml
unless params[:desktop].nil? or params[:desktop].empty?
@yaml[:desktop] = Hash.new if @yaml[:desktop].nil?
params[:desktop].each do |key, val|
@yaml[:desktop][key] = val
end
ApplicationHelper.save_config_yaml(@yaml)
end
flash[:notice] = t('msg.update_success')
render(:partial => 'ajax_user_before_login', :layout => false)
end | CWE-89 | 0 |
def test_should_not_fall_for_xss_image_hack_with_uppercase_tags
assert_sanitized %(<IMG """><SCRIPT>alert("XSS")</SCRIPT>">), "<img>\">"
end | CWE-79 | 1 |
def Schema string_or_io
Schema.new(string_or_io)
end | CWE-611 | 13 |
def self.get_from_name(user_name)
SqlHelper.validate_token([user_name])
begin
user = User.where("name='#{user_name}'").first
rescue => evar
Log.add_error(nil, evar)
end
return user
end | CWE-89 | 0 |
def self.from_yaml(input)
Gem.load_yaml
input = normalize_yaml_input input
spec = YAML.load input
if spec && spec.class == FalseClass then
raise Gem::EndOfYAMLException
end
unless Gem::Specification === spec then
raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
end
spec.specification_version ||= NONEXISTENT_SPECIFICATION_VERSION
spec.reset_nil_attributes_to_default
spec
end | CWE-502 | 15 |
def get_order
Log.add_info(request, params.inspect)
mail_account_id = params[:mail_account_id]
@mail_account = MailAccount.find_by_id(mail_account_id)
if @mail_account.user_id != @login_user.id
flash[:notice] = t('msg.need_to_be_owner')
redirect_to(:controller => 'desktop', :action => 'show')
return
end
@mail_filters = MailFilter.get_for(mail_account_id)
render(:partial => 'ajax_order', :layout => false)
rescue => evar
Log.add_error(request, evar)
render(:partial => 'ajax_order', :layout => false)
end | CWE-89 | 0 |
def download(url, remote_headers = {})
headers = remote_headers.
reverse_merge('User-Agent' => "CarrierWave/#{CarrierWave::VERSION}")
begin
file = OpenURI.open_uri(process_uri(url.to_s), headers)
rescue StandardError => e
raise CarrierWave::DownloadError, "could not download file: #{e.message}"
end
CarrierWave::Downloader::RemoteFile.new(file)
end | CWE-918 | 16 |
def _unmarshal(val, options)
unmarshal?(val, options) ? Marshal.load(val) : val
end | CWE-502 | 15 |
def test_parse_memory_nil
assert_raises(ArgumentError) do
@parser.parse_memory(nil)
end
end | CWE-241 | 68 |
it "with Pathname command and params" do
cl = subject.build_command_line(Pathname.new("/usr/bin/ruby"), "-v" => nil)
expect(cl).to eq "/usr/bin/ruby -v"
end | CWE-78 | 6 |
def ajax_delete_items
Log.add_info(request, params.inspect)
folder_id = params[:id]
unless params[:check_item].blank?
is_admin = @login_user.admin?(User::AUTH_ITEM)
count = 0
params[:check_item].each do |item_id, value|
if value == '1'
begin
item = Item.find(item_id)
next if !is_admin and item.user_id != @login_user.id
item.destroy
rescue => evar
Log.add_error(request, evar)
end
count += 1
end
end
flash[:notice] = t('item.deleted', :count => count)
end
get_items
end | CWE-89 | 0 |
def self.load_yaml
return if @yaml_loaded
return unless defined?(gem)
test_syck = ENV['TEST_SYCK']
# Only Ruby 1.8 and 1.9 have syck
test_syck = false unless /^1\./ =~ RUBY_VERSION
unless test_syck
begin
gem 'psych', '>= 1.2.1'
rescue Gem::LoadError
# It's OK if the user does not have the psych gem installed. We will
# attempt to require the stdlib version
end
begin
# Try requiring the gem version *or* stdlib version of psych.
require 'psych'
rescue ::LoadError
# If we can't load psych, thats fine, go on.
else
# If 'yaml' has already been required, then we have to
# be sure to switch it over to the newly loaded psych.
if defined?(YAML::ENGINE) && YAML::ENGINE.yamler != "psych"
YAML::ENGINE.yamler = "psych"
end
require 'rubygems/psych_additions'
require 'rubygems/psych_tree'
end
end
require 'yaml'
# If we're supposed to be using syck, then we may have to force
# activate it via the YAML::ENGINE API.
if test_syck and defined?(YAML::ENGINE)
YAML::ENGINE.yamler = "syck" unless YAML::ENGINE.syck?
end
# Now that we're sure some kind of yaml library is loaded, pull
# in our hack to deal with Syck's DefaultKey ugliness.
require 'rubygems/syck_hack'
@yaml_loaded = true
end | CWE-502 | 15 |
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 | CWE-78 | 6 |
def schedule_all
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
if @login_user.nil? or params[:display].nil? or params[:display] == 'all'
params[:display] = 'all'
con = EquipmentHelper.get_scope_condition_for(@login_user)
else
display_type = params[:display].split('_').first
display_id = params[:display].split('_').last
case display_type
when 'group'
if @login_user.get_groups_a(true).include?(display_id)
con = SqlHelper.get_sql_like([:groups], "|#{display_id}|")
end
when 'team'
if @login_user.get_teams_a.include?(display_id)
con = SqlHelper.get_sql_like([:teams], "|#{display_id}|")
end
end
end | CWE-89 | 0 |
def query
Log.add_info(request, '') # Not to show passwords.
unless @login_user.admin?(User::AUTH_ZEPTAIR)
render(:text => 'ERROR:' + t('msg.need_to_be_admin'))
return
end
target_user = nil
SqlHelper.validate_token([params[:user_id], params[:zeptair_id], params[:group_id]])
unless params[:user_id].blank?
target_user = User.find(params[:user_id])
end
unless params[:zeptair_id].blank?
zeptair_id = params[:zeptair_id]
target_user = User.where("zeptair_id=#{zeptair_id}").first
end
if target_user.nil?
if params[:group_id].blank?
sql = 'select distinct Item.* from items Item, attachments Attachment'
sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
sql << ' order by Item.user_id ASC'
else
group_ids = [params[:group_id]]
if params[:recursive] == 'true'
group_ids += Group.get_childs(params[:group_id], true, false)
end
groups_con = []
group_ids.each do |group_id|
groups_con << SqlHelper.get_sql_like(['User.groups'], "|#{@group_id}|")
end
sql = 'select distinct Item.* from items Item, attachments Attachment, users User'
sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
sql << " and (Item.user_id=User.id and (#{groups_con.join(' or ')}))"
sql << ' order by Item.user_id ASC'
end
@post_items = Item.find_by_sql(sql)
else
@post_item = ZeptairPostHelper.get_item_for(target_user)
end
rescue => evar
Log.add_error(request, evar)
render(:text => 'ERROR:' + t('msg.system_error'))
end | CWE-89 | 0 |
def name
FIELD_NAME_MAP[@name.to_s.downcase] || @name
end | CWE-93 | 33 |
detectMimeType(filename) {
if (!filename) {
return defaultMimeType;
}
let parsed = path.parse(filename);
let extension = (parsed.ext.substr(1) || parsed.name || '')
.split('?')
.shift()
.trim()
.toLowerCase();
let value = defaultMimeType;
if (extensions.has(extension)) {
value = extensions.get(extension);
}
if (Array.isArray(value)) {
return value[0];
}
return value;
}, | CWE-88 | 3 |
it "handles Symbol keys with tailing '='" do
cl = subject.build_command_line("true", :abc= => "def")
expect(cl).to eq "true --abc=def"
end | CWE-78 | 6 |
def update_config
Log.add_info(request, params.inspect)
yaml = ApplicationHelper.get_config_yaml
unless params[:timecard].nil? or params[:timecard].empty?
yaml[:timecard] = Hash.new if yaml[:timecard].nil?
params[:timecard].each do |key, val|
yaml[:timecard][key] = val
end
ApplicationHelper.save_config_yaml(yaml)
end
@yaml_timecard = yaml[:timecard]
@yaml_timecard = Hash.new if @yaml_timecard.nil?
flash[:notice] = t('msg.update_success')
render(:action => 'configure')
end | CWE-89 | 0 |
def test_html5_data_attributes_without_hyphenation
assert_equal("<div data-author_id='123' data-biz='baz' data-foo='bar'></div>\n",
render("%div{:data => {:author_id => 123, :foo => 'bar', :biz => 'baz'}}",
:hyphenate_data_attrs => false))
assert_equal("<div data-one_plus_one='2'></div>\n",
render("%div{:data => {:one_plus_one => 1+1}}",
:hyphenate_data_attrs => false))
assert_equal("<div data-foo='Here's a \"quoteful\" string.'></div>\n",
render(%{%div{:data => {:foo => %{Here's a "quoteful" string.}}}}, | CWE-79 | 1 |
it "should find a user by first name or last name" do
@cur_user.stub(:pref).and_return(:activity_user => 'Billy')
controller.instance_variable_set(:@current_user, @cur_user)
User.should_receive(:where).with("upper(first_name) LIKE upper('%Billy%') OR upper(last_name) LIKE upper('%Billy%')").and_return([@user])
controller.send(:activity_user).should == 1
end | CWE-89 | 0 |
it :test_render_parse_nil_param do
assert_raises(ArgumentError) { parser.parse_memory(nil) }
end | CWE-241 | 68 |
def process_cors(env)
resource, error = match_resource(env)
if resource
Result.hit(env)
cors = resource.to_headers(env)
cors
else
Result.miss(env, error)
nil
end
end | CWE-22 | 2 |
def test_attr_wrapper
assert_equal("<p strange=*attrs*></p>\n", render("%p{ :strange => 'attrs'}", :attr_wrapper => '*'))
assert_equal("<p escaped='quo\"te'></p>\n", render("%p{ :escaped => 'quo\"te'}", :attr_wrapper => '"'))
assert_equal("<p escaped=\"quo'te\"></p>\n", render("%p{ :escaped => 'quo\\'te'}", :attr_wrapper => '"'))
assert_equal("<p escaped=\"q'uo"te\"></p>\n", render("%p{ :escaped => 'q\\'uo\"te'}", :attr_wrapper => '"'))
assert_equal("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n", render("!!! XML", :attr_wrapper => '"', :format => :xhtml))
end | CWE-79 | 1 |
def url_valid?(url)
url = begin
URI.parse(url)
rescue StandardError
false
end
url.is_a?(URI::HTTP) || url.is_a?(URI::HTTPS)
end | CWE-79 | 1 |
def show_tree
if params[:action] == 'show_tree'
Log.add_info(request, params.inspect)
end
con = []
con << "(user_id=#{@login_user.id})"
account_xtype = params[:mail_account_xtype]
unless account_xtype.blank?
SqlHelper.validate_token([account_xtype])
con << "(xtype='#{account_xtype}')"
end
@mail_accounts = MailAccount.find_all(con.join(' and '))
mail_account_ids = []
@mail_accounts.each do |mail_account|
mail_account_ids << mail_account.id
if MailFolder.where("mail_account_id=#{mail_account.id}").count <= 0
@login_user.create_default_mail_folders(mail_account.id)
end
Email.destroy_by_user(@login_user.id, "status='#{Email::STATUS_TEMPORARY}'")
end
@folder_tree = MailFolder.get_tree_for(@login_user, mail_account_ids)
end | CWE-89 | 0 |
def test_full_sanitize_allows_turning_off_encoding_special_chars
assert_equal '&', full_sanitize('&')
assert_equal '&', full_sanitize('&', encode_special_chars: false)
end | CWE-79 | 1 |
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-79 | 1 |
def generate(type, str)
case type
when :md5
attribute_value = '{MD5}' + Base64.encode64(Digest::MD5.digest(str)).chomp!
when :sha
attribute_value = '{SHA}' + Base64.encode64(Digest::SHA1.digest(str)).chomp!
when :ssha
srand; salt = (rand * 1000).to_i.to_s
attribute_value = '{SSHA}' + Base64.encode64(Digest::SHA1.digest(str + salt) + salt).chomp!
else
raise Net::LDAP::HashTypeUnsupportedError, "Unsupported password-hash type (#{type})"
end | CWE-916 | 34 |
it 'returns correct link' do
data = {
cutoff: false,
user: 'Julia Nguyen',
comment: 'Hello',
typename: 'typename',
type: 'type_comment_moment',
typeid: 1,
commentable_id: 1
}
expect(comment_link(uniqueid, data)).to eq('<a id="uniqueid" href="/moments/1">Julia Nguyen commented "Hello" on typename</a>')
end | CWE-79 | 1 |
def sanitize(params)
return [] if params.nil? || params.empty?
params.collect do |k, v|
[sanitize_key(k), sanitize_value(v)]
end
end | CWE-78 | 6 |
def self.applied_paid_hlds(user_id, start_date, end_date)
SqlHelper.validate_token([user_id, start_date, end_date])
sql = "SELECT COUNT(*) FROM timecards WHERE user_id = #{user_id} AND date >= '#{start_date}' AND date <= '#{end_date}'"
sum = 0.0
self.workcodes.each do |key, params|
paidhld_rate = params[WKCODE_PARAM_PAIDHLD]
if paidhld_rate > 0.0
num = Timecard.count_by_sql(sql + " AND workcode='#{key}'")
sum += num * paidhld_rate
end
end
return sum
end | CWE-89 | 0 |
def test_extract_symlink_parent
skip 'symlink not supported' if Gem.win_platform?
package = Gem::Package.new @gem
tgz_io = util_tar_gz do |tar|
tar.mkdir 'lib', 0755
tar.add_symlink 'lib/link', '../..', 0644
tar.add_file 'lib/link/outside.txt', 0644 do |io| io.write 'hi' end
end
# Extract into a subdirectory of @destination; if this test fails it writes
# a file outside destination_subdir, but we want the file to remain inside
# @destination so it will be cleaned up.
destination_subdir = File.join @destination, 'subdir'
FileUtils.mkdir_p destination_subdir
e = assert_raises Gem::Package::PathError do
package.extract_tar_gz tgz_io, destination_subdir
end
assert_equal("installing into parent path ../outside.txt of " +
"#{destination_subdir} is not allowed", e.message)
end | CWE-22 | 2 |
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 | CWE-79 | 1 |
it "with dofollowify enabled, links should be nofollowed" do
@blog.dofollowify = true
@blog.save
expect(nofollowify_links('<a href="http://myblog.net">my blog</a>')).
to eq('<a href="http://myblog.net">my blog</a>')
end | CWE-79 | 1 |
def self.get_my_folder(user_id)
return Folder.where("(owner_id=#{user_id}) and (xtype='#{Folder::XTYPE_USER}')").first
end | CWE-89 | 0 |
def destroy
current_user.invalidate_all_sessions!
super
end | CWE-613 | 7 |
def self.generate_key_pair(key_base_name, recipient, real_name)
public_key_file_name = "#{key_base_name}.pub"
private_key_file_name = "#{key_base_name}.sec"
script = generate_key_script(public_key_file_name, private_key_file_name, recipient, real_name)
script_file = Tempfile.new('gpg-script')
begin
script_file.write(script)
script_file.close
result = system("gpg --batch --gen-key #{script_file.path}")
raise RuntimeError.new('gpg failed') unless result
ensure
script_file.close
script_file.unlink
end
end | CWE-94 | 14 |
it "returns the right category group permissions for an anon user" do
json = described_class.new(category, scope: Guardian.new, root: false).as_json
expect(json[:group_permissions]).to eq([
{ permission_type: CategoryGroup.permission_types[:full], group_name: Group[:everyone]&.name }
])
end | CWE-276 | 45 |
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], group_name: group.name },
{ permission_type: CategoryGroup.permission_types[:full], group_name: private_group.name },
{ permission_type: CategoryGroup.permission_types[:full], group_name: user_group.name },
{ permission_type: CategoryGroup.permission_types[:readonly], group_name: 'everyone' },
])
end | CWE-276 | 45 |
def stub_bad_jwks
stub_request(:get, 'https://samples.auth0.com/.well-known/jwks-bad.json')
.to_return(
status: 404
)
end | CWE-347 | 25 |
func validateWebhook(actor *db.User, l macaron.Locale, w *db.Webhook) (field, msg string, ok bool) {
if !actor.IsAdmin {
// 🚨 SECURITY: Local addresses must not be allowed by non-admins to prevent SSRF,
// see https://github.com/gogs/gogs/issues/5366 for details.
payloadURL, err := url.Parse(w.URL)
if err != nil {
return "PayloadURL", l.Tr("repo.settings.webhook.err_cannot_parse_payload_url", err), false
}
if netutil.IsLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) {
return "PayloadURL", l.Tr("repo.settings.webhook.err_cannot_use_local_addresses"), false
}
}
return "", "", true
} | CWE-918 | 16 |
func (v *validator) ValidateSignature(auth kolide.Auth) (kolide.Auth, error) {
info := auth.(*resp)
status, err := info.status()
if err != nil {
return nil, errors.New("missing or malformed response")
}
if status != Success {
return nil, errors.Errorf("response status %s", info.statusDescription())
}
decoded, err := base64.StdEncoding.DecodeString(info.rawResponse())
if err != nil {
return nil, errors.Wrap(err, "based64 decoding response")
}
doc := etree.NewDocument()
err = doc.ReadFromBytes(decoded)
if err != nil || doc.Root() == nil {
return nil, errors.Wrap(err, "parsing xml response")
}
elt := doc.Root()
signed, err := v.validateSignature(elt)
if err != nil {
return nil, errors.Wrap(err, "signing verification failed")
}
// We've verified that the response hasn't been tampered with at this point
signedDoc := etree.NewDocument()
signedDoc.SetRoot(signed)
buffer, err := signedDoc.WriteToBytes()
if err != nil {
return nil, errors.Wrap(err, "creating signed doc buffer")
}
var response Response
err = xml.Unmarshal(buffer, &response)
if err != nil {
return nil, errors.Wrap(err, "unmarshalling signed doc")
}
info.setResponse(&response)
return info, nil
} | CWE-290 | 85 |
func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
// Logic based on response type or status
if noBodyExpected(requestMethod) {
return 0, nil
}
if status/100 == 1 {
return 0, nil
}
switch status {
case 204, 304:
return 0, nil
}
// Logic based on Transfer-Encoding
if chunked(te) {
return -1, nil
}
// Logic based on Content-Length
cl := strings.TrimSpace(header.get("Content-Length"))
if cl != "" {
n, err := parseContentLength(cl)
if err != nil {
return -1, err
}
return n, nil
} else {
header.Del("Content-Length")
}
if !isResponse && requestMethod == "GET" {
// RFC 2616 doesn't explicitly permit nor forbid an
// entity-body on a GET request so we permit one if
// declared, but we default to 0 here (not -1 below)
// if there's no mention of a body.
return 0, nil
}
// Body-EOF logic based on other methods (like closing, or chunked coding)
return -1, nil
} | CWE-444 | 41 |
func (*UpdateAccountRequest) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{36}
} | CWE-613 | 7 |
func (x *DeleteStorageObjectRequest) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[21]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | CWE-613 | 7 |
func (*ListPurchasesRequest) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{28}
} | CWE-613 | 7 |
func (mbox *Mailbox) newClient() (*client.Client, error) {
var imapClient *client.Client
var err error
if mbox.TLS {
config := new(tls.Config)
config.InsecureSkipVerify = mbox.IgnoreCertErrors
imapClient, err = client.DialTLS(mbox.Host, config)
} else {
imapClient, err = client.Dial(mbox.Host)
}
if err != nil {
return imapClient, err
}
err = imapClient.Login(mbox.User, mbox.Pwd)
if err != nil {
return imapClient, err
}
_, err = imapClient.Select(mbox.Folder, mbox.ReadOnly)
if err != nil {
return imapClient, err
}
return imapClient, nil
} | CWE-918 | 16 |
func (x *UpdateAccountRequest) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[36]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | CWE-613 | 7 |
func (*LeaderboardRequest) Descriptor() ([]byte, []int) {
return file_console_proto_rawDescGZIP(), []int{25}
} | CWE-613 | 7 |
func (p *BinaryProtocol) readStringBody(size int32) (value string, err error) {
if size < 0 {
return "", nil
}
if uint64(size) > p.trans.RemainingBytes() {
return "", invalidDataLength
}
var buf []byte
if int(size) <= len(p.buffer) {
buf = p.buffer[0:size]
} else {
buf = make([]byte, size)
}
_, e := io.ReadFull(p.trans, buf)
return string(buf), NewProtocolException(e)
} | CWE-770 | 37 |
func isRepositoryGitPath(path string) bool {
return strings.HasSuffix(path, ".git") ||
strings.Contains(path, ".git"+string(os.PathSeparator)) ||
// Windows treats ".git." the same as ".git"
strings.HasSuffix(path, ".git.") ||
strings.Contains(path, ".git."+string(os.PathSeparator))
} | CWE-78 | 6 |
func (p *HTTPClient) closeResponse() error {
var err error
if p.response != nil && p.response.Body != nil {
// The docs specify that if keepalive is enabled and the response body is not
// read to completion the connection will never be returned to the pool and
// reused. Errors are being ignored here because if the connection is invalid
// and this fails for some reason, the Close() method will do any remaining
// cleanup.
io.Copy(ioutil.Discard, p.response.Body)
err = p.response.Body.Close()
}
p.response = nil
return err
} | CWE-770 | 37 |
func (x *UnlinkDeviceRequest) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[35]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | CWE-613 | 7 |
func (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error {
switch m.Device {
case "cgroup":
// No mount point(s) need to be created:
//
// * for v1, mount points are saved by CRIU because
// /sys/fs/cgroup is a tmpfs mount
//
// * for v2, /sys/fs/cgroup is a real mount, but
// the mountpoint appears as soon as /sys is mounted
return nil
case "bind":
// The prepareBindMount() function checks if source
// exists. So it cannot be used for other filesystem types.
if err := prepareBindMount(m, c.config.Rootfs); err != nil {
return err
}
default:
// for all other filesystems just create the mountpoints
dest, err := securejoin.SecureJoin(c.config.Rootfs, m.Destination)
if err != nil {
return err
}
if err := checkProcMount(c.config.Rootfs, dest, ""); err != nil {
return err
}
if err := os.MkdirAll(dest, 0o755); err != nil {
return err
}
}
return nil
} | CWE-190 | 19 |
func (x *RuntimeInfo) Reset() {
*x = RuntimeInfo{}
if protoimpl.UnsafeEnabled {
mi := &file_console_proto_msgTypes[41]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
} | CWE-613 | 7 |
func TestResourceServer_ValidateAccessToken(t *testing.T) {
r := newMockResourceServer(t)
_, err := r.ValidateAccessToken(context.Background(), "myserver", sampleIDToken)
assert.Error(t, err)
} | CWE-613 | 7 |
func TestEscapeJSONString(t *testing.T) {
for _, str := range []string{"", "foobar", `foo"bar`, `foo\bar`, "foo\n\tbar"} {
escaped := EscapeJSONString(str)
var unmarshaled string
err := json.Unmarshal([]byte(`"` + escaped + `"`), &unmarshaled)
require.NoError(t, err, str)
assert.Equal(t, str, unmarshaled, str)
}
} | CWE-178 | 40 |
func TestCORSFilter_AllowedDomains(t *testing.T) {
for _, each := range allowedDomainInput {
tearDown()
ws := new(WebService)
ws.Route(ws.PUT("/cors").To(dummy))
Add(ws)
cors := CrossOriginResourceSharing{
AllowedDomains: each.domains,
CookiesAllowed: true,
Container: DefaultContainer}
Filter(cors.Filter)
httpRequest, _ := http.NewRequest("PUT", "http://api.his.com/cors", nil)
httpRequest.Header.Set(HEADER_Origin, each.origin)
httpWriter := httptest.NewRecorder()
DefaultContainer.Dispatch(httpWriter, httpRequest)
actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin)
if actual != each.origin && each.allowed {
t.Fatal("expected to be accepted")
}
if actual == each.origin && !each.allowed {
t.Fatal("did not expect to be accepted")
}
}
} | CWE-639 | 9 |
func (x *UserList) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[39]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | CWE-613 | 7 |
func (x *CallApiEndpointRequest) ProtoReflect() protoreflect.Message {
mi := &file_console_proto_msgTypes[12]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
} | CWE-613 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.