Code Monkey home page Code Monkey logo

safe-settings's Introduction

GitHub Safe-Settings

Create a release

Safe-settings – an app to manage policy-as-code and apply repository settings across an organization.

  1. In safe-settings, all the settings are stored centrally in an admin repo within the organization. Unlike the GitHub Repository Settings App, the settings files cannot be in individual repositories.

    It is possible specify a custom repo instead of the admin repo with ADMIN_REPO. See Environment variables for more details.

  2. The settings in the default branch are applied. If the settings are changed on a non-default branch and a PR is created to merge the changes, the app runs in a dry-run mode to evaluate and validate the changes. Checks pass or fail based on the dry-run results.

  3. In safe-settings the settings can have 2 types of targets:

    1. org - These settings are applied to the organization. Org-targeted settings are defined in .github/settings.yml. Currently, only rulesets are supported as org-targeted settings.
    2. repo - These settings are applied to repositories.
  4. For the repo-targeted settings, there can be 3 levels at which the settings are managed:

    1. Org-level settings are defined in .github/settings.yml

      It is possible to override this behavior and specify a different filename for the settings.yml file with SETTINGS_FILE_PATH. Similarly, the .github directory can be overridden with CONFIG_PATH. See Environment variables for more details.

    2. Suborg level settings. A suborg is an arbitrary collection of repos belonging to projects, business units, or teams. The suborg settings reside in a yaml file for each suborg in the .github/suborgs folder.

      In safe-settings, suborgs could be groups of repos based on repo names, or teams which the repos have collaborators from, or custom property values set for the repos

    3. Repo level settings. They reside in a repo specific yaml in .github/repos folder

  5. It is recommended to break the settings into org-level, suborg-level, and repo-level units. This will allow different teams to define and manage policies for their specific projects or business units. With CODEOWNERS, this will allow different people to be responsible for approving changes in different projects.

Note

The suborg and repo level settings directory structure cannot be customized.

Settings files must have a .yml extension only. For now, the .yaml extension is ignored.

How it works

Events

