Class: Entitlements::Backend::GitHubTeam::Service

Inherits:
Service::GitHub show all
Includes:
Contracts::Builtin, Contracts::Core
Defined in:
lib/entitlements/backend/github_team/service.rb

Defined Under Namespace

Classes: TeamNotFound

Constant Summary collapse

C =
::Contracts

Constants inherited from Service::GitHub

Service::GitHub::MAX_GRAPHQL_RESULTS, Service::GitHub::MAX_GRAPHQL_RETRIES, Service::GitHub::WAIT_BETWEEN_GRAPHQL_RETRIES

Instance Attribute Summary

Attributes inherited from Service::GitHub

#addr, #ignore_not_found, #org, #ou, #token

Instance Method Summary collapse

Methods inherited from Service::GitHub

#enterprise?, #identifier, #invalidate_org_members_predictive_cache, #org_members, #org_members_from_predictive_cache?, #pending_members

Constructor Details

#initialize(org:, token:, ou:, addr: nil, ignore_not_found: false) ⇒ Service

Returns a new instance of Service.



35
36
37
38
39
40
# File 'lib/entitlements/backend/github_team/service.rb', line 35

def initialize(org:, token:, ou:, addr: nil, ignore_not_found: false)
  super
  Entitlements.cache[:github_team_members] ||= {}
  Entitlements.cache[:github_team_members][org_signature] ||= {}
  @team_cache = Entitlements.cache[:github_team_members][org_signature]
end

Instance Method Details

#create_team(entitlement_group:) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/entitlements/backend/github_team/service.rb', line 269

def create_team(entitlement_group:)
  team_name = entitlement_group.cn.downcase
  team_options = { name: team_name, repo_names: [], privacy: "closed" }

  begin
     = entitlement_group.
    unless ["parent_team_name"].nil?

      begin
        parent_team_data = graphql_team_data(["parent_team_name"])
        team_options[:parent_team_id] = parent_team_data[:team_id]
      rescue TeamNotFound
        # if the parent team does not exist, create it (think `mkdir -p` logic here)
        result = octokit.create_team(
          org,
          { name: ["parent_team_name"], repo_names: [], privacy: "closed" }
        )

        Entitlements.logger.debug "created parent team #{["parent_team_name"]} with id #{result[:id]}"

        team_options[:parent_team_id] = result[:id]
      end

      Entitlements.logger.debug "create_team(team=#{team_name}) Parent team #{["parent_team_name"]} with id #{team_options[:parent_team_id]} found"
    end
  rescue Entitlements::Models::Group::NoMetadata
    Entitlements.logger.debug "create_team(team=#{team_name}) No metadata found"
  end

  Entitlements.logger.debug "create_team(team=#{team_name})"
  result = octokit.create_team(org, team_options)
  Entitlements.logger.debug "created team #{team_name} with id #{result[:id]}"
  true
rescue Octokit::UnprocessableEntity => e
  Entitlements.logger.debug "create_team(team=#{team_name}) ERROR - #{e.message}"
  false
end

#from_predictive_cache?(entitlement_group) ⇒ Boolean

Returns:

  • (Boolean)


139
140
141
142
143
# File 'lib/entitlements/backend/github_team/service.rb', line 139

def from_predictive_cache?(entitlement_group)
  team_identifier = entitlement_group.cn.downcase
  read_team(entitlement_group) unless @team_cache[team_identifier]
  @team_cache[team_identifier] && @team_cache[team_identifier][:cache] ? true : false
end

#invalidate_predictive_cache(entitlement_group) ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/entitlements/backend/github_team/service.rb', line 152

def invalidate_predictive_cache(entitlement_group)
  # If the entry was not from the predictive cache in the first place, just return.
  # This really should not get called if that's the case, but regardless, we don't
  # want to pointlessly hit the API twice.
  return unless from_predictive_cache?(entitlement_group)

  # The entry did come from the predictive cache. Clear out all of the local caches
  # in this object and re-read the data from the API.
  team_identifier = entitlement_group.cn.downcase
  dn = "cn=#{team_identifier},#{ou}"
  Entitlements.logger.debug "Invalidating cache entry for #{dn}"
  Entitlements::Data::Groups::Cached.invalidate(dn)
  @team_cache.delete(team_identifier)
  read_team(entitlement_group)
  nil
