js-api 0.3.20__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. {js_api-0.3.20 → js_api-0.4.0}/PKG-INFO +13 -2
  2. {js_api-0.3.20 → js_api-0.4.0}/README.md +12 -1
  3. {js_api-0.3.20 → js_api-0.4.0}/pyproject.toml +1 -1
  4. {js_api-0.3.20 → js_api-0.4.0}/src/controllers/webhook.py +147 -31
  5. {js_api-0.3.20 → js_api-0.4.0}/src/js_api.egg-info/PKG-INFO +13 -2
  6. js_api-0.4.0/tests/test_webhook.py +286 -0
  7. js_api-0.3.20/tests/test_webhook.py +0 -123
  8. {js_api-0.3.20 → js_api-0.4.0}/LICENSE +0 -0
  9. {js_api-0.3.20 → js_api-0.4.0}/setup.cfg +0 -0
  10. {js_api-0.3.20 → js_api-0.4.0}/src/__init__.py +0 -0
  11. {js_api-0.3.20 → js_api-0.4.0}/src/api.py +0 -0
  12. {js_api-0.3.20 → js_api-0.4.0}/src/controllers/__init__.py +0 -0
  13. {js_api-0.3.20 → js_api-0.4.0}/src/controllers/docker.py +0 -0
  14. {js_api-0.3.20 → js_api-0.4.0}/src/controllers/health_check.py +0 -0
  15. {js_api-0.3.20 → js_api-0.4.0}/src/controllers/ip.py +0 -0
  16. {js_api-0.3.20 → js_api-0.4.0}/src/controllers/valentines_day.py +0 -0
  17. {js_api-0.3.20 → js_api-0.4.0}/src/database.py +0 -0
  18. {js_api-0.3.20 → js_api-0.4.0}/src/js_api.egg-info/SOURCES.txt +0 -0
  19. {js_api-0.3.20 → js_api-0.4.0}/src/js_api.egg-info/dependency_links.txt +0 -0
  20. {js_api-0.3.20 → js_api-0.4.0}/src/js_api.egg-info/requires.txt +0 -0
  21. {js_api-0.3.20 → js_api-0.4.0}/src/js_api.egg-info/top_level.txt +0 -0
  22. {js_api-0.3.20 → js_api-0.4.0}/src/models.py +0 -0
  23. {js_api-0.3.20 → js_api-0.4.0}/src/util/__init__.py +0 -0
  24. {js_api-0.3.20 → js_api-0.4.0}/src/util/auth.py +0 -0
  25. {js_api-0.3.20 → js_api-0.4.0}/src/util/docker.py +0 -0
  26. {js_api-0.3.20 → js_api-0.4.0}/src/util/healthcheck.py +0 -0
  27. {js_api-0.3.20 → js_api-0.4.0}/src/util/logging.py +0 -0
  28. {js_api-0.3.20 → js_api-0.4.0}/src/util/mail.py +0 -0
  29. {js_api-0.3.20 → js_api-0.4.0}/tests/test_beszel.py +0 -0
  30. {js_api-0.3.20 → js_api-0.4.0}/tests/test_docker.py +0 -0
  31. {js_api-0.3.20 → js_api-0.4.0}/tests/test_health_check.py +0 -0
  32. {js_api-0.3.20 → js_api-0.4.0}/tests/test_ip.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: js-api
3
- Version: 0.3.20
3
+ Version: 0.4.0
4
4
  Summary: Custom API written in Python using FastAPI
5
5
  Author-email: Jack Stockley <jack@jstockley.com>
6
6
  Project-URL: Homepage, https://github.com/jnstockley/api
