Skip to content

Commit

Permalink
Merge branch 'main' of github.com:GeekMasher/ghastoolkit
Browse files Browse the repository at this point in the history
  • Loading branch information
GeekMasher committed Apr 28, 2023
2 parents 82d73c3 + 0bbab13 commit 7abb873
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/ghastoolkit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@


# Octokit
from ghastoolkit.octokit.github import GitHub
from ghastoolkit.octokit.github import GitHub, Repository
from ghastoolkit.octokit.octokit import Octokit, RestRequest, GraphQLRequest
from ghastoolkit.octokit.codescanning import CodeScanning
from ghastoolkit.octokit.secretscanning import SecretScanning
Expand Down
42 changes: 42 additions & 0 deletions src/ghastoolkit/octokit/dependabot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import logging
from typing import Optional

from requests import options

from ghastoolkit import GitHub, Repository
from ghastoolkit.octokit.octokit import GraphQLRequest


logger = logging.getLogger("ghastoolkit.octokit.dependabot")


class Dependabot:
def __init__(self, repository: Optional[Repository] = None) -> None:
self.repository = repository or GitHub.repository
self.graphql = GraphQLRequest(repository)

def getAlerts(self) -> list[dict]:
"""Get Dependabot alerts from GraphQL API"""
results = []

while True:
data = self.graphql.query(
"GetDependencyAlerts",
options={"owner": self.repository.owner, "repo": self.repository.repo},
)
alerts = (
data.get("data", {})
.get("repository", {})
.get("vulnerabilityAlerts", {})
)

results.extend(alerts.get("edges", []))

if not alerts.get("pageInfo", {}).get("hasNextPage"):
logger.debug(f"GraphQL cursor hit end page")
break

self.graphql.cursor = alerts.get("pageInfo", {}).get("endCursor", "")

logger.debug(f"Number of Dependabot Alerts :: {len(results)}")
return results
7 changes: 6 additions & 1 deletion src/ghastoolkit/octokit/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ def getPullRequestNumber(self) -> int:

@property
def clone_url(self) -> str:
if GitHub.token:
if GitHub.github_app:
url = urlparse(GitHub.instance)
return f"{url.scheme}://x-access-token:{GitHub.token}@{url.netloc}/{self.owner}/{self.repo}.git"
elif GitHub.token:
url = urlparse(GitHub.instance)
return f"{url.scheme}://{GitHub.token}@{url.netloc}/{self.owner}/{self.repo}.git"
return f"{GitHub.instance}/{self.owner}/{self.repo}.git"
Expand Down Expand Up @@ -77,6 +80,8 @@ class GitHub:
api_rest: str = "https://api.github.com"
api_graphql: str = "https://api.github.com/graphql"

github_app: bool = False

@staticmethod
def init(
repository: Optional[str] = None,
Expand Down
34 changes: 34 additions & 0 deletions src/ghastoolkit/octokit/graphql/GetDependencyAlerts.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
repository(owner: "$owner", name: "$repo") {
vulnerabilityAlerts(first: 100, states: [OPEN], $cursor) {
totalCount
pageInfo {
hasNextPage
endCursor
}
edges {
node {
createdAt
dismissReason
securityVulnerability {
package {
ecosystem
name
}
}
securityAdvisory {
ghsaId
severity
cwes(first: 100) {
edges {
node {
cweId
}
}
}
}
}
}
}
}
}
9 changes: 7 additions & 2 deletions src/ghastoolkit/octokit/octokit.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

# Assume REST requests are being done by a GitHub Token, not
# a GitHub App which has a higher limit
# https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#rate-limiting
REST_MAX_CALLS = 80 # ~5000 per hour

__OCTOKIT_PATH__ = os.path.dirname(os.path.realpath(__file__))
Expand Down Expand Up @@ -198,6 +199,7 @@ class GraphQLRequest:
def __init__(self, repository: Optional[Repository] = None) -> None:
self.repository = repository or GitHub.repository
self.session = Session()
self.cursor = ""
# https://docs.github.com/en/rest/overview/authenticating-to-the-rest-api
self.session.headers = {
"Accept": "application/vnd.github.hawkgirl-preview+json",
Expand All @@ -207,11 +209,14 @@ def __init__(self, repository: Optional[Repository] = None) -> None:

self.loadQueries(DEFAULT_GRAPHQL_PATHS)

def query(self, name: str, options: dict[str, Any]) -> dict:
def query(self, name: str, options: dict[str, Any] = {}) -> dict:
query_content = self.queries.get(name)
if not query_content:
return {}
query = self.formatQuery(query_content, **options)

cursor = f'after: "{self.cursor}"' if self.cursor != "" else ""

query = self.formatQuery(query_content, cursor=cursor, **options)

response = self.session.post(
GitHub.api_graphql, json={"query": query}, timeout=30
Expand Down
7 changes: 7 additions & 0 deletions tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@ def test_parseReference(self):
class TestRepository(unittest.TestCase):
def setUp(self) -> None:
GitHub.token = None
GitHub.github_app = False

return super().setUp()

def test_branch(self):
repo = Repository("GeekMasher", "ghastoolkit", reference="refs/heads/main")
self.assertEqual(repo.reference, "refs/heads/main")
Expand All @@ -66,3 +69,7 @@ def test_clone_url(self):
GitHub.token = "test_token"
self.assertEqual(repo.clone_url, "https://test_token@github.com/GeekMasher/ghastoolkit.git")

GitHub.github_app = True
GitHub.token = "test_token"
self.assertEqual(repo.clone_url, "https://x-access-token:test_token@github.com/GeekMasher/ghastoolkit.git")

0 comments on commit 7abb873

Please sign in to comment.