end

#read_team(entitlement_group) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/entitlements/backend/github_team/service.rb', line 49

def read_team(entitlement_group)
  team_identifier = entitlement_group.cn.downcase
  @team_cache[team_identifier] ||= begin
    dn = "cn=#{team_identifier},#{ou}"
    begin
       = entitlement_group.
    rescue Entitlements::Models::Group::NoMetadata
       = nil
    end

    if (cached_members = Entitlements::Data::Groups::Cached.members(dn))
      Entitlements.logger.debug "Loading GitHub team #{identifier}:#{org}/#{team_identifier} from cache"

       = Entitlements::Data::Groups::Cached.(dn)
      # If both the cached and entitlement metadata are nil, our team metadata is nil
      # If one of the cached or entitlement metadata is nil, we use the other populated metadata hash as-is
      # If both cached and entitlement metadata exist, we combine the two hashes with the cached metadata taking precedence
      #
      # The reason we do this is because an entitlement file should be 1:1 to a GitHub Team. However,
      # entitlements files allow for metadata tags and the GitHub.com Team does not have a place to store those.
      # Therefore, we must combine any existing entitlement metadata entries into the Team metadata hash
      if .nil?
         = 
      elsif .nil?
         = 
      else
        # Always merge the current state metadata (cached or API call) into the entitlement metadata, so that the current state takes precedent
         = .merge()
      end

      team = Entitlements::Backend::GitHubTeam::Models::Team.new(
        team_id: -1,
        team_name: team_identifier,
        members: cached_members,
        ou:,
        metadata: 
      )

      { cache: true, value: team }
    else
      Entitlements.logger.debug "Loading GitHub team #{identifier}:#{org}/#{team_identifier}"

      begin
        teamdata = graphql_team_data(team_identifier)
        # The entitlement metadata may have GitHub.com Team metadata which it wants to set, so we must
        # overwrite that metadata with what we get from the API
        if teamdata[:parent_team_name].nil?
           = 
        else
           = {
            "parent_team_name" => teamdata[:parent_team_name]
          }
          if .nil?
             = 
          else
            # Always merge the current state metadata (cached or API call) into the entitlement metadata, so that the current state takes precedent
             = .merge()
          end
        end

        maintainers = teamdata[:members].select { |u| teamdata[:roles][u] == "maintainer" }
         ||= {}
         = .merge({ "team_maintainers" => maintainers.any? ? maintainers.join(",") : nil })

        team = Entitlements::Backend::GitHubTeam::Models::Team.new(
          team_id: teamdata[:team_id],
          team_name: team_identifier,
          members: Set.new(teamdata[:members]),
          ou:,
          metadata: 
        )
      rescue TeamNotFound
        Entitlements.logger.warn "Team #{team_identifier} does not exist in this GitHub.com organization. If applied, the team will be created."
        return nil
      end

      { cache: false, value: team }
    end
  end

  @team_cache[team_identifier][:value]
end

#sync_team(desired_state, current_state) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/entitlements/backend/github_team/service.rb', line 175

