CVE-2016-7078 (Ruby, published 2018-09-10T15:29Z)
Description: value: foreman before version 1.15.0 is vulnerable to an information leak through organizations and locations feature. When a user is assigned _no_ organizations/locations, they are able to view all resources instead of none (mirroring an administrator's view). The user's actions are still limited by their assigned permissions, e.g. to control viewing, editing and deletion.
Severity: MEDIUM (CVSS v3 base score: 4.3)
Weakness: CWE-200 \u2014 Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
Repository: https://github.com/theforeman/foreman
Files changed:
app/controllers/concerns/foreman/controller/smart_proxy_auth.rb
app/controllers/users_controller.rb
app/models/concerns/taxonomix.rb
app/models/host/base.rb
app/services/sso/base.rb
app/services/sso/oauth.rb
app/services/tax_host.rb
db/migrate/20130908100439_delete_orphaned_records.rb
db/seeds.d/07-provisioning_templates.rb
db/seeds.d/08-partition_tables.rb
db/seeds.d/10-installation_media.rb
test/active_support_test_case_helper.rb
test/controllers/api/v1/auth_source_ldaps_controller_test.rb
test/controllers/api/v1/compute_resources_controller_test.rb
test/controllers/api/v1/config_templates_controller_test.rb
test/controllers/api/v1/domains_controller_test.rb
test/controllers/api/v1/environments_controller_test.rb
test/controllers/api/v1/hostgroups_controller_test.rb
test/controllers/api/v1/media_controller_test.rb
test/controllers/api/v1/ptables_controller_test.rb
test/controllers/api/v1/smart_proxies_controller_test.rb
test/controllers/api/v1/subnets_controller_test.rb
test/controllers/api/v1/users_controller_test.rb
test/controllers/api/v2/auth_source_ldaps_controller_test.rb
test/controllers/api/v2/compute_resources_controller_test.rb
test/controllers/api/v2/config_reports_controller_test.rb
test/controllers/api/v2/config_templates_controller_test.rb
test/controllers/api/v2/domains_controller_test.rb
test/controllers/api/v2/environments_controller_test.rb
test/controllers/api/v2/hostgroups_controller_test.rb
test/controllers/api/v2/hosts_controller_test.rb
test/controllers/api/v2/locations_controller_test.rb
test/controllers/api/v2/media_controller_test.rb
test/controllers/api/v2/parameters_controller_test.rb
test/controllers/api/v2/provisioning_templates_controller_test.rb
test/controllers/api/v2/ptables_controller_test.rb
test/controllers/api/v2/realms_controller_test.rb
test/controllers/api/v2/reports_controller_test.rb
test/controllers/api/v2/smart_proxies_controller_test.rb
test/controllers/api/v2/subnets_controller_test.rb
test/controllers/api/v2/users_controller_test.rb
test/controllers/application_controller_subclass_test.rb
test/controllers/auth_source_ldaps_controller_test.rb
test/controllers/compute_resources_controller_test.rb
test/controllers/compute_resources_vms_controller_test.rb
test/controllers/domains_controller_test.rb
test/controllers/environments_controller_test.rb
test/controllers/fact_values_controller_test.rb
test/controllers/hostgroups_controller_test.rb
test/controllers/hosts_controller_test.rb
test/controllers/images_controller_test.rb
test/controllers/locations_controller_test.rb
test/controllers/media_controller_test.rb
test/controllers/organizations_controller_test.rb
test/controllers/provisioning_templates_controller_test.rb
test/controllers/puppetclasses_controller_test.rb
test/controllers/realms_controller_test.rb
test/controllers/smart_proxies_controller_test.rb
test/controllers/subnets_controller_test.rb
test/controllers/unattended_controller_test.rb
test/controllers/users_controller_test.rb
test/controllers/variable_lookup_keys_controller_test.rb
test/factories/domain.rb
test/factories/host_related.rb
test/factories/smart_proxy.rb
test/factories/subnet.rb
test/factories/user_related.rb
test/fixtures/taxable_taxonomies.yml
test/integration/location_test.rb
test/integration/organization_test.rb
test/models/concerns/api_taxonomy_scope_test.rb
test/models/fact_value_test.rb
test/models/host_test.rb
test/models/nic_test.rb
test/models/report_test.rb
test/models/shared/taxonomies_base_test.rb
test/models/subnet/ipv6_test.rb
test/models/subnet_test.rb
test/models/taxonomix_test.rb
test/models/taxonomy_test.rb
test/models/user_test.rb
test/test_helper.rb
test/unit/has_many_common_test.rb
test/unit/puppet_class_importer_test.rb
test/unit/sso/basic_test.rb
test/unit/tasks/seeds_test.rb
Commit message: Fixes #16982 - Scope properly when no taxonomies are set

The default scope for hosts and other objects did not restrict
properly by taxonomies. An user without organizations or
locations, could do anything it's permissions allow to.
The list of hosts was unrestricted and showed hosts in
any location or organization.

This is fixed to work so that:

Users without taxonomies, when set to 'any context' cannot see
anything (at all)

Users with taxonomies, when set to 'any context' can see
everything within all of their taxonomies context (including
children taxonomies).

Admins set to 'any context' can see everything - regardless
of whether it has a taxonomy or not.

Users or admins set to some organization/location scope
can only see stuff within scope.


Vulnerable code:
    allowed_smart_proxies = features.blank? ? SmartProxy.all : SmartProxy.with_features(*features)
  def auth_smart_proxy(proxies = SmartProxy.all, require_cert = true)
    if !request.post? && params[:status].blank? && User.exists?(session[:user].presence)
    taxonomy_join_table = :taxable_taxonomies
    has_many taxonomy_join_table.to_sym, :dependent => :destroy, :as => :taxable
             :through => taxonomy_join_table, :source => :taxonomy,
             :through => taxonomy_join_table, :source => :taxonomy,
      scope = block_given? ? yield : where('1=1')
      if SETTINGS[:locations_enabled] && loc.present?
        inner_ids_loc = if Location.ignore?(self.to_s)
                          self.unscoped.pluck("#{table_name}.id")
                        else
                          inner_select(loc, inner_method)
                        end
      if SETTINGS[:organizations_enabled] && org.present?
        inner_ids_org = if Organization.ignore?(self.to_s)
                          self.unscoped.pluck("#{table_name}.id")
                        else
                          inner_select(org, inner_method)
                        end
      end
      inner_ids   = inner_ids_loc & inner_ids_org if (inner_ids_loc && inner_ids_org)
      inner_ids ||= inner_ids_loc if inner_ids_loc
      inner_ids ||= inner_ids_org if inner_ids_org
      # In the case of users we want the taxonomy scope to get both the users of the taxonomy and admins.
      inner_ids.concat(admin_ids) if inner_ids && self == User
      inner_ids
      conditions[:organization_id] = Array(org).map { |o| o.subtree_ids }.flatten.uniq if org.present?
      conditions[:location_id] = Array(loc).map { |l| l.subtree_ids }.flatten.uniq if loc.present?
      User.except_hidden.find_by_login(self.user)
          User.find_by_login(user_name).tap do |obj|
      ids[col] = Array(taxonomy.send(col))
      ids["#{taxonomy_type.tableize.singularize}_ids"] = taxonomy_type.constantize.pluck(:id)
      ids[col] = populate_values ? Array(self.send(col)) : []
    Audit.unscoped.where("user_id NOT IN (?)", User.pluck(:id)).update_all(:user_id => nil)
    Domain.where("dns_id NOT IN (?)", SmartProxy.pluck(:id)).update_all(:dns_id => nil)
    Subnet.where("dhcp_id NOT IN (?)", SmartProxy.pluck(:id)).update_all(:dhcp_id => nil)
    Subnet.where("dns_id NOT IN (?)", SmartProxy.pluck(:id)).update_all(:dns_id => nil)
    Subnet.where("tftp_id NOT IN (?)", SmartProxy.pluck(:id)).update_all(:tftp_id => nil)
    Image.where("architecture_id NOT IN (?)", Architecture.pluck(:id)).update_all(:architecture_id => nil)
    Image.where("compute_resource_id NOT IN (?)", ComputeResource.pluck(:id)).update_all(:compute_resource_id => nil)
    Nic::Base.where("domain_id NOT IN (?)", Domain.pluck(:id)).update_all(:domain_id => nil)
    Nic::Base.where("host_id NOT IN (?)", Host::Base.pluck(:id)).update_all(:host_id => nil)
    Nic::Base.where("subnet_id NOT IN (?)", Subnet.pluck(:id)).update_all(:subnet_id => nil)
    OsDefaultTemplate.where("config_template_id NOT IN (?)", FakeConfigTemplate.pluck(:id)).update_all(:config_template_id => nil)
    OsDefaultTemplate.where("template_kind_id NOT IN (?)", TemplateKind.pluck(:id)).update_all(:template_kind_id => nil)
    TemplateCombination.where("config_template_id NOT IN (?)", FakeConfigTemplate.pluck(:id)).update_all(:config_template_id => nil)
    TemplateCombination.where("environment_id NOT IN (?)", Environment.pluck(:id)).update_all(:environment_id => nil)
  kinds[type] = TemplateKind.find_by_name(type)
  kinds[type] ||= TemplateKind.create(:name => type)
organizations = Organization.all
locations = Location.all
    { :name => 'pxelinux_discovery', :source => 'snippets/_pxelinux_discovery.erb', :snippet => true },
    if (t = ProvisioningTemplate.find_by_name(input[:name])) && !audit_modified?(ProvisioningTemplate, input[:name])
organizations = Organization.all
locations = Location.all
    if (p = Ptable.find_by_name(input[:name])) && !audit_modified?(Ptable, input[:name])
os_suse = Operatingsystem.where(:type => "Suse") || Operatingsystem.where("name LIKE ?", "suse")
    next if Medium.where(['name = ? OR path = ?', input[:name], input[:path]]).any?
      permission = Permission.find_by_name("#{operation}_#{type}") || FactoryGirl.create(:permission, :name => "#{operation}_#{type}")
    assert_difference('AuthSourceLdap.count', 1) do
    assert_difference('AuthSourceLdap.count', -1) do
    assert_equal "new_description", ComputeResource.find_by_name('mycompute').description
    assert_difference('ComputeResource.count', -1) do
    assert_equal "new_description", ComputeResource.find_by_name('mycompute').description
    assert_difference('ComputeResource.count', -1) do
    assert ProvisioningTemplate.exists?(config_template.id)
    refute ProvisioningTemplate.exists?(config_template.id)
    put :update, { :id => Domain.first.to_param, :domain => { :name => "domain.new" } }
    assert_equal "domain.new", Domain.first.name
    assert_difference('Environment.count') do
    assert_difference('Environment.count', -1) do
    assert_difference('Hostgroup.count') do
    assert_difference('Hostgroup.count', -1) do
    assert_no_difference('Hostgroup.count') do
    assert_difference('Hostgroup.count') do
    assert_equal hostgroups(:common).id.to_s, Hostgroup.find_by_name("db").ancestry
    assert_difference('Medium.count', +1) do
    assert_difference('Medium.count', -1) do
    assert_difference('Ptable.count') do
    assert_difference('Ptable.count', -0) do
    assert_difference('Ptable.count', -1) do
    assert_difference('SmartProxy.count') do
    assert_difference('SmartProxy.count', -1) do
    assert_difference('Environment.count', 2) do
        assert_difference('Puppetclass.count', 1) do
      assert_difference('Puppetclass.count', 0) do
    assert_difference('Environment.count', -1) do
      assert_difference('Environment.find_by_name("env1").puppetclasses.count', -2) do
    assert_difference('LookupKey.count', 1) do
    assert_difference('Environment.count', 0) do
      assert_difference('Environment.count', 1) do
    assert_difference('Subnet::Ipv4.count') do
    assert_equal 'Subnet::Ipv4', Subnet.find_by_name('QA2').type
    assert_difference('Subnet::Ipv6.count') do
    assert_equal 'Subnet::Ipv6', Subnet.find_by_name('QA2').type
    assert_difference('Subnet.count', -1) do
    assert_difference('Subnet.count', 0) do
    mod_user = User.find_by_id(user.id)
    assert User.find_by_id(user.id).admin?
    mod_user = User.find_by_id(user.id)
    mod_user = User.find_by_id(user.id)
    mod_user = User.find_by_id(user.id)
    assert !User.exists?(user.id)
      assert User.exists?(user.id)
      assert User.find_by_login('new_admin').admin?
  test "#update should allow updating mysel without any special permissions" do
    assert_difference('AuthSourceLdap.count', 1) do
    assert_difference('AuthSourceLdap.count', -1) do
    assert_equal "new_description", ComputeResource.find_by_name('mycompute').description
    assert_difference('ComputeResource.count', -1) do
    assert_equal "new_description", ComputeResource.find_by_name('mycompute').description
    assert_difference('ComputeResource.count', -1) do
      post :create, {:config_report => create_a_puppet_transaction_report }
      assert_equal 403, @response.status
      assert_equal 403, @response.status
      assert_equal 403, @response.status
      assert_equal 403, @response.status
    refute Report.find_by_id(report.id)
    assert ProvisioningTemplate.exists?(config_template.id)
    refute ProvisioningTemplate.exists?(config_template.id)
    assert_equal "domain.new", Domain.first.name
    assert_equal 2, assigns(:domains).length
    assert_equal assigns(:domains), [domains(:mydomain), domains(:yourdomain)]
    assert_equal 1, assigns(:domains).length
    assert_equal assigns(:domains), [domains(:mydomain)]
    assert_difference('Environment.count') do
    assert_difference('Environment.count', -1) do
    assert_difference('Hostgroup.count') do
    assert_difference('Hostgroup.count', -1) do
    assert_difference('Hostgroup.count') do
    assert_no_difference('Hostgroup.count') do
    assert_difference('Hostgroup.count') do
    assert_equal hostgroups(:common).id.to_s, Hostgroup.find_by_name("db").ancestry
    assert_equal compute_attrs.vm_interfaces.count, last_record.interfaces.count
    assert_equal expected_compute_attributes(compute_attrs, 0), last_record.interfaces.find_by_mac('00:11:22:33:44:00').compute_attributes
    assert_equal expected_compute_attributes(compute_attrs, 1), last_record.interfaces.find_by_mac('00:11:22:33:44:01').compute_attributes
    @host.interfaces.reload
    assert_equal compute_attrs.vm_interfaces.count, @host.interfaces.count
    assert_equal expected_compute_attributes(compute_attrs, 0), @host.interfaces.find_by_primary(true).compute_attributes
    assert_equal expected_compute_attributes(compute_attrs, 1), @host.interfaces.find_by_primary(false).compute_attributes
    assert_equal hostgroup, Host.find_by(:name => hostname).hostgroup
    assert_difference('Location.count', -1) do
    assert_difference('Location.count', -1) do
    @location.ignore_types = ["Hostgroup", "Environment", "User", "Medium", "Subnet", "SmartProxy", "ProvisioningTemplate", "ComputeResource", "Realm"]
        put :update, { :id => @location.to_param, :location => { :domain_ids => Domain.pluck(:id) } }
    assert_difference('Medium.count', +1) do
    assert_difference('Medium.count', -1) do
    assert_equal '123', Host.find_by_name(@host.name).parameters.order("parameters.updated_at").last.value
    assert_equal Domain.find_by_name("mydomain.net").parameters.order("parameters.updated_at").last.value, "123"
    assert_equal Subnet.find_by_name("five").parameters.order("parameters.updated_at").last.value, "123"
    assert_equal Hostgroup.find_by_name("Common").group_parameters.order("parameters.updated_at").last.value, "123"
    assert_equal Operatingsystem.find_by_name("Redhat").parameters.order("parameters.updated_at").last.value, "123"
    assert ProvisioningTemplate.exists?(provisioning_template.id)
    refute ProvisioningTemplate.exists?(provisioning_template.id)
    assert_difference('Ptable.count') do
    assert_difference('Ptable.count') do
    assert_difference('Ptable.count', -0) do
    assert_difference('Ptable.count', -1) do
    put :update, { :id => Realm.first.to_param, :realm => { :name => "realm.new" } }
    assert_equal "realm.new", Realm.first.name
    refute Realm.find_by_id(realm['id'])
    assert_equal 2, assigns(:realms).length
    assert_equal assigns(:realms), [realms(:myrealm), realms(:yourrealm)]
    assert_equal 1, assigns(:realms).length
    assert_equal assigns(:realms), [realms(:myrealm)]
    expected_proxy_ids = SmartProxy.with_features("TFTP").map { |p| p.id }
    expected_proxy_ids = SmartProxy.with_features("TFTP").map { |p| p.id }
    assert_difference('SmartProxy.count') do
    assert_difference('SmartProxy.count', -1) do
    assert_difference('Environment.count', 2) do
        assert_difference('Puppetclass.count', 1) do
      assert_difference('Puppetclass.count', 0) do
    assert_difference('Environment.count', -1) do
      assert_difference('Environment.find_by_name("env1").puppetclasses.count', -2) do
    assert_difference('LookupKey.count', 1) do
    assert_difference('Environment.count', 0) do
      assert_difference('Environment.count', 1) do
    assert_difference('Environment.count', 0) do
    assert_difference('LookupKey.count', 0) do
     post :import_puppetclasses, {:id => smart_proxies(:puppetmaster).id, :except => 'new,updated'}, set_session_user
      assert_difference('Puppetclass.count', 1) do
      assert_difference('Puppetclass.count', 2) do
    assert_difference('Subnet.count') do
    assert_difference('Subnet.count') do
    subnet = Subnet.find_by_name(valid_v4_attrs[:name])
    assert_difference('Subnet.count') do
    assert_difference('Subnet.count', -1) do
    assert_difference('Subnet.count', 0) do
    mod_user = User.find_by_id(user.id)
    assert User.find_by_id(user.id).admin?
    mod_user = User.find_by_id(user.id)
    mod_user = User.find_by_id(user.id)
    mod_user = User.find_by_id(user.id)
    assert !User.exists?(user.id)
      assert User.exists?(user.id)
      user = FactoryGirl.create(:user)
      get :index, {}, set_session_user.merge(:user => user.id)
      assert_redirected_to edit_user_path(user)
    @model = AuthSourceLdap.first
    post :create, {:auth_source_ldap => {:name => AuthSourceLdap.first.name}}, set_session_user
    put :update, {:id => AuthSourceLdap.first, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user
    put :update, {:id => AuthSourceLdap.first.id, :format => "weird", :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user
    wierd_id = "#{AuthSourceLdap.first.id}.weird"
    put :update, {:id => wierd_id, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user
    parameterized_id = "#{AuthSourceLdap.first.id}-#{AuthSourceLdap.first.name.parameterize}"
    put :update, {:id => parameterized_id, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user
    put :update, {:id => AuthSourceLdap.first, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user
    auth_source_ldap = AuthSourceLdap.first
    User.where(:auth_source_id => auth_source_ldap.id).update_all(:auth_source_id => nil)
    assert !AuthSourceLdap.exists?(auth_source_ldap.id)
      get :edit, { :id => AuthSourceLdap.first.id },
    auth_source_ldap = AuthSourceLdap.find(auth_source_ldap.id)
    put :test_connection, {:id => AuthSourceLdap.first, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user
    put :test_connection, {:id => AuthSourceLdap.first, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user
    auth_source_ldap_params = { :name => AuthSourceLdap.first.name,
    put :update, { :id => AuthSourceLdap.first,
      AuthSourceLdap.first.organizations.to_a
      AuthSourceLdap.first.locations.to_a
    assert_difference('ComputeResource.count', 0) do
    assert_difference('ComputeResource.count', +1) do
    @compute_resource = ComputeResource.find(@compute_resource.id)
    @compute_resource = ComputeResource.find(@compute_resource.id)
    assert_difference('ComputeResource.count', 0) do
    assert_difference('ComputeResource.count', 0) do
    assert_difference('ComputeResource.count', -1) do
    @model = Domain.first
    put :update, {:id => Domain.first.to_param, :domain => {:name => Domain.first.name }}, set_session_user
    put :update, {:id => Domain.first.to_param, :domain => {:name => Domain.first.name }}, set_session_user
    domain = Domain.first
    get :edit, {:id => Domain.first.id}
    assert_difference 'Environment.count' do
    env = Environment.find(environment.id)
    assert_difference('Environment.count', -1) do
    assert Environment.find_by_name("env1").puppetclasses.map(&:name).sort == ["a", "b", "c"]
    envs = Environment.find_by_name("env1").puppetclasses.map(&:name).sort
    assert envs == ["a", "b", "c"]
    assert Environment.find_by_name("env3").puppetclasses.map(&:name).sort == []
        {"obsolete" =>
          {"env1"  => '["a","b","c","_destroy_"]'}
        }
      }, set_session_user
    assert Environment.find_by_name("env1").hosts.count > 0
    assert Environment.find_by_name("env1")
         {"changed" =>
              {"new" =>
                   {"new" => '{"a":{"new":{}}}'}
              }
         }, set_session_user
    assert(Environment.all.map(&:name).include?('new'), 'Should include environment with name "new"')
    users(:one).roles = [Role.default, Role.find_by_name('Viewer')]
    get :nest, {:id => Hostgroup.first.id}, set_session_user
    get :clone, {:id => Hostgroup.first}, set_session_user
    get :edit, {:id => Hostgroup.first}, set_session_user
    put :update, {:id => Hostgroup.first, :hostgroup => { :name => '' }}, set_session_user
    put :update, {:id => Hostgroup.first, :hostgroup => { :name => Hostgroup.first.name }}, set_session_user
    get :edit, {:id => Hostgroup.first.id}, set_session_user.merge(:user => users(:one).id)
    assert_equal @response.status, 403
    xhr :post, :domain_selected, {:id => Hostgroup.first, :hostgroup => {}, :domain_id => domain.id, :format => :json}, set_session_user
    xhr :post, :domain_selected, {:id => Hostgroup.first, :hostgroup => {}, :format => :json, :domain_id => nil}, set_session_user
    post :architecture_selected, {:id => Hostgroup.first, :hostgroup => {}, :architecture_id => nil}, set_session_user
      hostgroup = Hostgroup.where(:name => "test_it").last
      assert_equal "overridden", hostgroup.parameters["x"]
      child.reload
      assert_equal "overridden", child.parameters["x"]
      child.reload
      assert_equal "overridden", child.parameters["y"]
      assert_equal "", child.parameters["x"]
    assert_difference 'Host.count' do
    assert_difference 'Host.count' do
    assert_difference('Host.count', -1) do
    hosts.map! {|h| Host.find(h.id)}
    hosts.each { |host| assert_equal hostgroup, host.hostgroup }
      host = Host.find_by_name name
      assert_not_nil host
      assert_equal host.hostgroup, hostgroup
    assert_equal environments(:global_puppetmaster), Host.find(@host1.id).environment
    assert_equal environments(:global_puppetmaster), Host.find(@host2.id).environment
    assert Host.find(@host1.id).environment == hostgroup.environment
    assert Host.find(@host2.id).environment == hostgroup.environment
    assert_equal users(:one).id_and_type, Host.find(@host1.id).is_owned_by
    assert_equal users(:one).id_and_type, Host.find(@host2.id).is_owned_by
        assert_equal proxy, host.reload.puppet_ca_proxy
    host = Host.first
    assert_difference "location.hosts.count", (Host.count - cnt_hosts_location) do
    assert_difference "organization.hosts.count", (Host.count - cnt_hosts_organization) do
    assert_difference('Image.count') do
    assert_redirected_to compute_resource_path(@image.compute_resource)
    assert_redirected_to compute_resource_path(@image.compute_resource)
    assert_redirected_to compute_resource_path(@image.compute_resource)
  test "should clone location with assocations" do
    assert_difference "Location.count", 1 do
      post :create, {:location => {:name => "location_dup_name",
                                 :environment_ids => location_dup.environment_ids,
                                 :hostgroup_ids => location_dup.hostgroup_ids,
                                 :subnet_ids => location_dup.hostgroup_ids,
                                 :domain_ids => location_dup.domain_ids,
                                 :medium_ids => location_dup.medium_ids,
                                 :user_ids => location_dup.user_ids,
                                 :smart_proxy_ids => location_dup.smart_proxy_ids,
                                 :provisioning_template_ids => location_dup.provisioning_template_ids,
                                 :compute_resource_ids => location_dup.compute_resource_ids,
                                 :organization_ids => location_dup.organization_ids
                               }
                   }, set_session_user
    assert_equal new_location.environment_ids.sort, location.environment_ids.sort
    assert_equal new_location.hostgroup_ids.sort, location.hostgroup_ids.sort
    assert_equal new_location.environment_ids.sort, location.environment_ids.sort
    assert_equal new_location.domain_ids.sort, location.domain_ids.sort
    assert_equal new_location.medium_ids.sort, location.medium_ids.sort
    assert_equal new_location.user_ids.sort, location.user_ids.sort
    assert_equal new_location.smart_proxy_ids.sort, location.smart_proxy_ids.sort
    assert_equal new_location.provisioning_template_ids.sort, location.provisioning_template_ids.sort
    assert_equal new_location.compute_resource_ids.sort, location.compute_resource_ids.sort
    assert_equal new_location.organization_ids.sort, location.organization_ids.sort
    put :update, {:id => Medium.first, :medium => {:name => nil}}, set_session_user
    put :update, {:id => Medium.first, :medium => {:name => "MyUpdatedMedia"}}, set_session_user
    get :edit, {:id => Medium.first.id}, set_session_user.merge(:user => users(:one).id)
  test "should clone organization with assocations" do
    assert_difference "Organization.count", 1 do
      post :create, {:organization => {:name => "organization_dup_name",
                                       :environment_ids => organization_dup.environment_ids,
                                       :hostgroup_ids => organization_dup.hostgroup_ids,
                                       :subnet_ids => organization_dup.hostgroup_ids,
                                       :domain_ids => organization_dup.domain_ids,
                                       :medium_ids => organization_dup.medium_ids,
                                       :user_ids => organization_dup.user_ids,
                                       :smart_proxy_ids => organization_dup.smart_proxy_ids,
                                       :provisioning_template_ids => organization_dup.provisioning_template_ids,
                                       :compute_resource_ids => organization_dup.compute_resource_ids,
                                       :location_ids => organization_dup.location_ids
      }
    assert_equal new_organization.environment_ids.sort, organization.environment_ids.sort
    assert_equal new_organization.hostgroup_ids.sort, organization.hostgroup_ids.sort
    assert_equal new_organization.environment_ids.sort, organization.environment_ids.sort
    assert_equal new_organization.domain_ids.sort, organization.domain_ids.sort
    assert_equal new_organization.medium_ids.sort, organization.medium_ids.sort
    assert_equal new_organization.user_ids.sort, organization.user_ids.sort
    assert_equal new_organization.smart_proxy_ids.sort, organization.smart_proxy_ids.sort
    assert_equal new_organization.provisioning_template_ids.sort, organization.provisioning_template_ids.sort
    assert_equal new_organization.compute_resource_ids.sort, organization.compute_resource_ids.sort
    assert_equal new_organization.location_ids.sort, organization.location_ids.sort
    assert_equal ProvisioningTemplate.find(templates(:pxekickstart).id).locked, true
    assert_equal ProvisioningTemplate.find(templates(:locked).id).locked, false
    assert ProvisioningTemplate.exists?(config_template.id)
    assert !ProvisioningTemplate.exists?(config_template.id)
      assert_difference('TemplateCombination.count', 1) do
        assert_difference('ProvisioningTemplate.count', 1) do
        @template_combination.reload
        assert_equal new_environment, @template_combination.environment
    lookup_keys_added = overridable_lookup_keys(puppetclass, assigns(:obj))
    assert_equal 1, lookup_keys_added.count
    assert lookup_keys_added.map(&:key).include?("special_info")
    refute lookup_keys_added.map(&:key).include?("custom_class_param")
    lookup_keys_added = overridable_lookup_keys(puppetclass, hostgroup)
    assert_equal 2, lookup_keys_added.count
    assert lookup_keys_added.map(&:key).include?("special_info")
    assert lookup_keys_added.map(&:key).include?("custom_class_param")
    lookup_keys_added = overridable_lookup_keys(puppetclass, host)
    assert_equal 2, lookup_keys_added.count
    assert lookup_keys_added.map(&:key).include?("special_info")
    assert lookup_keys_added.map(&:key).include?("custom_class_param")
    lookup_keys_added = overridable_lookup_keys(puppetclass, hostgroup)
    assert_equal 2, lookup_keys_added.count
    assert lookup_keys_added.map(&:key).include?("special_info")
    assert lookup_keys_added.map(&:key).include?("custom_class_param")
    env = FactoryGirl.create(:environment)
    env = FactoryGirl.create(:environment)
    put :update, {:id => Realm.first.name,
                  :realm => { :realm_proxy_id => SmartProxy.first.id } }, set_session_user
    assert_equal SmartProxy.first.id, Realm.first.realm_proxy_id
    put :update, {:id => SmartProxy.first,:smart_proxy => {:url => "http://elsewhere.com:8443"}}, set_session_user
    assert_equal "http://elsewhere.com:8443", SmartProxy.first.url
    @model = Subnet.first
    put :update, {:id => Subnet.first, :subnet => {:network => nil}}, set_session_user
    put :update, {:id => Subnet.first, :subnet => {:network => '192.168.100.10'}}, set_session_user
    assert_equal '192.168.100.10', Subnet.first.network
    assert Subnet.exists?(subnet.id)
    subnet = Subnet.first
    subnet.hosts.clear
    subnet.interfaces.clear
    subnet.domains.clear
    delete :destroy, {:id => subnet}, set_session_user
    assert !Subnet.exists?(subnet.id)
    assert_difference 'Subnet.count', 1 do
    user = FactoryGirl.create(:user, :with_mail, :admin => false)
    FactoryGirl.create(:filter, :role => user.roles.first, :permissions => Permission.where(:name => 'view_hosts'), :search => "name = #{@rh_host.name}")
    FactoryGirl.create(:filter, :role => user.roles.first, :permissions => Permission.where(:name => 'view_hosts'), :search => "name = does_not_exist")
    refute User.find_by_login('foo').admin
    assert User.find_by_login('foo').admin
    mod_user = User.find_by_id(user.id)
    user = User.find_by_id(user.id)
    mod_user = User.find_by_id(user.id)
    mod_user = User.find_by_id(user.id)

    assert User.exists?(user.id)
    assert !User.find_by_login(user.login).mail.blank?
    assert_redirected_to edit_user_path(User.find_by_login('ares'))
    get :edit, { :id => users(:two) }
    put :update, { :id => users(:two).id, :user => { :firstname => 'test' } }
    user = User.find_by_login('ldap-user')
      updated_user = User.find(users(:one).id)
  def setup_user
    @request.session[:user] = users(:one).id
    users(:one).roles       = [Role.default, Role.find_by_name('Viewer')]
  end

    setup_user
    setup_user
      location
      organization
one:
  taxonomy: location1
  taxable: one
  taxable_type: "Subnet"

three:
  taxonomy: organization1
  taxable: one
  taxable_type: "Subnet"

ten:
  taxonomy: location1
  taxable: one
  taxable_type: "Medium"

ten2:
  taxonomy: organization1
  taxable: one
  taxable_type: "Medium"

    FactoryGirl.create(:host)
    assert_new_button(locations_path,"New Location",new_location_path)
    FactoryGirl.create(:host)
      users(:one).locations << taxonomies(:location1)
      users(:one).locations << taxonomies(:location1)
      users(:one).organizations << taxonomies(:organization1)
      FactoryGirl.create(:filter, :role => user_role.role, :permissions => Permission.where(:name => 'view_hosts'), :unlimited => true)
    assert_difference('LookupValue.count') do
      :subnet => subnets(:two), :architecture => architectures(:x86_64), :puppet_proxy => smart_proxies(:puppetmaster), :medium => media(:one),
    interface = Nic::Managed.create! :ip => "3.3.4.127", :mac => "cabbccddeeff", :host => FactoryGirl.create(:host), :subnet => subnet, :name => "a" + FactoryGirl.create(:host).name, :domain => domain
      user_role = FactoryGirl.create(:user_user_role)
      FactoryGirl.create(:filter, :role => user_role.role, :permissions => Permission.where(:name => 'view_hosts'), :search => "hostgroup_id = #{@target_host.hostgroup_id}")
      as_user user_role.owner do
        assert_equal @target_reports.map(&:id).sort, Report.my_reports.map(&:id).sort
      end
      assert_equal selected_ids[:subnet_ids].sort, subnet_ids.sort
      assert_equal selected_ids[:medium_ids].sort, medium_ids.sort
      assert_equal selected_ids[:hostgroup_ids], []
      assert_equal selected_ids[:user_ids], [users(:scoped).id]
      assert_equal selected_ids[:compute_resource_ids], [compute_resources(:one).id]
      taxonomy_dup.name = "taxonomy_dup_name"
      assert taxonomy_dup.save!
                                     users(:one)).pluck(:id).sort
      assert_equal parent.selected_ids, taxonomy.inherited_ids
      parent.update_attribute(:domains,[domain1,domain2])
      parent.update_attribute(:subnets,[subnet])
                         :"#{taxonomy_name}"         => parent,
                         :"#{taxonomy_name}"         => parent,
      taxonomy.selected_or_inherited_ids.each do |k,v|
        assert_equal v.sort, parent.used_and_selected_ids[k].sort
    test "multiple inheritence" do
    assert_equal subnet, Subnet::Ipv6.subnet_for(get_ip(subnet, 10))
    assert_match /is being used by/, subnet.errors.full_messages.join("\n")
      user = FactoryGirl.create(:user, :organizations => [@org, org2])
  test ".taxable_ids can work with empty array returning nil" do
    dummy_class = @dummy.class
    assert_nil dummy_class.taxable_ids([], [])
  end
  test ".taxable_ids (and .inner_select) can work with array of taxonomies" do
    loc1 = FactoryGirl.create(:location)
    loc2 = FactoryGirl.create(:location, :parent_id => loc1.id)
    loc3 = FactoryGirl.create(:location, :parent_id => loc2.id)
    loc4 = FactoryGirl.create(:location)
    org = FactoryGirl.create(:organization)
    env1 = FactoryGirl.create(:environment, :organizations => [org], :locations => [loc2])
    env2 = FactoryGirl.create(:environment, :organizations => [org])
    env3 = FactoryGirl.create(:environment, :locations => [loc2])
    env4 = FactoryGirl.create(:environment, :locations => [loc4])
    env5 = FactoryGirl.create(:environment, :locations => [loc1])
    env6 = FactoryGirl.create(:environment, :locations => [loc3])

    taxable_ids = Environment.taxable_ids([loc2, loc4], org, :subtree_ids)
    visible = [ env1 ]
    invisible = [ env2, env3, env4, env5, env6 ]
    visible.each { |env| assert_includes taxable_ids, env.id }
    invisible.each { |env| refute_includes taxable_ids, env.id }

    taxable_ids = Environment.taxable_ids([], org, :subtree_ids)
    visible = [ env1, env2 ]
    invisible = [ env3, env4, env5, env6 ]
    visible.each { |env| assert_includes taxable_ids, env.id }
    invisible.each { |env| refute_includes taxable_ids, env.id }

    taxable_ids = Environment.taxable_ids(loc2, [], :subtree_ids)
    visible = [ env1, env3, env5, env6 ]
    invisible = [ env2, env4 ]
    visible.each { |env| assert_includes taxable_ids, env.id }
    invisible.each { |env| refute_includes taxable_ids, env.id }

    taxable_ids = Environment.taxable_ids([loc2, loc4], [], :subtree_ids)
    visible = [ env1, env3, env4, env5, env6 ]
    invisible = [ env2 ]
    visible.each { |env| assert_includes taxable_ids, env.id }
    invisible.each { |env| refute_includes taxable_ids, env.id }
    used_organizations = user.used_organization_ids
    assert_empty used_organizations
    assert_equal used_organizations.count, 0
    user = FactoryGirl.create(:user)
      assert_not_equal last_login, User.find(user.id).last_login_on
      reloaded_user = User.find(user.id)
    record = User.new :login => "dummy", :mail => "j@j.com", :auth_source_id => AuthSourceInternal.first.id
    record               = User.new :login    => "dummy", :mail => "j@j.com", :auth_source_id => AuthSourceInternal.first.id,
                                    :role_ids => [create_role.id.to_s]
      record               = User.new :login    => "dummy", :mail => "j@j.com", :auth_source_id => AuthSourceInternal.first.id,
                                      :role_ids => [extra_role.id].map(&:to_s)
    user = FactoryGirl.create(:user)
    user.organizations << org1
    as_user user do
      new_user = FactoryGirl.build(:user)
      refute new_user.save
    users(:one).default_location = Location.first
    users(:one).default_organization = Organization.first
        assert User.current.locations << Location.current
        assert User.current.organizations << Organization.current
  setup :setup_set_script_name, :set_api_user, :turn_off_login, :disable_webpack
      assert_equal @envs, lks.last.environments
      assert_equal @envs, lks.last.environments
      assert_equal @envs, lks.last.environments
    User.current = FactoryGirl.build(:user, :admin => true)
      assert_difference 'User.where(:login => "admin").count', 1 do
      user = User.find_by_login('admin')
      assert_difference 'User.where(:login => "seed_test").count', 1 do
      user = User.find_by_login('seed_test')
    count = Ptable.count
    assert_not_equal count, Ptable.count
    refute Ptable.where(:os_family => nil).any?
    count = Medium.count
    assert_not_equal count, Medium.count
    refute Medium.where(:os_family => nil).any?
    count = ProvisioningTemplate.count
    assert_not_equal count, ProvisioningTemplate.count
        assert Ptable.where(:template => File.read(tmpl)).any?, "No partition table containing #{tmpl}"
        assert ProvisioningTemplate.where(:template => File.read(tmpl)).any?, "No template containing #{tmpl}"
    count = Bookmark.where(:public => true).count
    assert_not_equal count, Bookmark.where(:public => true).count
    ProvisioningTemplate.without_auditing { ProvisioningTemplate.find_by_name('Kickstart default').update_attributes(:template => 'test') }
    refute_equal ProvisioningTemplate.find_by_name('Kickstart default').template, 'test'
    assert_equal 1, ProvisioningTemplate.destroy_all(:name => 'Kickstart default').size
    refute ProvisioningTemplate.find_by_name('Kickstart default')
    tmpl = ProvisioningTemplate.find_by_name('Kickstart default')
    refute ProvisioningTemplate.find_by_name('Kickstart default')
    assert Organization.find_by_name('seed_test')
    refute Organization.find_by_name('seed_test')
    assert Location.find_by_name('seed_test')
    refute Location.find_by_name('seed_test')
    assert_equal [], view_permissions - Role.find_by_name('Viewer').permissions

Fixed code:
    allowed_smart_proxies = if features.blank?
                              SmartProxy.unscoped.all
                            else
                              SmartProxy.unscoped.with_features(*features)
                            end
  def auth_smart_proxy(proxies = SmartProxy.unscoped.all, require_cert = true)
    if !request.post? && params[:status].blank? && User.unscoped.exists?(session[:user].presence)
  TAXONOMY_JOIN_TABLE = :taxable_taxonomies
    has_many TAXONOMY_JOIN_TABLE, :dependent => :destroy, :as => :taxable
             :through => TAXONOMY_JOIN_TABLE, :source => :taxonomy,
             :through => TAXONOMY_JOIN_TABLE, :source => :taxonomy,
      scope = block_given? ? yield : where(nil)
      return scope unless Taxonomy.enabled_taxonomies.present?
      # Return everything (represented by nil), including objects without
      # taxonomies. This value should only be returned for admin users.
      return nil if any_context?(loc) && any_context?(org) &&
        User.current.try(:admin?)

      ids = unscoped.pluck(:id)
      ids &= inner_ids(loc, Location, inner_method) if SETTINGS[:locations_enabled]
      ids &= inner_ids(org, Organization, inner_method) if SETTINGS[:organizations_enabled]

      if self == User
        # In the case of users we want the taxonomy scope to get both the users
        # of the taxonomy, admins, and the current user.
        ids.concat(admin_ids)
        ids << User.current.id if User.current.present?

      ids
    end

    # Returns the IDs available for the passed context.
    # Passing a nil or [] value as taxonomy equates to "Any context".
    # Any other value will be understood as 'IDs available in this taxonomy'.
    def inner_ids(taxonomy, taxonomy_class, inner_method)
      return unscoped.pluck("#{table_name}.id") if taxonomy_class.ignore?(to_s)
      return inner_select(taxonomy, inner_method) if taxonomy.present?
      return [] unless User.current.present?
      # Any available taxonomy to the current user
      return unscoped.pluck("#{table_name}.id") if User.current.admin?

      taxonomy_relation = taxonomy_class.to_s.underscore.pluralize
      any_context_taxonomies = User.current.
        taxonomy_and_child_ids(:"#{taxonomy_relation}")
      unscoped.joins(TAXONOMY_JOIN_TABLE).
        where("#{TAXONOMY_JOIN_TABLE}.taxonomy_id" => any_context_taxonomies).
        pluck(:id)
    end

    def any_context?(taxonomy)
      taxonomy.blank?
      conditions[:organization_id] = Array(org).map { |o| o.subtree_ids }.flatten.uniq unless org.nil?
      conditions[:location_id] = Array(loc).map { |l| l.subtree_ids }.flatten.uniq unless loc.nil?
      User.unscoped.except_hidden.find_by_login(self.user)
          User.unscoped.find_by_login(user_name).tap do |obj|
      ids[col] = Array(taxonomy.send(col)).uniq
      ids["#{taxonomy_type.tableize.singularize}_ids"] = taxonomy_type.constantize.pluck(:id).uniq
      ids[col] = populate_values ? Array(self.send(col)).uniq : []
    Audit.unscoped.where("user_id NOT IN (?)", User.unscoped.pluck(:id)).update_all(:user_id => nil)
    Domain.where("dns_id NOT IN (?)", SmartProxy.unscoped.pluck(:id)).update_all(:dns_id => nil)
    Subnet.where("dhcp_id NOT IN (?)", SmartProxy.unscoped.pluck(:id)).update_all(:dhcp_id => nil)
    Subnet.where("dns_id NOT IN (?)", SmartProxy.unscoped.pluck(:id)).update_all(:dns_id => nil)
    Subnet.where("tftp_id NOT IN (?)", SmartProxy.unscoped.pluck(:id)).update_all(:tftp_id => nil)
    Image.where("architecture_id NOT IN (?)", Architecture.unscoped.pluck(:id)).update_all(:architecture_id => nil)
    Image.where("compute_resource_id NOT IN (?)", ComputeResource.unscoped.pluck(:id)).update_all(:compute_resource_id => nil)
    Nic::Base.where("domain_id NOT IN (?)", Domain.unscoped.pluck(:id)).update_all(:domain_id => nil)
    Nic::Base.where("host_id NOT IN (?)", Host::Base.unscoped.pluck(:id)).update_all(:host_id => nil)
    Nic::Base.where("subnet_id NOT IN (?)", Subnet.unscoped.pluck(:id)).update_all(:subnet_id => nil)
    OsDefaultTemplate.where("config_template_id NOT IN (?)", FakeConfigTemplate.unscoped.pluck(:id)).update_all(:config_template_id => nil)
    OsDefaultTemplate.where("template_kind_id NOT IN (?)", TemplateKind.unscoped.pluck(:id)).update_all(:template_kind_id => nil)
    TemplateCombination.where("config_template_id NOT IN (?)", FakeConfigTemplate.unscoped.pluck(:id)).update_all(:config_template_id => nil)
    TemplateCombination.where("environment_id NOT IN (?)", Environment.unscoped.pluck(:id)).update_all(:environment_id => nil)
  kinds[type] = TemplateKind.unscoped.find_by_name(type)
  kinds[type] ||= TemplateKind.unscoped.create(:name => type)
organizations = Organization.unscoped.all
locations = Location.unscoped.all
    if (t = ProvisioningTemplate.unscoped.find_by_name(input[:name])) && !audit_modified?(ProvisioningTemplate, input[:name])
organizations = Organization.unscoped.all
locations = Location.unscoped.all
    if (p = Ptable.unscoped.find_by_name(input[:name])) && !audit_modified?(Ptable, input[:name])
os_suse = Operatingsystem.unscoped.where(:type => "Suse") || Operatingsystem.unscoped.where("name LIKE ?", "suse")
    next if Medium.unscoped.where(['name = ? OR path = ?', input[:name], input[:path]]).any?
  setup :set_admin
  def set_admin
    User.current = users(:admin)
  end

      permission = Permission.find_by_name("#{operation}_#{type}") ||
        FactoryGirl.create(:permission, :name => "#{operation}_#{type}")
    assert_difference('AuthSourceLdap.unscoped.count', 1) do
    assert_difference('AuthSourceLdap.unscoped.count', -1) do
    assert_equal "new_description",
      ComputeResource.unscoped.find_by_name('mycompute').description
    assert_difference('ComputeResource.unscoped.count', -1) do
    assert_equal "new_description",
      ComputeResource.unscoped.find_by_name('mycompute').description
    assert_difference('ComputeResource.unscoped.count', -1) do
    assert ProvisioningTemplate.unscoped.exists?(config_template.id)
    refute ProvisioningTemplate.unscoped.exists?(config_template.id)
    put :update, { :id => Domain.unscoped.first.to_param, :domain => { :name => "domain.new" } }
    assert_equal "domain.new", Domain.unscoped.first.name
    assert_difference('Environment.unscoped.count') do
    assert_difference('Environment.unscoped.count', -1) do
    assert_difference('Hostgroup.unscoped.count') do
    assert_difference('Hostgroup.unscoped.count', -1) do
    assert_no_difference('Hostgroup.unscoped.count') do
    assert_difference('Hostgroup.unscoped.count') do
    assert_equal hostgroups(:common).id.to_s, Hostgroup.unscoped.find_by_name("db").ancestry
    assert_difference('Medium.unscoped.count', +1) do
    assert_difference('Medium.unscoped.count', -1) do
    assert_difference('Ptable.unscoped.count') do
    assert_difference('Ptable.unscoped.count', -0) do
    assert_difference('Ptable.unscoped.count', -1) do
    assert_difference('SmartProxy.unscoped.count') do
    assert_difference('SmartProxy.unscoped.count', -1) do
    assert_difference('Environment.unscoped.count', 2) do
        assert_difference('Puppetclass.unscoped.count', 1) do
      assert_difference('Puppetclass.unscoped.count', 0) do
    assert_difference('Environment.unscoped.count', -1) do
      assert_difference('Environment.unscoped.find_by_name("env1").puppetclasses.count', -2) do
    assert_difference('LookupKey.unscoped.count', 1) do
    assert_difference('Environment.unscoped.count', 0) do
      assert_difference('Environment.unscoped.count', 1) do
    assert_difference('Subnet::Ipv4.unscoped.count') do
    assert_equal 'Subnet::Ipv4', Subnet.unscoped.find_by_name('QA2').type
    assert_difference('Subnet::Ipv6.unscoped.count') do
    assert_equal 'Subnet::Ipv6', Subnet.unscoped.find_by_name('QA2').type
    assert_difference('Subnet.unscoped.count', -1) do
    assert_difference('Subnet.unscoped.count', 0) do
    mod_user = User.unscoped.find_by_id(user.id)
    assert User.unscoped.find_by_id(user.id).admin?
    mod_user = User.unscoped.find_by_id(user.id)
    mod_user = User.unscoped.find_by_id(user.id)
    mod_user = User.unscoped.find_by_id(user.id)
    refute User.unscoped.exists?(user.id)
      assert User.unscoped.exists?(user.id)
      assert User.unscoped.find_by_login('new_admin').admin?
  test "#update should allow updating myself without any special permissions" do
    assert_difference('AuthSourceLdap.unscoped.count', 1) do
    assert_difference('AuthSourceLdap.unscoped.count', -1) do
    assert_equal "new_description",
      ComputeResource.unscoped.find_by_name('mycompute').description
    assert_difference('ComputeResource.unscoped.count', -1) do
    assert_equal "new_description",
      ComputeResource.unscoped.find_by_name('mycompute').description
    assert_difference('ComputeResource.unscoped.count', -1) do
      proxy.update_attribute(:url, 'http://configreports.foreman')
      post :create, { :config_report => create_a_puppet_transaction_report }
      assert_response :forbidden
      assert_response :forbidden
      assert_response :forbidden
      assert_response :forbidden
    refute Report.unscoped.find_by_id(report.id)
    assert ProvisioningTemplate.unscoped.exists?(config_template.id)
    refute ProvisioningTemplate.unscoped.exists?(config_template.id)
    templates(:pxekickstart).organizations = User.current.organizations
    templates(:pxekickstart).locations = User.current.locations
    assert_equal "domain.new", Domain.unscoped.first.name
    assert_equal taxonomies(:location1).domains.length, assigns(:domains).length
    assert_equal assigns(:domains), taxonomies(:location1).domains
    assert_equal taxonomies(:organization1).domains.length, assigns(:domains).length
    assert_equal taxonomies(:organization1).domains, assigns(:domains)
    assert_difference('Environment.unscoped.count') do
    assert_difference('Environment.unscoped.count', -1) do
    assert_difference('Hostgroup.unscoped.count') do
    assert_difference('Hostgroup.unscoped.count', -1) do
    assert_difference('Hostgroup.unscoped.count') do
    assert_no_difference('Hostgroup.unscoped.count') do
    assert_difference('Hostgroup.unscoped.count') do
    assert_equal hostgroups(:common).id.to_s,
      Hostgroup.unscoped.find_by_name("db").ancestry
    as_admin do
      assert_equal compute_attrs.vm_interfaces.count,
        last_record.interfaces.count
      assert_equal expected_compute_attributes(compute_attrs, 0),
        last_record.interfaces.find_by_mac('00:11:22:33:44:00').compute_attributes
      assert_equal expected_compute_attributes(compute_attrs, 1),
        last_record.interfaces.find_by_mac('00:11:22:33:44:01').compute_attributes
    end
    as_admin do
      @host.interfaces.reload
      assert_equal compute_attrs.vm_interfaces.count, @host.interfaces.count
      assert_equal expected_compute_attributes(compute_attrs, 0), @host.interfaces.find_by_primary(true).compute_attributes
      assert_equal expected_compute_attributes(compute_attrs, 1), @host.interfaces.find_by_primary(false).compute_attributes
    end
    assert_equal hostgroup.id, Host.find_by(:name => hostname).hostgroup_id
    proxy.update_attribute(:url, 'https://factsimporter.foreman')
    assert_difference('Location.unscoped.count', -1) do
    assert_difference('Location.unscoped.count', -1) do
    @location.ignore_types = ["Hostgroup", "Environment", "User", "Medium",
                              "Subnet", "SmartProxy", "ProvisioningTemplate",
                              "ComputeResource", "Realm"]
        put :update, {
          :id => @location.to_param,
          :location => { :domain_ids => Domain.unscoped.pluck(:id) }
        }
        User.current = users(:admin)
        # as_admin gets invalidated after the call, so we need to restore it
        # in order to make the call to @location.domains.count  in the right
        # context
    assert_difference('Medium.unscoped.count', +1) do
    assert_difference('Medium.unscoped.count', -1) do
    assert_equal '123', Host.unscoped.find_by_name(@host.name).parameters.
      order("parameters.updated_at").last.value
    assert_equal Domain.unscoped.find_by_name("mydomain.net").parameters.
      order("parameters.updated_at").last.value, "123"
    assert_equal Subnet.unscoped.find_by_name("five").parameters.
      order("parameters.updated_at").last.value, "123"
    assert_equal Hostgroup.unscoped.find_by_name("Common").group_parameters.
      order("parameters.updated_at").last.value, "123"
    assert_equal Operatingsystem.unscoped.find_by_name("Redhat").parameters.
      order("parameters.updated_at").last.value, "123"
    assert ProvisioningTemplate.unscoped.exists?(provisioning_template.id)
    refute ProvisioningTemplate.unscoped.exists?(provisioning_template.id)
    assert_difference('Ptable.unscoped.count') do
    assert_difference('Ptable.unscoped.count') do
    assert_difference('Ptable.unscoped.count', 0) do
    assert_difference('Ptable.unscoped.count', -1) do
    realm_id = Realm.unscoped.first.id
    put :update, { :id => realm_id, :realm => { :name => "realm.new" } }
    assert_equal "realm.new", Realm.unscoped.find(realm_id).name
    refute Realm.unscoped.find_by_id(realm['id'])
    assert_equal taxonomies(:location1).realms.length, assigns(:realms).length
    assert_equal assigns(:realms), taxonomies(:location1).realms
    assert_equal taxonomies(:organization1).realms.length, assigns(:realms).length
    assert_equal assigns(:realms), taxonomies(:organization1).realms
      proxy.update_attribute(:url, 'http://foremanimporter.report')
    expected_proxy_ids = SmartProxy.unscoped.with_features("TFTP").map { |p| p.id }
    expected_proxy_ids = SmartProxy.unscoped.with_features("TFTP").map { |p| p.id }
    assert_difference('SmartProxy.unscoped.count') do
    assert_difference('SmartProxy.unscoped.count', -1) do
    assert_difference('Environment.unscoped.count', 2) do
        assert_difference('Puppetclass.unscoped.count', 1) do
      assert_difference('Puppetclass.unscoped.count', 0) do
    assert_difference('Environment.unscoped.count', -1) do
      assert_difference('Environment.unscoped.find_by_name("env1").puppetclasses.count', -2) do
    assert_difference('LookupKey.unscoped.count', 1) do
    assert_difference('Environment.unscoped.count', 0) do
      assert_difference('Environment.unscoped.count', 1) do
    assert_difference('Environment.unscoped.count', 0) do
    assert_difference('LookupKey.unscoped.count', 0) do
      post :import_puppetclasses, {:id => smart_proxies(:puppetmaster).id, :except => 'new,updated'}, set_session_user
      assert_difference('Puppetclass.unscoped.count', 1) do
      assert_difference('Puppetclass.unscoped.count', 2) do
    assert_difference('Subnet.unscoped.count') do
    assert_difference('Subnet.unscoped.count') do
    subnet = Subnet.unscoped.find_by_name(valid_v4_attrs[:name])
    assert_difference('Subnet.unscoped.count') do
    assert_difference('Subnet.unscoped.count', -1) do
    assert_difference('Subnet.unscoped.count', 0) do
    mod_user = User.unscoped.find_by_id(user.id)
    assert User.unscoped.find_by_id(user.id).admin?
    mod_user = User.unscoped.find_by_id(user.id)
    mod_user = User.unscoped.find_by_id(user.id)
    mod_user = User.unscoped.find_by_id(user.id)
    refute User.unscoped.exists?(user.id)
      assert User.unscoped.exists?(user.id)
      as_admin do
        @user = FactoryGirl.create(:user)
      end
      get :index, {}, set_session_user.merge(:user => @user.id)
      assert_redirected_to edit_user_path(@user)
    @model = AuthSourceLdap.unscoped.first
    post :create, {:auth_source_ldap => {:name => AuthSourceLdap.unscoped.first.name}}, set_session_user
    put :update, {:id => AuthSourceLdap.unscoped.first, :auth_source_ldap => {:name => AuthSourceLdap.unscoped.first.name} }, set_session_user
    put :update, {:id => AuthSourceLdap.unscoped.first.id, :format => "weird", :auth_source_ldap => {:name => AuthSourceLdap.unscoped.first.name} }, set_session_user
    wierd_id = "#{AuthSourceLdap.unscoped.first.id}.weird"
    put :update, {:id => wierd_id, :auth_source_ldap => {:name => AuthSourceLdap.unscoped.first.name} }, set_session_user
    parameterized_id = "#{AuthSourceLdap.unscoped.first.id}-#{AuthSourceLdap.unscoped.first.name.parameterize}"
    put :update, {:id => parameterized_id, :auth_source_ldap => {:name => AuthSourceLdap.unscoped.first.name} }, set_session_user
    put :update, {:id => AuthSourceLdap.unscoped.first, :auth_source_ldap => {:name => AuthSourceLdap.unscoped.first.name} }, set_session_user
    auth_source_ldap = AuthSourceLdap.unscoped.first
    User.unscoped.where(:auth_source_id => auth_source_ldap.id).update_all(:auth_source_id => nil)
    refute AuthSourceLdap.unscoped.exists?(auth_source_ldap.id)
      get :edit, { :id => AuthSourceLdap.unscoped.first.id },
    auth_source_ldap = AuthSourceLdap.unscoped.find(auth_source_ldap.id)
    put :test_connection, {:id => AuthSourceLdap.unscoped.first, :auth_source_ldap => {:name => AuthSourceLdap.unscoped.first.name} }, set_session_user
    put :test_connection, {:id => AuthSourceLdap.unscoped.first, :auth_source_ldap => {:name => AuthSourceLdap.unscoped.first.name} }, set_session_user
    auth_source_ldap_params = { :name => AuthSourceLdap.unscoped.first.name,
    put :update, { :id => AuthSourceLdap.unscoped.first,
      AuthSourceLdap.unscoped.first.organizations.to_a
      AuthSourceLdap.unscoped.first.locations.to_a
    assert_difference('ComputeResource.unscoped.count', 0) do
    assert_difference('ComputeResource.unscoped.count', +1) do
    @compute_resource = ComputeResource.unscoped.find(@compute_resource.id)
    @compute_resource = ComputeResource.unscoped.find(@compute_resource.id)
    assert_difference('ComputeResource.unscoped.count', 0) do
    assert_difference('ComputeResource.unscoped.count', 0) do
    assert_difference('ComputeResource.unscoped.count', -1) do
    @compute_resource.organizations = User.current.organizations
    @compute_resource.locations = User.current.locations
    @model = domains(:mydomain)
    put :update, {:id => @model.to_param, :domain => {:name => @model.name }}, set_session_user
    put :update, {:id => @model.to_param, :domain => {:name => @model.name }}, set_session_user
    domain = @model
    get :edit, {:id => @model.id}
    assert_difference 'Environment.unscoped.count' do
    env = Environment.unscoped.find(environment.id)
    assert_difference('Environment.unscoped.count', -1) do
    assert_equal ["a", "b", "c"],
      Environment.unscoped.find_by_name("env1").puppetclasses.map(&:name).sort
    envs = Environment.unscoped.find_by_name("env1").puppetclasses.map(&:name).sort
    assert_equal ["a", "b", "c"], envs
    assert_equal [], Environment.unscoped.find_by_name("env3").puppetclasses.map(&:name).sort
       {"obsolete" =>
        {"env1"  => '["a","b","c","_destroy_"]'}
       }
    }, set_session_user
    assert Environment.unscoped.find_by_name("env1").hosts.count > 0
    assert Environment.unscoped.find_by_name("env1")
      {"changed" =>
       {"new" =>
        {"new" => '{"a":{"new":{}}}'}
       }
    }, set_session_user
    assert(Environment.unscoped.all.map(&:name).include?('new'), 'Should include environment with name "new"')
    as_admin do
      users(:one).roles = [Role.default, Role.find_by_name('Viewer')]
    end
    get :nest, {:id => hostgroups(:common).id}, set_session_user
    get :clone, {:id => hostgroups(:common)}, set_session_user
    get :edit, {:id => hostgroups(:common)}, set_session_user
    put :update, {:id => hostgroups(:common), :hostgroup => { :name => '' }}, set_session_user
    put :update, {:id => hostgroups(:common), :hostgroup => { :name => hostgroups(:common).name }}, set_session_user
    get :edit, {:id => hostgroups(:common).id}, set_session_user.merge(:user => users(:one).id)
    assert_response :forbidden
    xhr :post, :domain_selected, {:id => hostgroups(:common), :hostgroup => {}, :domain_id => domain.id, :format => :json}, set_session_user
    xhr :post, :domain_selected, {:id => hostgroups(:common), :hostgroup => {}, :format => :json, :domain_id => nil}, set_session_user
    post :architecture_selected, {:id => hostgroups(:common), :hostgroup => {}, :architecture_id => nil}, set_session_user
      hostgroup = Hostgroup.unscoped.where(:name => "test_it").last
      as_admin do
        assert_equal "overridden", hostgroup.parameters["x"]
      end
      as_admin do
        child.reload
        assert_equal "overridden", child.parameters["x"]
      end
      as_admin do
        child.reload
        assert_equal "overridden", child.parameters["y"]
        assert_equal "", child.parameters["x"]
      end
    assert_difference 'Host.unscoped.count' do
    assert_difference 'Host.unscoped.count' do
    assert_difference('Host.unscoped.count', -1) do
      @host2.organization = users(:two).organizations.first
      @host2.location = users(:two).locations.first
    as_admin do
      hosts.each { |host| assert_equal hostgroup, host.reload.hostgroup }
    end
      as_admin do
        host = Host.unscoped.find_by_name(name)
        assert_not_nil host
        assert_equal host.hostgroup, hostgroup
      end
    as_admin do
      assert_equal environments(:global_puppetmaster), @host1.reload.environment
      assert_equal environments(:global_puppetmaster), @host2.reload.environment
    end
    assert_equal hostgroup.environment_id, Host.unscoped.find(@host1.id).environment_id
    assert_equal hostgroup.environment_id, Host.unscoped.find(@host2.id).environment_id
    as_admin do
      assert_equal users(:one).id_and_type, @host1.reload.is_owned_by
      assert_equal users(:one).id_and_type, @host2.reload.is_owned_by
    end
        as_admin do
          assert_equal proxy, host.reload.puppet_ca_proxy
        end
    host = Host.first
    assert_difference "location.hosts.count", (Host.unscoped.count - cnt_hosts_location) do
    assert_difference "organization.hosts.count", (Host.unscoped.count - cnt_hosts_organization) do
    User.current.organizations << taxonomies(:organization1)
    User.current.locations << taxonomies(:location1)
    assert_difference('Image.unscoped.count') do
    as_admin do
      assert_redirected_to compute_resource_path(@image.compute_resource)
    end
    as_admin do
      assert_redirected_to compute_resource_path(@image.compute_resource)
    end
    as_admin do
      assert_redirected_to compute_resource_path(@image.compute_resource)
    end
  test "should clone location with associations" do
    assert_difference "Location.unscoped.count", 1 do
      post :create, {
        :location => location_dup.selected_ids.each { |_,v| v.uniq! }
          .merge(:name => 'location_dup_name')
      }, set_session_user
    assert_equal new_location.environment_ids.uniq.sort, location.environment_ids.uniq.sort
    assert_equal new_location.hostgroup_ids.uniq.sort, location.hostgroup_ids.uniq.sort
    assert_equal new_location.environment_ids.uniq.sort, location.environment_ids.uniq.sort
    assert_equal new_location.domain_ids.uniq.sort, location.domain_ids.uniq.sort
    assert_equal new_location.medium_ids.uniq.sort, location.medium_ids.uniq.sort
    assert_equal new_location.user_ids.uniq.sort, location.user_ids.uniq.sort
    assert_equal new_location.smart_proxy_ids.uniq.sort, location.smart_proxy_ids.uniq.sort
    assert_equal new_location.provisioning_template_ids.uniq.sort, location.provisioning_template_ids.uniq.sort
    assert_equal new_location.compute_resource_ids.uniq.sort, location.compute_resource_ids.uniq.sort
    assert_equal new_location.organization_ids.uniq.sort, location.organization_ids.uniq.sort
    put :update, {:id => @model, :medium => {:name => nil}}, set_session_user
    put :update, {:id => @model, :medium => {:name => "MyUpdatedMedia"}}, set_session_user
    get :edit, {:id => @model.id}, set_session_user.merge(:user => users(:one).id)
  test "should clone organization with associations" do
    assert_difference "Organization.unscoped.count", 1 do
      post :create, {
        :organization => organization_dup.selected_ids.each { |_,v| v.uniq! }
          .merge(:name => 'organization_dup_name')
    assert_equal new_organization.environment_ids.uniq.sort, organization.environment_ids.uniq.sort
    assert_equal new_organization.hostgroup_ids.uniq.sort, organization.hostgroup_ids.uniq.sort
    assert_equal new_organization.environment_ids.uniq.sort, organization.environment_ids.uniq.sort
    assert_equal new_organization.domain_ids.uniq.sort, organization.domain_ids.uniq.sort
    assert_equal new_organization.medium_ids.uniq.sort, organization.medium_ids.uniq.sort
    assert_equal new_organization.user_ids.uniq.sort, organization.user_ids.uniq.sort
    assert_equal new_organization.smart_proxy_ids.uniq.sort, organization.smart_proxy_ids.uniq.sort
    assert_equal new_organization.provisioning_template_ids.uniq.sort, organization.provisioning_template_ids.uniq.sort
    assert_equal new_organization.compute_resource_ids.uniq.sort, organization.compute_resource_ids.uniq.sort
    assert_equal new_organization.location_ids.uniq.sort, organization.location_ids.uniq.sort
    assert_equal ProvisioningTemplate.unscoped.find(templates(:pxekickstart).id).locked, true
    assert_equal ProvisioningTemplate.unscoped.find(templates(:locked).id).locked, false
    assert ProvisioningTemplate.unscoped.exists?(config_template.id)
    assert !ProvisioningTemplate.unscoped.exists?(config_template.id)
      assert_difference('TemplateCombination.unscoped.count', 1) do
        assert_difference('ProvisioningTemplate.unscoped.count', 1) do
        as_admin do
          @template_combination.reload
          assert_equal new_environment, @template_combination.environment
        end
    as_admin do
      lookup_keys_added = overridable_lookup_keys(puppetclass, assigns(:obj))
      assert_equal 1, lookup_keys_added.count
      assert lookup_keys_added.map(&:key).include?("special_info")
      refute lookup_keys_added.map(&:key).include?("custom_class_param")
    end
    as_admin do
      lookup_keys_added = overridable_lookup_keys(puppetclass, hostgroup)
      assert_equal 2, lookup_keys_added.count
      assert lookup_keys_added.map(&:key).include?("special_info")
      assert lookup_keys_added.map(&:key).include?("custom_class_param")
    end
    as_admin do
      lookup_keys_added = overridable_lookup_keys(puppetclass, host)
      assert_equal 2, lookup_keys_added.count
      assert lookup_keys_added.map(&:key).include?("special_info")
      assert lookup_keys_added.map(&:key).include?("custom_class_param")
    end
    as_admin do
      lookup_keys_added = overridable_lookup_keys(puppetclass, hostgroup)
      assert_equal 2, lookup_keys_added.count
      assert lookup_keys_added.map(&:key).include?("special_info")
      assert lookup_keys_added.map(&:key).include?("custom_class_param")
    end
    env = FactoryGirl.create(:environment,
                             :organizations => [users(:one).organizations.first],
                             :locations => [users(:one).locations.first])
    env = FactoryGirl.create(:environment,
                             :organizations => [users(:one).organizations.first],
                             :locations => [users(:one).locations.first])
    realm_id = Realm.unscoped.first.id
    proxy_id = SmartProxy.unscoped.first.id
    put :update, {:id => realm_id,
                  :realm => { :realm_proxy_id => proxy_id } }, set_session_user
    assert_equal proxy_id, Realm.unscoped.find(realm_id).realm_proxy_id
    put :update, {:id => SmartProxy.unscoped.first,
                  :smart_proxy => {:url => "http://elsewhere.com:8443"}}, set_session_user
    assert_equal "http://elsewhere.com:8443", SmartProxy.unscoped.first.url
    @model = subnets(:one)
    subnet_id = @model
    put :update, {:id => subnet_id, :subnet => {:network => nil}}, set_session_user
    put :update, {:id => @model, :subnet => {:network => '192.168.100.10'}}, set_session_user
    assert_equal '192.168.100.10', Subnet.unscoped.find(@model).network
    assert Subnet.unscoped.exists?(subnet.id)
    @model.hosts.clear
    @model.interfaces.clear
    @model.domains.clear
    delete :destroy, {:id => @model}, set_session_user
    refute Subnet.exists?(@model.id)
    assert_difference 'Subnet.unscoped.count', 1 do
      users(:one).organizations << @rh_host.organization
      users(:one).locations << @rh_host.location
    user = FactoryGirl.create(:user, :with_mail, :admin => false,
                              :organizations => [@org], :locations => [@loc])
    FactoryGirl.create(:filter, :role => user.roles.first,
                       :permissions => Permission.where(:name => 'view_hosts'),
                       :search => "name = #{@rh_host.name}")
    FactoryGirl.create(:filter, :role => user.roles.first,
                       :permissions => Permission.where(:name => 'view_hosts'),
                       :search => "name = does_not_exist")
    refute User.unscoped.find_by_login('foo').admin
    assert User.unscoped.find_by_login('foo').admin
    mod_user = User.unscoped.find_by_id(user.id)
    user = User.unscoped.find_by_id(user.id)
    mod_user = User.unscoped.find_by_id(user.id)

    mod_user = User.unscoped.find_by_id(user.id)
    assert User.unscoped.exists?(user.id)
    assert !User.unscoped.find_by_login(user.login).mail.blank?
    assert_redirected_to edit_user_path(User.unscoped.find_by_login('ares'))
    get :edit, { :id => users(:two) }, set_session_user
    put :update, { :id => users(:two).id, :user => { :firstname => 'test' } },
      set_session_user
    AuthSourceLdap.any_instance.stubs(:organizations).returns([taxonomies(:organization1)])
    AuthSourceLdap.any_instance.stubs(:locations).returns([taxonomies(:location1)])
    user = User.unscoped.find_by_login('ldap-user')
      updated_user = User.unscoped.find(users(:one).id)
    setup_users
    setup_users
    organizations { [Organization.find_by_name('Organization 1')] } if SETTINGS[:organizations_enabled]
    locations { [Location.find_by_name('Location 1')] } if SETTINGS[:locations_enabled]
    organizations { [Organization.find_by_name('Organization 1')] } if SETTINGS[:organizations_enabled]
    locations { [Location.find_by_name('Location 1')] } if SETTINGS[:locations_enabled]
    organization { Organization.find_by_name('Organization 1') } if SETTINGS[:organizations_enabled]
    location { Location.find_by_name('Location 1') } if SETTINGS[:locations_enabled]
    organizations { [Organization.find_by_name('Organization 1')] } if SETTINGS[:organizations_enabled]
    locations { [Location.find_by_name('Location 1')] } if SETTINGS[:locations_enabled]
    organizations { [Organization.find_by_name('Organization 1')] } if SETTINGS[:organizations_enabled]
    locations { [Location.find_by_name('Location 1')] } if SETTINGS[:locations_enabled]

    organizations { [Organization.find_by_name('Organization 1')] } if SETTINGS[:organizations_enabled]
    locations { [Location.find_by_name('Location 1')] } if SETTINGS[:locations_enabled]
    organizations { [ Organization.find_by_name('Organization 1') ] }
    locations { [ Location.find_by_name('Location 1') ] }

user_one_org:
  taxonomy: organization1
  taxable: one
  taxable_type: "User"

user_one_loc:
  taxonomy: location1
  taxable: one
  taxable_type: "User"

subnet_one_org:
  taxonomy: organization1
  taxable: one
  taxable_type: "Subnet"

subnet_one_loc:
  taxonomy: location1
  taxable: one
  taxable_type: "Subnet"

compute_mycompute_org:
  taxonomy: organization1
  taxable: mycompute
  taxable_type: "ComputeResource"

compute_mycompute_loc:
  taxonomy: location1
  taxable: mycompute
  taxable_type: "ComputeResource"

hostgroup_common_org:
  taxonomy: organization1
  taxable: common
  taxable_type: "Hostgroup"

hostgroup_common_loc:
  taxonomy: location1
  taxable: common
  taxable_type: "Hostgroup"

medium_one_org:
  taxonomy: organization1
  taxable: one
  taxable_type: "Medium"

medium_one_loc:
  taxonomy: location1
  taxable: one
  taxable_type: "Medium"

auth_source_ldap_one_org:
  taxonomy: organization1
  taxable: one
  taxable_type: "AuthSource"

auth_source_ldap_one_loc:
  taxonomy: location1
  taxable: one
  taxable_type: "AuthSource"
    FactoryGirl.create(:host, :location => nil)
    assert_new_button(locations_path, "New Location", new_location_path)
    FactoryGirl.create(:host, :organization => nil)
      FactoryGirl.create(:filter, :role => user_role.role,
                         :permissions => Permission.unscoped.where(:name => 'view_hosts'),
                         :unlimited => true)
      target_host.organization = user_role.owner.organizations.first
      target_host.location = user_role.owner.locations.first
      other_host.organization = user_role.owner.organizations.first
      other_host.location = user_role.owner.locations.first
    assert_difference('LookupValue.unscoped.count') do
      :subnet => subnets(:two), :architecture => architectures(:x86_64),
      :puppet_proxy => smart_proxies(:puppetmaster), :medium => media(:one),
      :organization => nil, :location => nil,
    users(:one).organizations << [org1, org2, org3]
    interface = FactoryGirl.build(:nic_managed,
                                  :ip => "3.3.4.127",
                                  :mac => "cabbccddeeff",
                                  :host => FactoryGirl.create(:host),
                                  :subnet => subnet,
                                  :name => "a" + FactoryGirl.create(:host).name,
                                  :domain => domain)
      setup_user('view', 'hosts',
                 "hostgroup_id = #{@target_host.hostgroup_id}")
      assert_equal @target_reports.map(&:id).sort, Report.my_reports.map(&:id).sort
                                  :"#{opposite_taxonomy}_ids" => [],
      assert_equal selected_ids[:subnet_ids].sort, subnet_ids.uniq.sort
      assert_equal selected_ids[:medium_ids].sort, medium_ids.uniq.sort
      assert_equal selected_ids[:hostgroup_ids], [hostgroups(:common).id]
      assert_equal selected_ids[:user_ids], [users(:one).id, users(:scoped).id]
      assert_equal selected_ids[:compute_resource_ids], [compute_resources(:one).id, compute_resources(:mycompute).id]
      taxonomy_dup.name = "taxonomy_dup_name_#{rand}"
      assert taxonomy_dup.save
                                     users(:one)).sort
      as_admin do
        assert_equal parent.selected_ids, taxonomy.inherited_ids
      end
      parent.update_attribute(:domains, [domain1, domain2])
      parent.update_attribute(:subnets, [subnet])
                         :"#{taxonomy_name}" => parent,
                         :"#{taxonomy_name}" => parent,
      taxonomy.inherited_ids.each do |k,v|
        assert_equal v.sort, parent.selected_ids[k].sort
    test "multiple inheritance" do
    assert_equal subnet, Subnet::Ipv6.unscoped.subnet_for(get_ip(subnet, 10))
    assert_match /is used by/, subnet.errors.full_messages.join("\n")
      user = FactoryGirl.create(:user, :organizations => [@org, org2],
                                :locations => [])
  describe '#taxable_ids' do
    test "can work with empty array returning nil" do
      assert_nil @dummy.class.taxable_ids([], [])
    end
    test 'returns IDs for non-admin user of any context when no org/loc' do
      assert @dummy.class.all.count > 1

      as_user(:one) do
        any_org = User.current.organizations
        any_loc = User.current.locations

        visible_dummies = any_org.map(&:"#{@dummy.class.table_name}").flatten.map(&:id) &
          any_loc.map(&:"#{@dummy.class.table_name}").flatten.map(&:id)

        # We need to call '.taxable_ids' using the Environment class because
        # '.taxable_ids' will look for the 'taxable_taxonomies.taxable_type'
        # table of the caller.
        # Since TaxonomixDummy is defined in terms of the Environment table,
        # the table will have Environment, not TaxonomixDummy as taxable_type
        assert_equal visible_dummies, Environment.taxable_ids(nil, nil)
        assert_equal visible_dummies, Environment.taxable_ids([], [])
      end
    end

    test "can work with array of taxonomies" do
      loc1 = FactoryGirl.create(:location)
      loc2 = FactoryGirl.create(:location, :parent_id => loc1.id)
      loc3 = FactoryGirl.create(:location, :parent_id => loc2.id)
      loc4 = FactoryGirl.create(:location)
      org = FactoryGirl.create(:organization)
      env1 = FactoryGirl.create(:environment, :organizations => [org], :locations => [loc2])
      env2 = FactoryGirl.create(:environment, :organizations => [org])
      env3 = FactoryGirl.create(:environment, :locations => [loc2])
      env4 = FactoryGirl.create(:environment, :locations => [loc4])
      env5 = FactoryGirl.create(:environment, :locations => [loc1])
      env6 = FactoryGirl.create(:environment, :locations => [loc3])
      taxable_ids = Environment.taxable_ids([loc2, loc4], org, :subtree_ids)
      visible = [ env1 ]
      invisible = [ env2, env3, env4, env5, env6 ]
      visible.each { |env| assert_includes taxable_ids, env.id }
      invisible.each { |env| refute_includes taxable_ids, env.id }

      taxable_ids = Environment.taxable_ids([], org, :subtree_ids)
      visible = [ env1, env2 ]
      invisible = [ env3, env4, env5, env6 ]
      visible.each { |env| assert_includes taxable_ids, env.id }
      invisible.each { |env| refute_includes taxable_ids, env.id }

      taxable_ids = Environment.taxable_ids(loc2, [], :subtree_ids)
      visible = [ env1, env3, env5, env6 ]
      invisible = [ env2, env4 ]
      visible.each { |env| assert_includes taxable_ids, env.id }
      invisible.each { |env| refute_includes taxable_ids, env.id }

      taxable_ids = Environment.taxable_ids([loc2, loc4], [], :subtree_ids)
      visible = [ env1, env3, env4, env5, env6 ]
      invisible = [ env2 ]
      visible.each { |env| assert_includes taxable_ids, env.id }
      invisible.each { |env| refute_includes taxable_ids, env.id }
    end
    as_admin do
      used_organizations = user.used_organization_ids
      assert_empty used_organizations
      assert_equal used_organizations.count, 0
    end
  end

  context 'admin permissions' do
    test "returns only visible objects when org/loc are selected" do
      scoped_environments = Environment.
        with_taxonomy_scope([taxonomies(:organization1)])
      assert scoped_environments.include?(*taxonomies(:organization1).environments)
      assert_not_equal Environment.unscoped.all, scoped_environments
      assert_equal taxonomies(:organization1).environments, scoped_environments
    end

    test "returns nil (all objects) when there are no org/loc" do
      assert_equal User.with_taxonomy_scope([],[]).sort, User.unscoped.all.sort
    end
  end

  test 'current user ID and admin IDs are always visible' do
    as_user(:one) do
      scoped_users = User.with_taxonomy_scope([],[])
      assert_include scoped_users, User.current
      assert_include scoped_users, users(:admin)
    end
  end

  test 'users can only see objects scoped to its current taxonomies' do
    # Environment in organization 1 and location 1 cannot be seen by an user
    # who is scoped to organization 1 and location 2
    users(:one).organizations = [taxonomies(:organization1)]
    users(:one).locations = [taxonomies(:location2)]
    unreachable_env = FactoryGirl.create(
      :environment,
      :organizations => [taxonomies(:organization1)],
      :locations => [taxonomies(:location1)])

    as_user(:one) do
      assert_not_include Environment.all, unreachable_env
    end
    user = FactoryGirl.create(:user, :organizations => [])
      assert_not_equal last_login, User.unscoped.find(user.id).last_login_on
      reloaded_user = User.unscoped.find(user.id)
    record = User.new :login => "dummy", :mail => "j@j.com",
      :auth_source_id => AuthSourceInternal.first.id,
      :organizations => User.current.organizations,
      :locations => User.current.locations
    record               = User.new(:login => "dummy", :mail => "j@j.com",
      :auth_source_id => AuthSourceInternal.first.id,
      :role_ids => [create_role.id.to_s],
      :organizations => User.current.organizations,
      :locations => User.current.locations)
      record               = User.new(:login => "dummy", :mail => "j@j.com",
                                      :auth_source_id => AuthSourceInternal.first.id,
                                      :role_ids => [extra_role.id.to_s],
                                      :organizations => User.current.organizations,
                                      :locations => User.current.locations)
    record.organizations = User.current.organizations
    record.locations = User.current.locations
    user = FactoryGirl.create(:user, :organizations => [org1], :locations => [])
    as_user(user) do
      new_user = FactoryGirl.build(:user, :organizations => [], :locations => [])
      refute new_user.valid?
    users(:one).default_location = taxonomies(:location2)
    users(:one).default_organization = taxonomies(:organization2)
      # User 'one' contains location1 already
      # User 'one' contains organization1 already
  setup :setup_set_script_name, :set_api_user, :turn_off_login,
    :disable_webpack, :set_admin

  def set_admin
    User.current = users(:admin)
  end
    host.hostgroup.subnet.locations = [host.location]
    host.hostgroup.subnet.organizations = [host.organization]
    host.hostgroup.subnet6.locations = [host.location]
    host.hostgroup.subnet6.organizations = [host.organization]
      assert_equal @envs.to_a.sort, lks.last.environments.to_a.sort
      assert_equal @envs.to_a.sort, lks.last.environments.sort
      assert_equal @envs.to_a.sort, lks.last.environments.to_a.sort
    User.current = nil
    User.current = FactoryGirl.build(:user, :admin => true,
                                     :organizations => [], :locations => [])
      assert_difference 'User.unscoped.where(:login => "admin").count', 1 do
      user = User.unscoped.find_by_login('admin')
      assert_difference 'User.unscoped.where(:login => "seed_test").count', 1 do
      user = User.unscoped.find_by_login('seed_test')
    count = Ptable.unscoped.count
    assert_not_equal count, Ptable.unscoped.count
    refute Ptable.unscoped.where(:os_family => nil).any?
    count = Medium.unscoped.count
    assert_not_equal count, Medium.unscoped.count
    refute Medium.unscoped.where(:os_family => nil).any?
    count = ProvisioningTemplate.unscoped.count
    assert_not_equal count, ProvisioningTemplate.unscoped.count
        assert Ptable.unscoped.where(:template => File.read(tmpl)).any?, "No partition table containing #{tmpl}"
        assert ProvisioningTemplate.unscoped.where(:template => File.read(tmpl)).any?, "No template containing #{tmpl}"
    count = Bookmark.unscoped.where(:public => true).count
    assert_not_equal count, Bookmark.unscoped.where(:public => true).count
    ProvisioningTemplate.without_auditing { ProvisioningTemplate.unscoped.find_by_name('Kickstart default').update_attributes(:template => 'test') }
    refute_equal ProvisioningTemplate.unscoped.find_by_name('Kickstart default').template, 'test'
    assert_equal 1, ProvisioningTemplate.unscoped.
      destroy_all(:name => 'Kickstart default').size
    refute ProvisioningTemplate.unscoped.find_by_name('Kickstart default')
    tmpl = ProvisioningTemplate.unscoped.find_by_name('Kickstart default')
    refute ProvisioningTemplate.unscoped.find_by_name('Kickstart default')
    assert Organization.unscoped.find_by_name('seed_test')
    refute Organization.unscoped.find_by_name('seed_test')
    assert Location.unscoped.find_by_name('seed_test')
    refute Location.unscoped.find_by_name('seed_test')
    assert_equal [], view_permissions - Role.unscoped.find_by_name('Viewer').permissions