Module: Entitlements

Includes:
Contracts::Core
Defined in:
lib/entitlements.rb,
lib/entitlements.rb,
lib/entitlements/cli.rb,
lib/entitlements/extras.rb,
lib/entitlements/plugins.rb,
lib/entitlements/rule/base.rb,
lib/entitlements/util/util.rb,
lib/entitlements/data/groups.rb,
lib/entitlements/data/people.rb,
lib/entitlements/extras/base.rb,
lib/entitlements/util/mirror.rb,
lib/entitlements/auditor/base.rb,
lib/entitlements/models/group.rb,
lib/entitlements/service/ldap.rb,
lib/entitlements/models/action.rb,
lib/entitlements/models/person.rb,
lib/entitlements/plugins/dummy.rb,
lib/entitlements/util/override.rb,
lib/entitlements/data/people/ldap.rb,
lib/entitlements/data/people/yaml.rb,
lib/entitlements/data/people/dummy.rb,
lib/entitlements/data/groups/cached.rb,
lib/entitlements/plugins/posix_group.rb,
lib/entitlements/data/people/combined.rb,
lib/entitlements/extras/orgchart/base.rb,
lib/entitlements/backend/base_provider.rb,
lib/entitlements/backend/ldap/provider.rb,
lib/entitlements/extras/orgchart/logic.rb,
lib/entitlements/data/groups/calculated.rb,
lib/entitlements/extras/ldap_group/base.rb,
lib/entitlements/plugins/group_of_names.rb,
lib/entitlements/backend/base_controller.rb,
lib/entitlements/backend/ldap/controller.rb,
lib/entitlements/backend/dummy/controller.rb,
lib/entitlements/data/groups/calculated/base.rb,
lib/entitlements/data/groups/calculated/ruby.rb,
lib/entitlements/data/groups/calculated/text.rb,
lib/entitlements/data/groups/calculated/yaml.rb,
lib/entitlements/backend/member_of/controller.rb,
lib/entitlements/extras/orgchart/person_methods.rb,
lib/entitlements/extras/orgchart/rules/management.rb,
lib/entitlements/data/groups/calculated/rules/base.rb,
lib/entitlements/data/groups/calculated/rules/group.rb,
lib/entitlements/extras/ldap_group/rules/ldap_group.rb,
lib/entitlements/data/groups/calculated/filters/base.rb,
lib/entitlements/extras/orgchart/rules/direct_report.rb,
lib/entitlements/data/groups/calculated/modifiers/base.rb,
lib/entitlements/data/groups/calculated/rules/username.rb,
lib/entitlements/data/groups/calculated/modifiers/expiration.rb,
lib/entitlements/data/groups/calculated/filters/member_of_group.rb,
lib/entitlements/extras/ldap_group/filters/member_of_ldap_group.rb

Overview

Filter class to remove members of a particular LDAP group.

Defined Under Namespace

Modules: Extras Classes: Auditor, Backend, Cli, Data, ERB, Models, Plugins, Rule, Service, Util

Constant Summary collapse

C =
::Contracts
IGNORED_FILES =
Set.new(%w[README.md PR_TEMPLATE.md])

Class Method Summary collapse

Class Method Details

.auditorsObject



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/entitlements.rb', line 306

def self.auditors
  @auditors ||= begin
    if Entitlements.config.key?("auditors")
      Entitlements.config["auditors"].map do |auditor|
        unless auditor.is_a?(Hash)
          # :nocov:
          raise ArgumentError, "Configuration error: Expected auditor to be a hash, got #{auditor.inspect}!"
          # :nocov:
        end

        auditor_class = auditor.fetch("auditor_class")

        begin
          clazz = Kernel.const_get("Entitlements::Auditor::#{auditor_class}")
        rescue NameError
          raise ArgumentError, "Auditor class #{auditor_class.inspect} is invalid"
        end

        clazz.new(logger, auditor)
      end
    else
      []
    end
  end
end

.backendsObject



204
205
206
# File 'lib/entitlements.rb', line 204

def self.backends
  @backends || {}
end

.cacheObject

This is a global cache for the whole run of entitlements. To avoid passing objects around, since Entitlements by its nature is a run-once-upon-demand application.

Takes no arguments.

Returns a Hash that contains the cache.

Note: Since this is hit a lot, to avoid the performance penalty, Contracts is not used here. :nocov:



574
575
576
577
578
579
# File 'lib/entitlements.rb', line 574

def self.cache
  @cache ||= {
    calculated: {},
    file_objects: {}
  }
end

.calculateObject



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/entitlements.rb', line 355

def self.calculate
  # Load extras that are configured.
  Entitlements.load_extras if Entitlements.config.key?("extras")

  # Pre-fetch people from configured people data sources.
  Entitlements.prefetch_people

  # Register filters that are configured.
  Entitlements.register_filters if Entitlements.config.key?("filters")

  # Keep track of the total change count.
  cache[:change_count] = 0

  max_parallelism = Entitlements.config["max_parallelism"] || 1

  # Calculate old and new membership in each group.
  thread_pool = Concurrent::FixedThreadPool.new(max_parallelism)
  logger.debug("Begin prefetch and validate for all groups")
  prep_start = Time.now
  futures = Entitlements.child_classes.map do |group_name, obj|
    Concurrent::Future.execute({ executor: thread_pool }) do
      group_start = Time.now
      logger.debug("Begin prefetch and validate for #{group_name}")
      obj.prefetch
      obj.validate
      logger.debug("Finished prefetch and validate for #{group_name} in #{Time.now - group_start}")
    end
  end

  futures.each(&:value!)
  logger.debug("Finished all prefetch and validate in #{Time.now - prep_start}")

  logger.debug("Begin all calculations")
  calc_start = Time.now
  actions = []
  Entitlements.child_classes.map do |group_name, obj|
    obj.calculate
    if obj.change_count > 0
      logger.debug "Group #{group_name.inspect} contributes #{obj.change_count} change(s)."
      cache[:change_count] += obj.change_count
    end
    actions.concat(obj.actions)
  end
  logger.debug("Finished all calculations in #{Time.now - calc_start}")
  logger.debug("Finished all prefetch, validate, and calculation in #{Time.now - prep_start}")

  actions
end

.child_classesObject



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/entitlements.rb', line 282

def self.child_classes
  @child_classes ||= begin
    backend_obj = Entitlements.config["groups"].map do |group_name, data|
      [group_name, Entitlements.backends[data["type"]][:class].new(group_name)]
    end.compact.to_h

    # Sort first by priority, then by whether this is a mirror or not (mirrors go last), and
    # finally by the length of the OU name from shortest to longest.
    backend_obj.sort_by do |k, v|
      [
        v.priority,
        Entitlements.config["groups"][k] && Entitlements.config["groups"][k].key?("mirror") ? 1 : 0,
        k.length
      ]
    end.to_h
  end
end

.configObject



111
112
113
114
115
116
# File 'lib/entitlements.rb', line 111

def self.config
  @config ||= begin
    content = ERB.render_from_hash(File.read(config_file), {})
    ::YAML.safe_load(content)
  end
end

.config=(config_hash) ⇒ Object



124
125
126
# File 'lib/entitlements.rb', line 124

def self.config=(config_hash)
  @config = config_hash
end

.config_fileObject



133
134
135
# File 'lib/entitlements.rb', line 133

def self.config_file
  @config_file || File.expand_path("../config/entitlements/config.yaml", File.dirname(__FILE__))
end

.config_file=(path) ⇒ Object



142
143
144
145
146
147
148
149
# File 'lib/entitlements.rb', line 142

def self.config_file=(path)
  unless File.file?(path)
    raise "Specified config file = #{path.inspect} but it does not exist!"
  end

  @config_file = path
  @config = nil
end

.config_pathObject

Get the configuration path for the groups. This is based on the relative location to the configuration file if it doesn’t start with a “/”.

Takes no arguments.

Returns a String with the config path.



157
158
159
160
161
162
# File 'lib/entitlements.rb', line 157

def self.config_path
  return @config_path_override if @config_path_override
  base = config.fetch("configuration_path")
  return base if base.start_with?("/")
  File.expand_path(base, File.dirname(config_file))
end

.config_path=(path) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/entitlements.rb', line 172

def self.config_path=(path)
  unless path.start_with?("/")
    raise ArgumentError, "Path must be absolute when setting config_path!"
  end

  unless File.directory?(path)
    raise Errno::ENOENT, "config_path #{path.inspect} is not a directory!"
  end

  @config["configuration_path"] = path if @config
  @config_path_override = path