def sync_team(desired_state, current_state)
  begin
     = desired_state.
  rescue Entitlements::Models::Group::NoMetadata
     = {}
  end

  begin
     = current_state.
  rescue Entitlements::Models::Group::NoMetadata, NoMethodError
     = {}
  end

  changed_parent_team = false
  unless ["parent_team_name"] == ["parent_team_name"]
    # TODO: I'm hard-coding a block for deletes, for now. I'm doing that by making sure we dont set the desired parent_team_id to nil for teams where it is already set
    # :nocov:
    if ["parent_team_name"].nil?
      Entitlements.logger.debug "sync_team(team=#{current_state.team_name}): IGNORING GitHub Parent Team DELETE"
    else
      # :nocov:
      Entitlements.logger.debug "sync_team(#{current_state.team_name}=#{current_state.team_id}): Parent team change found - From #{["parent_team_name"] || "No Parent Team"} to #{["parent_team_name"]}"
      desired_parent_team_id = team_by_name(org_name: org, team_name: ["parent_team_name"])[:id]
      unless desired_parent_team_id.nil?
        # TODO: I'm hard-coding a block for deletes, for now. I'm doing that by making sure we dont set the desired parent_team_id to nil for teams where it is already set
        update_team(team: current_state, metadata: { parent_team_id: desired_parent_team_id })
      end
      changed_parent_team = true
    end
  end

  desired_team_members = Set.new(desired_state.member_strings.map { |u| u.downcase })
  current_team_members = Set.new(current_state.member_strings.map { |u| u.downcase })

  added_members = desired_team_members - current_team_members
  removed_members = current_team_members - desired_team_members

  added_members.select! { |username| add_user_to_team(user: username, team: current_state) }
  removed_members.select! { |username| remove_user_from_team(user: username, team: current_state) }

  added_maintainers = Set.new
  removed_maintainers = Set.new
  unless ["team_maintainers"] == ["team_maintainers"]
    if ["team_maintainers"].nil?
      # We will not delete ALL maintainers from a team and leave it without maintainers.
      Entitlements.logger.debug "sync_team(#{current_state.team_name}=#{current_state.team_id}): IGNORING GitHub Team Maintainer DELETE"
    else
      desired_maintainers_str = ["team_maintainers"] # not nil, we tested that above
      desired_maintainers = Set.new(desired_maintainers_str.split(",").map { |u| u.strip.downcase })
      unless desired_maintainers.subset?(desired_team_members)
        maintainer_not_member = desired_maintainers - desired_team_members
        Entitlements.logger.warn "sync_team(#{current_state.team_name}=#{current_state.team_id}): Maintainers must be a subset of team members. Desired maintainers: #{maintainer_not_member.to_a} are not members. Ignoring."
        desired_maintainers = desired_maintainers.intersection(desired_team_members)
      end

      current_maintainers_str = ["team_maintainers"]
      current_maintainers = Set.new(
        current_maintainers_str.nil? ? [] : current_maintainers_str.split(",").map { |u| u.strip.downcase }
      )
      # We ignore any current maintainer who is not a member of the team according to the team spec
      # This avoids messing with teams who have been manually modified to add a maintainer
      current_maintainers = current_maintainers.intersection(desired_team_members)
      added_maintainers = desired_maintainers - current_maintainers
      removed_maintainers = current_maintainers - desired_maintainers
      if added_maintainers.empty? && removed_maintainers.empty?
        Entitlements.logger.debug "sync_team(#{current_state.team_name}=#{current_state.team_id}): Textual change but no semantic change in maintainers. It is remains: #{current_maintainers.to_a}."
      else
        Entitlements.logger.debug "sync_team(#{current_state.team_name}=#{current_state.team_id}): Maintainer members change found - From #{current_maintainers.to_a} to #{desired_maintainers.to_a}"
        added_maintainers.select! do |username|
          add_user_to_team(user: username, team: current_state, role: "maintainer")
        end

        ## We only touch previous maintainers who are actually still going to be members of the team
        removed_maintainers = removed_maintainers.intersection(desired_team_members)
        ## Downgrade membership to default (role: "member")
        removed_maintainers.select! do |username|
          add_user_to_team(user: username, team: current_state, role: "member")
        end
      end
    end
  end

  Entitlements.logger.debug "sync_team(#{current_state.team_name}=#{current_state.team_id}): Added #{added_members.count}, removed #{removed_members.count}"
  added_members.any? || removed_members.any? || added_maintainers.any? || removed_maintainers.any? || changed_parent_team
end

#team_by_name(org_name:, team_name:) ⇒ Object



336
337
338
# File 'lib/entitlements/backend/github_team/service.rb', line 336

def team_by_name(org_name:, team_name:)
  octokit.team_by_name(org_name, team_name)
end

#update_team(team:, metadata: {}) ⇒ Object



316
317
318
319
320
321
322
323
324
325
# File 'lib/entitlements/backend/github_team/service.rb', line 316

def update_team(team:, metadata: {})
  Entitlements.logger.debug "update_team(team=#{team.team_name})"
  options = { name: team.team_name, repo_names: [], privacy: "closed",
              parent_team_id: [:parent_team_id] }
  octokit.update_team(team.team_id, options)
  true
rescue Octokit::UnprocessableEntity => e
  Entitlements.logger.debug "update_team(team=#{team.team_name}) ERROR - #{e.message}"
  false
end