Skip to content

Commit e107743

Browse files
authored
Merge pull request #1 from jitsecurity/sc-19672-create-a-tool-to-generate-teams-from-github
initial commit
2 parents 521bd5b + cad283f commit e107743

6 files changed

Lines changed: 373 additions & 0 deletions

File tree

.gitignore

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
__pycache__/
2+
*.py[cod]
3+
*x24py.class
4+
*.so
5+
.Python
6+
env/
7+
build/
8+
dist/
9+
*.egg-info/
10+
*.egg
11+
.idea/
12+
.vscode/
13+
.ipy*
14+
.ipy*/*
15+
.env
16+
.env*/*
17+
venv*
18+
venv*/*
19+
.ipynb_checkpoints
20+
.DS_*
21+
node_modules/

LICENSE

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
Apache License
2+
Version 2.0, January 2004
3+
http://www.apache.org/licenses/
4+
5+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6+
7+
1. Definitions.
8+
9+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10+
11+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12+
13+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14+
15+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16+
17+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18+
19+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20+
21+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22+
23+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24+
25+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26+
27+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28+
29+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30+
31+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32+
33+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34+
35+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36+
37+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38+
39+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40+
41+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42+
43+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44+
45+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46+
47+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48+
49+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50+
51+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52+
53+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54+
55+
END OF TERMS AND CONDITIONS
56+
57+
APPENDIX: How to apply the Apache License to your work.
58+
59+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60+
61+
Copyright [yyyy] [name of copyright owner]
62+
63+
Licensed under the Apache License, Version 2.0 (the "License");
64+
you may not use this file except in compliance with the License.
65+
You may obtain a copy of the License at
66+
67+
http://www.apache.org/licenses/LICENSE-2.0
68+
69+
Unless required by applicable law or agreed to in writing, software
70+
distributed under the License is distributed on an "AS IS" BASIS,
71+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72+
See the License for the specific language governing permissions and
73+
limitations under the License.

Makefile

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
install:
2+
@if ! command -v python3 >/dev/null 2>&1; then \
3+
echo "Python 3 is required but it's not installed. Please install Python 3 and try again." >&2; \
4+
exit 1; \
5+
fi
6+
@if [ ! -d "venv-jit" ]; then \
7+
python3 -m venv venv-jit; \
8+
fi
9+
source venv-jit/bin/activate && pip install -r requirements.txt
10+
11+
configure:
12+
@read -p "Enter GitHub organization name: " org_name; \
13+
read -p "Enter JIT API client ID: " client_id; \
14+
read -p "Enter JIT API client secret: " client_secret; \
15+
read -p "Enter GitHub Personal token (PAT): " github_token; \
16+
echo "ORGANIZATION_NAME=$$org_name" > .env; \
17+
echo "JIT_CLIENT_ID=$$client_id" >> .env; \
18+
echo "JIT_CLIENT_SECRET=$$client_secret" >> .env; \
19+
echo "GITHUB_API_TOKEN=$$github_token" >> .env
20+
21+
run:
22+
source venv-jit/bin/activate && python main.py
23+
24+
help:
25+
@echo "Usage: make [target]"
26+
@echo ""
27+
@echo "Targets:"
28+
@echo " install Install dependencies"
29+
@echo " configure Configure environment variables"
30+
@echo " run Run the main script"
31+
@echo " help Show this help message"

README.md

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,86 @@
11
# jit-create-teams-from-github-topics
2+
3+
This project is a Python script that interacts with the GitHub API and the JIT Teams API.\
4+
It lists the repository names and topics for a given GitHub organization and generates teams according to the topics from Github.
5+
6+
## Prerequisites
7+
8+
- Python 3.x
9+
- Git
10+
11+
## Installation
12+
13+
1. Clone the repository:
14+
15+
```shell
16+
git clone git@github.com:jitsecurity/jit-create-teams-from-github-topics.git
17+
```
18+
19+
2. Change into the project directory:
20+
21+
```shell
22+
cd jit-create-teams-from-github-topics
23+
```
24+
25+
3. Create a virtual environment and install the required dependencies:
26+
27+
```shell
28+
make install
29+
```
30+
31+
## Configuration
32+
33+
Before running the script, you need to configure the necessary environment variables. Follow these steps:
34+
35+
1. Run the configuration command:
36+
37+
```shell
38+
make configure
39+
```
40+
41+
2. Enter the required information when prompted:
42+
- GitHub organization name
43+
- API client ID
44+
- API client secret
45+
- GitHub token
46+
47+
3. The command will generate a `.env` file with the provided information.
48+
49+
## Usage
50+
51+
To run the script and retrieve the repository names and topics, use the following command:
52+
53+
```shell
54+
make run
55+
```
56+
57+
### Using external json file with the --input argument
58+
59+
You can also provide a JSON file containing team details using the `--input` argument. The JSON file should have the following structure:
60+
61+
```json
62+
[
63+
{
64+
"name": "Repository 1",
65+
"topics": ["topic1", "topic2"]
66+
},
67+
{
68+
"name": "Repository 2",
69+
"topics": ["topic3"]
70+
}
71+
]
72+
```
73+
74+
To use the `--input` argument, run the following command:
75+
76+
```shell
77+
python main.py --input path/to/teams.json
78+
```
79+
80+
Replace `path/to/teams.json` with the actual path to your JSON file.
81+
82+
## Development
83+
84+
To override the default Frontegg authentication endpoint, you can set the `FRONTEGG_AUTH_ENDPOINT` environment variable. If the variable is not set, the default value will be used.
85+
86+
To override Jit's API end point, you can set the `JIT_API_ENDPOINT` environment variable. If the variable is not set, the default value will be used.

main.py

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
import argparse
2+
import json
3+
import os
4+
from typing import List
5+
6+
import requests
7+
from dotenv import load_dotenv
8+
from github import Github
9+
from pydantic import BaseModel, ValidationError
10+
11+
# Load environment variables from .env file
12+
load_dotenv()
13+
14+
ORGANIZATION_NAME = os.getenv("ORGANIZATION_NAME")
15+
FRONTEGG_AUTH_URL = os.getenv("FRONTEGG_AUTH_URL", "https://jit.frontegg.com/identity/resources/auth/v1/api-token")
16+
JIT_API_ENDPOINT = os.getenv("JIT_API_ENDPOINT", "https://api.jit.io")
17+
GITHUB_TOKEN = os.getenv("GITHUB_API_TOKEN")
18+
JIT_CLIENT_SECRET = os.getenv("JIT_CLIENT_SECRET")
19+
JIT_CLIENT_ID = os.getenv("JIT_CLIENT_ID")
20+
21+
22+
class RepositoryDetails(BaseModel):
23+
name: str
24+
topics: List[str]
25+
26+
27+
def get_topics_for_teams():
28+
try:
29+
# Create a GitHub instance using the token
30+
github = Github(GITHUB_TOKEN)
31+
32+
# Get the organization
33+
organization = github.get_organization(ORGANIZATION_NAME)
34+
35+
# List to store repository details
36+
repositories = []
37+
38+
# Iterate over repositories in the organization
39+
for repo in organization.get_repos():
40+
# Get the repository name
41+
repo_name = repo.name
42+
43+
# Get the repository topics
44+
topics = repo.get_topics()
45+
46+
# Create a Repository instance with repository details
47+
repo_details = RepositoryDetails(name=repo_name, topics=topics)
48+
49+
# Add repository details to the list
50+
repositories.append(repo_details)
51+
52+
return repositories
53+
except Exception as e:
54+
print(f"Failed to retrieve teams: {str(e)}")
55+
return None
56+
57+
58+
def list_assets(token):
59+
try:
60+
# Make a GET request to the asset API
61+
url = f"{JIT_API_ENDPOINT}/asset"
62+
headers = {
63+
"Authorization": f"Bearer {token}"
64+
}
65+
response = requests.get(url, headers=headers)
66+
67+
# Check if the request was successful
68+
if response.status_code == 200:
69+
# Parse the response JSON
70+
assets = response.json()
71+
72+
return assets
73+
else:
74+
print(f"Failed to retrieve assets. Status code: {response.status_code}")
75+
return None
76+
except Exception as e:
77+
print(f"Failed to retrieve assets: {str(e)}")
78+
return None
79+
80+
81+
def get_jwt_token():
82+
payload = {
83+
"clientId": JIT_CLIENT_ID,
84+
"secret": JIT_CLIENT_SECRET
85+
}
86+
headers = {
87+
"accept": "application/json",
88+
"content-type": "application/json"
89+
}
90+
91+
response = requests.post(FRONTEGG_AUTH_URL, json=payload, headers=headers)
92+
93+
if response.status_code == 200:
94+
return response.json().get('accessToken')
95+
else:
96+
print(f"Failed to retrieve JWT token. Status code: {response.status_code}")
97+
return None
98+
99+
100+
def main():
101+
# Create the argument parser
102+
parser = argparse.ArgumentParser(description="Retrieve teams and assets")
103+
104+
# Add the --input argument
105+
parser.add_argument("--input", help="Path to a JSON file")
106+
107+
# Parse the command line arguments
108+
args = parser.parse_args()
109+
110+
# Check if the --input argument is provided
111+
if args.input:
112+
# Check if the file exists and is a JSON file
113+
if not os.path.isfile(args.input):
114+
print("Error: File does not exist.")
115+
return
116+
if not args.input.endswith(".json"):
117+
print("Error: File is not a JSON file.")
118+
return
119+
120+
# Read the JSON file
121+
with open(args.input, "r") as file:
122+
json_data = file.read()
123+
124+
# Parse the JSON data
125+
try:
126+
teams = [RepositoryDetails(**team) for team in json.loads(json_data)]
127+
except ValidationError as e:
128+
print(f"Failed to validate input file: {e}")
129+
return
130+
else:
131+
# Call the get_teams function
132+
teams = get_topics_for_teams()
133+
if not teams:
134+
print("Failed to retrieve Teams. Exiting...")
135+
return
136+
137+
# Convert the list to JSON format
138+
json_data = json.dumps([t.model_dump() for t in teams], indent=2)
139+
140+
# Print the JSON data
141+
print(json_data)
142+
143+
# Call the list_assets function
144+
token = get_jwt_token()
145+
if not token:
146+
print("Failed to retrieve JWT token. Exiting...")
147+
return
148+
149+
assets = list_assets(token)
150+
if not assets:
151+
print("Failed to retrieve assets. Exiting...")
152+
return
153+
154+
# Print the assets
155+
print(assets)
156+
157+
158+
if __name__ == '__main__':
159+
main()

requirements.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
pydantic==2.1.1
2+
PyGithub==1.59.1
3+
python-dotenv==1.0.0
4+
requests==2.31.0

0 commit comments

Comments
 (0)