-
Notifications
You must be signed in to change notification settings - Fork 9
Add enterprise team membership support #299
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
buckelij
wants to merge
2
commits into
main
Choose a base branch
from
buckelij-add-enterprise-teams
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require_relative "github_enterprise_team/controller" | ||
| require_relative "github_enterprise_team/provider" | ||
| require_relative "github_enterprise_team/service" | ||
| require_relative "github_team/models/team" | ||
| require_relative "../config/retry" | ||
|
|
||
| Retry.setup! |
80 changes: 80 additions & 0 deletions
80
lib/entitlements/backend/github_enterprise_team/controller.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| module Entitlements | ||
| class Backend | ||
| class GitHubEnterpriseTeam | ||
| class Controller < Entitlements::Backend::BaseController | ||
| def self.priority | ||
| 40 | ||
| end | ||
|
|
||
| register | ||
|
|
||
| include ::Contracts::Core | ||
| C = ::Contracts | ||
|
|
||
| # group_name - Name of the corresponding group in the entitlements configuration file. | ||
| # config - Optionally, a Hash of configuration information (configuration is referenced if empty). | ||
| Contract String, C::Maybe[C::HashOf[String => C::Any]] => C::Any | ||
| def initialize(group_name, config = nil) | ||
| super | ||
| @provider = Entitlements::Backend::GitHubEnterpriseTeam::Provider.new(config: @config) | ||
| end | ||
|
|
||
| def prefetch | ||
| teams = Entitlements::Data::Groups::Calculated.read_all(group_name, config) | ||
| teams.each do |team_slug| | ||
| provider.read(Entitlements::Data::Groups::Calculated.read(team_slug)) | ||
| end | ||
| end | ||
|
|
||
| Contract C::None => C::Any | ||
| def calculate | ||
| changed = Entitlements::Data::Groups::Calculated.read_all(group_name, config).filter_map do |team_slug| | ||
| group = Entitlements::Data::Groups::Calculated.read(team_slug) | ||
| diff = provider.diff(group) | ||
|
|
||
| if diff[:added].empty? && diff[:removed].empty? | ||
| logger.debug "UNCHANGED: No GitHub enterprise team changes for #{group_name}:#{team_slug}" | ||
| next | ||
| end | ||
|
|
||
| Entitlements::Models::Action.new(team_slug, provider.read(group), group, group_name) | ||
| end | ||
|
|
||
| print_differences(key: group_name, added: [], removed: [], changed:) | ||
| @actions = changed | ||
| end | ||
|
|
||
| Contract Entitlements::Models::Action => C::Any | ||
| def apply(action) | ||
| unless action.updated.is_a?(Entitlements::Models::Group) | ||
| logger.fatal "#{action.dn}: GitHub enterprise team membership cannot remove a team" | ||
| raise RuntimeError, "Invalid Operation" | ||
| end | ||
|
|
||
| if provider.commit(action.updated) | ||
| logger.debug "APPLY: Updating GitHub enterprise team #{action.dn}" | ||
| else | ||
| logger.warn "DID NOT APPLY: Changes not needed to #{action.dn}" | ||
| end | ||
| end | ||
|
|
||
| Contract String, C::HashOf[String => C::Any] => nil | ||
| def validate_config!(key, data) | ||
| spec = COMMON_GROUP_CONFIG.merge({ | ||
| "addr" => { required: false, type: String }, | ||
| "base" => { required: true, type: String }, | ||
| "enterprise" => { required: true, type: String }, | ||
| "token" => { required: true, type: String }, | ||
| }) | ||
| Entitlements::Util::Util.validate_attr!(spec, data, "GitHub enterprise team group #{key.inspect}") | ||
| end | ||
|
|
||
| private | ||
|
|
||
| attr_reader :provider | ||
| end | ||
| end | ||
| end | ||
| end |
47 changes: 47 additions & 0 deletions
47
lib/entitlements/backend/github_enterprise_team/provider.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require_relative "service" | ||
|
|
||
| module Entitlements | ||
| class Backend | ||
| class GitHubEnterpriseTeam | ||
| class Provider < Entitlements::Backend::BaseProvider | ||
| include ::Contracts::Core | ||
| C = ::Contracts | ||
|
|
||
| Contract C::KeywordArgs[ | ||
| config: C::HashOf[String => C::Any], | ||
| ] => C::Any | ||
| def initialize(config:) | ||
| @github = Entitlements::Backend::GitHubEnterpriseTeam::Service.new( | ||
| enterprise: config.fetch("enterprise"), | ||
| addr: config.fetch("addr", nil), | ||
| token: config.fetch("token"), | ||
| ou: config.fetch("base") | ||
| ) | ||
| @team_cache = {} | ||
| end | ||
|
|
||
| Contract Entitlements::Models::Group => Entitlements::Models::Group | ||
| def read(entitlement_group) | ||
| slug = Entitlements::Util::Util.any_to_cn(entitlement_group.cn.downcase) | ||
| @team_cache[slug] ||= github.read_team(entitlement_group) | ||
| end | ||
|
|
||
| Contract Entitlements::Models::Group => Hash[added: C::SetOf[String], removed: C::SetOf[String]] | ||
| def diff(entitlement_group) | ||
| diff_existing_updated(read(entitlement_group), entitlement_group) | ||
| end | ||
|
|
||
| Contract Entitlements::Models::Group => C::Bool | ||
| def commit(entitlement_group) | ||
| github.sync_team(entitlement_group, read(entitlement_group)) | ||
| end | ||
|
|
||
| private | ||
|
|
||
| attr_reader :github | ||
| end | ||
| end | ||
| end | ||
| end |
152 changes: 152 additions & 0 deletions
152
lib/entitlements/backend/github_enterprise_team/service.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require_relative "../github_team/models/team" | ||
| require_relative "../../service/github" | ||
|
|
||
| require "cgi" | ||
| require "json" | ||
| require "net/http" | ||
| require "set" | ||
| require "uri" | ||
|
|
||
| module Entitlements | ||
| class Backend | ||
| class GitHubEnterpriseTeam | ||
| class Service < Entitlements::Service::GitHub | ||
| include ::Contracts::Core | ||
| C = ::Contracts | ||
|
|
||
| API_VERSION = "2026-03-10" | ||
| PER_PAGE = 100 | ||
|
|
||
| class APIError < RuntimeError | ||
| attr_reader :body, :status | ||
|
|
||
| def initialize(status, body) | ||
| @status = status | ||
| @body = body | ||
| super("GitHub enterprise team API returned HTTP #{status}: #{body}") | ||
| end | ||
| end | ||
|
|
||
| class TeamNotFound < APIError; end | ||
|
|
||
| attr_reader :enterprise | ||
|
|
||
| Contract C::KeywordArgs[ | ||
| addr: C::Maybe[String], | ||
| enterprise: String, | ||
| token: String, | ||
| ou: String, | ||
| ] => C::Any | ||
| def initialize(enterprise:, token:, ou:, addr: nil) | ||
| @enterprise = enterprise | ||
| super(addr:, org: enterprise, token:, ou:) | ||
| end | ||
|
|
||
| Contract Entitlements::Models::Group => Entitlements::Backend::GitHubTeam::Models::Team | ||
| def read_team(entitlement_group) | ||
| team_name = entitlement_group.cn.downcase | ||
| members = list_members(team_name) | ||
| metadata = entitlement_group.metadata | ||
| Entitlements::Backend::GitHubTeam::Models::Team.new( | ||
| team_id: -1, | ||
| team_name:, | ||
| members: Set.new(members.map { |member| member.fetch("login").downcase }), | ||
| ou:, | ||
| metadata: | ||
| ) | ||
| rescue Entitlements::Models::Group::NoMetadata | ||
| Entitlements::Backend::GitHubTeam::Models::Team.new( | ||
| team_id: -1, | ||
| team_name:, | ||
| members: Set.new(members.map { |member| member.fetch("login").downcase }), | ||
| ou:, | ||
| metadata: nil | ||
| ) | ||
| end | ||
|
|
||
| Contract Entitlements::Models::Group, Entitlements::Backend::GitHubTeam::Models::Team => C::Bool | ||
| def sync_team(desired_state, current_state) | ||
| desired_members = Set.new(desired_state.member_strings.map(&:downcase)) | ||
| current_members = Set.new(current_state.member_strings.map(&:downcase)) | ||
| added_members = desired_members - current_members | ||
| removed_members = current_members - desired_members | ||
|
|
||
| bulk_update(current_state.team_name, "add", added_members) if added_members.any? | ||
| bulk_update(current_state.team_name, "remove", removed_members) if removed_members.any? | ||
|
|
||
| Entitlements.logger.debug( | ||
| "sync_enterprise_team(#{current_state.team_name}): Added #{added_members.count}, removed #{removed_members.count}" | ||
| ) | ||
| added_members.any? || removed_members.any? | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def list_members(team_name) | ||
| members = [] | ||
| page = 1 | ||
|
|
||
| loop do | ||
| path = "#{team_path(team_name)}/memberships?per_page=#{PER_PAGE}&page=#{page}" | ||
| page_members = request(Net::HTTP::Get, path) | ||
| members.concat(page_members) | ||
| break if page_members.length < PER_PAGE | ||
|
|
||
| page += 1 | ||
| end | ||
|
|
||
| members | ||
| rescue APIError => e | ||
| raise TeamNotFound.new(e.status, e.body) if e.status == 404 | ||
|
|
||
| raise | ||
| end | ||
|
|
||
| def bulk_update(team_name, operation, usernames) | ||
| request( | ||
| Net::HTTP::Post, | ||
| "#{team_path(team_name)}/memberships/#{operation}", | ||
| body: { usernames: usernames.to_a } | ||
| ) | ||
| end | ||
|
|
||
| def team_path(team_name) | ||
| "/enterprises/#{escape(enterprise)}/teams/#{escape(team_name)}" | ||
| end | ||
|
|
||
| def escape(value) | ||
| CGI.escape(value).gsub("+", "%20") | ||
| end | ||
|
|
||
| def request(request_class, path, body: nil) | ||
| uri = URI.parse("#{(addr || "https://api.github.com").sub(%r{/+\z}, "")}#{path}") | ||
| request = request_class.new(uri) | ||
| request["Accept"] = "application/vnd.github+json" | ||
| request["Authorization"] = "Bearer #{token}" | ||
| request["X-GitHub-Api-Version"] = API_VERSION | ||
| if body | ||
| request["Content-Type"] = "application/json" | ||
| request.body = JSON.generate(body) | ||
| end | ||
|
|
||
| response = Retryable.with_context(:default) do | ||
| result = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http| | ||
| http.request(request) | ||
| end | ||
| status = result.code.to_i | ||
| raise APIError.new(status, result.body) if status == 429 || status >= 500 | ||
|
|
||
| result | ||
| end | ||
| raise APIError.new(response.code.to_i, response.body) unless response.is_a?(Net::HTTPSuccess) | ||
|
|
||
| return nil if response.body.nil? || response.body.empty? | ||
|
|
||
| JSON.parse(response.body) | ||
| end | ||
| end | ||
| end | ||
| end | ||
| end |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.