@@ -27,7 +27,7 @@ This is a custom API, written in Python using FastAPI, to help me accomplish tas
27
27
  Simplest setup is to start from [compose.yml](https://github.com/jnstockley/api/blob/dev/compose.yml) and [template.env](https://github.com/jnstockley/api/blob/dev/template.env), which should be renamed to `.env`
28
28
 
29
29
  ### Environment Vairables
30
- - `API_KEY` - Any long, random string. Keep this secret as this is the only form of authentication for the API. All routes require it, except `/health-check/`
30
+ - `API_KEY` - A long, random string used to authenticate API requests. The health check is public, and the GitHub webhook uses its own signing secret.
31
31
  - `DATABASE_URL` - The URL to connect to postgres DB. Must start with `postgresql+psycopg://`. Should be in the format specifiec in [template.env](https://github.com/jnstockley/api/blob/dev/template.env)
32
32
  - `TZ` - Timezone of the container
33
33
  - `PGTZ` - Timezone the Postgres container should use
@@ -36,10 +36,16 @@ Simplest setup is to start from [compose.yml](https://github.com/jnstockley/api/
36
36
  - `NEXTCLOUD_TALK_SECRET` - Shared secret of the registered Nextcloud Talk bot used by `/webhook/databasus`
37
37
  - `BESZEL_NEXTCLOUD_TALK_TOKEN` - Conversation token for the separate Beszel Talk bot used by `/webhook/beszel`
38
38
  - `BESZEL_NEXTCLOUD_TALK_SECRET` - Shared secret of the registered Beszel Talk bot
39
+ - `GITHUB_WEBHOOK_SECRET` - Signing secret configured on the GitHub webhook
40
+ - `GITHUB_NEXTCLOUD_TALK_TOKEN` - Conversation token for GitHub code scanning notifications
41
+ - `GITHUB_NEXTCLOUD_TALK_SECRET` - Shared secret of the Talk bot that sends GitHub notifications
39
42
 
40
43
  ## Webhooks
41
44
  - `POST /webhook/databasus` - Forwards a `header` and `message` to a Nextcloud Talk conversation via the [Nextcloud Talk Bot API](https://nextcloud-talk.readthedocs.io/en/latest/bot-list/), using the [nctalk](https://pypi.org/project/nctalk/) package. Requires the `X-API-KEY` header and a JSON body: `{"header": "...", "message": "..."}`
42
45
  - `POST /webhook/beszel` - Forwards Beszel's generic JSON notifications (`{"title": "...", "message": "..."}`) using a separate Talk bot. Requires the `X-API-KEY` header. Posts the title in bold followed by the message. Returns `{"status": "sent"}` on success, `422` for invalid payloads, `500` for missing or insecure Talk configuration, or `502` when delivery fails.
46
+ - `POST /webhook/github/code-scanning` - Verifies GitHub's `X-Hub-Signature-256` signature and sends a Talk message with the repository, alert number, and alert link. It handles `created`, `fixed`, `closed_by_user`, `reopened`, `reopened_by_user`, and `updated_assignment`. Signed pings, unrelated events, and other actions such as `appeared_in_branch` return `{"status": "ignored"}`.
47
+
48
+ For Trivy findings, the message also includes Package, Severity, Installed Version, and Fixed Version when GitHub includes those details in the finding message.
43
49
 
44
50
  ### Beszel setup
45
51
 
@@ -54,5 +60,10 @@ Simplest setup is to start from [compose.yml](https://github.com/jnstockley/api/
54
60
  The `generic://` service uses HTTPS by default. URL-encode the API key if it contains special characters. `template=json` supplies the `title` and `message` fields, and `@X-API-KEY` adds the authentication header.
55
61
  4. Send a test notification from Beszel, then enable alerts in its systems table.
56
62
 
63
+ ### GitHub setup
64
+
65
+ 1. Enable a Nextcloud Talk bot in the destination conversation. Set `NEXTCLOUD_URL`, `GITHUB_NEXTCLOUD_TALK_TOKEN`, `GITHUB_NEXTCLOUD_TALK_SECRET`, and a random `GITHUB_WEBHOOK_SECRET` in `.env`, then recreate the API container.
66
+ 2. In the GitHub repository or organization, create a webhook with the HTTPS payload URL `https://api.example.com/webhook/github/code-scanning` and content type `application/json`. Use the value of `GITHUB_WEBHOOK_SECRET` in GitHub's **Secret** field and select **Code scanning alerts** under individual events. [GitHub webhook setup](https://docs.github.com/en/webhooks/using-webhooks/creating-webhooks)
67
+
57
68
  ## How to Access
58
69
  Using the [compose.yml](https://github.com/jnstockley/api/blob/dev/compose.yml) file, you can access the API at `http://<IP>:5000/health-check`. If everything is setup correctly, you should see `{"status":"ok"}`
@@ -5,7 +5,7 @@ This is a custom API, written in Python using FastAPI, to help me accomplish tas
5
5
  Simplest setup is to start from [compose.yml](https://github.com/jnstockley/api/blob/dev/compose.yml) and [template.env](https://github.com/jnstockley/api/blob/dev/template.env), which should be renamed to `.env`
6
6
 
7
7
  ### Environment Vairables
8
- - `API_KEY` - Any long, random string. Keep this secret as this is the only form of authentication for the API. All routes require it, except `/health-check/`
8
+ - `API_KEY` - A long, random string used to authenticate API requests. The health check is public, and the GitHub webhook uses its own signing secret.
9
9
  - `DATABASE_URL` - The URL to connect to postgres DB. Must start with `postgresql+psycopg://`. Should be in the format specifiec in [template.env](https://github.com/jnstockley/api/blob/dev/template.env)
10
10
  - `TZ` - Timezone of the container
11
11
  - `PGTZ` - Timezone the Postgres container should use
@@ -14,10 +14,16 @@ Simplest setup is to start from [compose.yml](https://github.com/jnstockley/api/
14
14
  - `NEXTCLOUD_TALK_SECRET` - Shared secret of the registered Nextcloud Talk bot used by `/webhook/databasus`
15
15
  - `BESZEL_NEXTCLOUD_TALK_TOKEN` - Conversation token for the separate Beszel Talk bot used by `/webhook/beszel`
16
16
  - `BESZEL_NEXTCLOUD_TALK_SECRET` - Shared secret of the registered Beszel Talk bot
17
+ - `GITHUB_WEBHOOK_SECRET` - Signing secret configured on the GitHub webhook
18
+ - `GITHUB_NEXTCLOUD_TALK_TOKEN` - Conversation token for GitHub code scanning notifications
19
+ - `GITHUB_NEXTCLOUD_TALK_SECRET` - Shared secret of the Talk bot that sends GitHub notifications
17
20
 
18
21
  ## Webhooks
19
22
  - `POST /webhook/databasus` - Forwards a `header` and `message` to a Nextcloud Talk conversation via the [Nextcloud Talk Bot API](https://nextcloud-talk.readthedocs.io/en/latest/bot-list/), using the [nctalk](https://pypi.org/project/nctalk/) package. Requires the `X-API-KEY` header and a JSON body: `{"header": "...", "message": "..."}`
20
23
  - `POST /webhook/beszel` - Forwards Beszel's generic JSON notifications (`{"title": "...", "message": "..."}`) using a separate Talk bot. Requires the `X-API-KEY` header. Posts the title in bold followed by the message. Returns `{"status": "sent"}` on success, `422` for invalid payloads, `500` for missing or insecure Talk configuration, or `502` when delivery fails.
24
+ - `POST /webhook/github/code-scanning` - Verifies GitHub's `X-Hub-Signature-256` signature and sends a Talk message with the repository, alert number, and alert link. It handles `created`, `fixed`, `closed_by_user`, `reopened`, `reopened_by_user`, and `updated_assignment`. Signed pings, unrelated events, and other actions such as `appeared_in_branch` return `{"status": "ignored"}`.
25
+
26
+ For Trivy findings, the message also includes Package, Severity, Installed Version, and Fixed Version when GitHub includes those details in the finding message.
21
27
 
22
28
  ### Beszel setup
23
29
 
@@ -32,5 +38,10 @@ Simplest setup is to start from [compose.yml](https://github.com/jnstockley/api/
32
38
  The `generic://` service uses HTTPS by default. URL-encode the API key if it contains special characters. `template=json` supplies the `title` and `message` fields, and `@X-API-KEY` adds the authentication header.
33
39
  4. Send a test notification from Beszel, then enable alerts in its systems table.
34
40
 
41
+ ### GitHub setup
42
+
43
+ 1. Enable a Nextcloud Talk bot in the destination conversation. Set `NEXTCLOUD_URL`, `GITHUB_NEXTCLOUD_TALK_TOKEN`, `GITHUB_NEXTCLOUD_TALK_SECRET`, and a random `GITHUB_WEBHOOK_SECRET` in `.env`, then recreate the API container.
44
+ 2. In the GitHub repository or organization, create a webhook with the HTTPS payload URL `https://api.example.com/webhook/github/code-scanning` and content type `application/json`. Use the value of `GITHUB_WEBHOOK_SECRET` in GitHub's **Secret** field and select **Code scanning alerts** under individual events. [GitHub webhook setup](https://docs.github.com/en/webhooks/using-webhooks/creating-webhooks)
45
+
35
46
  ## How to Access
36
47
  Using the [compose.yml](https://github.com/jnstockley/api/blob/dev/compose.yml) file, you can access the API at `http://<IP>:5000/health-check`. If everything is setup correctly, you should see `{"status":"ok"}`
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "js-api"
3
- version = "0.3.20"
3
+ version = "0.4.0"
4
4
  description = "Custom API written in Python using FastAPI"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.15, <3.16"
@@ -1,14 +1,31 @@
1
+ import hmac
1
2
  import os
2
3
 
3
- from fastapi import APIRouter, HTTPException, Security
4
+ from fastapi import APIRouter, HTTPException, Request, Security
4
5
  from nctalk import TalkMessenger
5
- from pydantic import BaseModel, Field
6
+ from pydantic import BaseModel, Field, HttpUrl, ValidationError
7
+ from starlette.concurrency import run_in_threadpool
6
8
 
7
9
  from util.auth import get_token_header
8
10
  from util.logging import logger
9
11
  from util.mail import EmailSender, SMTPConfig, TemplateRenderer
10
12
 
11
- router = APIRouter(prefix="/webhook", dependencies=[Security(get_token_header)])
13
+ router = APIRouter(prefix="/webhook")
14
+
15
+ CODE_SCANNING_ACTIONS = {
16
+ "created": "created",
17
+ "closed_by_user": "dismissed",
18
+ "fixed": "fixed",
19
+ "reopened": "reopened",
20
+ "reopened_by_user": "reopened",
21
+ "updated_assignment": "assignment updated",
22
+ }
23
+ TRIVY_NOTIFICATION_FIELDS = (
24
+ "Package",
25
+ "Severity",
26
+ "Installed Version",
27
+ "Fixed Version",
28
+ )
12
29
 
13
30
 
14
31
  class NextcloudTalkWebhook(BaseModel):
@@ -21,6 +38,37 @@ class BeszelWebhook(BaseModel):
21
38
  message: str = Field(..., min_length=1, max_length=32000)
22
39
 
23
40
 
41
+ class GitHubCodeScanningTool(BaseModel):
42
+ name: str
43
+
44
+
45
+ class GitHubCodeScanningMessage(BaseModel):
46
+ text: str | None = None
47
+
48
+
49
+ class GitHubCodeScanningInstance(BaseModel):
50
+ ref: str | None = None
51
+ message: GitHubCodeScanningMessage | None = None
52
+
53
+
54
+ class GitHubCodeScanningAlert(BaseModel):
55
+ number: int = Field(gt=0)
56
+ html_url: HttpUrl
57
+ tool: GitHubCodeScanningTool | None = None
58
+ most_recent_instance: GitHubCodeScanningInstance | None = None
59
+ instances: list[GitHubCodeScanningInstance] = Field(default_factory=list)
60
+
61
+
62
+ class GitHubRepository(BaseModel):
63
+ full_name: str = Field(min_length=1)
64
+
65
+
66
+ class GitHubCodeScanningWebhook(BaseModel):
67
+ alert: GitHubCodeScanningAlert
68
+ repository: GitHubRepository
69
+ ref: str | None = None
70
+
71
+
24
72
  class PveUpsWebhook(BaseModel):
25
73
  subject: str = Field(..., min_length=1, max_length=200)
26
74
  body: str = Field(..., min_length=1, max_length=32000)
@@ -32,16 +80,10 @@ class PveUpsWebhook(BaseModel):
32
80
  to: str = Field(..., min_length=1, max_length=32000)
33
81
 
34
82
 
35
- @router.post("/databasus")
36
- async def databasus(webhook: NextcloudTalkWebhook):
37
- if webhook.header.strip() == "":
38
- raise HTTPException(status_code=422, detail="header cannot be empty")
39
- if webhook.message.strip() == "":
40
- raise HTTPException(status_code=422, detail="message cannot be empty")
41
-
83
+ def send_nextcloud_talk(message: str, config_prefix: str) -> None:
42
84
  endpoint_url = os.environ.get("NEXTCLOUD_URL", "").strip()
43
- token = os.environ.get("NEXTCLOUD_TALK_TOKEN", "").strip()
44
- secret = os.environ.get("NEXTCLOUD_TALK_SECRET", "").strip()
85
+ token = os.environ.get(f"{config_prefix}_TOKEN", "").strip()
86
+ secret = os.environ.get(f"{config_prefix}_SECRET", "").strip()
45
87
 
46
88
  if not endpoint_url or not token or not secret:
47
89
  raise HTTPException(status_code=500, detail="Nextcloud Talk is not configured")
@@ -50,46 +92,120 @@ async def databasus(webhook: NextcloudTalkWebhook):
50
92
 
51
93
  messenger = TalkMessenger(endpoint_url=endpoint_url, token=token, secret=secret)
52
94
 
53
- message = f"**{webhook.header}**\n{webhook.message}"
54
-
55
95
  if not messenger.send(message):
56
- logger.error("Failed to send message to Nextcloud Talk")
96
+ logger.error("Failed to send message to Nextcloud Talk (%s)", config_prefix)
57
97
  raise HTTPException(
58
98
  status_code=502, detail="Failed to send message to Nextcloud Talk"
59
99
  )
60
100
 
101
+
102
+ def trivy_notification_details(
103
+ alert: GitHubCodeScanningAlert, ref: str | None
104
+ ) -> list[str]:
105
+ if alert.tool is None or alert.tool.name.casefold() != "trivy":
106
+ return []
107
+
108
+ instances = list(alert.instances)
109
+ if alert.most_recent_instance is not None:
110
+ instances.insert(0, alert.most_recent_instance)
111
+ if ref:
112
+ instances.sort(key=lambda instance: instance.ref != ref)
113
+
114
+ for instance in instances:
115
+ if instance.message is None or not instance.message.text:
116
+ continue
117
+
118
+ fields = {}
119
+ for line in instance.message.text.splitlines():
120
+ label, _, value = line.partition(":")
121
+ if label in ("Match", "Message", "Link"):
122
+ break
123
+ if label in TRIVY_NOTIFICATION_FIELDS and value.strip():
124
+ fields[label] = value.strip()
125
+
126
+ if fields:
127
+ return [
128
+ f"{label}: {fields[label]}"
129
+ for label in TRIVY_NOTIFICATION_FIELDS
130
+ if label in fields
131
+ ]
132
+
133
+ return []
134
+
135
+
136
+ @router.post("/databasus", dependencies=[Security(get_token_header)])
137
+ async def databasus(webhook: NextcloudTalkWebhook):
138
+ if webhook.header.strip() == "":
139
+ raise HTTPException(status_code=422, detail="header cannot be empty")
140
+ if webhook.message.strip() == "":
141
+ raise HTTPException(status_code=422, detail="message cannot be empty")
142
+
143
+ send_nextcloud_talk(f"**{webhook.header}**\n{webhook.message}", "NEXTCLOUD_TALK")
61
144
  return {"status": "sent"}
62
145
 
63
146
 
64
- @router.post("/beszel")
147
+ @router.post("/beszel", dependencies=[Security(get_token_header)])
65
148
  async def beszel(webhook: BeszelWebhook):
66
149
  if webhook.title.strip() == "":
67
150
  raise HTTPException(status_code=422, detail="title cannot be empty")
68
151
  if webhook.message.strip() == "":
69
152
  raise HTTPException(status_code=422, detail="message cannot be empty")
70
153
 
71
- endpoint_url = os.environ.get("NEXTCLOUD_URL", "").strip()
72
- token = os.environ.get("BESZEL_NEXTCLOUD_TALK_TOKEN", "").strip()
73
- secret = os.environ.get("BESZEL_NEXTCLOUD_TALK_SECRET", "").strip()
154
+ send_nextcloud_talk(
155
+ f"**{webhook.title}**\n{webhook.message}", "BESZEL_NEXTCLOUD_TALK"
156
+ )
157
+ return {"status": "sent"}
74
158
 
75
- if not endpoint_url or not token or not secret:
76
- raise HTTPException(status_code=500, detail="Nextcloud Talk is not configured")
77
- if not endpoint_url.startswith("https://"):
78
- raise HTTPException(status_code=500, detail="NEXTCLOUD_URL must use https://")
79
159
 
80
- messenger = TalkMessenger(endpoint_url=endpoint_url, token=token, secret=secret)
81
- message = f"**{webhook.title}**\n{webhook.message}"
160
+ @router.post("/github/code-scanning")
161
+ async def github_code_scanning_alert(request: Request):
162
+ secret = os.environ.get("GITHUB_WEBHOOK_SECRET", "")
163
+ if not secret.strip():
164
+ raise HTTPException(status_code=500, detail="GitHub webhook is not configured")
82
165
 
83
- if not messenger.send(message):
84
- logger.error("Failed to send Beszel message to Nextcloud Talk")
85
- raise HTTPException(
86
- status_code=502, detail="Failed to send message to Nextcloud Talk"
87
- )
166
+ body = await request.body()
167
+ digest = hmac.digest(secret.encode(), body, "sha256").hex()
168
+ signature = request.headers.get("X-Hub-Signature-256", "")
169
+ if not hmac.compare_digest(signature.encode(), f"sha256={digest}".encode()):
170
+ raise HTTPException(status_code=401, detail="Invalid GitHub webhook signature")
88
171
 
172
+ if request.headers.get("X-GitHub-Event") != "code_scanning_alert":
173
+ return {"status": "ignored"}
174
+
175
+ try:
176
+ payload = await request.json()
177
+ except ValueError as exc:
178
+ raise HTTPException(
179
+ status_code=422, detail="Invalid GitHub webhook JSON"
180
+ ) from exc
181
+
182
+ action = payload.get("action") if isinstance(payload, dict) else None
183
+ if not isinstance(action, str) or not action:
184
+ raise HTTPException(status_code=422, detail="Missing or invalid GitHub action")
185
+ if action not in CODE_SCANNING_ACTIONS:
186
+ return {"status": "ignored"}
187
+
188
+ try:
189
+ webhook = GitHubCodeScanningWebhook.model_validate(payload)
190
+ except ValidationError as exc:
191
+ raise HTTPException(
192
+ status_code=422, detail="Invalid GitHub code scanning alert payload"
193
+ ) from exc
194
+
195
+ description = CODE_SCANNING_ACTIONS[action]
196
+ message = "\n".join(
197
+ [
198
+ f"**GitHub code scanning alert {description}**",
199
+ f"{webhook.repository.full_name} #{webhook.alert.number}",
200
+ *trivy_notification_details(webhook.alert, webhook.ref),
201
+ str(webhook.alert.html_url),
202
+ ]
203
+ )
204
+ await run_in_threadpool(send_nextcloud_talk, message, "GITHUB_NEXTCLOUD_TALK")
89
205
  return {"status": "sent"}
90
206
 
91
207
 
92
- @router.post("/pve-ups")
208
+ @router.post("/pve-ups", dependencies=[Security(get_token_header)])
93
209
  async def pve_ups(webhook: PveUpsWebhook):
94
210
  if not os.environ.get("SMTP_HOST") or not os.environ.get("SMTP_PORT"):
95
211
  raise HTTPException(status_code=500, detail="SMTP is not configured")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: js-api
3
- Version: 0.3.20
3
+ Version: 0.4.0
4
4
  Summary: Custom API written in Python using FastAPI
5
5
  Author-email: Jack Stockley <jack@jstockley.com>
6
6
  Project-URL: Homepage, https://github.com/jnstockley/api
@@ -27,7 +27,7 @@ This is a custom API, written in Python using FastAPI, to help me accomplish tas
27
27
  Simplest setup is to start from [compose.yml](https://github.com/jnstockley/api/blob/dev/compose.yml) and [template.env](https://github.com/jnstockley/api/blob/dev/template.env), which should be renamed to `.env`
28
28
 
29
29
  ### Environment Vairables
30
- - `API_KEY` - Any long, random string. Keep this secret as this is the only form of authentication for the API. All routes require it, except `/health-check/`
30
+ - `API_KEY` - A long, random string used to authenticate API requests. The health check is public, and the GitHub webhook uses its own signing secret.
31
31
  - `DATABASE_URL` - The URL to connect to postgres DB. Must start with `postgresql+psycopg://`. Should be in the format specifiec in [template.env](https://github.com/jnstockley/api/blob/dev/template.env)
32
32
  - `TZ` - Timezone of the container
33
33
  - `PGTZ` - Timezone the Postgres container should use
@@ -36,10 +36,16 @@ Simplest setup is to start from [compose.yml](https://github.com/jnstockley/api/
36
36
  - `NEXTCLOUD_TALK_SECRET` - Shared secret of the registered Nextcloud Talk bot used by `/webhook/databasus`
37
37
  - `BESZEL_NEXTCLOUD_TALK_TOKEN` - Conversation token for the separate Beszel Talk bot used by `/webhook/beszel`
38
38
  - `BESZEL_NEXTCLOUD_TALK_SECRET` - Shared secret of the registered Beszel Talk bot
39
+ - `GITHUB_WEBHOOK_SECRET` - Signing secret configured on the GitHub webhook
40
+ - `GITHUB_NEXTCLOUD_TALK_TOKEN` - Conversation token for GitHub code scanning notifications
41
+ - `GITHUB_NEXTCLOUD_TALK_SECRET` - Shared secret of the Talk bot that sends GitHub notifications
39
42
 
40
43
  ## Webhooks
41
44
  - `POST /webhook/databasus` - Forwards a `header` and `message` to a Nextcloud Talk conversation via the [Nextcloud Talk Bot API](https://nextcloud-talk.readthedocs.io/en/latest/bot-list/), using the [nctalk](https://pypi.org/project/nctalk/) package. Requires the `X-API-KEY` header and a JSON body: `{"header": "...", "message": "..."}`
42
45
  - `POST /webhook/beszel` - Forwards Beszel's generic JSON notifications (`{"title": "...", "message": "..."}`) using a separate Talk bot. Requires the `X-API-KEY` header. Posts the title in bold followed by the message. Returns `{"status": "sent"}` on success, `422` for invalid payloads, `500` for missing or insecure Talk configuration, or `502` when delivery fails.
46
+ - `POST /webhook/github/code-scanning` - Verifies GitHub's `X-Hub-Signature-256` signature and sends a Talk message with the repository, alert number, and alert link. It handles `created`, `fixed`, `closed_by_user`, `reopened`, `reopened_by_user`, and `updated_assignment`. Signed pings, unrelated events, and other actions such as `appeared_in_branch` return `{"status": "ignored"}`.
47
+
48
+ For Trivy findings, the message also includes Package, Severity, Installed Version, and Fixed Version when GitHub includes those details in the finding message.
43
49
 
44
50
  ### Beszel setup
45
51
 
@@ -54,5 +60,10 @@ Simplest setup is to start from [compose.yml](https://github.com/jnstockley/api/
54
60
  The `generic://` service uses HTTPS by default. URL-encode the API key if it contains special characters. `template=json` supplies the `title` and `message` fields, and `@X-API-KEY` adds the authentication header.
55
61
  4. Send a test notification from Beszel, then enable alerts in its systems table.
56
62
 
63
+ ### GitHub setup
64
+
65
+ 1. Enable a Nextcloud Talk bot in the destination conversation. Set `NEXTCLOUD_URL`, `GITHUB_NEXTCLOUD_TALK_TOKEN`, `GITHUB_NEXTCLOUD_TALK_SECRET`, and a random `GITHUB_WEBHOOK_SECRET` in `.env`, then recreate the API container.
66
+ 2. In the GitHub repository or organization, create a webhook with the HTTPS payload URL `https://api.example.com/webhook/github/code-scanning` and content type `application/json`. Use the value of `GITHUB_WEBHOOK_SECRET` in GitHub's **Secret** field and select **Code scanning alerts** under individual events. [GitHub webhook setup](https://docs.github.com/en/webhooks/using-webhooks/creating-webhooks)
67
+
57
68
  ## How to Access
58
69
  Using the [compose.yml](https://github.com/jnstockley/api/blob/dev/compose.yml) file, you can access the API at `http://<IP>:5000/health-check`. If everything is setup correctly, you should see `{"status":"ok"}`
@@ -0,0 +1,286 @@
1
+ import hmac
2
+ import json
3
+ import os
4
+ from unittest import TestCase
5
+ from unittest.mock import patch
6
+
7
+ from fastapi.testclient import TestClient
8
+ from sqlalchemy.orm import sessionmaker
9
+ from testcontainers.postgres import PostgresContainer
10
+
11
+ import models
12
+ from database import engine, get_db
13
+ from src.api import app
14
+
15
+ postgres = PostgresContainer("postgres:17-alpine").start()
16
+
17
+ DATABASE_URL = postgres.get_connection_url(driver="psycopg")
18
+ os.environ["DATABASE_URL"] = DATABASE_URL
19
+
20
+ models.Base.metadata.create_all(bind=engine)
21
+
22
+ TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
23
+
24
+ client = TestClient(app)
25
+
26
+
27
+ def override_get_db():
28
+ database = TestingSessionLocal()
29
+ yield database
30
+ database.close()
31
+
32
+
33
+ app.dependency_overrides[get_db] = override_get_db
34
+
35
+
36
+ class TestWebhook(TestCase):
37
+ github_secret = "github-test-secret"
38
+
39
+ def setUp(self):
40
+ os.environ["NEXTCLOUD_URL"] = "https://nextcloud.example.com"
41
+ os.environ["NEXTCLOUD_TALK_TOKEN"] = "test-token"
42
+ os.environ["NEXTCLOUD_TALK_SECRET"] = "test-secret"
43
+ self.github_alert = {
44
+ "number": 42,
45
+ "html_url": "https://github.com/example/project/security/code-scanning/42",
46
+ }
47
+
48
+ def test_missing_body(self):
49
+ api_key = os.environ["API_KEY"]
50
+ header = {"X-API-KEY": api_key}
51
+ response = client.post("/webhook/databasus", headers=header, json={})
52
+ assert response.status_code == 422
53
+
54
+ def test_empty_header(self):
55
+ api_key = os.environ["API_KEY"]
56
+ header = {"X-API-KEY": api_key}
57
+ response = client.post(
58
+ "/webhook/databasus",
59
+ headers=header,
60
+ json={"header": "", "message": "hello"},
61
+ )
62
+ assert response.status_code == 422
63
+
64
+ def test_empty_message(self):
65
+ api_key = os.environ["API_KEY"]
66
+ header = {"X-API-KEY": api_key}
67
+ response = client.post(
68
+ "/webhook/databasus",
69
+ headers=header,
70
+ json={"header": "title", "message": ""},
71
+ )
72
+ assert response.status_code == 422
73
+
74
+ def test_not_configured(self):
75
+ api_key = os.environ["API_KEY"]
76
+ header = {"X-API-KEY": api_key}
77
+ del os.environ["NEXTCLOUD_URL"]
78
+ try:
79
+ response = client.post(
80
+ "/webhook/databasus",
81
+ headers=header,
82
+ json={"header": "title", "message": "hello"},
83
+ )
84
+ assert response.status_code == 500
85
+ finally:
86
+ os.environ["NEXTCLOUD_URL"] = "https://nextcloud.example.com"
87
+
88
+ def test_insecure_url(self):
89
+ api_key = os.environ["API_KEY"]
90
+ header = {"X-API-KEY": api_key}
91
+ os.environ["NEXTCLOUD_URL"] = "http://nextcloud.example.com"
92
+ try:
93
+ response = client.post(
94
+ "/webhook/databasus",
95
+ headers=header,
96
+ json={"header": "title", "message": "hello"},
97
+ )
98
+ assert response.status_code == 500
99
+ finally:
100
+ os.environ["NEXTCLOUD_URL"] = "https://nextcloud.example.com"
101
+
102
+ @patch("controllers.webhook.TalkMessenger.send", return_value=True)
103
+ def test_send_message(self, mock_send):
104
+ api_key = os.environ["API_KEY"]
105
+ header = {"X-API-KEY": api_key}
106
+ response = client.post(
107
+ "/webhook/databasus",
108
+ headers=header,
109
+ json={"header": "title", "message": "hello"},
110
+ )
111
+ assert response.status_code == 200
112
+ assert response.json() == {"status": "sent"}
113
+ mock_send.assert_called_once_with("**title**\nhello")
114
+
115
+ @patch("controllers.webhook.TalkMessenger.send", return_value=False)
116
+ def test_send_message_failure(self, mock_send):
117
+ api_key = os.environ["API_KEY"]
118
+ header = {"X-API-KEY": api_key}
119
+ response = client.post(
120
+ "/webhook/databasus",
121
+ headers=header,
122
+ json={"header": "title", "message": "hello"},
123
+ )
124
+ assert response.status_code == 502
125
+
126
+ def test_missing_api_key(self):
127
+ response = client.post(
128
+ "/webhook/databasus",
129
+ json={"header": "title", "message": "hello"},
130
+ )
131
+ assert response.status_code in (401, 422)
132
+
133
+ def deliver_github(self, event, payload, *, secret=github_secret):
134
+ body = json.dumps(payload).encode()
135
+ headers = {"Content-Type": "application/json", "X-GitHub-Event": event}
136
+ if secret is not None:
137
+ signature = hmac.digest(secret.encode(), body, "sha256").hex()
138
+ headers["X-Hub-Signature-256"] = f"sha256={signature}"
139
+
140
+ with patch.dict(
141
+ os.environ,
142
+ {
143
+ "GITHUB_WEBHOOK_SECRET": self.github_secret,
144
+ "GITHUB_NEXTCLOUD_TALK_TOKEN": "github-test-token",
145
+ "GITHUB_NEXTCLOUD_TALK_SECRET": "github-talk-test-secret",
146
+ },
147
+ ):
148
+ return client.post(
149
+ "/webhook/github/code-scanning", content=body, headers=headers
150
+ )
151
+
152
+ @patch("controllers.webhook.TalkMessenger.send", return_value=True)
153
+ def test_github_notifies_for_created_and_updated_alerts(self, mock_send):
154
+ actions = {
155
+ "created": "created",
156
+ "fixed": "fixed",
157
+ "closed_by_user": "dismissed",
158
+ "reopened": "reopened",
159
+ "reopened_by_user": "reopened",
160
+ "updated_assignment": "assignment updated",
161
+ }
162
+ for action, description in actions.items():
163
+ with self.subTest(action=action):
164
+ mock_send.reset_mock()
165
+ response = self.deliver_github(
166
+ "code_scanning_alert",
167
+ {
168
+ "action": action,
169
+ "alert": self.github_alert,
170
+ "repository": {"full_name": "example/project"},
171
+ },
172
+ )
173
+ assert response.status_code == 200
174
+ assert response.json() == {"status": "sent"}
175
+ mock_send.assert_called_once_with(
176
+ f"**GitHub code scanning alert {description}**\n"
177
+ f"example/project #42\n{self.github_alert['html_url']}"
178
+ )
179
+
180
+ @patch("controllers.webhook.TalkMessenger.send", return_value=True)
181
+ def test_github_includes_trivy_vulnerability_details(self, mock_send):
182
+ instance = {
183
+ "ref": "refs/heads/main",
184
+ "message": {
185
+ "text": (
186
+ "Package: example-lib\nInstalled Version: 1:2.0-r1\n"
187
+ "Vulnerability EXAMPLE-123\nSeverity: CRITICAL\n"
188
+ "Fixed Version: 1:2.0-r2, 1:2.1-r1\nLink: https://example.com/advisory"
189
+ )
190
+ },
191
+ }
192
+ for action, instance_data in (
193
+ ("created", {"instances": [instance]}),
194
+ ("reopened", {"most_recent_instance": instance}),
195
+ ):
196
+ with self.subTest(action=action):
197
+ mock_send.reset_mock()
198
+ response = self.deliver_github(
199
+ "code_scanning_alert",
200
+ {
201
+ "action": action,
202
+ "ref": "refs/heads/main",
203
+ "alert": {
204
+ **self.github_alert,
205
+ "tool": {"name": "Trivy"},
206
+ **instance_data,
207
+ },
208
+ "repository": {"full_name": "example/project"},
209
+ },
210
+ )
211
+ assert response.status_code == 200
212
+ mock_send.assert_called_once_with(
213
+ f"**GitHub code scanning alert {action}**\nexample/project #42\n"
214
+ "Package: example-lib\nSeverity: CRITICAL\n"
215
+ "Installed Version: 1:2.0-r1\nFixed Version: 1:2.0-r2, 1:2.1-r1\n"
216
+ f"{self.github_alert['html_url']}"
217
+ )
218
+
219
+ @patch("controllers.webhook.TalkMessenger.send", return_value=True)
220
+ def test_github_trivy_secret_omits_match_text(self, mock_send):
221
+ response = self.deliver_github(
222
+ "code_scanning_alert",
223
+ {
224
+ "action": "created",
225
+ "alert": {
226
+ **self.github_alert,
227
+ "tool": {"name": "Trivy"},
228
+ "most_recent_instance": {
229
+ "message": {
230
+ "text": "Secret Test Token\nSeverity: HIGH\nMatch: redacted-fixture"
231
+ }
232
+ },
233
+ },
234
+ "repository": {"full_name": "example/project"},
235
+ },
236
+ )
237
+ assert response.status_code == 200
238
+ mock_send.assert_called_once_with(
239
+ "**GitHub code scanning alert created**\nexample/project #42\n"
240
+ f"Severity: HIGH\n{self.github_alert['html_url']}"
241
+ )
242
+
243
+ @patch("controllers.webhook.TalkMessenger.send", return_value=True)
244
+ def test_github_ignores_other_deliveries(self, mock_send):
245
+ for event, payload in (
246
+ ("ping", {"zen": "Keep it simple."}),
247
+ ("issues", {"action": "created"}),
248
+ ("code_scanning_alert", {"action": "appeared_in_branch"}),
249
+ ("code_scanning_alert", {"action": "unknown"}),
250
+ ):
251
+ with self.subTest(event=event, payload=payload):
252
+ response = self.deliver_github(event, payload)
253
+ assert response.status_code == 200
254
+ assert response.json() == {"status": "ignored"}
255
+ mock_send.assert_not_called()
256
+
257
+ @patch("controllers.webhook.TalkMessenger.send", return_value=True)
258
+ def test_github_rejects_unverified_deliveries(self, mock_send):
259
+ for secret in (None, "wrong-secret"):
260
+ with self.subTest(secret=secret):
261
+ response = self.deliver_github(
262
+ "code_scanning_alert", {"action": "created"}, secret=secret
263
+ )
264
+ assert response.status_code == 401
265
+ mock_send.assert_not_called()
266
+
267
+ @patch("controllers.webhook.TalkMessenger.send", return_value=True)
268
+ def test_github_rejects_incomplete_alerts(self, mock_send):
269
+ response = self.deliver_github(
270
+ "code_scanning_alert", {"action": "created", "alert": self.github_alert}
271
+ )
272
+ assert response.status_code == 422
273
+ mock_send.assert_not_called()
274
+
275
+ @patch("controllers.webhook.TalkMessenger.send", return_value=False)
276
+ def test_github_reports_talk_delivery_failure(self, mock_send):
277
+ response = self.deliver_github(
278
+ "code_scanning_alert",
279
+ {
280
+ "action": "created",
281
+ "alert": self.github_alert,
282
+ "repository": {"full_name": "example/project"},
283
+ },
284
+ )
285
+ assert response.status_code == 502
286
+ mock_send.assert_called_once()
@@ -1,123 +0,0 @@
1
- import os
2
- from unittest import TestCase
3
- from unittest.mock import patch
4
-
5
- from fastapi.testclient import TestClient
6
- from sqlalchemy.orm import sessionmaker
7
- from testcontainers.postgres import PostgresContainer
8
-
9
- import models
10
- from database import engine, get_db
11
- from src.api import app
12
-
13
- postgres = PostgresContainer("postgres:17-alpine").start()
14
-
15
- DATABASE_URL = postgres.get_connection_url(driver="psycopg")
16
- os.environ["DATABASE_URL"] = DATABASE_URL
17
-
18
- models.Base.metadata.create_all(bind=engine)
19
-
20
- TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
21
-
22
- client = TestClient(app)
23
-
24
-
25
- def override_get_db():
26
- database = TestingSessionLocal()
27
- yield database
28
- database.close()
29
-
30
-
31
- app.dependency_overrides[get_db] = override_get_db
32
-
33
-
34
- class TestWebhook(TestCase):
35
- def setUp(self):
36
- os.environ["NEXTCLOUD_URL"] = "https://nextcloud.example.com"
37
- os.environ["NEXTCLOUD_TALK_TOKEN"] = "test-token"
38
- os.environ["NEXTCLOUD_TALK_SECRET"] = "test-secret"
39
-
40
- def test_missing_body(self):
41
- api_key = os.environ["API_KEY"]
42
- header = {"X-API-KEY": api_key}
43
- response = client.post("/webhook/databasus", headers=header, json={})
44
- assert response.status_code == 422
45
-
46
- def test_empty_header(self):
47
- api_key = os.environ["API_KEY"]
48
- header = {"X-API-KEY": api_key}
49
- response = client.post(
50
- "/webhook/databasus",
51
- headers=header,
52
- json={"header": "", "message": "hello"},
53
- )
54
- assert response.status_code == 422
55
-
56
- def test_empty_message(self):
57
- api_key = os.environ["API_KEY"]
58
- header = {"X-API-KEY": api_key}
59
- response = client.post(
60
- "/webhook/databasus",
61
- headers=header,
62
- json={"header": "title", "message": ""},
63
- )
64
- assert response.status_code == 422
65
-
66
- def test_not_configured(self):
67
- api_key = os.environ["API_KEY"]
68
- header = {"X-API-KEY": api_key}
69
- del os.environ["NEXTCLOUD_URL"]
70
- try:
71
- response = client.post(
72
- "/webhook/databasus",
73
- headers=header,
74
- json={"header": "title", "message": "hello"},
75
- )
76
- assert response.status_code == 500
77
- finally:
78
- os.environ["NEXTCLOUD_URL"] = "https://nextcloud.example.com"
79
-
80
- def test_insecure_url(self):
81
- api_key = os.environ["API_KEY"]
82
- header = {"X-API-KEY": api_key}
83
- os.environ["NEXTCLOUD_URL"] = "http://nextcloud.example.com"
84
- try:
85
- response = client.post(
86
- "/webhook/databasus",
87
- headers=header,
88
- json={"header": "title", "message": "hello"},
89
- )
90
- assert response.status_code == 500
91
- finally:
92
- os.environ["NEXTCLOUD_URL"] = "https://nextcloud.example.com"
93
-
94
- @patch("controllers.webhook.TalkMessenger.send", return_value=True)
95
- def test_send_message(self, mock_send):
96
- api_key = os.environ["API_KEY"]
97
- header = {"X-API-KEY": api_key}
98
- response = client.post(
99
- "/webhook/databasus",
100
- headers=header,
101
- json={"header": "title", "message": "hello"},
102
- )
103
- assert response.status_code == 200
104
- assert response.json() == {"status": "sent"}
105
- mock_send.assert_called_once_with("**title**\nhello")
106
-
107
- @patch("controllers.webhook.TalkMessenger.send", return_value=False)
108
- def test_send_message_failure(self, mock_send):
109
- api_key = os.environ["API_KEY"]
110
- header = {"X-API-KEY": api_key}
111
- response = client.post(
112
- "/webhook/databasus",
113
- headers=header,
114
- json={"header": "title", "message": "hello"},
115
- )
116
- assert response.status_code == 502
117
-
118
- def test_missing_api_key(self):
119
- response = client.post(
120
- "/webhook/databasus",
121
- json={"header": "title", "message": "hello"},
122
- )
123
- assert response.status_code in (401, 422)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes