Module: Entitlements

Includes:
Contracts::Core
Defined in:
lib/entitlements.rb,
lib/version.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, Version 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

Methods included from Contracts::Core

common, extended, included

Class Method Details

.auditorsObject



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/entitlements.rb', line 319

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



217
218
219
# File 'lib/entitlements.rb', line 217

def self.backends
  @backends || {}
end

.build_statsdObject



373
374
375
376
377
378
379
380
381
382
383
# File 'lib/entitlements.rb', line 373

def self.build_statsd
  host = Resolv.getaddress(ENV.fetch("DOGSTATSD_HOST", "localhost"))
  port = Integer(ENV.fetch("DOGSTATSD_PORT", 28_125))
  tags = [
    "application:entitlements",
    "kube_pod_name:#{ENV.fetch('KUBE_POD_NAME', 'not-on-kubernetes')}",
    "app_env:#{ENV.fetch('APP_ENV', 'development')}",
    "deployment_id:#{metric_deployment_id}"
  ]
  Datadog::Statsd.new(host, port, tags: tags)
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:



658
659
660
661
662
663
# File 'lib/entitlements.rb', line 658

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

.calculateObject



415
416
417
# File 'lib/entitlements.rb', line 415

def self.calculate
  timed_operation(phase: "calculate_total", span: "parent") { calculate_actions }
end

.calculate_actionsObject



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
# File 'lib/entitlements.rb', line 419

def self.calculate_actions
  # Load extras that are configured.
  if Entitlements.config.key?("extras")
    timed_operation(phase: "load_extras") { Entitlements.load_extras }
  end

  # Pre-fetch people from configured people data sources.
  timed_operation(phase: "prefetch_people") { Entitlements.prefetch_people }

  # Register filters that are configured.
  if Entitlements.config.key?("filters")
    timed_operation(phase: "register_filters") { Entitlements.register_filters }
  end

  # 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}")
      provider = Entitlements.config["groups"].fetch(group_name).fetch("type")
      timed_operation(phase: "prefetch", provider: provider, target: group_name, concurrent: true) { obj.prefetch }
      timed_operation(phase: "validate", provider: provider, target: group_name, concurrent: true) { 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|
    provider = Entitlements.config["groups"].fetch(group_name).fetch("type")
    timed_operation(phase: "calculate", provider: provider, target: group_name) { 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



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/entitlements.rb', line 295

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

.close_statsdObject



368
369
370
371
# File 'lib/entitlements.rb', line 368

def self.close_statsd
  @statsd&.close
  @statsd = nil
end

.configObject



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

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

.config=(config_hash) ⇒ Object



137
138
139
# File 'lib/entitlements.rb', line 137

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

.config_fileObject



146
147
148
# File 'lib/entitlements.rb', line 146

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

.config_file=(path) ⇒ Object



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

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.



170
171
172
173
174
175
# File 'lib/entitlements.rb', line 170

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



185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/entitlements.rb', line 185

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



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

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

.execute(actions:) ⇒ Object



484
485
486
# File 'lib/entitlements.rb', line 484

def self.execute(actions:)
  timed_operation(phase: "execute_total", span: "parent") { execute_actions(actions: actions) }
end

.execute_actions(actions:) ⇒ Object



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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
# File 'lib/entitlements.rb', line 488

def self.execute_actions(actions:)
  # Set up auditors.
  Entitlements.auditors.each do |auditor|
    timed_operation(phase: "audit_setup", provider: auditor.provider_id) { auditor.setup }
  end

  # 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 |group_name, obj|
      provider = Entitlements.config["groups"].fetch(group_name).fetch("type")
      timed_operation(phase: "preapply", provider: provider, target: group_name) { obj.preapply }
    end

    # Apply changes from all actions.
    actions.each do |action|
      obj = Entitlements.child_classes.fetch(action.ou)
      provider = Entitlements.config["groups"].fetch(action.ou).fetch("type")
      timed_operation(phase: "apply", provider: provider, target: action.ou, count: 1) do
        obj.apply(action)
      end
      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
          timed_operation(phase: "audit_commit", provider: audit.provider_id) do
            audit.commit(
              actions: actions,
              successful_actions: successful_actions,
              provider_exception: provider_exception
            )
          end
          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



227
228
229
230
231
232
233
234
# File 'lib/entitlements.rb', line 227

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:



351
352
353
# File 'lib/entitlements.rb', line 351

def self.logger
  @logger ||= dummy_logger
end

.metric_deployment_idObject



385
386
387
# File 'lib/entitlements.rb', line 385

def self.metric_deployment_id
  ENV["HEAVEN_DEPLOYMENT_ID"] || ENV["GITHUB_RUN_ID"] || "not-in-deployment"
end

.person_extra_methodsObject



285
286
287
# File 'lib/entitlements.rb', line 285

def self.person_extra_methods
  @person_extra_methods
end

.prefetch_peopleObject



621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# File 'lib/entitlements.rb', line 621

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)
      timed_operation(phase: "prefetch_people_source", provider: ds_config.fetch("type"), target: ds_name) do
        people_obj.read
      end
      [ds_name, people_obj]
    end.to_h

    objects.fetch(people_data_source_name)
  end
end

.record_loaded_extra(clazz) ⇒ Object



242
243
244
245
# File 'lib/entitlements.rb', line 242

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

.register_backend(identifier, clazz, priority) ⇒ Object



206
207
208
209
# File 'lib/entitlements.rb', line 206

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

.register_filtersObject



253
254
255
256
257
258
259
260
261
262
263
# File 'lib/entitlements.rb', line 253

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



275
276
277
# File 'lib/entitlements.rb', line 275

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



87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/entitlements.rb', line 87

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

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

.reset_extras!Object



100
101
102
103
104
105
106
# File 'lib/entitlements.rb', line 100

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



355
356
357
# File 'lib/entitlements.rb', line 355

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

.set_statsd(statsd) ⇒ Object



364
365
366
# File 'lib/entitlements.rb', line 364

def self.set_statsd(statsd)
  @statsd = statsd
end

.statsdObject

:nocov:



360
361
362
# File 'lib/entitlements.rb', line 360

def self.statsd
  @statsd ||= build_statsd
end

.timed_operation(phase:, provider: nil, target: nil, span: "leaf", concurrent: false, count: nil) ⇒ Object



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/entitlements.rb', line 389

def self.timed_operation(phase:, provider: nil, target: nil, span: "leaf", concurrent: false, count: nil)
  tags = [
    "phase:#{phase}",
    "status:error",
    "span:#{span}",
    "concurrent:#{concurrent}"
  ]
  tags << "provider:#{provider}" if provider
  tags << "target:#{target}" if target
  tags << "count:#{count}" if count

  statsd.time("entitlements.operation.duration", tags: tags) do
    result = yield
    tags[1] = "status:success"
    result
  end
end

.validate_configuration_file!Object



563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
# File 'lib/entitlements.rb', line 563

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