├── pyproject.toml
├── .gitignore
├── .github
├── dependabot.yml
└── workflows
│ ├── pytype.yaml
│ └── python.yaml
├── tests
├── suspend_app_form.html
├── add_app_form.html
├── new_org_form.html
├── github_form.html
├── __init__.py
├── usage_report.csv
├── update_app_permissions.html
├── request_report_form.html
├── security_analysis_form.html
└── test_api.py
├── requirements.txt
├── AUTHORS
├── github_nonpublic_api
├── __init__.py
└── api.py
├── setup.cfg
├── docs
├── contributing.md
└── code-of-conduct.md
├── setup.py
├── README.md
└── LICENSE
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.ruff]
2 | line-length = 100
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | .pytest_cache
3 | .vscode
4 | build
5 | dist
6 | __pycache__
7 | *.egg-info
8 | _build
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: "pip"
4 | directory: "/" # Location of package manifests
5 | schedule:
6 | interval: "weekly"
7 |
--------------------------------------------------------------------------------
/tests/suspend_app_form.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
--------------------------------------------------------------------------------
/tests/add_app_form.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
--------------------------------------------------------------------------------
/tests/new_org_form.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | absl-py==2.3.0
2 | configobj==5.0.9
3 | html5lib==1.1
4 | pyotp==2.9.0
5 | pytest==8.4.0
6 | requests==2.32.4
7 | ruff==0.11.13
8 | six==1.17.0
9 | typing_extensions==4.13.2
10 | urllib3==2.4.0
11 | webencodings==0.5.1
--------------------------------------------------------------------------------
/tests/github_form.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/AUTHORS:
--------------------------------------------------------------------------------
1 | # This is the list of significant contributors
2 | #
3 | # This does not necessarily list everyone who has contributed code
4 | # especially since many employees of one corporation may be contributing
5 | # To see the full list of contributors, see the revision history in
6 | # source control
7 |
8 | Alphabet
9 | Google LLC
10 |
--------------------------------------------------------------------------------
/.github/workflows/pytype.yaml:
--------------------------------------------------------------------------------
1 | name: pytype check
2 |
3 | on:
4 | push:
5 |
6 | jobs:
7 | check:
8 | strategy:
9 | fail-fast: false
10 | matrix:
11 | runner:
12 | - 'ubuntu-latest'
13 | - 'self-hosted'
14 | runs-on: ${{ matrix.runner }}
15 | steps:
16 | - uses: actions/checkout@v2
17 | - name: pytypes checker
18 | uses: theahura/pytypes-action@main
19 | with:
20 | args: -d import-error
21 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 The Authors (see AUTHORS file)
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
--------------------------------------------------------------------------------
/github_nonpublic_api/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 The Authors (see AUTHORS file)
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | name = github_nonpublic_api
3 | description_file =
4 | README.md
5 | author = Bill Napier
6 | author_email = napier@google.com
7 | home_page = https://github.com/google/github_nonpublic_api
8 | summary = This project is developing a python library that can be used to access 'NonPublic' parts of the GitHub API.
9 | license = Apache-2
10 | python_requires = >=3.8
11 | classifier =
12 | License :: OSI Approved :: Apache Software License
13 | Operating System :: OS Independent
14 | Programming Language :: Python
15 | Programming Language :: Python :: Implementation :: CPython
16 | Programming Language :: Python :: 3 :: Only
17 | Programming Language :: Python :: 3
18 | Programming Language :: Python :: 3.8
19 | Programming Language :: Python :: 3.9
20 |
21 | [files]
22 | packages =
23 | github_nonpublic_api
--------------------------------------------------------------------------------
/tests/usage_report.csv:
--------------------------------------------------------------------------------
1 | Date,Product,SKU,Quantity,Unit Type,Price Per Unit ($),Multiplier,Owner,Repository Slug,Username,Actions Workflow,Notes
2 | 2023-06-26,Actions,Compute - UBUNTU,84,minute,0.008,1.0,testorg,testrepo,testuser,.github/workflows/ci.yaml,
3 | 2023-06-26,Actions,Compute - UBUNTU,15,minute,0.008,1.0,testorg,testrepo,testuser,.github/workflows/ci.yaml,
4 | 2023-06-26,Actions,Compute - WINDOWS,18,minute,0.016,2.0,testorg,testrepo,testuser,.github/workflows/ci.yaml,
5 | 2023-06-26,Actions,Compute - WINDOWS,5,minute,0.016,2.0,testorg,testrepo,testuser,.github/workflows/ci.yaml,
6 | 2023-06-27,Actions,Compute - UBUNTU,18,minute,0.008,1.0,testorg,testrepo,obada-ab,.github/workflows/ci.yaml,
7 | 2023-06-27,Actions,Compute - WINDOWS,2,minute,0.016,2.0,testorg,testrepo,obada-ab,.github/workflows/ci.yaml,
8 | 2023-06-28,Actions,Compute - UBUNTU,45,minute,0.008,1.0,testorg,testrepo,obada-ab,.github/workflows/ci.yaml,
9 | 2023-06-28,Actions,Compute - WINDOWS,12,minute,0.016,2.0,testorg,testrepo,obada-ab,.github/workflows/ci.yaml,
--------------------------------------------------------------------------------
/docs/contributing.md:
--------------------------------------------------------------------------------
1 | # How to Contribute
2 |
3 | We'd love to accept your patches and contributions to this project.
4 |
5 | ## Before you begin
6 |
7 | ### Sign our Contributor License Agreement
8 |
9 | Contributions to this project must be accompanied by a
10 | [Contributor License Agreement](https://cla.developers.google.com/about) (CLA).
11 | You (or your employer) retain the copyright to your contribution; this simply
12 | gives us permission to use and redistribute your contributions as part of the
13 | project.
14 |
15 | If you or your current employer have already signed the Google CLA (even if it
16 | was for a different project), you probably don't need to do it again.
17 |
18 | Visit to see your current agreements or to
19 | sign a new one.
20 |
21 | ### Review our Community Guidelines
22 |
23 | This project follows [Google's Open Source Community
24 | Guidelines](https://opensource.google/conduct/).
25 |
26 | ## Contribution process
27 |
28 | ### Code Reviews
29 |
30 | All submissions, including submissions by project members, require review. We
31 | use GitHub pull requests for this purpose. Consult
32 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
33 | information on using pull requests.
34 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 The Authors (see AUTHORS file)
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | # Licensed under the Apache License, Version 2.0 (the "License");
16 | # you may not use this file except in compliance with the License.
17 | # You may obtain a copy of the License at
18 | #
19 | # http://www.apache.org/licenses/LICENSE-2.0
20 | #
21 | # Unless required by applicable law or agreed to in writing, software
22 | # distributed under the License is distributed on an "AS IS" BASIS,
23 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
24 | # implied.
25 | # See the License for the specific language governing permissions and
26 | # limitations under the License.
27 |
28 | import setuptools
29 |
30 | setuptools.setup()
--------------------------------------------------------------------------------
/.github/workflows/python.yaml:
--------------------------------------------------------------------------------
1 | name: 'Python lint and test'
2 |
3 | on:
4 | push:
5 | workflow_dispatch:
6 |
7 | jobs:
8 | build:
9 | strategy:
10 | fail-fast: false
11 | matrix:
12 | python-version: ['3.12']
13 | runner:
14 | - 'ubuntu-latest'
15 | - 'self-hosted'
16 |
17 | runs-on: ${{ matrix.runner }}
18 | steps:
19 | - uses: 'actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744' # ratchet:actions/checkout@v3
20 | - name: 'Set up Python ${{ matrix.python-version }}'
21 | uses: 'actions/setup-python@65d7f2d534ac1bc67fcd62888c5f4f3d2cb2b236' # ratchet:actions/setup-python@v4
22 | with:
23 | python-version: '${{ matrix.python-version }}'
24 | - name: 'Install dependencies'
25 | run: |
26 | python -m pip install --upgrade pip
27 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
28 | - name: 'Lint with ruff'
29 | run: |
30 | # stop the build if there are Python syntax errors or undefined names
31 | ruff check --output-format=github --select=E9,F63,F7,F82 --target-version=py37 .
32 | # default set of ruff rules with GitHub Annotations
33 | ruff check --output-format=github --target-version=py37 .
34 | - name: 'Test with pytest'
35 | run: |
36 | pytest
37 |
--------------------------------------------------------------------------------
/tests/update_app_permissions.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # GitHub NonPublic API
2 |
3 | This project is developing a python library that can be used to access "NonPublic" parts of the GitHub API. These are URL endpoints that are used as part of the UI, for which there is no Public API endpoint in the GitHub REST API or GitHub GraphQL API.
4 |
5 | ## Source Code Headers
6 |
7 | Every file containing source code must include copyright and license
8 | information. This includes any JS/CSS files that you might be serving out to
9 | browsers. (This is to help well-intentioned people avoid accidental copying that
10 | doesn't comply with the license.)
11 |
12 | Apache header:
13 |
14 | Copyright 2022 Google LLC
15 |
16 | Licensed under the Apache License, Version 2.0 (the "License");
17 | you may not use this file except in compliance with the License.
18 | You may obtain a copy of the License at
19 |
20 | https://www.apache.org/licenses/LICENSE-2.0
21 |
22 | Unless required by applicable law or agreed to in writing, software
23 | distributed under the License is distributed on an "AS IS" BASIS,
24 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25 | See the License for the specific language governing permissions and
26 | limitations under the License.
27 |
28 | ## For Developers
29 |
30 | Create a new virtual environment and install the required tools.
31 |
32 | ```bash
33 | python -m venv ~/{some envpath}/github_nonpublic
34 |
35 | pip install --upgrade setuptools,build,pip
36 |
37 | pip install -r requirements.txt
38 | ```
39 |
40 | Testing:
41 |
42 | ```bash
43 | python -m pytest
44 | ```
45 |
46 | Linting:
47 |
48 | ```bash
49 | ruff --output-format=github --select=E9,F63,F7,F82 --target-version=py37 .
50 |
51 | ruff --output-format=github --target-version=py37 .
52 | ```
53 |
54 | Adding license headers:
55 |
56 | ```bash
57 | go run github.com/google/addlicense@v1.1.1 -c "The Authors (see AUTHORS file)" -l apache -v ./**/*.py
58 | ```
59 |
--------------------------------------------------------------------------------
/tests/request_report_form.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
47 |
48 |
--------------------------------------------------------------------------------
/docs/code-of-conduct.md:
--------------------------------------------------------------------------------
1 | # Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, gender identity and expression, level of
9 | experience, education, socio-economic status, nationality, personal appearance,
10 | race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or reject
41 | comments, commits, code, wiki edits, issues, and other contributions that are
42 | not aligned to this Code of Conduct, or to ban temporarily or permanently any
43 | contributor for other behaviors that they deem inappropriate, threatening,
44 | offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | This Code of Conduct also applies outside the project spaces when the Project
56 | Steward has a reasonable belief that an individual's behavior may have a
57 | negative impact on the project or its community.
58 |
59 | ## Conflict Resolution
60 |
61 | We do not believe that all conflict is bad; healthy debate and disagreement
62 | often yield positive results. However, it is never okay to be disrespectful or
63 | to engage in behavior that violates the project’s code of conduct.
64 |
65 | If you see someone violating the code of conduct, you are encouraged to address
66 | the behavior directly with those involved. Many issues can be resolved quickly
67 | and easily, and this gives people more control over the outcome of their
68 | dispute. If you are unable to resolve the matter for any reason, or if the
69 | behavior is threatening or harassing, report it. We are dedicated to providing
70 | an environment where participants feel welcome and safe.
71 |
72 | Reports should be directed to *[PROJECT STEWARD NAME(s) AND EMAIL(s)]*, the
73 | Project Steward(s) for *[PROJECT NAME]*. It is the Project Steward’s duty to
74 | receive and address reported violations of the code of conduct. They will then
75 | work with a committee consisting of representatives from the Open Source
76 | Programs Office and the Google Open Source Strategy team. If for any reason you
77 | are uncomfortable reaching out to the Project Steward, please email
78 | opensource@google.com.
79 |
80 | We will investigate every complaint, but you may not receive a direct response.
81 | We will use our discretion in determining when and how to follow up on reported
82 | incidents, which may range from not taking action to permanent expulsion from
83 | the project and project-sponsored spaces. We will notify the accused of the
84 | report and provide them an opportunity to discuss it before any action is taken.
85 | The identity of the reporter will be omitted from the details of the report
86 | supplied to the accused. In potentially harmful situations, such as ongoing
87 | harassment or threats to anyone's safety, we may take action without notice.
88 |
89 | ## Attribution
90 |
91 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4,
92 | available at
93 | https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
94 |
--------------------------------------------------------------------------------
/tests/security_analysis_form.html:
--------------------------------------------------------------------------------
1 |
2 |
28 |
54 |
80 |
--------------------------------------------------------------------------------
/tests/test_api.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 The Authors (see AUTHORS file)
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | """Unit tests for api.py."""
16 |
17 | import os
18 | from unittest import TestCase, mock
19 |
20 | from github_nonpublic_api import api
21 |
22 | GITHUB_FORM_HTML = os.path.join(os.path.dirname(__file__), 'github_form.html')
23 | NEW_ORG_FORM_HTML = os.path.join(
24 | os.path.dirname(__file__), 'new_org_form.html')
25 | ADD_APP_FORM_HTML = os.path.join(
26 | os.path.dirname(__file__), 'add_app_form.html')
27 | SUSPEND_APP_FORM = os.path.join(
28 | os.path.dirname(__file__), 'suspend_app_form.html')
29 | REQUEST_REPORT_FORM_HTML = os.path.join(
30 | os.path.dirname(__file__), 'request_report_form.html')
31 | DOWNLOAD_USAGE_REPORT_CSV = os.path.join(
32 | os.path.dirname(__file__), 'usage_report.csv')
33 | UPDATE_APP_PERMISSIONS_FORM_HTML = os.path.join(
34 | os.path.dirname(__file__), 'update_app_permissions.html')
35 | SECURITY_ANALYSIS_FORM_HTML = os.path.join(
36 | os.path.dirname(__file__), 'security_analysis_form.html')
37 |
38 |
39 | class TestApi(TestCase):
40 | def _seed_session_with_file(self, filename):
41 | self.session = mock.MagicMock()
42 | with open(filename) as fp:
43 | self.session.get.return_value.text = fp.read()
44 |
45 | """Unit tests for api.py."""
46 |
47 | def test_get_and_submit_form(self):
48 | self._seed_session_with_file(GITHUB_FORM_HTML)
49 |
50 | def _data_callback(data):
51 | data['add'] = 'yes'
52 |
53 | api._get_and_submit_form(
54 | session=self.session, url='http://github.com', data_callback=_data_callback)
55 |
56 | self.session.post.assert_called_once_with(
57 | 'http://github.com/foo', data=dict(add='yes', key='value'))
58 |
59 | def test_get_and_submit_form_by_id(self):
60 | self._seed_session_with_file(GITHUB_FORM_HTML)
61 |
62 | api._get_and_submit_form(
63 | session=self.session, url='http://github.com',
64 | form_matcher=lambda form: form.attrib.get('id') == 'form2')
65 |
66 | self.session.post.assert_called_once_with(
67 | 'http://github.com/form2', data=dict(key='value2'))
68 |
69 | def test_get_and_submit_form_by_id_error(self):
70 | self._seed_session_with_file(GITHUB_FORM_HTML)
71 |
72 | with self.assertRaises(ValueError):
73 | api._get_and_submit_form(
74 | session=self.session, url='http://github.com',
75 | form_matcher=lambda form: False)
76 |
77 | def test_create_business_org(self):
78 | self._seed_session_with_file(NEW_ORG_FORM_HTML)
79 | gh = api.Api(username='user', password='pass', session=self.session)
80 | gh.create_organization(org_name='test', contact_email='nobody@google.com',
81 | org_usage=api.OrganizationUsage.BUSINESS,
82 | business_name='A Fake Business')
83 | self.session.post.assert_called_once_with(
84 | 'https://github.com/account/organizations/new_org', data={
85 | 'authenticity_token': 'value',
86 | 'agreed_to_terms': 'yes',
87 | 'terms_of_service_type': 'corporate',
88 | 'organization[billing_email]': 'nobody@google.com',
89 | 'organization[profile_name]': 'test',
90 | 'organization[login]': 'test',
91 | 'organization[company_name]': 'A Fake Business',
92 | })
93 |
94 | def test_create_personal_org(self):
95 | self._seed_session_with_file(NEW_ORG_FORM_HTML)
96 | gh = api.Api(username='user', password='pass', session=self.session)
97 | gh.create_organization(org_name='test', contact_email='nobody@google.com',
98 | org_usage=api.OrganizationUsage.PERSONAL)
99 | self.session.post.assert_called_once_with(
100 | 'https://github.com/account/organizations/new_org', data={
101 | 'authenticity_token': 'value',
102 | 'agreed_to_terms': 'yes',
103 | 'terms_of_service_type': 'standard',
104 | 'organization[billing_email]': 'nobody@google.com',
105 | 'organization[profile_name]': 'test',
106 | 'organization[login]': 'test',
107 | })
108 |
109 | def test_request_usage_report(self):
110 | self._seed_session_with_file(REQUEST_REPORT_FORM_HTML)
111 | gh = api.Api(username='user', password='pass', session=self.session)
112 | gh.request_usage(enterprise_name='test-enterprise', days=7)
113 | self.session.post.assert_called_once_with(
114 | 'https://github.com/enterprises/test-enterprise/settings/metered_exports', data={
115 | 'authenticity_token': 'value',
116 | 'days': 7,
117 | })
118 |
119 | def test_install_app_on_org(self):
120 | self._seed_session_with_file(ADD_APP_FORM_HTML)
121 | gh = api.Api(username='user', password='pass', session=self.session)
122 | gh.install_application_in_organization(app_name='test-app', org_id=42)
123 | self.session.post.assert_called_once_with(
124 | 'https://github.com/apps/test-app/installations', data={
125 | 'authenticity_token': 'value',
126 | 'install_target': 'all',
127 | })
128 |
129 | def test_suspend_app_toggle(self):
130 | self._seed_session_with_file(SUSPEND_APP_FORM)
131 | gh = api.Api(username='user', password='pass', session=self.session)
132 | gh.toggle_app_suspended(org_name='test-org', app_install_id=42)
133 | self.session.post.assert_called_once_with(
134 | 'https://github.com/long/url/suspended', data={
135 | 'authenticity_token': 'value',
136 | })
137 |
138 | def test_download_usage_report(self):
139 | self._seed_session_with_file(DOWNLOAD_USAGE_REPORT_CSV)
140 | gh = api.Api(username='user', password='pass', session=self.session)
141 | gh.download_usage_report(enterprise_name='test-enterprise', report_id=1)
142 | self.session.get.assert_called_once_with('https://github.com/enterprises/test-enterprise/settings/metered_exports/1')
143 |
144 | def test_update_app_permissions(self):
145 | self._seed_session_with_file(UPDATE_APP_PERMISSIONS_FORM_HTML)
146 | gh = api.Api(username='user', password='pass', session=self.session)
147 | gh.approve_updated_app_permissions(org_name='test-org', app_install_id='42')
148 | self.session.post.assert_called_once_with(
149 | 'https://github.com/organizations/test-org/settings/installations/42/permissions/update',
150 | data={
151 | '_method': 'put',
152 | 'authenticity_token': 'value',
153 | 'version_id': '112233',
154 | 'integration_fingerprint': 'value',
155 | },
156 | )
157 |
158 | def test_update_security_analysis_settings_code_scanning(self):
159 | self._seed_session_with_file(SECURITY_ANALYSIS_FORM_HTML)
160 | gh = api.Api(username='user', password='pass', session=self.session)
161 | gh.update_security_analysis_settings(org_name='test-org', code_scanning_autofix=False)
162 | self.session.post.assert_called_once_with(
163 | 'https://github.com/organizations/test-org/settings/security_analysis/update?owner=test-org',
164 | data={
165 | '_method': 'put',
166 | 'authenticity_token': 'sekr3t_2',
167 | 'code_scanning_autofix': 'disabled',
168 | },
169 | )
170 |
171 | def test_update_security_analysis_settings_code_scanning_3p(self):
172 | self._seed_session_with_file(SECURITY_ANALYSIS_FORM_HTML)
173 | gh = api.Api(username='user', password='pass', session=self.session)
174 | gh.update_security_analysis_settings(org_name='test-org', code_scanning_autofix_third_party_tools=True)
175 | self.session.post.assert_called_once_with(
176 | 'https://github.com/organizations/test-org/settings/security_analysis/update?owner=test-org',
177 | data={
178 | '_method': 'put',
179 | 'authenticity_token': 'sekr3t_3',
180 | 'code_scanning_autofix_third_party_tools': 'enabled',
181 | },
182 | )
183 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/github_nonpublic_api/api.py:
--------------------------------------------------------------------------------
1 | # Copyright 2024 The Authors (see AUTHORS file)
2 | #
3 | # Licensed under the Apache License, Version 2.0 (the "License");
4 | # you may not use this file except in compliance with the License.
5 | # You may obtain a copy of the License at
6 | #
7 | # http://www.apache.org/licenses/LICENSE-2.0
8 | #
9 | # Unless required by applicable law or agreed to in writing, software
10 | # distributed under the License is distributed on an "AS IS" BASIS,
11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | # See the License for the specific language governing permissions and
13 | # limitations under the License.
14 |
15 | """An API to do things that aren't in the official public GitHub REST API."""
16 |
17 | import os.path
18 | import functools
19 | from enum import Enum
20 | import re
21 | from urllib.parse import urljoin
22 |
23 | import html5lib
24 | import pyotp
25 | import requests
26 | from absl import logging
27 | from configobj import ConfigObj
28 | from typing import Optional
29 |
30 |
31 | def _get_and_submit_form(
32 | session, url: str, data_callback=None, form_matcher=lambda form: True
33 | ):
34 | logging.info("Fetching URL %s", url)
35 | response = session.get(url)
36 | response.raise_for_status()
37 |
38 | logging.info("Fetching URL %s", response.url)
39 | for redirect_response in response.history:
40 | logging.info("Redirected from: %s", redirect_response.url)
41 |
42 | doc = html5lib.parse(response.text, namespaceHTMLElements=False)
43 | forms = doc.findall(".//form")
44 |
45 | submit_form = None
46 | for form in forms:
47 | if form_matcher(form):
48 | submit_form = form
49 | break
50 | if submit_form is None:
51 | raise ValueError("Unable to find form")
52 |
53 | action_url = submit_form.attrib["action"]
54 | # Look at all the inputs under the given form.
55 | inputs = submit_form.findall(".//input")
56 |
57 | data = dict()
58 | for form_input in inputs:
59 | value = form_input.attrib.get("value")
60 | if value and "name" in form_input.attrib:
61 | data[form_input.attrib["name"]] = value
62 |
63 | # Have the caller provide additional data
64 | if data_callback:
65 | data_callback(data)
66 |
67 | logging.debug("Form data: %s", str(data))
68 |
69 | submit_url = urljoin(url, action_url)
70 | logging.info("Posting form to URL %s", submit_url)
71 |
72 | response = session.post(submit_url, data=data)
73 | response.raise_for_status()
74 | return response
75 |
76 |
77 | def _get_url_with_session(session, url: str):
78 | logging.info("Fetching URL %s", url)
79 | response = session.get(url)
80 | response.raise_for_status()
81 | return response
82 |
83 |
84 | def create_login_session(
85 | username: str,
86 | password: str,
87 | tfa_callback,
88 | session: Optional[requests.Session] = None,
89 | ) -> requests.Session:
90 | """Create a requests.Session object with logged in GitHub cookies for the user."""
91 | session = session or requests.Session()
92 |
93 | # Clear cookies before re-authentication
94 | session.cookies.clear()
95 |
96 | def _login_callback(data):
97 | data.update(dict(login=username, password=password))
98 |
99 | _get_and_submit_form(
100 | session=session, url="https://github.com/login", data_callback=_login_callback
101 | )
102 |
103 | def _tfa_callback(data):
104 | data.update(dict(otp=tfa_callback()))
105 |
106 | _get_and_submit_form(
107 | session=session,
108 | url="https://github.com/sessions/two-factor",
109 | data_callback=_tfa_callback,
110 | )
111 |
112 | return session
113 |
114 |
115 | _CREATE_ORG_URL = "https://github.com/account/organizations/new?plan=free"
116 | _INSTALL_APP_URL = "https://github.com/apps/{app_name}/installations/new/permissions?target_id={org_id}"
117 | _APP_SUSPEND_URL = "https://github.com/organizations/{org_name}/settings/installations/{app_install_id}"
118 | _REQUEST_USAGE_URL = "https://github.com/enterprises/{enterprise_name}/settings/billing"
119 | _USAGE_REPORT_URL = "https://github.com/enterprises/{enterprise_name}/settings/metered_exports/{report_id}"
120 | _REQUEST_DORMANTUSERS_URL = (
121 | "https://github.com/enterprises/{enterprise_name}/settings/compliance"
122 | )
123 | _UPDATE_APP_INSTALL_URL = "https://github.com/organizations/{org_name}/settings/installations/{app_install_id}/permissions/update"
124 | _UPDATE_SECURITY_ANALYSIS_URL = (
125 | "https://github.com/organizations/{org_name}/settings/security_analysis"
126 | )
127 | _UPDATE_GHAS_SETTINGS_URL = (
128 | "https://github.com/organizations/{org_name}/settings/security_analysis/ghas_settings"
129 | )
130 |
131 |
132 |
133 |
134 | class OrganizationUsage(Enum):
135 | """Organization Usage for Organization Creation."""
136 |
137 | PERSONAL = "standard"
138 | BUSINESS = "corporate"
139 |
140 |
141 | class Api(object):
142 | """API Endpoing for doing non-public things to GitHub.
143 |
144 | Ideally these would all exist as REST API endpoints, but instead we get
145 | to pretend to be a real user.
146 | """
147 |
148 | def __init__(
149 | self,
150 | username: str,
151 | password: str,
152 | tfa_callback=None,
153 | session: Optional[requests.Session] = None,
154 | ):
155 | self._session = session or create_login_session(
156 | username=username,
157 | password=password,
158 | tfa_callback=tfa_callback,
159 | session=session,
160 | )
161 |
162 | def request_usage(self, enterprise_name: str, days: int = 30) -> requests.Response:
163 | """Requests a GitHub usage report.
164 |
165 | Github will send an email link when the report is available.
166 | """
167 |
168 | def _request_usage_callback(data):
169 | data["days"] = days
170 |
171 | action = f"/enterprises/{enterprise_name}/settings/metered_exports"
172 | url = url = _REQUEST_USAGE_URL.format(enterprise_name=enterprise_name)
173 | return _get_and_submit_form(
174 | session=self._session,
175 | url=url,
176 | data_callback=_request_usage_callback,
177 | form_matcher=lambda form: form.attrib.get("action") == action,
178 | )
179 |
180 | def create_organization(
181 | self,
182 | org_name: str,
183 | contact_email: str,
184 | org_usage: OrganizationUsage,
185 | business_name: Optional[str] = None,
186 | ) -> requests.Response:
187 | """Create the specified GitHub organization.
188 |
189 | Right now, only creates free tier organizations.
190 | """
191 |
192 | def _create_org_callback(data):
193 | data["organization[profile_name]"] = org_name
194 | data["organization[login]"] = org_name
195 | data["organization[billing_email]"] = contact_email
196 | data["terms_of_service_type"] = org_usage.value
197 | data["agreed_to_terms"] = "yes"
198 | if org_usage == OrganizationUsage.BUSINESS:
199 | data["organization[company_name]"] = business_name
200 |
201 | return _get_and_submit_form(
202 | session=self._session,
203 | url=_CREATE_ORG_URL,
204 | data_callback=_create_org_callback,
205 | form_matcher=lambda f: f.attrib.get("id") == "org-new-form",
206 | )
207 |
208 | def install_application_in_organization(
209 | self, app_name: str, org_id: int
210 | ) -> requests.Response:
211 | """Installs the specified app on the given organization."""
212 | url = _INSTALL_APP_URL.format(app_name=app_name, org_id=org_id)
213 |
214 | def _install_app_callback(data):
215 | data["install_target"] = "all"
216 |
217 | return _get_and_submit_form(
218 | session=self._session,
219 | url=url,
220 | data_callback=_install_app_callback,
221 | form_matcher=lambda form: app_name in form.attrib.get("action"),
222 | )
223 |
224 | def toggle_app_suspended(
225 | self, org_name: str, app_install_id: int
226 | ) -> requests.Response:
227 | """Set this applicaiton install to be suspended or not."""
228 | url = _APP_SUSPEND_URL.format(org_name=org_name, app_install_id=app_install_id)
229 |
230 | return _get_and_submit_form(
231 | session=self._session,
232 | url=url,
233 | form_matcher=lambda f: "suspended" in f.attrib.get("action"),
234 | )
235 |
236 | def download_usage_report(
237 | self, enterprise_name: str, report_id: int
238 | ) -> requests.Response:
239 | """Download a usage report based on an id recieved in an email"""
240 | url = _USAGE_REPORT_URL.format(
241 | enterprise_name=enterprise_name, report_id=report_id
242 | )
243 | return _get_url_with_session(session=self._session, url=url)
244 |
245 | def request_dormant_users_report(self, enterprise_name: str) -> requests.Response:
246 | """Requests a GitHub dormant users report.
247 |
248 | Github will send an email link when the report is available.
249 | """
250 |
251 | action = f"/enterprises/{enterprise_name}/settings/dormant-users/exports"
252 | url = url = _REQUEST_DORMANTUSERS_URL.format(enterprise_name=enterprise_name)
253 | return _get_and_submit_form(
254 | session=self._session,
255 | url=url,
256 | form_matcher=lambda form: form.attrib.get("action") == action,
257 | )
258 |
259 | def download_dormant_users_report(self, enterprise_name: str) -> requests.Response:
260 | """Download a usage report based on an id received in an email"""
261 | url = _REQUEST_DORMANTUSERS_URL.format(enterprise_name=enterprise_name)
262 | page = _get_url_with_session(session=self._session, url=url)
263 | try:
264 | page_content = page.content.decode("utf-8")
265 | except UnicodeDecodeError:
266 | raise ValueError("Unable to decode page content as UTF-8.")
267 | link = re.search(
268 | r"https://github.com/enterprises/alphabet/settings/dormant-users/exports/[0-9A-Fa-f]{8}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{4}\-[0-9A-Fa-f]{12}",
269 | page_content,
270 | )
271 | if link is None:
272 | raise ValueError("Unable to find dormant users report link in content.")
273 | return _get_url_with_session(session=self._session, url=link.group(0))
274 |
275 | def approve_updated_app_permissions(
276 | self,
277 | org_name: str,
278 | app_install_id: str,
279 | ) -> requests.Response:
280 | """Approve a request for updated permissions for a GitHub app installation in an org"""
281 |
282 | return _get_and_submit_form(
283 | session=self._session,
284 | url=_UPDATE_APP_INSTALL_URL.format(
285 | org_name=org_name,
286 | app_install_id=app_install_id,
287 | ),
288 | form_matcher=lambda f: f.attrib.get("class")
289 | == "js-integrations-install-form",
290 | )
291 |
292 | def update_security_analysis_settings(
293 | self,
294 | org_name: str,
295 | code_scanning_autofix_third_party_tools: Optional[bool] = None,
296 | code_scanning_autofix: Optional[bool] = None,
297 | ):
298 | def _form_matcher(doc, name):
299 | return doc.findall(".//input[@name='%s']" % name)
300 |
301 | if code_scanning_autofix is not None:
302 | def _data_callback(data):
303 | data['code_scanning_autofix'] = 'enabled' if code_scanning_autofix else 'disabled'
304 | _get_and_submit_form(
305 | session=self._session,
306 | url=_UPDATE_GHAS_SETTINGS_URL.format(
307 | org_name=org_name,
308 | ),
309 | form_matcher=functools.partial(_form_matcher, name='code_scanning_autofix'),
310 | data_callback=_data_callback
311 | )
312 | if code_scanning_autofix_third_party_tools is not None:
313 | def _data_callback(data):
314 | data['code_scanning_autofix_third_party_tools'] = 'enabled' if code_scanning_autofix_third_party_tools else 'disabled'
315 | _get_and_submit_form(
316 | session=self._session,
317 | url=_UPDATE_GHAS_SETTINGS_URL.format(
318 | org_name=org_name,
319 | ),
320 | form_matcher=functools.partial(_form_matcher, name='code_scanning_autofix_third_party_tools'),
321 | data_callback=_data_callback
322 | )
323 |
324 | if __name__ == "__main__":
325 | config = ConfigObj(os.path.expanduser("~/github.ini"), _inspec=True)
326 |
327 | api = Api(
328 | username=config["username"],
329 | password=config["password"],
330 | tfa_callback=lambda: pyotp.TOTP(config["otp_seed"]).now(),
331 | )
332 |
--------------------------------------------------------------------------------