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

.auditors ⇒ Object



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/entitlements.rb', line 339

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

.backends ⇒ Object



237
238
239
# File 'lib/entitlements.rb', line 237

def self.backends
  @backends || {}
end

.build_statsd ⇒ Object



393
394
395
396
397
398
399
400
401
402
403
# File 'lib/entitlements.rb', line 393

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

.cache ⇒ Object

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:



695
696
697
698
699
700
# File 'lib/entitlements.rb', line 695

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

.calculate ⇒ Object



435
436
437
# File 'lib/entitlements.rb', line 435

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

.calculate_actions ⇒ Object



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
474
475
476
477
478
479
480
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
# File 'lib/entitlements.rb', line 439

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
  jobs = Entitlements.child_classes
  completions = Queue.new

  begin
    jobs.each do |group_name, obj|
      thread_pool.post 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}")
        completions << nil
      rescue => e
        completions << e
      end
    end

    jobs.size.times do
      exception = completions.pop
      raise exception if exception
    end
  ensure
    thread_pool.kill
  end
  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|
    group_start = Time.now
    logger.debug("Begin calculation for #{group_name}")
    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)
    logger.debug("Finished calculation for #{group_name} in #{Time.now - group_start}")
  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_classes ⇒ Object



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/entitlements.rb', line 315

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_statsd ⇒ Object



388
389
390
391
# File 'lib/entitlements.rb', line 388

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

.config ⇒ Object



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

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

.config=(config_hash) ⇒ Object



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

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

.config_file ⇒ Object



166
167
168
# File 'lib/entitlements.rb', line 166

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

.config_file=(path) ⇒ Object



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

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_path ⇒ Object

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.



190
191
192
193
194
195
# File 'lib/entitlements.rb', line 190

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



205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/entitlements.rb', line 205

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_logger ⇒ Object



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

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

.evaluation_time ⇒ Object



106
107
108
# File 'lib/entitlements.rb', line 106

def self.evaluation_time
  @evaluation_time ||= Time.now
end

.evaluation_time=(value) ⇒ Object



116
117
118
# File 'lib/entitlements.rb', line 116

def self.evaluation_time=(value)
  @evaluation_time = value
end

.execute(actions:) ⇒ Object



521
522
523
# File 'lib/entitlements.rb', line 521

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

.execute_actions(actions:) ⇒ Object



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
556
557
558
559
560
561
562
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
# File 'lib/entitlements.rb', line 525

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_extras ⇒ Object



247
248
249
250
251
252
253
254
# File 'lib/entitlements.rb', line 247

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

.logger ⇒ Object

Global logger for this run of Entitlements.

Takes no arguments.

Returns a Logger. :nocov:



371
372
373
# File 'lib/entitlements.rb', line 371

def self.logger
  @logger ||= dummy_logger
end

.metric_deployment_id ⇒ Object



405
406
407
# File 'lib/entitlements.rb', line 405

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

.person_extra_methods ⇒ Object



305
306
307
# File 'lib/entitlements.rb', line 305

def self.person_extra_methods
  @person_extra_methods
end

.prefetch_people ⇒ Object



658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
# File 'lib/entitlements.rb', line 658

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



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

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

.register_backend(identifier, clazz, priority) ⇒ Object



226
227
228
229
# File 'lib/entitlements.rb', line 226

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

.register_filters ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
# File 'lib/entitlements.rb', line 273

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



295
296
297
# File 'lib/entitlements.rb', line 295

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



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

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

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

.reset_extras! ⇒ Object



120
121
122
123
124
125
126
# File 'lib/entitlements.rb', line 120

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



375
376
377
# File 'lib/entitlements.rb', line 375

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

.set_statsd(statsd) ⇒ Object



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

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

.statsd ⇒ Object

:nocov:



380
381
382
# File 'lib/entitlements.rb', line 380

def self.statsd
  @statsd ||= build_statsd
end

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



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'lib/entitlements.rb', line 409

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



600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
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
648
# File 'lib/entitlements.rb', line 600

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