The App listens to the following webhook events:

  • push: If the settings are created or modified, that is, if push happens in the default branch of the admin repo and the file added or changed is .github/settings.yml or .github/repos/*.ymlor .github/suborgs/*.yml, then the settings would be applied either globally to all the repos, or specific repos. For each repo, the settings that are actually applied depend on the default settings for the org, overlaid with settings for the suborg that the repo belongs to, overlaid with the settings for that specific repo.

  • repository.created: If a repository is created in the org, the settings for the repo - the default settings for the org, overlaid with settings for the suborg that the repo belongs to, overlaid with the settings for that specific repo - is applied.

  • branch_protection_rule: If a branch protection rule is modified or deleted, safe-settings will sync the settings to prevent any unauthorized changes.

  • repository.edited: For e.g. If the default branch is renamed, or if topics change, safe-settings will sync the settings, to prevent any unauthorized changes.

  • repository.renamed: If a repository is renamed, the default behavior is safe-settings will ignore this (for backward-compatibility). If BLOCK_REPO_RENAME_BY_HUMAN env variable is set to true, safe-settings will revert the repo to the previous name unless it is renamed using a bot. If it is renamed using a bot, it will try to copy the existing <old-repo>.yml to <new-repo>.yml so that the repo config yml stays consistent. If a <new-repo.yml> file already exists, it doesn't create a new one.

  • pull_request.opened, pull_request.reopened, check_suite.requested: If the settings are changed, but it is not in the default branch, and there is an existing PR, the code will validate the settings changes by running safe-settings in nop mode and update the PR with the dry-run status.

  • repository_ruleset: If the ruleset settings are modified in the UI manually, safe-settings will sync the settings to prevent any unauthorized changes.

  • member_change_events: If a member is added or removed from a repository, safe-settings will sync the settings to prevent any unauthorized changes.

  • member', team.added_to_repository, team.removed_from_repository, team.edited: safe-settings will sync the settings to prevent any unauthorized changes.

  • custom_property_values: If new repository properties are set for a repository, safe-settings will run to so that if a sub-org config is defined by that property, it will be applied for the repo

Use safe-settings to rename repos

If you rename a <repo.yml> that corresponds to a repo, safe-settings will rename the repo to the new name. This behavior will take effect whether the env variable BLOCK_REPO_RENAME_BY_HUMAN is set or not.

Restricting safe-settings to specific repos

safe-settings can be turned on only to a subset of repos by specifying them in the runtime settings file, deployment-settings.yml. If no file is specified, then the following repositories - 'admin', '.github', 'safe-settings' are exempted by default. A sample of deployment-settings file is found here.

To apply safe-settings only to a specific list of repos, add them to the restrictedRepos section as include array.

To ignore safe-settings for a specific list of repos, add them to the restrictedRepos section as exclude array.

Note

The include and exclude attributes support as well regular expressions. By default they look for regex, Example include: ['SQL'] will look apply to repos with SQL and SQL_ and SQL- etc if you want only SQL repo then use include:['^SQL$']

Custom rules

Admins setting up safe-settings can include custom rules that would be validated before applying a setting or overriding a broader scoped setting.

The code has to return true if validation is successful, or false if it isn't.

If the validation fails, the error attribute specified would be used to create the error message in the logs or in the PR checks.

The first use case is where a custom rule has to be applied for a setting on its own. For e.g. No collaborator should be given admin permissions.

For this type of validation, admins can provide custom code as configvalidators which validates the setting by itself.

For e.g. for the case above, it would look like:

configvalidators:
  - plugin: collaborators
    error: |
      `Admin role cannot be assigned to collaborators`
    script: |
      console.log(`baseConfig ${JSON.stringify(baseconfig)}`)
      return baseconfig.permission != 'admin'

For convenience this script has access to a variable, baseconfig, that contains the setting that is be applied.

The second use case is where custom rule has to be applied when a setting in the org or suborg level is being overridden. Such as, when default branch protection is being overridden.

For this type of validation, admins can provide custom code as overridevalidators. The script can access two variables, baseconfig and overrideconfig which represent the base setting and the setting that is overriding it.

A sample would look like:

overridevalidators:
  - plugin: branches
    error: |
      `Branch protection required_approving_review_count cannot be overidden to a lower value`
    script: |
      console.log(`baseConfig ${JSON.stringify(baseconfig)}`)
      console.log(`overrideConfig ${JSON.stringify(overrideconfig)}`)
      if (baseconfig.protection.required_pull_request_reviews.required_approving_review_count && overrideconfig.protection.required_pull_request_reviews.required_approving_review_count ) {
        return overrideconfig.protection.required_pull_request_reviews.required_approving_review_count >= baseconfig.protection.required_pull_request_reviews.required_approving_review_count
      }
      return true

A sample of deployment-settings file is found here.

Performance

When there are 1000s of repos to be managed -- and there is a global settings change -- safe-settings will have to work efficiently and only make the necessary API calls.

The app also has to complete the work within an hour: the lifetime of the GitHub app token.

To address these constraints the following design decisions have been implemented:

  1. Probot automatically handles rate and abuse limits.
  2. Instead of loading all the repo contents from .github/repos/*, it will selectively load the specific repo file based on which repo settings has changed, or a subset of the repo files associated with suborg settings that has changed. The only time all the repo files will be loaded is if there is a global settings file change.
  3. The PR check will only provide a summary of errors and changes. (Providing the details of changes for 1000s of repos will error out.)
  4. To ensure it handles updates to GitHub intelligently, it will compare the changes with the settings in GitHub, and will call the API only if there are real changes.

Comparing changes with GitHub

To determine if there are real changes, the code will generate a detailed list of additions, modifications, and deletions compared to the settings in GitHub:

For e.g:

If the settings is:

{
  "branches": [
    {
      "name": "master",
      "protection": {
        "required_pull_request_reviews": {
          "required_approving_review_count": 2,
          "dismiss_stale_reviews": false,
          "require_code_owner_reviews": true,
          "dismissal_restrictions": {}
        },
        "required_status_checks": {
          "strict": true,
          "contexts": []
        },
        "enforce_admins": false
      }
    }
  ]
}

and the settings in GitHub is:

{
  "branches": [
    {
      "name": "master",
      "protection": {
        "url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection",
        "required_status_checks": {
          "url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection/required_status_checks",
          "strict": true,
          "contexts": [],
          "contexts_url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection/required_status_checks/contexts",
          "checks": []
        },
        "restrictions": {
          "url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection/restrictions",
          "users_url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection/restrictions/users",
          "teams_url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection/restrictions/teams",
          "apps_url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection/restrictions/apps",
          "users": [],
          "teams": [],
          "apps": []
        },
        "required_pull_request_reviews": {
          "url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection/required_pull_request_reviews",
          "dismiss_stale_reviews": true,
          "require_code_owner_reviews": true,
          "required_approving_review_count": 2,
          "dismissal_restrictions": {
            "url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection/dismissal_restrictions",
            "users_url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection/dismissal_restrictions/users",
            "teams_url": "https://api.github.com/repos/decyjphr-org/test/branches/develop/protection/dismissal_restrictions/teams",
            "users": [],
            "teams": []
          }
        },
        "required_signatures": false,
        "enforce_admins": false,
        "required_linear_history": false,
        "allow_force_pushes": {
          "enabled": false
        },
        "allow_deletions": false,
        "required_conversation_resolution": false
      }
    }
  ]
}

the results of comparison would be:

{
      "additions": {},
      "modifications": {
        "branches": [
          {
            "protection": {
              "required_pull_request_reviews": {
                "dismiss_stale_reviews": false
              }
            },
            "name": "master"
          }
        ]
      },
      "deletions": {},
      "hasChanges": true
    }

Schedule

The App can be configured to apply the settings on a schedule. This could be a way to address configuration drift since webhooks are not always guaranteed to be delivered.

To periodically converge the settings to the configuration, set the CRON environment variable. See Environment variables for more details.

Pull Request Workflow

Safe-settings explicitly looks in the admin repo in the organization for the settings files. The admin repo could be a restricted repository with branch protections and CODEOWNERS

In that set up, when changes happen to the settings files and there is a PR for merging the changes back to the default branch in the admin repo, safe-settings will run checks – which will run in nop mode and produce a report of the changes that would happen, including the API calls and the payload.

For e.g. If we have override validators that will fail if org-level branch protections are overridden at the repo or suborg level with a lesser number of required approvers, here is an screenshot of what users will see in the PR.

image

Note

If you don't want the PR message to have these details, they can be turned off with CREATE_PR_COMMENT. See Environment variables for more details.

Here is a screenshot of what the users will see in the checkrun page:

image

Error handling

The app creates a Check at the end of its processing to indicate if there were any errors. The Check is called safe-settings and corresponds to the latest commit on the default branch of the admin repo.

Here is an example of a checkrun result:

image

And the checkrun page will look like this:

image

The Settings File

The settings file can be used to set the policies at the org, suborg or repo level.

The following can be configured:

  • Repository settings - home page, url, visibility, has_issues, has_projects, wikis, etc.
  • Default branch - naming and renaming
  • Topics
  • Custom properties
  • Teams and permissions
  • Collaborators and permissions
  • Issue labels
  • Milestones
  • Branch protections - if the name of the branch is default in the settings, it is applied to the default branch of the repo.
  • Autolinks
  • Repository name validation using regex pattern
  • Rulesets

It is possible to provide an include or exclude settings to restrict the collaborators, teams, labels to a list of repos or exclude a set of repos for a collaborator.

See docs/sample-settings/settings.yml for a sample settings file.

Additional values

In addition to the values in the file above, the settings file can have some additional values:

  1. force_create: This is set in the repo-level settings to force create the repo if the repo does not exist.
  2. template: This is set in the repo-level settings, and is used with the force_create flag to use a specific repo template when creating the repo
  3. suborgrepos: This is set in the suborg-level settings to define an array of repos. This field can also take a glob pattern to allow wild-card expression to specify repos in a suborg. For e.g. test* would include test, test1, testing, etc.
  4. The suborgteams section contains a list of teams, and all the repos belonging to the teams would be part of the suborg

Environment variables

You can pass environment variables; the easiest way to do it is via a .env file.

  1. CRON you can pass a cron input to run safe-settings at a regular schedule. This is based on node-cron. For eg.
# ┌────────────── second (optional)
# │ ┌──────────── minute
# │ │ ┌────────── hour
# │ │ │ ┌──────── day of month
# │ │ │ │ ┌────── month
# │ │ │ │ │ ┌──── day of week
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *
CRON=* * * * * # Run every minute
  1. Logging level can be set using LOG_LEVEL. For e.g.
LOG_LEVEL=trace
  1. Configure the source repository using ADMIN_REPO (default is admin). For e.g.
ADMIN_REPO=safe-settings-config
  1. Configure the config path using CONFIG_PATH (default is .github). For e.g.
CONFIG_PATH=.github
  1. Configure the settings file path using SETTINGS_FILE_PATH (default is settings.yml). For e.g.
SETTINGS_FILE_PATH=settings.yml
  1. Configure the deployment settings file path using DEPLOYMENT_CONFIG_FILE (default is deployment-settings.yml). For e.g.
DEPLOYMENT_CONFIG_FILE=deployment-settings.yml
  1. Enable the pull request comment using ENABLE_PR_COMMENT (default is true). For e.g.
ENABLE_PR_COMMENT=true
  1. Block repository renaming manually using BLOCK_REPO_RENAME_BY_HUMAN (default is false). For e.g.
BLOCK_REPO_RENAME_BY_HUMAN=true

Runtime Settings

  1. Besides the above settings files, the application can be bootstrapped with runtime settings.
  2. The runtime settings are configured in deployment-settings.yml that is in the directory from where the GitHub app is running.
  3. Currently the only setting that is possible are restrictedRepos: [... ] which allows you to configure a list of repos within your org that are excluded from the settings. If the deployment-settings.yml is not present, the following repos are added by default to the restrictedrepos list: 'admin', '.github', 'safe-settings'

Notes

  1. Label color can also start with #, e.g. color: '#F341B2'. Make sure to wrap it with quotes!
  2. Each top-level element under branch protection must be filled (eg: required_pull_request_reviews, required_status_checks, enforce_admins and restrictions). If you don't want to use one of them you must set it to null (see comments in the example above). Otherwise, none of the settings will be applied.
  3. The precedence order is repository > suborg > org (.github/repos/.yml > .github/suborgs/.yml > .github/settings.yml

How to use

  1. Deploy and install the app.

  2. Create an admin repo (or an alternative of your choosing) within your organization. Remember to set CONFIG_REPO if you choose something other than admin. See Environment variables for more details.

  3. Add the settings for the org, suborgs, and repos. Sample files can be found here.

License

safe-settings is licensed under the ISC license

safe-settings uses 3rd party libraries, each with their own license. These are found here.

safe-settings's People

Contributors

amenocal avatar anderssonjohan avatar ashanthalahiru avatar bkeepers avatar callmegreg avatar decyjphr avatar dependabot-preview[bot] avatar dependabot[bot] avatar elstudio avatar glyph-se avatar greenkeeper[bot] avatar greenkeeperio-bot avatar jasonetco avatar joshjohanning avatar jwsloan avatar markjm avatar martinm82 avatar mvegter avatar nicacioliveira avatar pedrolacerda avatar pholleran avatar piccobit avatar robandpdx avatar sjparkinson avatar stevoland avatar tcbyrd avatar travi avatar tspascoal avatar tunnckocore avatar v1v avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

safe-settings's Issues

Bug inside of the Repository plugin related to updateRepo function ambiguity

Problem Description

Inside of the repository class, we have an ambiguous return to updaterepo function that makes a bug when this function is called with nop variable true.

When the nop var is true, the function updaterepo returns an array of operations and when the nop var is false, the function returns one object with the repository data. Assuming that the expected response when the function is called is one array and the function update security expects one object with the repository data, we have a bug in this place.

I opened a PR with one solution for this with examples: #292

Adding webhook URL as settings

Hi @decyjphr
I am wondering if this is possible or not.
With the latest release I found that we have the option to add the autolink reference. So can we add the webhook urls also from the central repo settings just like the admin repo.
Can it be possible ? Or any sort of enhancement in this regard would be great

feat: Add support for GitHub Environments

Prerequisites:

New Feature

Same as repository-settings/app#607
Manage GitHub Environments with safe-settings at settings.yml and {repo}.yml
From #381: Similar to branch protection rules it would be great to configure deployment protection rules, deployment branches, secrets, and variables

Spam in audit log

Problem Description

Safe-settings is causing spam in the audit logs. Hopefully it would be better to check state before applying it.

image
image

What is actually happening

What is the expected behavior

Error output, if available

Context

Are you using the hosted instance of probot/settings or running your own?

Running our own

If running your own instance, are you using it with github.com or GitHub Enterprise?

github.com

Version of probot/settings

1.1.9

Version of GitHub Enterprise

check_run never stops when there are changes that are not safe-settings own

Problem Description

What is actually happening

If you have admin repo with files no related to safe-setting, when you create a pull request, safe-settings create a check_run to validate the changes. But if you modify other files, not related to safe-settings, the check run, never stops.

What is the expected behavior

After check_run created, if safe-settings no detect changes related to him, complete the check_run with success.

Error output, if available

  • N/A

Context

Are you using the hosted instance of probot/settings or running your own?

Own

If running your own instance, are you using it with github.com or GitHub Enterprise?

github.com

Version of probot/settings

safe-setting docker image: 2.0.12

Version of GitHub Enterprise

  • N/A

milestones.js plugin outdated

Problem Description

The milestones.js plugin is using an unexisting method listMilestonesForRepo instead of listMilestones.

What is actually happening

Milestones are not created because of an exception. The server stops abruptly:

What is the expected behavior

Merge common milestones (from .github/settings.yml) with suborgs and repos settings and create/patch in the GitHub org.

Error output, if available

C:\code\github\safe-settings\lib\plugins\milestones.js:17
    const options = this.github.issues.listMilestonesForRepo.endpoint.merge(Object.assign({ per_page: 100, state: 'all' }, this.repo))
                                                             ^

TypeError: Cannot read properties of undefined (reading 'endpoint')
    at Milestones.find (C:\code\github\safe-settings\lib\plugins\milestones.js:17:62)
    at Milestones.sync (C:\code\github\safe-settings\lib\plugins\diffable.js:81:19)
    at C:\code\github\safe-settings\lib\settings.js:164:80
    at Array.map (<anonymous>)
    at C:\code\github\safe-settings\lib\settings.js:163:26
    at async Promise.all (index 1)
    at async Function.syncAll (C:\code\github\safe-settings\lib\settings.js:11:5)

Node.js v17.6.0

Context

Are you using the hosted instance of probot/settings or running your own?

Running locally to test it. Running on prod in own hosts.

If running your own instance, are you using it with github.com or GitHub Enterprise?

github.com

Version of probot/settings

Current version [1.1.2-rc.1](https://github.com/github/safe-settings/releases/tag/1.1.2-rc.1)

Version of GitHub Enterprise

N/A.

Excluded repos are synched with settings when a repo is edited

Problem Description

When a repository that is on the exclusion list is edited changes are applied to it.

Repro steps:

  • add a settings.yml file
  • add a branch protection rule to admin repo
  • Check that the changes in settings.yml have been applied

What is actually happening

When a change is made to a repository that triggers a branch_protection_rule , repository.edited or repository.created event the settings.yml are applied to the repo even if the repo is on the excluded list.

This happens even the exclusion list is customized or the built in one is used. For example with the OOTB config this happens to admin repo

What is the expected behavior

Settings are not applied to a repository that is excluded if changes occur

Error output, if available


Context

Are you using the hosted instance of probot/settings or running your own?

If running your own instance, are you using it with github.com or GitHub Enterprise?

github.com

Version of probot/settings

safe settings version 0.1.0-rc.26
probot version 12.2.0

Version of GitHub Enterprise

How exactly does `safe-settings` handle situations that require human involvement?

I've read through the README multiple times, but it's not very obvious to me what exactly safe-settings does for some validations which can't just be applied to a repository. For example, what happens if a repository name doesn't pass the validation regex? Does safe-settings open an issue on the repository? Does it fail a status check on a pull request to force compliance? How do repo maintainers get notified of the issue and how can they learn what's failing?

Is there an example public org where this app is running on and could showcase how it works? Without understanding more of how this app works, I don't want to just install this on an organization.

allow_force_push flag is always disabled, with no way to configure

Problem Description

When branch protection is applied/enforced by safe-settings, the allow_force_push flag is always reset to 'disabled', and it appears there's no way to configure this setting for a repo.

What is actually happening

See above

What is the expected behavior

Wither 'allow_force_push' should not be changed if it is not configured by safe settings, or there should be a way to configure it in the repo protections file.

Context

Are you using the hosted instance of probot/settings or running your own?

Running our own

If running your own instance, are you using it with github.com or GitHub Enterprise?

github.com

Version of probot/settings

1.1.9

Version of GitHub Enterprise

N/A

Remove access from teams that are not specified in the config

Problem Description

What is actually happening

When I remove a team from the teams collection, said team is not removed from the repository's permissions.

What is the expected behavior

Only the teams listed under the teams should have access to the repository. If the teams key is missing from the configuration, I would expect the permissions to be handled from the repository's settings page.

I did not experiment with collaborators but I would expect a similar behavior.

Error output, if available

n/a

Context

Are you using the hosted instance of probot/settings or running your own?

Running my own

If running your own instance, are you using it with github.com or GitHub Enterprise?

GHEC

Version of probot/settings

safe-settings:2.0.0

Version of GitHub Enterprise

cloud

Safe Settings Validator check never stops

Problem Description

What is actually happening

Safe Settings Validator check always present never stops or cancels ( Starting NOP ... )

What is the expected behavior

to cancel at some point

Error output, if available


Context

On every pull request this safe settings validator check starts but never ends has been running : Starting NOP for Started 24d 23h 44m 47s ago, is it possible to disable this?

Are you using the hosted instance of probot/settings or running your own?

Self-Hosted Instance

If running your own instance, are you using it with github.com or GitHub Enterprise?

GitHub Enterprise

Version of probot/settings

not sure must be around 1-2 month old

Version of GitHub Enterprise

3.5.4

Enabling branch protection based on the branch patterns.

Prerequisites:

  • Is the functionality available in the GitHub UI? If so, please provide a link to information about the feature.

Yes, from github UI, I can enable branch protection rules on pattern like *-release which will apply these rules to all the branches with -release as the suffix.

Yes, this is available via github graphQL api ONLY. https://docs.github.com/en/graphql/reference/mutations#createbranchprotectionrule
https://docs.github.com/en/graphql/reference/input-objects#createbranchprotectionruleinput

  • If the functionality is not yet available in the API, it would be helpful if you
    contacted support (https://support.github.com/) or posted in the Community Forum (https://github.community/). Please
    include a link to the forum post if you create one or a copy of the response from support.

New Feature

Please describe the desired new functionality:

I want to enable branch protection rules based on a pattern. Today we can achieve this via Github UI and github graphQL apis. Adding this feature will help us to manage branch protection will less rules.

Support for Branch Protection `bypassForcePushAllowances`

Prerequisites:

Available via current UI:
Screen Shot 2022-08-17 at 1 49 29 pm

New Feature

Can safe-settings add support for specifying who can force push to a protected branch?
Currently we are only able to set allow_force_pushes: true | false for branch protection rules.

API support

This does not appear to be supported by the REST API.

However, this is available via the GraphQL API as bypassForcePushAllowances

TypeError: Cannot read property 'error' of undefined on POST

Problem Description

We are seeing the app throw a TypeError when any Github event triggers the webhook. The app is running on Kubernetes and deployed with Helm.

What is actually happening

The app throws a 500 and doesn't enforce any settings defined in the admin repo.

What is the expected behavior

The app returns a 200 and enforces the settings defined in the admin repo.

Error output, if available

AggregateError: 
    TypeError: Cannot read property 'error' of undefined
        at /opt/safe-settings/lib/configManager.js:20:18
        at async ConfigManager.loadYaml (/opt/safe-settings/lib/configManager.js:19:24)
        at async syncAllSettings (/opt/safe-settings/index.js:16:29)
        at async Promise.all (index 0)
        at async middleware (/opt/safe-settings/node_modules/@octokit/webhooks/dist-node/index.js:355:5)

Context

n/a

Are you using the hosted instance of probot/settings or running your own?

Running my own.

If running your own instance, are you using it with github.com or GitHub Enterprise?

github.com.

Version of probot/settings

^12.2.8

Version of GitHub Enterprise

n/a

Configurable org-level repository instead of fixed admin

Prerequisites:

  • Is the functionality available in the GitHub UI? If so, please provide a link to information about the feature.

No

New Feature

Please describe the desired new functionality:

Currently org-level default repo configuration where the settings.yml goes is fixed to admin only.
https://github.com/github/safe-settings/blob/main-enterprise/lib/configManager.js#L18

Other github apps allow different repositories, or have by default enabled .github as org-level. Examples:

This change would allow users to set the default repo at their convenience to store any github apps settings for any app, instead of having different repos within the org for multiple configurations.

Example of idea at deployment-settings.yml:

defaultOrgRepo: '.github'
restrictedRepos:
  # You can exclude certain repos from safe-settings processing
  #  If no file is specified, then the following repositories - 'admin', '.github', 'safe-settings' are exempted by default
  exclude: ['admin', '.github', 'safe-settings']
...

Timeouts with lambda functions

Problem Description and Context

In the organization where I work, we have more than 2k repositories and we have worries about this scenario because after I configured the lambda function with this application, I had a little problem with timeouts when we changed a single repository configuration and one push happens calling the lambda function.

The problem with timeouts happens when one patch in one repository make a change in the repository description. The default timeout is 3s, but after I changed to 6s, all pushes seems ok, but with this only little change we need 6s of timeout.

Question

Are there any specific timeout recommendations for lambda functions (and high timing is to be expected) or is it a performance issue you worry about in the future?

404 When force_create repo -> Not inserting Org Name

Problem Description

Working to prototype and implement safe-settings. While working through the bug, I created blank settings.yml, suborg file and a new repo file under .github/repos/test-repo.yml.

When creating a new yaml file for a repo and setting force-create to true, it throws a 404 when attempting to create the repository.

What is actually happening

When the application is trying to do an HTTP Post to github it is getting a 404. The 404 is caused by the URL not having the org name in it.

status: 404
request: {
method: "POST"
url: "https://api.github.com/orgs//repos"

What is the expected behavior

Repository is created

Error output, if available

status: 404
request: {
    method: "POST"
    url: "https://api.github.com/orgs//repos"
    headers: {
      "accept": "application/vnd.github.nebula-preview+json",
      "user-agent": "probot/12.2.0 octokit-core.js/3.5.1 Node.js/14.16.1 (win32; x64)",
      "authorization": "token [REDACTED]",
      "content-type": "application/json; charset=utf-8"
    }
    body: "{\"name\":\"test-repo-1\",\"force_create\":true,\"description\":\"description of the repo\",\"homepage\":\"https://example.github.io/\",\"auto_init\":true,\"private\":true,\"visibility\":\"private\",\"has_issues\":true,\"has_projects\":true,\"has_wiki\":true,\"default_branch\":\"main\",\"license_template\":\"mit\",\"repo\":\"test-repo\",\"owner\":\"test-org\"}"
    request: {
      "retryCount": 1
    }
}

Context

This is when first attempting to get the bot running and creating/maintaining repositories.

Are you using the hosted instance of probot/settings or running your own?

Running on NPM locally on my machine.

Using some custom settings for self signed certs.

Windows 10

If running your own instance, are you using it with github.com or GitHub Enterprise?

Github Enterprise Cloud

Version of probot/settings

Pulled a copy of the main branch and ran npm install tonight

Version of GitHub Enterprise

Github Enterprise Cloud

Inheritance, hierarchy in branch configuration

New Feature

We started using required_status_checks manage by safe-settings, but due to its behavior, we stopped using it because it did not meet what we wanted.
We want to have required_pull_request_reviews at the organization level, and required_status_checks with the common ones at the organization level, extend for some repositories and remove for others (required_status_checks: []).

Therefore, what we were looking for:
.github/settings.yaml

branches:
  - name: default
    protection:
      required_pull_request_reviews:
        required_approving_review_count: 1
        dismiss_stale_reviews: true
        require_code_owner_reviews: true
      required_status_checks:
        strict: true
        contexts:
          - "🔃 pre-commit"
      enforce_admins: true
      restrictions: null
      allow_force_pushes: false
      allow_deletions: false
      block_creations: true
      required_conversation_resolution: true

.github/repos/example.yml

branches:
  - name: default
    protection:
      required_status_checks:
        strict: true
        contexts:
          - "Lint, compile and build"

And we had to do something like this:

.github/repos/example.yml

branches:
  # CAUTION: before edit check default config in .github/settings.yml
  #   safe-settings do not merge config for branches, so you need to copy base
  #   config from .github/settings.yml and modify it with your repository config
  - name: default
    protection:
      required_pull_request_reviews:
        required_approving_review_count: 1
        dismiss_stale_reviews: true
        require_code_owner_reviews: true
      required_status_checks:
        strict: true
        contexts:
          - "🔃 pre-commit"
          - "Lint, compile and build"
      enforce_admins: true
      restrictions: null
      allow_force_pushes: false
      allow_deletions: false
      block_creations: true
      required_conversation_resolution: true

We also couldn't leave all the checks at the organization level because in the repositories that don't have those actions, the required_status_checks stays waiting, but nobody will validate it and the PR cannot be merged.

Extra syncronous way to update from pipeline.

New Feature

Extra syncronous way to update from pipeline, that would prevent our majority of problems, invalid configurations wich error logs are not available for the change requester.

This could fit with a nice github action.

Also a dry-mode (nop?) for pull request.

Advantages:

  • Visibilize error without having access to the service. Red/green pipeline (Also improve the error logs)
  • Avoid commiting wrong configs (nop mode)
  • When the pipeline has finish, the config have been updated (sync feedback)

This is compatible with the service still doing reconciliation.

Regards!

PD: seems that the https://github.com/github/safe-settings#pull-request-workflow is very related. we will check it.

Open Source safe-settings

This app would help to solve customers' issues with probot/settings by providing centralized, audited controls around repository configuration. Can we explore open-sourcing it either as part of the probot organization or through another channel?

[Documentation] - Add AWS lambda deployment documentation

I was wondering if safe-settings can be deployed on AWS lambda, since it is based on probot I assume this is possible, for the triggers, it is just matter of redirecting the webhook from the app to the lambda. Thanks in advance

Migrate all console.log to use probot logging

Problem Description

Hi all, there are a few places where console.log is being used in place of probot logging. Many of these look to be debug/testing logs. I was thinking of going through and moving them all to use probot logger, but there is nothing to prevent further usage in the future. Any thoughts on ensuring correct logging is used? I see the project uses standard right now, which doesnt allow for doing so via eslint.

If we reach consensus, I am happy to do the work

Label merge strategy

Prerequisites:

N/A

New Feature

At the moment labels are enforced at this moment.
I would like to have the option to only add/update labels and do not remove any labels that other github actions or developers want to use.
This properly means a merge strategy for labels. Overwrite vs Append

commentmessage can be too big and fail

Problem Description

There is a limit to comment in checks api summary. When there are a large number of changes (like changing a setting across all repos), this API call can fail, casuing no completion status to ever be posted

What is actually happening

Check run stays pending

What is the expected behavior

Check run completes

A simple solution we are using is to just make sure the comment fits in summary limits
image
but its not super pretty. I can implenent this solution if we want

Warning for new GH feature in beta

Hi folks, just creating this issue as a warning for an upcoming feature from GitHub

https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/managing-security-managers-in-your-organization

Setting a team as a security manager (as on org-wide setting, so out of "scope" of safe-settings app) causes the relevant team to be added to every repository in the organization. This causes safe-settings team differ to always identify out-of-sync teams for every repo, causing re-sync for every repo as well. Further, the attempted sync will fail with:

error calling find for Teams HttpError: You cannot remove repositories from a security manager team. for repo:

I think adding this team to global teams in settings.yaml will mitigate this (though I will need to check tomorrow), but there is no clear way to keep these settings and security managers in sync as of now

Repository settings not being updated in 2.0.12

Problem Description

I have updated our safe-settings deployment to 2.0.12 and it seems the updating of general repo settings are broken, such as "has_projects", "has_wiki", etc. Note that we are using suborgs configurations. The branches section works fine and protection rules etc are detected and updated correctly.

What is actually happening

The app does detect the changes from looking at cloudwatch:

  | 2022-09-29T14:09:03.892+01:00 | DEBUG (event): Result of comparing repo for changes = {
  | 2022-09-29T14:09:03.892+01:00 | "additions": {},
  | 2022-09-29T14:09:03.892+01:00 | "modifications": {
  | 2022-09-29T14:09:03.892+01:00 | "has_projects": false,
  | 2022-09-29T14:09:03.892+01:00 | "name": "gradle-scripts"
  | 2022-09-29T14:09:03.892+01:00 | },
  | 2022-09-29T14:09:03.892+01:00 | "hasChanges": true
  | 2022-09-29T14:09:03.892+01:00 | }

However, these changes are not applied and there is no log entry in the GitHub app log after "push" to indicate that it has attempted to update anything.

The last thing I can see in the logs is DEBUG (event): Not run in nop, not sure if that is relevant.

What is the expected behavior

That the top level repo settings should be updated when changed in the settings file.

Context

Are you using the hosted instance of probot/settings or running your own?

Our own, deployed to AWS via serverless.

If running your own instance, are you using it with github.com or GitHub Enterprise?

Github.com

Version of probot/settings

2.0.12

Missing trigger for adding repo to a team?

Problem Description

We are using suborgs with the suborgteams mechanism to specify repos associated with a team.

When we create a new repo, this app is triggered but as the repo is not yet associated with a team, it does not get processed by the app, and there is no trigger for when the repo does get added to a team after creation.

We added the "Team add" event for the app but that made no difference.

What is the expected behavior

Should there be a trigger for "Team add" as well to process repos for the cases where repos are listed via teams and a repo is added to a team?

Repository settings not being applied on Baseline change

Problem Description

Repository settings (.github/repos/*.yml) isn't overriding the baseline settings (.github/settings.yml)

What is actually happening

I'm updating the base configuration in .github/settings.yml, getting it approved and merging into the default_branch. One this gets detected by the Github App, it enforces that baseline configuration across the designated repositories WITHOUT considering the override settings in the repos folder. The result is that specific teams I've configured in the override file are removed since they aren't present merely in the .github/settings.yml.

What is the expected behavior

I would expect that when applying the default configuration, it would have followup step where it then applies the override settings from the repos folder/*.yml file. From first to last, a baseline configuration apply, followed by a SubOrg configuration override, followed by a Repo specific override.

Error output, if available

No errors in the Github App logs or the Probot logs.

Context

Using the probot application stood up in a kubernetes cluster in its own namespace. I deployed it using the helm chart provided and followed the instructions carefully.

Are you using the hosted instance of probot/settings or running your own?

Running my own. Deployed using the deploy.md instructions for helm charts.

If running your own instance, are you using it with github.com or GitHub Enterprise?

github.com, no Enterprise.

Version of probot/settings

v12.2.5

Version of GitHub Enterprise

Using Github without Enterprise

[Question] Safe-settings cron with lambda via serverless

I have my safe settings lambda up and running (via serverless) and verified everything works fine. I want to run these settings periodically via lambda setup. As this is a lambda function, node-cron does not make sense.

NOTE: I tried creating a Cloudwatch event to trigger lambda function. However that is triggering the Serverless handler webhook which is not actually running the settings bot code.

So what is the suggested approach in running the lambda periodically to reconfigure settings for all the repos in the organization ? Any documentation would be appreciated.

Hosted version of safe-settings

Prerequisites:

  • Is the functionality available in the GitHub UI? If so, please provide a link to information about the feature.
    N/A

New Feature

Please describe the desired new functionality:
This is more of a question than a feature request. The documentation says "See docs/deploy.md if you would like to run your own instance of this plugin." Does that mean not running our own instance of the plugin is an option?

In other words, is there a hosted option for safe-settings from GitHub?

Warning: possible change in GH API may cause issues with safe-settings

On latest versions:

When a change is triggered and safe-settings runs for a repository, the first change made is for repository settings. Something like

DEBUG (mark): GitHub request: PATCH https://api.github.com/repos/ORG/REPO - 422
    auto_init: true
    visibility: "internal"
    has_issues: false
    has_projects: false
    has_wiki: false
    allow_squash_merge: true
    allow_merge_commit: false
    allow_rebase_merge: false
    allow_auto_merge: true
    delete_branch_on_merge: true
    org: "REDACTED"

This request, however, has started to fail with the below message:

"data":{"message":"Visibility is already internal.","documentation_url":"https://github.com/pricing"}}

In case its relevant: this request also has the nebula header enabled "headers":{"accept":"application/vnd.github.nebula-preview+json"

I do not know where/how to track down possible changes to GH API that might cause this :/

cc @decyjphr

Explicit Returns on Validation Plugin

Explicit Returns on Validation Plugin

Please describe the desired new functionality:

Current Behavior

On the branch currently in #169, when a check fails, the message looks like this:

❌ Settings : Error: Branch protection required_approving_review_count cannot be overidden to a lower value

Expanding the line does not show anything.

Expected Behavior

Expanding the message displays, at a minimum, the file that was changed, or even better, a list of which repositories would be affected.

Essentially, an explicit message for the user, so that they have better info with which to approach their support team.

Members of teams are not synced

Problem Description

  • Add members to a team via .github/settings.yml
  • Add members manually to a team

What is actually happening

  • the members from .github/settings.yml are not auto added
  • the manually added member is left alone

What is the expected behavior

  • the members from .github/settings.yml should be synced
  • any members not in .github/settings.yml should be removed ie a full sync should happen

Context

Are you using the hosted instance of probot/settings or running your own?

hosted

Easier more clear instructions on what exactly is needed to deploy

it seems like the deploy instructions indicate that we have at least one required step:

  • create an admin repo add settings yaml files.

Then it's not clear which of the following we have to choose:

  • add some existing hosted safe-settings app to our org?
  • simply run docker run --rm -it -e APP_ID=*** -e GH_ORG=*** yadhav/safe-settings:2.0.9
  • fork the repo, clone it locally and go through all the pain in the ass stuff related to npm install, then develop some way to host this.
  • fork the repo, clone it locally and decide to deploy it to some k8s cluster
  • fork the repo, clone it locally and decide to deploy it to aws/serverless

Currently the documentation around deployment is very confusing when trying to understand what's needed depending on which of the above you want to do.

  • does .1 even exist?
  • as in .2 if we just want to run a docker container... can we just get away with specifying -e ...

Furthermore, there is contained in the documentation, language that seems to create confusion for first timers to github apps:

  • talk about "manifest flow", indicate there are hard ways and easy ways to setup the app. when following the links to "manifest flow" we end up on a page that then talks about using npx create... which would have us creating another repo... so now we have three repos, the admin repo, the safe-settings repo we forked, and now this other repo that you're telling us to make because: "just follow the manifest flow"

really what I'd like, is to only have an admin repo and then just join an existing app to my org.

The nop status check fails on pull requests with only 1 commit

Problem Description

@moensch discovered that pull requests with only 1 commit fail the nop status check.

What is actually happening

This just "hangs" forever:

image

What is the expected behavior

When you send another commit to this branch, then it succeeds:

image

Error output, if available

status: 404
request: {
    method: "GET"
    url: "https://api.github.com/repos/joshjohanning-org-safe-settings/admin/compare/0000000000000000000000000000000000000000...5f7d787b1a886fd614a9a5b271a5c149a904750f"
    headers: {
      "accept": "application/vnd.github.v3+json",
      "user-agent": "probot/12.2.0 octokit-core.js/3.5.1 Node.js/14.19.0 (linux; x64)",
      "authorization": "token [REDACTED]"
    }
    request: {}
}

Not sure where in the code this is, but I think we should be doing something like:

HEAD...5f7d787b1a886fd614a9a5b271a5c149a904750f

instead of

0000000000000000000000000000000000000000...5f7d787b1a886fd614a9a5b271a5c149a904750f

Context

Are you using the hosted instance of probot/settings or running your own?

Running my own

If running your own instance, are you using it with github.com or GitHub Enterprise?

github.com

Same repository that is part of multiple suborgs

Prerequisites:

  • Is the functionality available in the GitHub UI? If so, please provide a link to information about the feature.
    n/a

New Feature

What I am looking for exactly is a way to add required_status_checks from multiple base files to a repository. We extensively use monorepos and reusable workflows. Having a way to not repeat ourselves too much with the repo settings would facilitate maintenance quite a bit.

So I tried adding a single repo to multiple suborgs but the required_status_checks are not merged and only the checks from one suborg are synced. Every other checks are removed from the branch protections. Using suborgs for that purpose may not be appropriate though. What if a suborg requires 1 approval and the other one asks for 2 approvals? How to decide which one should be applied first?

I think a way to extend other config files and apply the extensions in the order they are specified could solve the issue. Many linter configs work this way. ie:

.github/repos/example.yml

"_extend":
  - webapp-react-frontend
  - webapp-bff

branches:   # Note that these are already merged to "root" and "one of the suborgs" settings
  - name: default
    protection:
      required_status_checks:
        contexts:
          - "Something very specific to this repo"

.github/templates/webapp-react-frontend.yml

branches:
  - name: default
    protection:
      required_status_checks:
        contexts:
          - "React / ESLint"

.github/templates/webapp-bff.yml

branches:
  - name: default
    protection:
      required_status_checks:
        contexts:
          - "BFF / Compile"

Visibility configuration files

Prerequisites:

  • Is the functionality available in the GitHub UI? If so, please provide a link to information about the feature.

Yes here

API "visibility" here
Octokit "Get a repository" here

Code Example to get visibility for all repos and match to the visibility config

        const repos = await octokit.rest.repos.listForOrg({
          org: org
        })

        for (var i = 0; i < repos.data.length; i++)
        {
          const repoName = repos.data[i].name

          const  results  = await octokit.rest.repos.get({
            owner: org,
            repo: repoName
            });

          switch (results.data.visibility) {
            case 'private':
              console.log(`Applying private.yml to ` + repoName);
              break;
            case 'public' :
              console.log(`Applying public.yml to ` + repoName);
              break;
            case 'internal' :
              console.log(`Applying internal.yml to ` + repoName);
              break;
            default:
              console.log(`Error accessing visibility for ` + repoName);
            }
          }

New Feature

Our organization requires different configurations for the different visibility options (public repos, private repos, internal repos).

For example:
We require a license file for all public repos, however this is not required for private or internal repos.

I did not see any documentation or code that alluded to this being a configuration option in the current state of Safe-Settings. Therefore, I am working on an enhancement in our forked version of Safe-Settings that would evaluate the various settings files in the following order:

settings.yml (org wide) -> (suborgs) -> visibility configurations (private.yml, public.yml, internal.yml) -> repos/(repo-name).yml

Would anyone else be interested in this feature? If so, please provide feedback, suggestions, etc.

❗ Significant changes coming in `safe-settings` v2

Background

This issue is to inform you that some significant changes are coming with #194 PR.
The full list of changes could be observed here:

The suborg-scalability branch has been kept up to date with the changes in main-enterprise. The list of changes that are in main-enterprise and not in suborg-scalability are here (Hopefully there are none by the time we merge )

Why

New features being added:

  1. safe-settings will not call syncAll for subOrg changes. It will instead call syncSubOrgs which builds the subOrg configs and repo configs for the specific repos based on the subOrg config.
  2. safe-settings can now scale to 1000s of repos because it compares the current configuration in GitHub with the changes being applied and only calls the API if there are changes
  3. In order to scale for 1000's of repos, when a PR is created for config changes, the check will not produce a verbose list of changes.
  4. If there are multiple repo and suborg config file changes in a push/commit, the code will process every config file in the commit : case1, case2
  5. To make it easy to trysafe-settings, you can now turn it on for only specific repos and allow for more gradual adoption. To enable it for specific repos use the include setting in the deployment-config.yml file:
restrictedRepos: 
  # You can exclude certain repos from safe-settings processing
  #  If no file is specified, then the following repositories - 'admin', '.github', 'safe-settings' are exempted by default
  exclude: ['admin', '.github', 'safe-settings']
  # Alternatively you can only include certain repos
  include: ['test']

Additional Toil

  • It is a lot of work to keep the suborg-scalability up to date with changes in the main-enterprise branch - More conflicts, more testing etc.
  • Avoid features already in the branch to be re-invented in the main-enterprise branch

Risks

  • There is a potential that some things that were working in main-enterprise could be broken (inadvertently) after the merge.
  • Any WIP in forks would require additional effort to integrate the new changes.

Versioning

I'll start a new version with these changes as 2.x
Also, I am planning to create a branch with the code from the current main-enterprise

Next Steps

  • Please add your comments to indicate your opinion on this merge
  • The merge won't happen for a few days; weeks, if that is the prevailing opinion.
  • If you can test the code in the branch, thank you 🙏🏾

Support for Branch Protection bypass_pull_request_allowances

New Feature

Can safe-settings add support for the "Allow specified actors to bypass required pull requests" feature of required pull request reviews for branch protection?

  • Is the functionality available in the GitHub UI? If so, please provide a link to information about the feature.

Available in the UI as:

Allow specified actors to bypass required pull requests
Specify people, teams, or apps who are allowed to bypass required pull requests.

Screen Shot 2022-07-25 at 10 41 15 AM

Available in the API as "bypass_pull_request_allowances".

Automatically Link Team to IdP Group after Team Creation for EMU Enterprise

Prerequisites:

  • Is the functionality available in the GitHub UI? If so, please provide a link to information about the feature.

Yes, the functionality can be found here.

API endpoint is here Not sure if this endpoint will work with EMU instances.

  • If the functionality is not yet available in the API, it would be helpful if you
    contacted support (https://support.github.com/) or posted in the Community Forum (https://github.community/). Please
    include a link to the forum post if you create one or a copy of the response from support.

New Feature

Please describe the desired new functionality:

When a team is provisioned by safe-settings, additional parameters can be provided that will link that team to an IdP group. This particular case is for EMU's, so this would be for Azure AD and Okta.

ReferenceError in settings.js for suborgs parsing

Problem Description

The suborgs functionality is broken and the app errors out when trying to parse a file in the .github/suborgs/ folder.

What is actually happening

The app fails with:

ERROR (event): subOrgConfigs is not defined
  ReferenceError: subOrgConfigs is not defined
    at Settings.getSubOrgConfig (.../safe-settings/lib/settings.js:166:9)

This is due to line 166 having an invalid reference return subOrgConfigs[k] which should be return this.subOrgConfigs[k]. The app works correctly after making this change locally.

What is the expected behavior

Correct parsing of the suborg yaml files.

Error output, if available

ERROR (event): subOrgConfigs is not defined
  ReferenceError: subOrgConfigs is not defined
    at Settings.getSubOrgConfig (.../safe-settings/lib/settings.js:166:9)

Context

Are you using the hosted instance of probot/settings or running your own?

Running my own using the latest code on main-enterprise

If running your own instance, are you using it with github.com or GitHub Enterprise?

GHEC

Version of probot/settings

Latest on main-enterprise

Version of GitHub Enterprise

[Question] Safe-settings cron with lambda via serverless

Problem Description

I have my safe settings lambda up and running (via serverless) and verified everything works fine. I want to run these settings periodically via lambda setup. As this is a lambda function, node-cron does not make sense.

NOTE: I tried creating a Cloudwatch event to trigger lambda function. However that is triggering the Serverless handler webhook which is not actually running the settings bot code.

So what is the suggested approach in running the lambda periodically to reconfigure settings for all the repos in the organization ? Any documentation would be appreciated.

Github SafeSettings invokes DELETE API on incorrect settings

Hello,

Github Safesettings calls the DELETE api to remove all the repositories when you add incorrect config in the settings.yml file. Error seems to be bit concerning as it calls delete api. Also, the error states that it will remove the repo on Mon, 01 Feb 2021.

Sanitized logs:
←[92mxxxx-safesettings-←[0m ←[32mxxxx-safesettings←[0m [@octokit/request] "DELETE https://api.github.com/teams/5430398/repos/{org}/{repo}" is deprecated. It is scheduled to be removed on Mon, 01 Feb 2021 00:00:00 GMT. See https://developer.github.com/changes/2020-01-21-moving-the-team-api-endpoints/
←[92mxxxx-safesettings←[0m ←[32mxxxx-safesettings←[0m error calling find for Teams HttpError: You cannot remove repositories from a security manager team. for repo: {"owner":"{org}","repo":"{repo}","branch":"main","required_pull_request_reviews":{"required_approving_review_count":1},"enforce_admins":null,"restrictions":null,"headers":{"accept":"application/vnd.github.hellcat-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.zzzax-preview+json"}} entries [{"name":"security-reader","permission":"security-scan-reviewer"}]

settings.yml:

repository:
teams:
  - name: security-reader
    permission: security-scan-reviewer
branches:  
  - name: default
    protection:      
      required_pull_request_reviews:
        required_approving_review_count: 1
      enforce_admins: 
      restrictions:

Note: We are building the docker image from the dockerFile provided in this repo and running the app on AKS platform.

Is this a bug within the code?

Checks reporting config differences when there aren't any

Problem Description

When I configure a repo with its existing branch protection config, there are two items which show as changed in the PR check which haven't changed.

What is actually happening

It looks like the comparison being done here https://github.com/github/safe-settings/blob/main-enterprise/lib/mergeDeep.js#L120-L126 is showing differences for some items when the config should be the same. The two example differences I am seeing are:

From github REST API (target):

"enforce_admins": {	
	"url": "https://api.github.com/repos/Introhive/introhive/branches/master/protection/enforce_admins",	
	"enabled": false
},

Is being compared with config (source):
"enforce_admins": false,
-----and-----
From github REST API(target):

"required_status_checks": {
	"url": "https://api.github.com/repos/Introhive/introhive/branches/master/protection/required_status_checks",	
	"strict": false,
    "contexts": [
      "task-list-completed",
      "codeclimate"
	],
	"contexts_url": "https://api.github.com/repos/Introhive/introhive/branches/master/protection/required_status_checks/contexts",
	"checks": [	
    {	
      "context": "task-list-completed",	
      "app_id": null	
    },
    {	
    	"context": "codeclimate",	
    	"app_id": null
    }	
]	

Is being compared with (source):

"required_status_checks": {
   "strict": false,	
   "contexts": [
     "task-list-completed",	
     "codeclimate"
	]
}

What is the expected behavior

I would expect the comparisons above to be done in a manner that doesn't indicate there are config changes.

Error output, if available

Branch Protection : introhive : Followings changes will be applied to the branch protection for archived_develop branch = { "additions": { "required_status_checks": { "strict": false } }, "modifications": { "enforce_admins": true } }

Branch Protection : introhive : Followings changes will be applied to the branch protection for master branch = { "additions": { "required_status_checks": { "strict": false }, "restrictions": { "teams": [ "committers", { "name": "Committers", "id": {{REDACTED}}, "node_id": ""id": {{REDACTED}}", "slug": "committers", "description": "Members who can merge PRs into master.", "privacy": "closed", "url": "https://api.github.com/organizations/({REDACTED}}/team/({REDACTED}}", "html_url": "https://github.com/orgs/Introhive/teams/committers", "members_url": "https://api.github.com/organizations/({REDACTED}}/team/({REDACTED}}/members{/member}", "repositories_url": "https://api.github.com/organizations/({REDACTED}}/team/({REDACTED}}/repos", "permission": "pull", "parent": null } ] } }, "modifications": { "enforce_admins": false } }

Context

We would like to be able to validate that these checks to show no changes as we roll safe-settings out for all repositories in our org.

Are you using the hosted instance of probot/settings or running your own?

Running our own

If running your own instance, are you using it with github.com or GitHub Enterprise?

github.com

Version of probot/settings

    "probot": "12.2.0"

safe-settings is synced up to the latest from the main-enterprise branch as of today.

Version of GitHub Enterprise

N/A

Using safe-settings to roll out organisation required workflows

Prerequisites:

  • Is the functionality available in the GitHub UI? If so, please provide a link to information about the feature.

Yes, standard commit functionality.

Yes, possible to create commits via the API.

  • If the functionality is not yet available in the API, it would be helpful if you
    contacted support (https://support.github.com/) or posted in the Community Forum (https://github.community/). Please
    include a link to the forum post if you create one or a copy of the response from support.

New Feature

Please describe the desired new functionality:

Can safe-settings be used or extended to be able to commit organisation-wide workflows across all repositories?

An example might be, wanting to run a security compliance action that will measure and report back the compliance state of the repository via a GitHub action.

Unable to add teams to a repo

Problem Description

Safe Settings is able to remove teams from a repo based on configuration, but not able to add teams to a repo.

What is actually happening

^^

What is the expected behavior

The GitHub teams should be added to the repo.

Error output, if available

No errors. There is a comment in the code refering to the GitHub API. Has the endpoint changed for github.com and this is not reflected in code?

Context

We are trying to run safe-settings with suborg's settings files.

Are you using the hosted instance of probot/settings or running your own?

We are running probot in our own container.

If running your own instance, are you using it with github.com or GitHub Enterprise?

Github.com

Version of probot/settings

Latest.

Version of GitHub Enterprise

NA

Support App ID for status source

Prerequisites:

  • Is the functionality available in the GitHub UI? If so, please provide a link to information about the feature.
    Yes
    not super clear in the docs, but available in UI
    image

  • Is the functionality available through the GitHub API? If the functionality is available, please provide links to the
    API documentation (https://developer.github.com/v3/) as well as the Octokit documentation (https://octokit.github.io/).
    Yes, search required_status_checks.checks[].app_id in https://octokit.github.io/rest.js/v18

New Feature

Please describe the desired new functionality:
In UI/API, we are able to choose which app is allowed to post certain statuses (or at least, which we accept for required status completion). Can we add this to safe-settings to ensure statuses come from gh actions

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.