diff --git a/.rubocop/cop/zammad/forbid_rand.rb b/.rubocop/cop/zammad/forbid_rand.rb new file mode 100644 index 000000000..c3f5151d4 --- /dev/null +++ b/.rubocop/cop/zammad/forbid_rand.rb @@ -0,0 +1,20 @@ +# Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/ + +module RuboCop + module Cop + module Zammad + class ForbidRand < Base + MSG = <<~ERROR_MESSAGE.freeze + Please avoid 'rand' if possible. It does not guarantee uniqueness which means that there is a risk of collisions. Possible alternatives: + - If you need unique values, consider using 'SecureRandom.uuid'. + - To randomly select a value from a list, use [].sample. + - To generate random test data that does not need to be unique, you can use 'Faker::*'. + ERROR_MESSAGE + + def on_send(node) + add_offense(node) if node.method_name.eql? :rand + end + end + end + end +end diff --git a/.rubocop/rubocop_zammad.rb b/.rubocop/rubocop_zammad.rb index f525ef923..f3e8764cd 100644 --- a/.rubocop/rubocop_zammad.rb +++ b/.rubocop/rubocop_zammad.rb @@ -9,3 +9,4 @@ require_relative 'cop/zammad/have_no_over_not_to' require_relative 'cop/zammad/no_to_sym_on_string' require_relative 'cop/zammad/prefer_negated_if_over_unless' require_relative 'cop/zammad/update_copyright' +require_relative 'cop/zammad/forbid_rand' diff --git a/app/controllers/long_polling_controller.rb b/app/controllers/long_polling_controller.rb index 5aa4a5ab5..d64230453 100644 --- a/app/controllers/long_polling_controller.rb +++ b/app/controllers/long_polling_controller.rb @@ -97,7 +97,7 @@ class LongPollingController < ApplicationController private def client_id_gen - rand(9_999_999_999).to_s + SecureRandom.uuid end def client_id_verify diff --git a/app/models/channel/driver/sms/message_bird.rb b/app/models/channel/driver/sms/message_bird.rb index be885eb24..2efb7052e 100644 --- a/app/models/channel/driver/sms/message_bird.rb +++ b/app/models/channel/driver/sms/message_bird.rb @@ -89,7 +89,7 @@ class Channel::Driver::Sms::MessageBird < Channel::Driver::Sms::Base name: 'message_bird', adapter: 'sms/message_bird', account: [ - { name: 'options::webhook_token', display: 'Webhook Token', tag: 'input', type: 'text', limit: 200, null: false, default: Digest::MD5.hexdigest(rand(999_999_999_999).to_s), disabled: true, readonly: true }, + { name: 'options::webhook_token', display: 'Webhook Token', tag: 'input', type: 'text', limit: 200, null: false, default: Digest::MD5.hexdigest(SecureRandom.uuid), disabled: true, readonly: true }, { name: 'options::token', display: 'Token', tag: 'input', type: 'text', limit: 255, null: false }, { name: 'options::sender', display: 'Sender', tag: 'input', type: 'text', limit: 200, null: false, placeholder: '+491710000000' }, { name: 'group_id', display: 'Destination Group', tag: 'select', null: false, relation: 'Group', nulloption: true, filter: { active: true } }, diff --git a/app/models/channel/driver/sms/twilio.rb b/app/models/channel/driver/sms/twilio.rb index aac66f396..a618fa134 100644 --- a/app/models/channel/driver/sms/twilio.rb +++ b/app/models/channel/driver/sms/twilio.rb @@ -100,7 +100,7 @@ class Channel::Driver::Sms::Twilio < Channel::Driver::Sms::Base name: 'twilio', adapter: 'sms/twilio', account: [ - { name: 'options::webhook_token', display: 'Webhook Token', tag: 'input', type: 'text', limit: 200, null: false, default: Digest::MD5.hexdigest(rand(999_999_999_999).to_s), disabled: true, readonly: true }, + { name: 'options::webhook_token', display: 'Webhook Token', tag: 'input', type: 'text', limit: 200, null: false, default: Digest::MD5.hexdigest(SecureRandom.uuid), disabled: true, readonly: true }, { name: 'options::account_id', display: 'Account SID', tag: 'input', type: 'text', limit: 200, null: false, placeholder: 'XXXXXX' }, { name: 'options::token', display: 'Token', tag: 'input', type: 'text', limit: 200, null: false }, { name: 'options::sender', display: 'Sender', tag: 'input', type: 'text', limit: 200, null: false, placeholder: '+491710000000' }, diff --git a/app/models/chat/session.rb b/app/models/chat/session.rb index aab42f497..5b3e5559b 100644 --- a/app/models/chat/session.rb +++ b/app/models/chat/session.rb @@ -40,7 +40,7 @@ class Chat::Session < ApplicationModel end def generate_session_id - self.session_id = Digest::MD5.hexdigest(Time.zone.now.to_s + rand(99_999_999_999_999).to_s) + self.session_id = Digest::MD5.hexdigest(SecureRandom.uuid) end def add_recipient(client_id, store = false) diff --git a/app/models/cti/driver/base.rb b/app/models/cti/driver/base.rb index 8bd45a70e..4de2ce046 100644 --- a/app/models/cti/driver/base.rb +++ b/app/models/cti/driver/base.rb @@ -156,7 +156,7 @@ class Cti::Driver::Base end end - id = rand(999_999_999) + id = SecureRandom.uuid PushMessages.send_to(user.id, { event: 'remote_task', data: { diff --git a/app/models/cti/log.rb b/app/models/cti/log.rb index 0ced08b9d..175e82fed 100644 --- a/app/models/cti/log.rb +++ b/app/models/cti/log.rb @@ -93,7 +93,7 @@ example data, can be used for demo from_comment: 'Franz Bauer', to: '4930609811111', to_comment: 'Bob Smith', - call_id: rand(999_999_999), + call_id: SecureRandom.uuid, comment: '', state: 'newCall', done: true, @@ -118,7 +118,7 @@ example data, can be used for demo from_comment: 'Franz Bauer', to: '4930609811111', to_comment: 'Bob Smith', - call_id: rand(999_999_999), + call_id: SecureRandom.uuid, comment: '', state: 'answer', done: true, @@ -146,7 +146,7 @@ example data, can be used for demo from_comment: 'Franz Bauer', to: '4930609811111', to_comment: 'Bob Smith', - call_id: rand(999_999_999), + call_id: SecureRandom.uuid, comment: '', state: 'hangup', comment: 'normalClearing', @@ -177,7 +177,7 @@ example data, can be used for demo from_comment: 'Franz Bauer', to: '4930609811111', to_comment: 'Bob Smith', - call_id: rand(999_999_999), + call_id: SecureRandom.uuid, comment: '', state: 'hangup', done: true, @@ -209,7 +209,7 @@ example data, can be used for demo from_comment: 'Franz Bauer', to: '4930609811111', to_comment: '', - call_id: rand(999_999_999), + call_id: SecureRandom.uuid, comment: '', state: 'hangup', done: true, @@ -241,7 +241,7 @@ example data, can be used for demo from_comment: 'Franz Bauer', to: '4930609811111', to_comment: 'Bob Smith', - call_id: rand(999_999_999), + call_id: SecureRandom.uuid, comment: '', state: 'hangup', done: true, @@ -271,7 +271,7 @@ example data, can be used for demo direction: 'in', from: '4930609854180', to: '4930609811112', - call_id: rand(999_999_999), + call_id: SecureRandom.uuid, comment: '', state: 'hangup', done: true, diff --git a/app/models/overview.rb b/app/models/overview.rb index 1947cd48f..1f2b81ea5 100644 --- a/app/models/overview.rb +++ b/app/models/overview.rb @@ -102,7 +102,7 @@ class Overview < ApplicationModel local_link.squeeze!('_') local_link = CGI.escape(local_link) if local_link.blank? - local_link = id || rand(999) + local_link = id || SecureRandom.uuid end check = true count = 0 diff --git a/app/models/setting.rb b/app/models/setting.rb index 63981d60e..99ca82c1b 100644 --- a/app/models/setting.rb +++ b/app/models/setting.rb @@ -140,7 +140,7 @@ reload config settings def reset_change_id @@current[name] = state_current[:value] - change_id = rand(999_999_999).to_s + change_id = SecureRandom.uuid logger.debug { "Setting.reset_change_id: set new cache, #{change_id}" } Cache.write('Setting::ChangeId', change_id, { expires_in: 24.hours }) @@lookup_at = nil # rubocop:disable Style/ClassVars diff --git a/app/models/ticket/article/adds_metadata_email.rb b/app/models/ticket/article/adds_metadata_email.rb index 4d7d805b0..7a2ebeaa1 100644 --- a/app/models/ticket/article/adds_metadata_email.rb +++ b/app/models/ticket/article/adds_metadata_email.rb @@ -45,7 +45,7 @@ module Ticket::Article::AddsMetadataEmail # generate message id, force it in production, in test allow to set it for testing reasons if !message_id || Rails.env.production? fqdn = Setting.get('fqdn') - self.message_id = "<#{DateTime.current.to_s(:number)}.#{ticket_id}.#{rand(999_999_999_999)}@#{fqdn}>" + self.message_id = "<#{DateTime.current.to_s(:number)}.#{ticket_id}.#{SecureRandom.uuid}@#{fqdn}>" end # generate message_id_md5 diff --git a/app/models/transaction/notification.rb b/app/models/transaction/notification.rb index 7ede5f1fa..3e89d8ef5 100644 --- a/app/models/transaction/notification.rb +++ b/app/models/transaction/notification.rb @@ -223,7 +223,7 @@ class Transaction::Notification changes: changes, reason: recipients_reason[user.id], }, - message_id: "", + message_id: "", references: ticket.get_references, main_object: ticket, attachments: attachments, diff --git a/app/models/user.rb b/app/models/user.rb index a80b81415..1816f11d6 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -920,7 +920,7 @@ try to find correct name # generate auto login if login.blank? - self.login = "auto-#{Time.zone.now.to_i}-#{rand(999_999)}" + self.login = "auto-#{SecureRandom.uuid}" end # check if login already exists @@ -929,7 +929,7 @@ try to find correct name while check exists = User.find_by(login: login) if exists && exists.id != id - self.login = "#{login}#{rand(999)}" + self.login = "#{login}#{rand(999)}" # rubocop:disable Zammad/ForbidRand else check = false end diff --git a/db/seeds/settings.rb b/db/seeds/settings.rb index 681180126..772cb2730 100644 --- a/db/seeds/settings.rb +++ b/db/seeds/settings.rb @@ -230,7 +230,7 @@ options = {} (10..99).each do |item| options[item] = item end -system_id = rand(10..99) +system_id = rand(10..99) # rubocop:disable Zammad/ForbidRand Setting.create_if_not_exists( title: 'SystemID', name: 'system_id', diff --git a/lib/email_helper/verify.rb b/lib/email_helper/verify.rb index 191f489cf..bbcb46c57 100644 --- a/lib/email_helper/verify.rb +++ b/lib/email_helper/verify.rb @@ -58,7 +58,7 @@ or def self.email(params) # send verify email - subject = params[:subject].presence || "##{rand(99_999_999_999)}" + subject = params[:subject].presence || "##{SecureRandom.hex(10)}" result = EmailHelper::Probe.outbound(params[:outbound], params[:sender], subject) if result[:result] != 'ok' result[:source] = 'outbound' diff --git a/lib/external_credential/facebook.rb b/lib/external_credential/facebook.rb index aaa212fa1..eb31e7f58 100644 --- a/lib/external_credential/facebook.rb +++ b/lib/external_credential/facebook.rb @@ -29,7 +29,7 @@ class ExternalCredential::Facebook ExternalCredential.callback_url('facebook'), ) oauth.get_app_access_token.inspect - state = rand(999_999_999_999).to_s + state = SecureRandom.uuid { request_token: state, # authorize_url: oauth.url_for_oauth_code(permissions: 'publish_pages, manage_pages, user_posts', state: state), diff --git a/lib/fill_db.rb b/lib/fill_db.rb index 2abd55a98..53df6acf3 100644 --- a/lib/fill_db.rb +++ b/lib/fill_db.rb @@ -1,5 +1,7 @@ # Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/ +require 'faker' + # rubocop:disable Rails/Output module FillDb @@ -53,7 +55,7 @@ or if you only want to create 100 tickets else (1..organizations).each do ActiveRecord::Base.transaction do - organization = Organization.create!(name: "FillOrganization::#{rand(999_999)}", active: true) + organization = Organization.create!(name: "FillOrganization::#{Faker::Number.number(digits: 6)}", active: true) organization_pool.push organization end end @@ -70,7 +72,7 @@ or if you only want to create 100 tickets (1..agents).each do ActiveRecord::Base.transaction do - suffix = rand(99_999).to_s + suffix = Faker::Number.number(digits: 5).to_s user = User.create_or_update( login: "filldb-agent-#{suffix}", firstname: "agent #{suffix}", @@ -96,12 +98,14 @@ or if you only want to create 100 tickets roles = Role.where(name: [ 'Customer']) groups_all = Group.all + true_or_false = [true, false] + (1..customers).each do ActiveRecord::Base.transaction do - suffix = rand(99_999).to_s + suffix = Faker::Number.number(digits: 5).to_s organization = nil - if organization_pool.present? && rand(2) == 1 - organization = organization_pool[ organization_pool.length - 1 ] + if organization_pool.present? && true_or_false.sample + organization = organization_pool.sample end user = User.create_or_update( login: "filldb-customer-#{suffix}", @@ -128,7 +132,7 @@ or if you only want to create 100 tickets else (1..groups).each do ActiveRecord::Base.transaction do - group = Group.create!(name: "FillGroup::#{rand(999_999)}", active: true) + group = Group.create!(name: "FillGroup::#{Faker::Number.number(digits: 6)}", active: true) group_pool.push group Role.where(name: 'Agent').first.users.where(active: true).each do |user| user_groups = user.groups @@ -146,7 +150,7 @@ or if you only want to create 100 tickets (1..overviews).each do ActiveRecord::Base.transaction do Overview.create!( - name: "Filloverview::#{rand(999_999)}", + name: "Filloverview::#{Faker::Number.number(digits: 6)}", role_ids: [Role.find_by(name: 'Agent').id], condition: { 'ticket.state_id' => { @@ -178,15 +182,15 @@ or if you only want to create 100 tickets (1..tickets).each do ActiveRecord::Base.transaction do - customer = customer_pool[ rand(customer_pool.length - 1) ] - agent = agent_pool[ rand(agent_pool.length - 1) ] + customer = customer_pool.sample + agent = agent_pool.sample ticket = Ticket.create!( - title: "some title äöüß#{rand(999_999)}", - group: group_pool[ rand(group_pool.length - 1) ], + title: "some title äöüß#{Faker::Number.number(digits: 6)}", + group: group_pool.sample, customer: customer, owner: agent, - state: state_pool[ rand(state_pool.length - 1) ], - priority: priority_pool[ rand(priority_pool.length - 1) ], + state: state_pool.sample, + priority: priority_pool.sample, updated_by_id: agent.id, created_by_id: agent.id, ) @@ -196,8 +200,8 @@ or if you only want to create 100 tickets ticket_id: ticket.id, from: customer.email, to: 'some_recipient@example.com', - subject: "some subject#{rand(999_999)}", - message_id: "some@id-#{rand(999_999)}", + subject: "some subject#{Faker::Number.number(digits: 6)}", + message_id: "some@id-#{Faker::Number.number(digits: 6)}", body: 'some message ...', internal: false, sender: Ticket::Article::Sender.where(name: 'Customer').first, diff --git a/lib/html_sanitizer.rb b/lib/html_sanitizer.rb index bfdd92955..2ca0819b9 100644 --- a/lib/html_sanitizer.rb +++ b/lib/html_sanitizer.rb @@ -415,7 +415,7 @@ reolace inline images with cid images =end - def self.replace_inline_images(string, prefix = rand(999_999_999)) + def self.replace_inline_images(string, prefix = SecureRandom.uuid) fqdn = Setting.get('fqdn') attachments_inline = [] filename_counter = 0 @@ -424,7 +424,7 @@ reolace inline images with cid images if node['src'] && node['src'] =~ %r{^(data:image/(jpeg|png);base64,.+?)$}i filename_counter += 1 file_attributes = StaticAssets.data_url_attributes($1) - cid = "#{prefix}.#{rand(999_999_999)}@#{fqdn}" + cid = "#{prefix}.#{SecureRandom.uuid}@#{fqdn}" filename = cid if file_attributes[:file_extention].present? filename = "image#{filename_counter}.#{file_attributes[:file_extention]}" diff --git a/lib/import/otrs/article/attachment_factory.rb b/lib/import/otrs/article/attachment_factory.rb index ef0b8c303..3342870ae 100644 --- a/lib/import/otrs/article/attachment_factory.rb +++ b/lib/import/otrs/article/attachment_factory.rb @@ -26,40 +26,24 @@ module Import decoded_filename = Base64.decode64(attachment['Filename']) decoded_content = Base64.decode64(attachment['Content']) - # TODO: should be done by a/the Storage object - # to handle fingerprinting - sha = Digest::SHA256.hexdigest(decoded_content) - retries = 3 - begin - queueing(sha, decoded_filename) + # rubocop:disable Style/ClassVars + @@mutex ||= Mutex.new + @@mutex.synchronize do + # rubocop:enable Style/ClassVars - log "Ticket #{local_article.ticket_id}, Article #{local_article.id} - Starting import for fingerprint #{sha} (#{decoded_filename})... Queue: #{@sha_queue[sha]}." - ActiveRecord::Base.transaction do - Store.add( - object: 'Ticket::Article', - o_id: local_article.id, - filename: decoded_filename.force_encoding('utf-8'), - data: decoded_content, - preferences: { - 'Mime-Type' => attachment['ContentType'], - 'Content-ID' => attachment['ContentID'], - 'content-alternative' => attachment['ContentAlternative'], - }, - created_by_id: 1, - ) - end - log "Ticket #{local_article.ticket_id}, Article #{local_article.id} - Finished import for fingerprint #{sha} (#{decoded_filename})... Queue: #{@sha_queue[sha]}." - rescue ActiveRecord::RecordNotUnique, ActiveRecord::StatementInvalid => e - log "Ticket #{local_article.ticket_id} - #{sha} - #{e.class}: #{e}" - sleep rand 3 - retry if !(retries -= 1).zero? - raise - rescue => e - log "Ticket #{local_article.ticket_id} - #{sha} - #{e}: #{attachment.inspect}" - raise - ensure - queue_cleanup(sha) + Store.add( + object: 'Ticket::Article', + o_id: local_article.id, + filename: decoded_filename.force_encoding('utf-8'), + data: decoded_content, + preferences: { + 'Mime-Type' => attachment['ContentType'], + 'Content-ID' => attachment['ContentID'], + 'content-alternative' => attachment['ContentAlternative'], + }, + created_by_id: 1, + ) end end @@ -73,40 +57,6 @@ module Import false end - - def queueing(sha, decoded_filename) - # this is (currently) needed for avoiding - # race conditions inserting attachments with - # the same fingerprint in the DB in concurrent threads - @sha_queue ||= {} - @sha_queue[sha] ||= [] - - return if !queueing_active? - - @sha_queue[sha].push(queue_id) - - while @sha_queue[sha].first != queue_id - sleep_time = 0.25 - log "Found active import for fingerprint #{sha} (#{decoded_filename})... sleeping #{sleep_time} seconds. Queue: #{@sha_queue[sha]}." - sleep sleep_time - end - end - - def queue_cleanup(sha) - return if !queueing_active? - - @sha_queue[sha].shift - end - - def queueing_active? - return if !queue_id - - true - end - - def queue_id - Thread.current[:thread_no] - end end end end diff --git a/lib/import/otrs/article_customer.rb b/lib/import/otrs/article_customer.rb index 03be17bb4..03ce2292e 100644 --- a/lib/import/otrs/article_customer.rb +++ b/lib/import/otrs/article_customer.rb @@ -11,6 +11,10 @@ module Import log "ERROR: Can't extract customer from Article #{article[:id]}" end + def self.mutex + @mutex ||= Mutex.new + end + class << self def find(article) @@ -48,9 +52,11 @@ module Import end def find_or_create(article) - return if self.class.find(article) + self.class.mutex.synchronize do + return if self.class.find(article) - create(article) + create(article) + end end def create(article) @@ -66,14 +72,6 @@ module Import updated_by_id: 1, created_by_id: 1, ) - rescue ActiveRecord::RecordNotUnique - log "User #{email} was handled by another thread, taking this." - - return if self.class.find(article) - - log "User #{email} wasn't created sleep and retry." - sleep rand 3 - retry end def roles diff --git a/lib/search_index_backend.rb b/lib/search_index_backend.rb index ddbad655d..be4af611b 100644 --- a/lib/search_index_backend.rb +++ b/lib/search_index_backend.rb @@ -1140,7 +1140,7 @@ helper method for making HTTP calls and raising error if response was not succes def self.pipeline(create: false) pipeline = Setting.get('es_pipeline') if create && pipeline.blank? - pipeline = "zammad#{rand(999_999_999_999)}" + pipeline = "zammad#{SecureRandom.uuid}" Setting.set('es_pipeline', pipeline) end pipeline diff --git a/lib/sequencer/state.rb b/lib/sequencer/state.rb index 9f770eab3..480c6b9ac 100644 --- a/lib/sequencer/state.rb +++ b/lib/sequencer/state.rb @@ -32,7 +32,7 @@ class Sequencer # # @example # state.provide(:sum) do - # some_value = rand(100) + # some_value = ... # some_value * 3 # end # diff --git a/lib/sessions/store/file.rb b/lib/sessions/store/file.rb index b89f5a6a8..4d63134a0 100644 --- a/lib/sessions/store/file.rb +++ b/lib/sessions/store/file.rb @@ -141,7 +141,7 @@ class Sessions::Store::File path = "#{@path}/spool/" FileUtils.mkpath path - file_path = "#{path}/#{Time.now.utc.to_f}-#{rand(99_999)}" + file_path = "#{path}/#{Time.now.utc.to_f}-#{SecureRandom.uuid}" write_with_lock(file_path, data.to_json) end diff --git a/spec/factories/ticket/flag.rb b/spec/factories/ticket/flag.rb index 6990dcebd..f5b95dc84 100644 --- a/spec/factories/ticket/flag.rb +++ b/spec/factories/ticket/flag.rb @@ -3,8 +3,8 @@ FactoryBot.define do factory :'ticket/flag', aliases: %i[ticket_flag] do ticket - key { "key_#{rand(100)}" } - value { "value_#{rand(100)}" } + key { "key_#{Faker::Food.fruits}" } + value { "value_#{Faker::Food.fruits}" } created_by_id { 1 } end end diff --git a/spec/factories/ticket/time_accounting.rb b/spec/factories/ticket/time_accounting.rb index 0bfdc454b..33c1632e0 100644 --- a/spec/factories/ticket/time_accounting.rb +++ b/spec/factories/ticket/time_accounting.rb @@ -3,7 +3,7 @@ FactoryBot.define do factory :'ticket/time_accounting', aliases: %i[ticket_time_accounting] do ticket - time_unit { rand(1..100) } + time_unit { Faker::Number.number(digits: 2) } created_by_id { 1 } trait :for_article do diff --git a/spec/lib/sessions/event/chat_agent_state_spec.rb b/spec/lib/sessions/event/chat_agent_state_spec.rb index d9285e009..22cd2abc6 100644 --- a/spec/lib/sessions/event/chat_agent_state_spec.rb +++ b/spec/lib/sessions/event/chat_agent_state_spec.rb @@ -4,7 +4,7 @@ require 'rails_helper' RSpec.describe Sessions::Event::ChatAgentState do - let(:client_id) { rand(123_456_789) } + let(:client_id) { SecureRandom.uuid } let(:chat) { Chat.first } let(:user) do diff --git a/spec/lib/sessions/event/chat_session_start_spec.rb b/spec/lib/sessions/event/chat_session_start_spec.rb index 4d6a8fcca..2b504cae4 100644 --- a/spec/lib/sessions/event/chat_session_start_spec.rb +++ b/spec/lib/sessions/event/chat_session_start_spec.rb @@ -3,7 +3,7 @@ require 'rails_helper' RSpec.describe Sessions::Event::ChatSessionStart do - let(:client_id) { rand(123_456_789) } + let(:client_id) { SecureRandom.uuid } let(:chat) { Chat.first } let(:chat_session) do Sessions.create('customer_session_id', { 'id' => customer.id }, {}) diff --git a/spec/lib/sessions/event/chat_transfer_spec.rb b/spec/lib/sessions/event/chat_transfer_spec.rb index 29d3060a5..3da3a00ce 100644 --- a/spec/lib/sessions/event/chat_transfer_spec.rb +++ b/spec/lib/sessions/event/chat_transfer_spec.rb @@ -3,7 +3,7 @@ require 'rails_helper' RSpec.describe Sessions::Event::ChatTransfer do - let(:client_id) { rand(123_456_789) } + let(:client_id) { SecureRandom.uuid } let(:chat) { Chat.first } let(:chat_transfer_into) { Chat.create!(name: 'chat 2', updated_by_id: 1, created_by_id: 1) } let(:chat_session) do diff --git a/spec/models/overview_spec.rb b/spec/models/overview_spec.rb index 824943969..2b6e248e4 100644 --- a/spec/models/overview_spec.rb +++ b/spec/models/overview_spec.rb @@ -1,6 +1,7 @@ # Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/ require 'rails_helper' +require 'models/application_model_examples' RSpec.describe Overview, type: :model do it_behaves_like 'ApplicationModel', can_assets: { associations: :users, selectors: :condition } @@ -48,7 +49,7 @@ RSpec.describe Overview, type: :model do it 'handles special chars' do overview = create(:overview, name: 'Д дФ ф') - expect(overview.link).to match(%r{^\d{1,3}$}) + expect(overview.link).to match(%r{^[a-z0-9-]{36}$}) end it 'removes special char fallback if possible' do diff --git a/spec/requests/api_auth_spec.rb b/spec/requests/api_auth_spec.rb index bba5f3038..708a5041f 100644 --- a/spec/requests/api_auth_spec.rb +++ b/spec/requests/api_auth_spec.rb @@ -183,14 +183,14 @@ RSpec.describe 'Api Auth', type: :request do expect(json_response).to be_a_kind_of(Array) expect(json_response).to be_truthy - name = "some org name #{rand(999_999_999)}" + name = "some org name #{SecureRandom.uuid}" post '/api/v1/organizations', params: { name: name }, as: :json expect(response).to have_http_status(:created) expect(json_response).to be_a_kind_of(Hash) expect(json_response['name']).to eq(name) expect(json_response).to be_truthy - name = "some org name #{rand(999_999_999)} - 2" + name = "some org name #{SecureRandom.uuid} - 2" put "/api/v1/organizations/#{json_response['id']}", params: { name: name }, as: :json expect(response).to have_http_status(:ok) expect(json_response).to be_a_kind_of(Hash) @@ -205,14 +205,14 @@ RSpec.describe 'Api Auth', type: :request do expect(json_response).to be_a_kind_of(Array) expect(json_response).to be_truthy - name = "some org name #{rand(999_999_999)}" + name = "some org name #{SecureRandom.uuid}" post '/api/v1/organizations', params: { name: name }, as: :json expect(response).to have_http_status(:created) expect(json_response).to be_a_kind_of(Hash) expect(json_response['name']).to eq(name) expect(json_response).to be_truthy - name = "some org name #{rand(999_999_999)} - 2" + name = "some org name #{SecureRandom.uuid} - 2" put "/api/v1/organizations/#{json_response['id']}", params: { name: name }, as: :json expect(response).to have_http_status(:ok) expect(json_response).to be_a_kind_of(Hash) @@ -227,14 +227,14 @@ RSpec.describe 'Api Auth', type: :request do expect(json_response).to be_a_kind_of(Array) expect(json_response).to be_truthy - name = "some org name #{rand(999_999_999)}" + name = "some org name #{SecureRandom.uuid}" post '/api/v1/organizations', params: { name: name }, as: :json expect(response).to have_http_status(:created) expect(json_response).to be_a_kind_of(Hash) expect(json_response['name']).to eq(name) expect(json_response).to be_truthy - name = "some org name #{rand(999_999_999)} - 2" + name = "some org name #{SecureRandom.uuid} - 2" put "/api/v1/organizations/#{json_response['id']}", params: { name: name }, as: :json expect(response).to have_http_status(:ok) expect(json_response).to be_a_kind_of(Hash) @@ -276,7 +276,7 @@ RSpec.describe 'Api Auth', type: :request do expect(json_response).to be_a_kind_of(Array) expect(json_response).to be_truthy - name = "some org name #{rand(999_999_999)}" + name = "some org name #{SecureRandom.uuid}" post '/api/v1/organizations', params: { name: name }, as: :json expect(response).to have_http_status(:forbidden) @@ -315,7 +315,7 @@ RSpec.describe 'Api Auth', type: :request do expect(json_response).to be_a_kind_of(Array) expect(json_response).to be_truthy - name = "some org name #{rand(999_999_999)}" + name = "some org name #{SecureRandom.uuid}" post '/api/v1/organizations', params: { name: name }, as: :json expect(response).to have_http_status(:forbidden) end diff --git a/spec/requests/integration/object_manager_attributes_spec.rb b/spec/requests/integration/object_manager_attributes_spec.rb index cab86079e..f53e1a901 100644 --- a/spec/requests/integration/object_manager_attributes_spec.rb +++ b/spec/requests/integration/object_manager_attributes_spec.rb @@ -333,9 +333,9 @@ RSpec.describe 'ObjectManager Attributes', type: :request do it 'does converts string to boolean for default value for boolean data type with true (01)', db_strategy: :reset do params = { - name: "customerdescription#{rand(999_999_999)}", + name: "customerdescription#{SecureRandom.uuid.tr('-', '_')}", object: 'Ticket', - display: "custom description#{rand(999_999_999)}", + display: "custom description#{SecureRandom.uuid.tr('-', '_')}", active: true, data_type: 'boolean', data_option: { @@ -384,9 +384,9 @@ RSpec.describe 'ObjectManager Attributes', type: :request do it 'does converts string to boolean for default value for boolean data type with false (02)', db_strategy: :reset do params = { - name: "customerdescription_#{rand(999_999_999)}", + name: "customerdescription_#{SecureRandom.uuid.tr('-', '_')}", object: 'Ticket', - display: "custom description #{rand(999_999_999)}", + display: "custom description #{SecureRandom.uuid.tr('-', '_')}", active: true, data_type: 'boolean', data_option: { @@ -894,9 +894,9 @@ RSpec.describe 'ObjectManager Attributes', type: :request do it 'does verify if attribute type can not be changed (07)', db_strategy: :reset do params = { - name: "customerdescription_#{rand(999_999_999)}", + name: "customerdescription_#{SecureRandom.uuid.tr('-', '_')}", object: 'Ticket', - display: "custom description #{rand(999_999_999)}", + display: "custom description #{SecureRandom.uuid.tr('-', '_')}", active: true, data_type: 'boolean', data_option: { @@ -958,9 +958,9 @@ RSpec.describe 'ObjectManager Attributes', type: :request do it 'does verify if attribute type can be changed (08)', db_strategy: :reset do params = { - name: "customerdescription_#{rand(999_999_999)}", + name: "customerdescription_#{SecureRandom.uuid.tr('-', '_')}", object: 'Ticket', - display: "custom description #{rand(999_999_999)}", + display: "custom description #{SecureRandom.uuid.tr('-', '_')}", active: true, data_type: 'input', data_option: { @@ -1041,9 +1041,9 @@ RSpec.describe 'ObjectManager Attributes', type: :request do context 'position handling', authenticated_as: -> { admin } do let(:params) do { - name: "customerdescription_#{rand(999_999_999)}", + name: "customerdescription_#{SecureRandom.uuid.tr('-', '_')}", object: 'Ticket', - display: "custom description #{rand(999_999_999)}", + display: "custom description #{SecureRandom.uuid.tr('-', '_')}", active: true, data_type: 'input', data_option: { diff --git a/spec/requests/knowledge_base/answer_attachments_cloning_spec.rb b/spec/requests/knowledge_base/answer_attachments_cloning_spec.rb index 696b1fa8b..cf67c76bb 100644 --- a/spec/requests/knowledge_base/answer_attachments_cloning_spec.rb +++ b/spec/requests/knowledge_base/answer_attachments_cloning_spec.rb @@ -12,7 +12,7 @@ RSpec.describe 'KnowledgeBase answer attachments cloning', type: :request, authe let(:current_user) { create(:agent) } it 'copies to given UploadCache' do - form_id = Random.rand(999..9999) + form_id = SecureRandom.uuid endpoint = "/api/v1/knowledge_bases/#{knowledge_base.id}/answers/#{published_answer.id}/attachments/clone_to_form" params = { form_id: form_id } diff --git a/spec/requests/long_polling_spec.rb b/spec/requests/long_polling_spec.rb index e8f202364..0e765c1c9 100644 --- a/spec/requests/long_polling_spec.rb +++ b/spec/requests/long_polling_spec.rb @@ -28,13 +28,13 @@ RSpec.describe 'LongPolling', type: :request do get '/api/v1/message_send', params: { data: {} }, as: :json expect(response).to have_http_status(:ok) expect(json_response).to be_a_kind_of(Hash) - expect(json_response['client_id'].to_i).to be_between(1, 9_999_999_999) + expect(json_response['client_id']).to be_a_uuid client_id = json_response['client_id'] get '/api/v1/message_send', params: { client_id: client_id, data: { event: 'spool' } }, as: :json expect(response).to have_http_status(:ok) expect(json_response).to be_a_kind_of(Hash) - expect(json_response['client_id'].to_i).to be_between(1, 9_999_999_999) + expect(json_response['client_id']).to be_a_uuid get '/api/v1/message_receive', params: { client_id: client_id, data: {} }, as: :json expect(response).to have_http_status(:unprocessable_entity) @@ -63,7 +63,7 @@ RSpec.describe 'LongPolling', type: :request do get '/api/v1/message_send', params: { data: {} }, as: :json expect(response).to have_http_status(:ok) expect(json_response).to be_a_kind_of(Hash) - expect(json_response['client_id'].to_i).to be_between(1, 9_999_999_999) + expect(json_response['client_id']).to be_a_uuid end it 'send with client_id' do @@ -82,7 +82,7 @@ RSpec.describe 'LongPolling', type: :request do authenticated_as(agent, token: create(:token, action: 'api', user_id: agent.id)) get '/api/v1/message_send', params: { data: { event: 'login' } }, as: :json expect(response).to have_http_status(:ok) - expect(json_response['client_id'].to_i).to be_between(1, 9_999_999_999) + expect(json_response['client_id']).to be_a_uuid client_id = json_response['client_id'] get '/api/v1/message_receive', params: { client_id: client_id, data: {} }, as: :json diff --git a/spec/requests/ticket_spec.rb b/spec/requests/ticket_spec.rb index 778fed4e3..732d8cff6 100644 --- a/spec/requests/ticket_spec.rb +++ b/spec/requests/ticket_spec.rb @@ -817,7 +817,7 @@ RSpec.describe 'Ticket', type: :request do end it 'does ticket with correct ticket id (02.04)' do - title = "ticket with corret ticket id testagent#{rand(999_999_999)}" + title = "ticket with corret ticket id testagent#{SecureRandom.uuid}" ticket = create( :ticket, title: title, @@ -1055,7 +1055,7 @@ RSpec.describe 'Ticket', type: :request do end it 'does ticket pagination (02.05)' do - title = "ticket pagination #{rand(999_999_999)}" + title = "ticket pagination #{SecureRandom.uuid}" tickets = [] (1..20).each do |count| ticket = create( @@ -1222,7 +1222,7 @@ RSpec.describe 'Ticket', type: :request do end it 'does ticket with correct ticket id (03.05)' do - title = "ticket with corret ticket id testme#{rand(999_999_999)}" + title = "ticket with corret ticket id testme#{SecureRandom.uuid}" ticket = create( :ticket, title: title, @@ -1427,7 +1427,7 @@ RSpec.describe 'Ticket', type: :request do end it 'does ticket show and response format (04.01)' do - title = "ticket testagent#{rand(999_999_999)}" + title = "ticket testagent#{SecureRandom.uuid}" ticket = create( :ticket, title: title, @@ -1511,7 +1511,7 @@ RSpec.describe 'Ticket', type: :request do end it 'does ticket index and response format (04.02)' do - title = "ticket testagent#{rand(999_999_999)}" + title = "ticket testagent#{SecureRandom.uuid}" ticket = create( :ticket, title: title, @@ -1606,7 +1606,7 @@ RSpec.describe 'Ticket', type: :request do end it 'does ticket create and response format (04.03)' do - title = "ticket testagent#{rand(999_999_999)}" + title = "ticket testagent#{SecureRandom.uuid}" params = { title: title, group: ticket_group.name, @@ -1677,7 +1677,7 @@ RSpec.describe 'Ticket', type: :request do end it 'does ticket update and response formats (04.04)' do - title = "ticket testagent#{rand(999_999_999)}" + title = "ticket testagent#{SecureRandom.uuid}" ticket = create( :ticket, title: title, @@ -2074,7 +2074,7 @@ RSpec.describe 'Ticket', type: :request do end it 'does ticket search sorted (08.01)' do - title = "ticket pagination #{rand(999_999_999)}" + title = "ticket pagination #{SecureRandom.uuid}" ticket1 = create( :ticket, diff --git a/spec/requests/user_spec.rb b/spec/requests/user_spec.rb index c074a19f5..74372088b 100644 --- a/spec/requests/user_spec.rb +++ b/spec/requests/user_spec.rb @@ -375,7 +375,7 @@ RSpec.describe 'User', type: :request do expect(json_response.count).to eq(2) # create user with admin role - firstname = "First test#{rand(999_999_999)}" + firstname = "First test#{SecureRandom.uuid}" role = Role.lookup(name: 'Admin') params = { firstname: "Admin#{firstname}", lastname: 'Admin Last', email: 'new_admin_by_agent@example.com', role_ids: [ role.id ] } post '/api/v1/users', params: params, as: :json @@ -966,7 +966,7 @@ RSpec.describe 'User', type: :request do end it 'does user search sortable' do - firstname = "user_search_sortable #{rand(999_999_999)}" + firstname = "user_search_sortable #{SecureRandom.uuid}" user1 = create( :customer, diff --git a/spec/scripts/websocket_server_spec.rb b/spec/scripts/websocket_server_spec.rb index 59d976032..1935ef707 100644 --- a/spec/scripts/websocket_server_spec.rb +++ b/spec/scripts/websocket_server_spec.rb @@ -20,7 +20,7 @@ describe 'websocket-server', type: :script do let(:error_msg) { "`start_tcp_server': no acceptor" } let(:ipv6_addr) { '::1/128' } # Prevent port assignment conflicts during parallel test execution - let(:port) { rand(60_000..65_000) } + let(:port) { rand(60_000..65_000) } # rubocop:disable Zammad/ForbidRand # Flush logs before do diff --git a/spec/support/custom_matchers/types.rb b/spec/support/custom_matchers/types.rb new file mode 100644 index 000000000..93023cad7 --- /dev/null +++ b/spec/support/custom_matchers/types.rb @@ -0,0 +1,8 @@ +# Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/ + +RSpec::Matchers.define :be_a_uuid do + match do |actual| + c = '[a-z0-9-]' + actual.match %r{^#{c}{8}-#{c}{4}-#{c}{4}-#{c}{4}-#{c}{12}$}i + end +end diff --git a/spec/support/searchindex_backend.rb b/spec/support/searchindex_backend.rb index 56bbc24f2..0bdb03a8b 100644 --- a/spec/support/searchindex_backend.rb +++ b/spec/support/searchindex_backend.rb @@ -43,9 +43,9 @@ prepares elasticsearch # Setting.set('es_password', 'zammad') if ENV['ES_INDEX_RAND'].present? - rand_id = ENV.fetch('CI_JOB_ID', "r#{rand(999)}") + rand_id = ENV.fetch('CI_JOB_ID', SecureRandom.uuid) test_method_name = self.class.description.gsub(%r{[^\w]}, '_') - ENV['ES_INDEX'] = "es_index_#{test_method_name.downcase}_#{rand_id}_#{rand(999_999_999)}" + ENV['ES_INDEX'] = "es_index_#{test_method_name.downcase}_#{rand_id.downcase}" end if ENV['ES_INDEX'].blank? raise "Need ES_INDEX - hint ES_INDEX='estest.local_zammad'" diff --git a/spec/system/login/message_spec.rb b/spec/system/login/message_spec.rb index 43783691f..78b4b0c6d 100644 --- a/spec/system/login/message_spec.rb +++ b/spec/system/login/message_spec.rb @@ -4,7 +4,7 @@ require 'rails_helper' RSpec.describe 'Login Message', type: :system, authenticated_as: false do context 'with maintenance_login_message' do - let(:message) { "badum tssss #{rand(99_999)}" } + let(:message) { "badum tssss #{SecureRandom.uuid}" } let(:alt_message) { 'lorem ipsum' } before { Setting.set 'maintenance_login_message', message } diff --git a/spec/system/manage/calendars_spec.rb b/spec/system/manage/calendars_spec.rb index 6b086a64e..be1608b6a 100644 --- a/spec/system/manage/calendars_spec.rb +++ b/spec/system/manage/calendars_spec.rb @@ -5,7 +5,7 @@ require 'rails_helper' RSpec.describe 'Manage > Calendars', type: :system do context 'Date' do - let(:calendar_title) { "test calendar #{rand(999_999_999)}" } + let(:calendar_title) { "test calendar #{SecureRandom.uuid}" } it 'show festivity dates correctly far away from UTC', time_zone: 'America/Sao_Paulo' do visit '/#manage/calendars' diff --git a/spec/system/manage/organizations_spec.rb b/spec/system/manage/organizations_spec.rb index 0aa55553d..abda4f8fd 100644 --- a/spec/system/manage/organizations_spec.rb +++ b/spec/system/manage/organizations_spec.rb @@ -33,7 +33,7 @@ RSpec.describe 'Manage > Organizations', type: :system do modal_ready - name = "Organization #{rand(999_999)}" + name = "Organization #{SecureRandom.uuid}" within '.modal-dialog' do fill_in 'name', with: name diff --git a/spec/system/system/maintenance_spec.rb b/spec/system/system/maintenance_spec.rb index 678474d76..da16bcce7 100644 --- a/spec/system/system/maintenance_spec.rb +++ b/spec/system/system/maintenance_spec.rb @@ -36,7 +36,7 @@ RSpec.describe 'Manage > Maintenance', type: :system do context 'when maintenance login message will be used', authenticated_as: :authenticate do def message - @message ||= "badum tssss #{rand(99_999)}" + @message ||= 'badum tssss' end def authenticate @@ -51,7 +51,7 @@ RSpec.describe 'Manage > Maintenance', type: :system do end it 'saves new maintenance_login_message' do - message_suffix = "tssss#{rand(99_999)}" + message_suffix = 'tssss' visit 'system/maintenance' diff --git a/test/browser/abb_one_group_test.rb b/test/browser/abb_one_group_test.rb index 8ff2a9a2a..9bfb88bbf 100644 --- a/test/browser/abb_one_group_test.rb +++ b/test/browser/abb_one_group_test.rb @@ -5,7 +5,7 @@ require 'browser_test_helper' class AgentTicketActionLevel0Test < TestCase def test_aaa_agent_ticket_create_with_one_group - agent = "bob.smith_one_group#{rand(99_999_999)}" + agent = "bob.smith_one_group#{SecureRandom.uuid}" @browser = browser_instance login( @@ -214,7 +214,7 @@ class AgentTicketActionLevel0Test < TestCase group_create( data: { - name: "some group #{rand(999_999_999)}", + name: "some group #{SecureRandom.uuid}", member: [ { login: 'admin@example.com', diff --git a/test/browser/admin_calendar_sla_test.rb b/test/browser/admin_calendar_sla_test.rb index fdb9a2942..8f0580aa2 100644 --- a/test/browser/admin_calendar_sla_test.rb +++ b/test/browser/admin_calendar_sla_test.rb @@ -12,8 +12,8 @@ class AdminCalendarSlaTest < TestCase ) tasks_close_all - calendar_name = "ZZZ some calendar #{rand(99_999_999)}" - sla_name = "ZZZ some sla #{rand(99_999_999)}" + calendar_name = "ZZZ some calendar #{SecureRandom.uuid}" + sla_name = "ZZZ some sla #{SecureRandom.uuid}" timezone = 'Europe/Berlin' timezone_verify = "Europe/Berlin\s\\(GMT\\+(2|1)\\)" calendar_create( diff --git a/test/browser/admin_channel_email_test.rb b/test/browser/admin_channel_email_test.rb index 694e19613..1d6be9f09 100644 --- a/test/browser/admin_channel_email_test.rb +++ b/test/browser/admin_channel_email_test.rb @@ -128,7 +128,7 @@ class AdminChannelEmailTest < TestCase # test the creation and cloning of Postmaster filters # confirm fix for issue #2170 - Cannot clone PostmasterFilter def test_filter_clone - filter_name = "Test Filter #{rand(999_999)}" + filter_name = "Test Filter #{SecureRandom.uuid}" @browser = browser_instance login( diff --git a/test/browser/admin_drag_drop_to_new_group_test.rb b/test/browser/admin_drag_drop_to_new_group_test.rb index d35786980..aea401ef8 100644 --- a/test/browser/admin_drag_drop_to_new_group_test.rb +++ b/test/browser/admin_drag_drop_to_new_group_test.rb @@ -39,7 +39,7 @@ class AdminDragDropToNewGroupTest < TestCase private def add_group - name = "dndgroup-#{rand(99_999_999)}" + name = "dndgroup-#{SecureRandom.uuid}" click(css: '.user-menu a[title=Admin') click(css: '.content.active a[href="#manage/groups"]') diff --git a/test/browser/admin_overview_test.rb b/test/browser/admin_overview_test.rb index 8e6033270..aa035a21f 100644 --- a/test/browser/admin_overview_test.rb +++ b/test/browser/admin_overview_test.rb @@ -4,7 +4,7 @@ require 'browser_test_helper' class AdminOverviewTest < TestCase def test_account_add - name = "some overview #{rand(99_999_999)}" + name = "some overview #{SecureRandom.uuid}" @browser = browser_instance login( @@ -40,7 +40,7 @@ class AdminOverviewTest < TestCase end def test_overview_group_by_direction - name = "overview_#{rand(99_999_999)}" + name = "overview_#{SecureRandom.uuid}" ticket_titles = (1..3).map { |i| "Priority #{i} ticket" } @browser = browser_instance diff --git a/test/browser/admin_permissions_granular_vs_full_test.rb b/test/browser/admin_permissions_granular_vs_full_test.rb index 8f4a8918c..fd0e131a7 100644 --- a/test/browser/admin_permissions_granular_vs_full_test.rb +++ b/test/browser/admin_permissions_granular_vs_full_test.rb @@ -4,7 +4,7 @@ require 'browser_test_helper' class AdminPermissionsGranularVsFullTest < TestCase def test_permissions_selecting - new_group_name = "permissions_test_group#{rand(99_999_999)}" + new_group_name = "permissions_test_group#{SecureRandom.uuid}" @browser = browser_instance login( username: 'admin@example.com', diff --git a/test/browser/admin_role_test.rb b/test/browser/admin_role_test.rb index e7a85f913..91f55ec4e 100644 --- a/test/browser/admin_role_test.rb +++ b/test/browser/admin_role_test.rb @@ -12,7 +12,7 @@ class AdminRoleTest < TestCase ) tasks_close_all - rand = rand(99_999_999).to_s + rand = SecureRandom.uuid login = "agent-role-#{rand}" firstname = "Role#{rand}" lastname = "Module#{rand}" @@ -171,8 +171,8 @@ class AdminRoleTest < TestCase tasks_close_all # create user - random = rand(999_999_999) - user_email = "admin.user.#{rand}@example.com" + random = SecureRandom.uuid + user_email = "admin.user.#{random}@example.com" user_create( data: { # login: "some login #{random}", @@ -230,7 +230,7 @@ class AdminRoleTest < TestCase # regression test for issue #2332 - Role-Filter shows inactive Roles def test_inactive_roles_do_not_show_in_role_filter - name = "some role #{rand(99_999_999)}" + name = "some role #{SecureRandom.uuid}" @browser = browser_instance login( diff --git a/test/browser/agent_organization_profile_test.rb b/test/browser/agent_organization_profile_test.rb index 0ec9edfdb..06eaa0dbf 100644 --- a/test/browser/agent_organization_profile_test.rb +++ b/test/browser/agent_organization_profile_test.rb @@ -5,8 +5,8 @@ require 'browser_test_helper' class AgentOrganizationProfileTest < TestCase def test_org_profile # work in one browser window - message = "1 #{rand(99_999_999)}" - note = "some note #{rand(99_999_999)}" + message = "1 #{SecureRandom.uuid}" + note = "some note #{SecureRandom.uuid}" @browser = browser_instance login( @@ -115,7 +115,7 @@ class AgentOrganizationProfileTest < TestCase tasks_close_all # work with two browser windows - message = "comment 1 #{rand(99_999_999_999_999_999)}" + message = "comment 1 #{SecureRandom.uuid}" # use current session browser1 = @browser diff --git a/test/browser/agent_ticket_attachment_test.rb b/test/browser/agent_ticket_attachment_test.rb index ebbb2d79f..2660b728f 100644 --- a/test/browser/agent_ticket_attachment_test.rb +++ b/test/browser/agent_ticket_attachment_test.rb @@ -203,7 +203,7 @@ class AgentTicketAttachmentTest < TestCase browser: browser2, ) - random = "ticket-actions-6-test-#{rand(999_999)}" + random = "ticket-actions-6-test-#{SecureRandom.uuid}" user_email = "#{random}@example.com" user_create( browser: browser2, diff --git a/test/browser/agent_ticket_email_signature_test.rb b/test/browser/agent_ticket_email_signature_test.rb index b1b02de25..4bed929ff 100644 --- a/test/browser/agent_ticket_email_signature_test.rb +++ b/test/browser/agent_ticket_email_signature_test.rb @@ -5,7 +5,7 @@ require 'browser_test_helper' class AgentTicketEmailSignatureTest < TestCase def test_agent_signature_check - suffix = rand(99_999_999_999_999_999).to_s + suffix = SecureRandom.uuid signature_name1 = "sig name 1 äöüß #{suffix}" signature_body1 = "--\nsig body 1 äöüß #{suffix}" signature_name2 = "sig name 2 äöüß #{suffix}" diff --git a/test/browser/agent_ticket_overview_group_by_organization_test.rb b/test/browser/agent_ticket_overview_group_by_organization_test.rb index e8b9e8743..71be076f0 100644 --- a/test/browser/agent_ticket_overview_group_by_organization_test.rb +++ b/test/browser/agent_ticket_overview_group_by_organization_test.rb @@ -10,7 +10,7 @@ class AgentTicketOverviewGroupByOrganizationTest < TestCase =end def test_grouping_by_organzation_overview - random = rand(999_999).to_s + random = SecureRandom.uuid user_email = "user_#{random}@example.com" overview_name = "overview_#{random}" diff --git a/test/browser/agent_ticket_overview_level1_test.rb b/test/browser/agent_ticket_overview_level1_test.rb index ca50fd8aa..dfe9ffb87 100644 --- a/test/browser/agent_ticket_overview_level1_test.rb +++ b/test/browser/agent_ticket_overview_level1_test.rb @@ -4,8 +4,8 @@ require 'browser_test_helper' class AgentTicketOverviewLevel1Test < TestCase def test_i - name1 = "name_low_#{rand(999_999)}" - name2 = "name_high_#{rand(999_999)}" + name1 = "name_low_#{SecureRandom.uuid}" + name2 = "name_high_#{SecureRandom.uuid}" browser1 = browser_instance login( diff --git a/test/browser/agent_ticket_overview_pending_til_test.rb b/test/browser/agent_ticket_overview_pending_til_test.rb index b53732027..20612760c 100644 --- a/test/browser/agent_ticket_overview_pending_til_test.rb +++ b/test/browser/agent_ticket_overview_pending_til_test.rb @@ -6,7 +6,7 @@ class AgentTicketOverviewPendingTil < TestCase # regression for issue #2367 - cannot sort by Pending Til def test_sorting_by_pending_til - name = "overview_pending_til_#{rand(999_999)}" + name = "overview_pending_til_#{SecureRandom.uuid}" @browser = browser_instance login( diff --git a/test/browser/agent_ticket_overview_tab_test.rb b/test/browser/agent_ticket_overview_tab_test.rb index 369156dea..387d07c62 100644 --- a/test/browser/agent_ticket_overview_tab_test.rb +++ b/test/browser/agent_ticket_overview_tab_test.rb @@ -26,7 +26,7 @@ class AgentTicketOverviewTabTest < TestCase ) tasks_close_all - title = "test #{rand(9_999_999)}" + title = "test #{SecureRandom.uuid}" # create new ticket ticket1 = ticket_create( diff --git a/test/browser/agent_ticket_tag_test.rb b/test/browser/agent_ticket_tag_test.rb index 4990b53a9..f9f8e950a 100644 --- a/test/browser/agent_ticket_tag_test.rb +++ b/test/browser/agent_ticket_tag_test.rb @@ -361,7 +361,7 @@ class AgentTicketTagTest < TestCase end def test_b_tags - tag_prefix = "tag#{rand(1000)}" + tag_prefix = 'tag6' @browser = browser_instance login( diff --git a/test/browser/agent_ticket_text_module_test.rb b/test/browser/agent_ticket_text_module_test.rb index 0a921bb82..1d44af719 100644 --- a/test/browser/agent_ticket_text_module_test.rb +++ b/test/browser/agent_ticket_text_module_test.rb @@ -4,8 +4,8 @@ require 'browser_test_helper' class AgentTicketTextModuleTest < TestCase def test_text_modules - random = "text_module_test_#{rand(99_999_999)}" - random2 = "text_module_test_#{rand(99_999_999)}" + random = "text_module_test_#{SecureRandom.uuid}" + random2 = "text_module_test_#{SecureRandom.uuid}" @browser = browser_instance login( @@ -57,9 +57,9 @@ class AgentTicketTextModuleTest < TestCase tasks_close_all # test with two browser windows - random = "text_II_module_test_#{rand(99_999_999)}" + random = "text_II_module_test_#{SecureRandom.uuid}" - user_rand = rand(99_999_999).to_s + user_rand = SecureRandom.uuid login = "agent-text-module-#{user_rand}" firstname = "Text#{user_rand}" lastname = "Module#{user_rand}" diff --git a/test/browser/agent_ticket_update4_test.rb b/test/browser/agent_ticket_update4_test.rb index 52f5c5532..f2bbaaa1a 100644 --- a/test/browser/agent_ticket_update4_test.rb +++ b/test/browser/agent_ticket_update4_test.rb @@ -18,7 +18,7 @@ class AgentTicketUpdate4Test < TestCase object_manager_attribute_create( data: { name: 'date1', - display: "Date-#{rand(999_999)}", + display: "Date-#{SecureRandom.uuid}", data_type: 'Date', }, ) diff --git a/test/browser/agent_user_manage_test.rb b/test/browser/agent_user_manage_test.rb index e9387ca16..d53c96e48 100644 --- a/test/browser/agent_user_manage_test.rb +++ b/test/browser/agent_user_manage_test.rb @@ -4,7 +4,7 @@ require 'browser_test_helper' class AgentUserManageTest < TestCase def test_agent_customer_ticket_create - random_number = rand(999_999) + random_number = SecureRandom.uuid customer_user_email = "customer-test-#{random_number}@example.com" firstname = "Customer Firstname #{random_number}" lastname = 'Customer Lastname' @@ -135,7 +135,7 @@ class AgentUserManageTest < TestCase end def test_agent_customer_ticket_zoom - customer_user_email = "customer-test-#{rand(999_999)}@example.com" + customer_user_email = "customer-test-#{SecureRandom.uuid}@example.com" firstname = 'Customer Firstname' lastname = 'Customer Lastname' fullname = "#{firstname} #{lastname} <#{customer_user_email}>" diff --git a/test/browser/agent_user_profile_test.rb b/test/browser/agent_user_profile_test.rb index 75dffe6b5..afffd1894 100644 --- a/test/browser/agent_user_profile_test.rb +++ b/test/browser/agent_user_profile_test.rb @@ -4,7 +4,7 @@ require 'browser_test_helper' class AgentUserProfileTest < TestCase def test_user_profile - message = "1 #{rand(99_999_999)}" + message = "1 #{SecureRandom.uuid}" @browser = browser_instance login( @@ -109,7 +109,7 @@ class AgentUserProfileTest < TestCase tasks_close_all # work with two browser windows - message = "comment 1 #{rand(99_999_999_999_999_999)}" + message = "comment 1 #{SecureRandom.uuid}" # use current session browser1 = @browser diff --git a/test/browser/first_steps_test.rb b/test/browser/first_steps_test.rb index 7fdb32482..33671b1d8 100644 --- a/test/browser/first_steps_test.rb +++ b/test/browser/first_steps_test.rb @@ -5,8 +5,8 @@ require 'browser_test_helper' class FirstStepsTest < TestCase def test_basic - agent = "bob.smith_#{rand(99_999_999)}" - customer = "customer.smith_#{rand(99_999_999)}" + agent = "bob.smith_#{SecureRandom.uuid}" + customer = "customer.smith_#{SecureRandom.uuid}" @browser = browser_instance login( diff --git a/test/browser/integration_cti_test.rb b/test/browser/integration_cti_test.rb index 6049cc177..7340d85d6 100644 --- a/test/browser/integration_cti_test.rb +++ b/test/browser/integration_cti_test.rb @@ -12,7 +12,7 @@ class IntegrationCtiTest < TestCase # Regression test for #2017 def test_nav_menu_notification_badge_clears - id = rand(99_999_999) + id = SecureRandom.uuid @browser = browser_instance login( @@ -78,7 +78,7 @@ class IntegrationCtiTest < TestCase # Regression test for #2018 def test_e164_numbers_displayed_in_prettified_format - id = rand(99_999_999) + id = SecureRandom.uuid @browser = browser_instance login( @@ -156,7 +156,7 @@ class IntegrationCtiTest < TestCase # Regression test for #2096 def test_inactive_users_displayed_inactive_in_caller_log - id = rand(99_999_999) + id = SecureRandom.uuid @browser = browser_instance login( @@ -216,7 +216,7 @@ class IntegrationCtiTest < TestCase # Regression test for #2075 def test_caller_ids_include_organization_names - id = rand(99_999_999) + id = SecureRandom.uuid @browser = browser_instance login( diff --git a/test/browser/integration_sipgate_test.rb b/test/browser/integration_sipgate_test.rb index 4f67d7461..887621321 100644 --- a/test/browser/integration_sipgate_test.rb +++ b/test/browser/integration_sipgate_test.rb @@ -5,7 +5,7 @@ require 'browser_test_helper' class IntegrationSipgateTest < TestCase # Regression test for #2017 def test_nav_menu_notification_badge_clears - id = rand(99_999_999) + id = SecureRandom.uuid @browser = browser_instance login( diff --git a/test/browser/maintenance_session_message_test.rb b/test/browser/maintenance_session_message_test.rb index bcecd7a2c..3363823a6 100644 --- a/test/browser/maintenance_session_message_test.rb +++ b/test/browser/maintenance_session_message_test.rb @@ -4,7 +4,7 @@ require 'browser_test_helper' class MaintenanceSessionMessageTest < TestCase def test_message - string = rand(99_999_999_999_999_999).to_s + string = SecureRandom.uuid title_html = "test #{string}" title_text = "test #{string}<\/b>" message_html = "message 1äöüß #{string}\n\n\nhttps://zammad.org" diff --git a/test/browser/manage_test.rb b/test/browser/manage_test.rb index 431899732..9ca575cc5 100644 --- a/test/browser/manage_test.rb +++ b/test/browser/manage_test.rb @@ -4,7 +4,7 @@ require 'browser_test_helper' class ManageTest < TestCase def test_user - random = "manage-test-#{rand(999_999)}" + random = "manage-test-#{SecureRandom.uuid}" user_email = "#{random}@example.com" # user management diff --git a/test/browser_test_helper.rb b/test/browser_test_helper.rb index 6df533809..59c740058 100644 --- a/test/browser_test_helper.rb +++ b/test/browser_test_helper.rb @@ -113,7 +113,7 @@ class TestCase < ActiveSupport::TestCase local_browser = browser_instance_remote break rescue => e - wait_until_ready = rand(5..13) + wait_until_ready = rand(5..13) # rubocop:disable Zammad/ForbidRand log('browser_instance', { rescure: true, count: count, sleep: wait_until_ready, exception: e }) sleep wait_until_ready diff --git a/test/integration/email_keep_on_server_test.rb b/test/integration/email_keep_on_server_test.rb index b6810041b..f9ba3c862 100644 --- a/test/integration/email_keep_on_server_test.rb +++ b/test/integration/email_keep_on_server_test.rb @@ -16,11 +16,11 @@ class EmailKeepOnServerTest < ActiveSupport::TestCase @server_login = ENV['KEEP_ON_MAIL_SERVER_ACCOUNT'].split(':')[0] @server_password = ENV['KEEP_ON_MAIL_SERVER_ACCOUNT'].split(':')[1] - @folder = "keep_on_mail_server_#{rand(999_999_999)}" + @folder = "keep_on_mail_server_#{SecureRandom.uuid}" email_address = EmailAddress.create!( realname: 'me Helpdesk', - email: "me#{rand(999_999_999)}@example.com", + email: "me#{SecureRandom.uuid}@example.com", updated_by_id: 1, created_by_id: 1, ) diff --git a/test/integration/email_postmaster_to_sender.rb b/test/integration/email_postmaster_to_sender.rb index aa9ba180c..b66625921 100644 --- a/test/integration/email_postmaster_to_sender.rb +++ b/test/integration/email_postmaster_to_sender.rb @@ -8,7 +8,7 @@ class EmailPostmasterToSender < ActiveSupport::TestCase setup do Setting.set('postmaster_max_size', 0.1) - @test_id = rand(999_999_999) + @test_id = SecureRandom.uuid # setup the IMAP account info for Zammad if ENV['MAIL_SERVER'].blank? diff --git a/test/integration/slack_test.rb b/test/integration/slack_test.rb index 2028d5ba9..e5113fc61 100644 --- a/test/integration/slack_test.rb +++ b/test/integration/slack_test.rb @@ -247,7 +247,7 @@ class SlackTest < ActiveSupport::TestCase end def hash_gen - (0...10).map { ('a'..'z').to_a[rand(26)] }.join + SecureRandom.hex(10) end def rand_word @@ -269,7 +269,7 @@ class SlackTest < ActiveSupport::TestCase 'be a good boy', 'invent new things', ] - words[rand(words.length)] + words.sample end def slack_check(channel_name, search_for) diff --git a/test/support/searchindex_helper.rb b/test/support/searchindex_helper.rb index a84d171b3..931471a7b 100644 --- a/test/support/searchindex_helper.rb +++ b/test/support/searchindex_helper.rb @@ -40,9 +40,9 @@ prepares elasticsearch # Setting.set('es_password', 'zammad') if ENV['ES_INDEX_RAND'].present? - rand_id = ENV.fetch('CI_JOB_ID', "r#{rand(999)}") + rand_id = ENV.fetch('CI_JOB_ID', "r#{SecureRandom.uuid}") test_method_name = method_name.gsub(%r{[^\w]}, '_') - ENV['ES_INDEX'] = "es_index_#{test_method_name.downcase}_#{rand_id}_#{rand(999_999_999)}" + ENV['ES_INDEX'] = "es_index_#{test_method_name.downcase}_#{rand_id.downcase}" end if ENV['ES_INDEX'].blank? raise "ERROR: Need ES_INDEX - hint ES_INDEX='estest.local_zammad'" diff --git a/test/unit/email_process_sender_is_system_address_or_agent_test.rb b/test/unit/email_process_sender_is_system_address_or_agent_test.rb index 1589ebd16..a33faaecf 100644 --- a/test/unit/email_process_sender_is_system_address_or_agent_test.rb +++ b/test/unit/email_process_sender_is_system_address_or_agent_test.rb @@ -16,7 +16,7 @@ class EmailProcessSenderIsSystemAddressOrAgent < ActiveSupport::TestCase end test 'process email with sender as system address check' do - subject = "some new subject #{rand(9_999_999)}" + subject = "some new subject #{SecureRandom.uuid}" email_raw_string = "From: me+is+customer@example.com To: customer@example.com Subject: #{subject} @@ -33,7 +33,7 @@ Some Text" assert_equal('me+is+customer@example.com', ticket.customer.email) # check article sender + customer of ticket - subject = "some new subject #{rand(9_999_999)}" + subject = "some new subject #{SecureRandom.uuid}" email_raw_string = "From: myzammad@system.test To: me+is+customer@example.com, customer@example.com Subject: #{subject} @@ -71,7 +71,7 @@ Some Text" assert_equal(ticket.id, ticket2.id) # follow-up not possible because subject has changed - subject = "new subject without ticket ref #{rand(9_999_999)}" + subject = "new subject without ticket ref #{SecureRandom.uuid}" email_raw_string = "From: me+is+customer@example.com To: myzammad@system.test Subject: #{subject} diff --git a/test/unit/object_cache_test.rb b/test/unit/object_cache_test.rb index 2d3bbf4e6..f25b7de7e 100644 --- a/test/unit/object_cache_test.rb +++ b/test/unit/object_cache_test.rb @@ -71,7 +71,7 @@ class ObjectCacheTest < ActiveSupport::TestCase # update group group1 = groups.first - group1.note = "some note #{rand(9_999_999_999)}" + group1.note = "some note #{SecureRandom.uuid}" group1.save assets = user1.assets({}) diff --git a/test/unit/organization_csv_import_test.rb b/test/unit/organization_csv_import_test.rb index 345f5370f..91a27e818 100644 --- a/test/unit/organization_csv_import_test.rb +++ b/test/unit/organization_csv_import_test.rb @@ -148,7 +148,7 @@ class OrganizationCsvImportTest < ActiveSupport::TestCase test 'simple import with members' do UserInfo.current_user_id = 1 - name = rand(999_999_999) + name = SecureRandom.uuid customer1 = User.create_or_update( login: "customer1-members#{name}@example.com", firstname: 'Member', diff --git a/test/unit/session_basic_test.rb b/test/unit/session_basic_test.rb index 7fa50acee..1a0ae0acb 100644 --- a/test/unit/session_basic_test.rb +++ b/test/unit/session_basic_test.rb @@ -65,7 +65,7 @@ class SessionBasicTest < ActiveSupport::TestCase agent1 = User.create_or_update( login: 'activity-stream-agent-1', firstname: 'Session', - lastname: "activity stream #{rand(99_999)}", + lastname: "activity stream #{SecureRandom.uuid}", email: 'activity-stream-agent1@example.com', password: 'agentpw', active: true, @@ -76,7 +76,7 @@ class SessionBasicTest < ActiveSupport::TestCase ) # create min. on activity record - random_name = "Random:#{rand(9_999_999_999)}" + random_name = "Random:#{SecureRandom.uuid}" Group.create_or_update( name: random_name, updated_by_id: 1, diff --git a/test/unit/session_enhanced_test.rb b/test/unit/session_enhanced_test.rb index 019748f0d..ff462f584 100644 --- a/test/unit/session_enhanced_test.rb +++ b/test/unit/session_enhanced_test.rb @@ -179,7 +179,7 @@ class SessionEnhancedTest < ActiveSupport::TestCase roles = Role.where(name: ['Agent']) groups = Group.all organization = Organization.create( - name: "SomeOrg::#{rand(999_999)}", active: true, + name: "SomeOrg::#{SecureRandom.uuid}", active: true, updated_by_id: 1, created_by_id: 1, ) diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index b99f4d1b0..c95cb651f 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -313,7 +313,7 @@ class UserTest < ActiveSupport::TestCase end test 'strange spaces' do - name = "#{Time.zone.now.to_i}-#{rand(999_999_999_999)}" + name = "#{Time.zone.now.to_i}-#{SecureRandom.uuid}" email = "customer_email#{name}@example.com" customer = User.create!( firstname: 'Role', @@ -329,7 +329,7 @@ class UserTest < ActiveSupport::TestCase assert_equal(email, customer.email) customer.destroy! - name = "#{Time.zone.now.to_i}-#{rand(999_999_999_999)}" + name = "#{Time.zone.now.to_i}-#{SecureRandom.uuid}" email = "customer_email#{name}@example.com" customer = User.create!( firstname: "\u{00a0}\u{00a0}Role", @@ -347,7 +347,7 @@ class UserTest < ActiveSupport::TestCase assert_equal(email, customer.email) customer.destroy! - name = "#{Time.zone.now.to_i}-#{rand(999_999_999_999)}" + name = "#{Time.zone.now.to_i}-#{SecureRandom.uuid}" email = "customer_email#{name}@example.com" customer = User.create!( firstname: "\u{200B}\u{200B}Role", @@ -365,7 +365,7 @@ class UserTest < ActiveSupport::TestCase assert_equal(email, customer.email) customer.destroy! - name = "#{Time.zone.now.to_i}-#{rand(999_999_999_999)}" + name = "#{Time.zone.now.to_i}-#{SecureRandom.uuid}" email = "customer_email#{name}@example.com" customer = User.create!( firstname: "\u{200B}\u{200B}Role\u{00a0}", @@ -383,7 +383,7 @@ class UserTest < ActiveSupport::TestCase assert_equal(email, customer.email) customer.destroy! - name = "#{Time.zone.now.to_i}-#{rand(999_999_999_999)}" + name = "#{Time.zone.now.to_i}-#{SecureRandom.uuid}" email = "customer_email#{name}@example.com" customer = User.create!( firstname: "\u{200a}\u{200b}\u{202F}\u{205F}Role\u{2007}\u{2008}", @@ -403,7 +403,7 @@ class UserTest < ActiveSupport::TestCase end test 'without email - but login eq email' do - name = rand(999_999_999) + name = SecureRandom.uuid login = "admin-role_without_email#{name}@example.com" email = "admin-role_without_email#{name}@example.com" @@ -441,7 +441,7 @@ class UserTest < ActiveSupport::TestCase end test 'without email - but login ne email' do - name = rand(999_999_999) + name = SecureRandom.uuid login = "admin-role_without_email#{name}" email = "admin-role_without_email#{name}@example.com" @@ -478,7 +478,7 @@ class UserTest < ActiveSupport::TestCase end test 'uniq email' do - name = rand(999_999_999) + name = SecureRandom.uuid email1 = "admin1-role_without_email#{name}@example.com" admin1 = User.create!( @@ -536,7 +536,7 @@ class UserTest < ActiveSupport::TestCase test 'uniq email - multiple use' do Setting.set('user_email_multiple_use', true) - name = rand(999_999_999) + name = SecureRandom.uuid email1 = "admin1-role_without_email#{name}@example.com" admin1 = User.create!( @@ -572,7 +572,7 @@ class UserTest < ActiveSupport::TestCase end test 'ensure roles' do - name = rand(999_999_999) + name = SecureRandom.uuid admin = User.create_or_update( login: "admin-role#{name}@example.com", firstname: 'Role', @@ -671,7 +671,7 @@ class UserTest < ActiveSupport::TestCase end test 'user default preferences' do - name = rand(999_999_999) + name = SecureRandom.uuid groups = Group.where(name: 'Users') roles = Role.where(name: 'Agent') agent1 = User.create_or_update( @@ -766,7 +766,7 @@ class UserTest < ActiveSupport::TestCase created_by_id: 1, updated_by_id: 1, ) - name = rand(999_999_999) + name = SecureRandom.uuid assert_raises(RuntimeError) do User.create_or_update( login: "customer-role#{name}@example.com", @@ -857,7 +857,7 @@ class UserTest < ActiveSupport::TestCase end test 'permission default' do - name = rand(999_999_999) + name = SecureRandom.uuid admin_count = User.with_permissions('admin').count admin = User.create_or_update( login: "admin-role#{name}@example.com", @@ -935,7 +935,7 @@ class UserTest < ActiveSupport::TestCase assert_equal(0, admin_count_inital) # create two admin users - random = rand(999_999_999) + random = SecureRandom.uuid admin1 = User.create_or_update( login: "1admin-role#{random}@example.com", firstname: 'Role', @@ -948,7 +948,7 @@ class UserTest < ActiveSupport::TestCase created_by_id: 1, ) - random = rand(999_999_999) + random = SecureRandom.uuid admin2 = User.create_or_update( login: "2admin-role#{random}@example.com", firstname: 'Role', @@ -961,7 +961,7 @@ class UserTest < ActiveSupport::TestCase created_by_id: 1, ) - random = rand(999_999_999) + random = SecureRandom.uuid admin3 = User.create_or_update( login: "2admin-role#{random}@example.com", firstname: 'Role', @@ -1015,7 +1015,7 @@ class UserTest < ActiveSupport::TestCase end test 'only valid agent in group permission check' do - name = rand(999_999_999) + name = SecureRandom.uuid group = Group.create!( name: "ValidAgentGroupPermission-#{name}", active: true, @@ -1061,7 +1061,7 @@ class UserTest < ActiveSupport::TestCase end test 'preferences[:notification_sound][:enabled] value check' do - name = rand(999_999_999) + name = SecureRandom.uuid roles = Role.where(name: 'Agent') agent1 = User.create!( @@ -1306,7 +1306,7 @@ class UserTest < ActiveSupport::TestCase ) group1 = Group.create_or_update( - name: "GroupWithoutPermission-#{rand(9_999_999_999)}", + name: "GroupWithoutPermission-#{SecureRandom.uuid}", active: true, updated_by_id: 1, created_by_id: 1,