end

.dummy_loggerObject



99
100
101
102
103
# File 'lib/entitlements.rb', line 99

def self.dummy_logger
  # :nocov:
  Logger.new(StringIO.new)
  # :nocov:
end

.execute(actions:) ⇒ Object



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/entitlements.rb', line 414

def self.execute(actions:)
  # Set up auditors.
  Entitlements.auditors.each { |auditor| auditor.setup }

  # Track any raised exception to pass to the auditors.
  provider_exception = nil
  audit_exceptions = []
  successful_actions = Set.new

  # Sort the child classes by priority
  begin
    # Pre-apply changes for each class.
    Entitlements.child_classes.each do |_, obj|
      obj.preapply
    end

    # Apply changes from all actions.
    actions.each do |action|
      obj = Entitlements.child_classes.fetch(action.ou)
      obj.apply(action)
      successful_actions.add(action.dn)
    end
  rescue => e
    # Populate 'provider_exception' for the auditors and then raise the exception.
    provider_exception = e
    raise e
  ensure
    # Run the audit "commit" action for each auditor. This needs to happen despite any failures that
    # may occur when pre-applying or applying actions, because actions might have been applied despite
    # any failures raised. Run each audit, even if one fails, and batch up the exceptions for the end.
    # If there was an original exception from one of the providers, this block will be executed and then
    # that original exception will be raised.
    if Entitlements.auditors.any?
      logger.debug "Recording data to #{Entitlements.auditors.size} audit provider(s)"
      Entitlements.auditors.each do |audit|
        begin
          audit.commit(
            actions: actions,
            successful_actions: successful_actions,
            provider_exception: provider_exception
          )
          logger.debug "Audit #{audit.description} completed successfully"
        rescue => e
          logger.error "Audit #{audit.description} failed: #{e.class} #{e.message}"
          e.backtrace.each { |line| logger.error line }
          audit_exceptions << e
        end
      end
    end
  end

  # If we get here there were no provider exceptions. If there were audit exceptions raise them here.
  # If there were multiple exceptions we can only raise the first one, but log a message indicating this.
  return if audit_exceptions.empty?

  if audit_exceptions.size > 1
    logger.warn "There were #{audit_exceptions.size} audit exceptions. Only the first one is raised."
  end
  raise audit_exceptions.first
end

.load_extrasObject



214
215
216
217
218
219
220
221
# File 'lib/entitlements.rb', line 214

def self.load_extras
  Entitlements.config.fetch("extras", {}).each do |extra_name, extra_cfg|
    path = extra_cfg.key?("path") ? Entitlements::Util::Util.absolute_path(extra_cfg["path"]) : nil
    logger.debug "Loading extra #{extra_name} (path = #{path || 'default'})"
    Entitlements::Extras.load_extra(extra_name, path)
  end
  nil
end

.loggerObject

Global logger for this run of Entitlements.

Takes no arguments.

Returns a Logger. :nocov:



338
339
340
# File 'lib/entitlements.rb', line 338

def self.logger
  @logger ||= dummy_logger
end

.person_extra_methodsObject



272
273
274
# File 'lib/entitlements.rb', line 272

def self.person_extra_methods
  @person_extra_methods
end

.prefetch_peopleObject



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/entitlements.rb', line 539

def self.prefetch_people
  Entitlements.cache[:people_obj] ||= begin
    people_data_sources = Entitlements.config.fetch("people", [])
    if people_data_sources.empty?
      raise ArgumentError, "At least one data source for people must be specified in the Entitlements configuration!"
    end

    # TODO: In the future, have separate data sources per group.
    people_data_source_name = Entitlements.config.fetch("people_data_source", "")
    if people_data_source_name.empty?
      raise ArgumentError, "The Entitlements configuration must define a people_data_source!"
    end
    unless people_data_sources.key?(people_data_source_name)
      raise ArgumentError, "The people_data_source #{people_data_source_name.inspect} is invalid!"
    end

    objects = people_data_sources.map do |ds_name, ds_config|
      people_obj = Entitlements::Data::People.new_from_config(ds_config)
      people_obj.read
      [ds_name, people_obj]
    end.to_h

    objects.fetch(people_data_source_name)
  end
end

.record_loaded_extra(clazz) ⇒ Object



229
230
231
232
# File 'lib/entitlements.rb', line 229

def self.record_loaded_extra(clazz)
  @extras_loaded ||= Set.new
  @extras_loaded.add(clazz)
end

.register_backend(identifier, clazz, priority) ⇒ Object



193
194
195
196
# File 'lib/entitlements.rb', line 193

def self.register_backend(identifier, clazz, priority)
  @backends ||= {}
  @backends[identifier] = { class: clazz, priority: priority }
end

.register_filtersObject



240
241
242
243
244
245
246
247
248
249
250
# File 'lib/entitlements.rb', line 240

def self.register_filters
  Entitlements.config.fetch("filters", {}).each do |filter_name, filter_cfg|
    filter_class = filter_cfg.fetch("class")
    filter_clazz = Kernel.const_get(filter_class)
    filter_config = filter_cfg.fetch("config", {})

    logger.debug "Registering filter #{filter_name} (class: #{filter_class})"
    Entitlements::Data::Groups::Calculated.register_filter(filter_name, { class: filter_clazz, config: filter_config })
  end
  nil
end

.register_person_extra_method(method_name, method_class_ref) ⇒ Object



262
263
264
# File 'lib/entitlements.rb', line 262

def self.register_person_extra_method(method_name, method_class_ref)
  @person_extra_methods[method_name.to_sym] = method_class_ref
end

.reset!Object

Reset all Entitlements state

Takes no arguments



75
76
77
78
79
80
81
82
83
84
85
# File 'lib/entitlements.rb', line 75

def self.reset!
  @cache = nil
  @child_classes = nil
  @config = nil
  @config_file = nil
  @config_path_override = nil
  @person_extra_methods = {}

  reset_extras!
  Entitlements::Data::Groups::Calculated.reset!
end

.reset_extras!Object



87
88
89
90
91
92
93
# File 'lib/entitlements.rb', line 87

def self.reset_extras!
  extras_loaded = @extras_loaded
  if extras_loaded
    extras_loaded.each { |clazz| clazz.reset! if clazz.respond_to?(:reset!) }
  end
  @extras_loaded = nil
end

.set_logger(logger) ⇒ Object



342
343
344
# File 'lib/entitlements.rb', line 342

def self.set_logger(logger)
  @logger = logger
end

.validate_configuration_file!Object



481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/entitlements.rb', line 481

def self.validate_configuration_file!
  # Required attributes
  spec = {
    "configuration_path" => { required: true, type: String },
    "backends"           => { required: false, type: Hash },
    "people"             => { required: true, type: Hash },
    "people_data_source"  => { required: true, type: String },
    "groups"             => { required: true, type: Hash },
    "auditors"           => { required: false, type: Array },
    "filters"            => { required: false, type: Hash },
    "extras"             => { required: false, type: Hash },
    "max_parallelism"    => { required: false, type: Integer },
  }

  Entitlements::Util::Util.validate_attr!(spec, Entitlements.config, "Entitlements configuration file")

  # Make sure each group has a valid type, and then forward the validator to the child class.
  # If a named backend is chosen, merge the parameters from the backend with the parameters given
  # for the class configuration, and then remove all indication that a backend was used.
  Entitlements.config["groups"].each do |key, data|
    if data.key?("backend")
      unless Entitlements.config["backends"] && Entitlements.config["backends"].key?(data["backend"])
        raise "Entitlements configuration group #{key.inspect} references non-existing backend #{data['backend'].inspect}!"
      end

      backend = Entitlements.config["backends"].fetch(data["backend"])
      unless backend.key?("type")
        raise "Entitlements backend #{data['backend'].inspect} is missing a type!"
      end

      # Priority in the merge is given to the specific OU configured. Backend data is filled
      # in only as default values when not otherwise defined.
      Entitlements.config["groups"][key] = backend.merge(data)
      Entitlements.config["groups"][key].delete("backend")
      data = Entitlements.config["groups"][key]
    end

    unless data["type"].is_a?(String)
      raise "Entitlements configuration group #{key.inspect} does not properly declare a type!"
    end

    unless Entitlements.backends.key?(data["type"])
      raise "Entitlements configuration group #{key.inspect} has invalid type (#{data['type'].inspect})"
    end
  end

  # Good if nothing is raised by here.
  nil
end