js-api 0.3.19__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 (36) hide show
  1. js_api-0.4.0/PKG-INFO +69 -0
  2. js_api-0.4.0/README.md +47 -0
  3. {js_api-0.3.19 → js_api-0.4.0}/pyproject.toml +1 -1
  4. js_api-0.4.0/src/controllers/webhook.py +277 -0
  5. js_api-0.4.0/src/js_api.egg-info/PKG-INFO +69 -0
  6. {js_api-0.3.19 → js_api-0.4.0}/src/js_api.egg-info/SOURCES.txt +1 -0
  7. js_api-0.4.0/tests/test_beszel.py +123 -0
  8. js_api-0.4.0/tests/test_webhook.py +286 -0
  9. js_api-0.3.19/PKG-INFO +0 -42
  10. js_api-0.3.19/README.md +0 -20
  11. js_api-0.3.19/src/controllers/webhook.py +0 -128
  12. js_api-0.3.19/src/js_api.egg-info/PKG-INFO +0 -42
  13. js_api-0.3.19/tests/test_webhook.py +0 -123
  14. {js_api-0.3.19 → js_api-0.4.0}/LICENSE +0 -0
  15. {js_api-0.3.19 → js_api-0.4.0}/setup.cfg +0 -0
  16. {js_api-0.3.19 → js_api-0.4.0}/src/__init__.py +0 -0
  17. {js_api-0.3.19 → js_api-0.4.0}/src/api.py +0 -0
  18. {js_api-0.3.19 → js_api-0.4.0}/src/controllers/__init__.py +0 -0
  19. {js_api-0.3.19 → js_api-0.4.0}/src/controllers/docker.py +0 -0
  20. {js_api-0.3.19 → js_api-0.4.0}/src/controllers/health_check.py +0 -0
  21. {js_api-0.3.19 → js_api-0.4.0}/src/controllers/ip.py +0 -0
  22. {js_api-0.3.19 → js_api-0.4.0}/src/controllers/valentines_day.py +0 -0
  23. {js_api-0.3.19 → js_api-0.4.0}/src/database.py +0 -0
  24. {js_api-0.3.19 → js_api-0.4.0}/src/js_api.egg-info/dependency_links.txt +0 -0
  25. {js_api-0.3.19 → js_api-0.4.0}/src/js_api.egg-info/requires.txt +0 -0
  26. {js_api-0.3.19 → js_api-0.4.0}/src/js_api.egg-info/top_level.txt +0 -0
  27. {js_api-0.3.19 → js_api-0.4.0}/src/models.py +0 -0
  28. {js_api-0.3.19 → js_api-0.4.0}/src/util/__init__.py +0 -0
  29. {js_api-0.3.19 → js_api-0.4.0}/src/util/auth.py +0 -0
  30. {js_api-0.3.19 → js_api-0.4.0}/src/util/docker.py +0 -0
  31. {js_api-0.3.19 → js_api-0.4.0}/src/util/healthcheck.py +0 -0
  32. {js_api-0.3.19 → js_api-0.4.0}/src/util/logging.py +0 -0
  33. {js_api-0.3.19 → js_api-0.4.0}/src/util/mail.py +0 -0
  34. {js_api-0.3.19 → js_api-0.4.0}/tests/test_docker.py +0 -0
  35. {js_api-0.3.19 → js_api-0.4.0}/tests/test_health_check.py +0 -0
  36. {js_api-0.3.19 → js_api-0.4.0}/tests/test_ip.py +0 -0
js_api-0.4.0/PKG-INFO ADDED
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: js-api
3
+ Version: 0.4.0
4
+ Summary: Custom API written in Python using FastAPI
5
+ Author-email: Jack Stockley <jack@jstockley.com>
6
+ Project-URL: Homepage, https://github.com/jnstockley/api
7
+ Project-URL: Repository, https://github.com/jnstockley/api.git
8
+ Project-URL: Issues, https://github.com/jnstockley/api/issues
9
+ Keywords: starter,template,python
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: <3.16,>=3.15
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: fastapi[standard]==0.165.0
15
+ Requires-Dist: sqlalchemy==2.1.9
16
+ Requires-Dist: sqlmodel==0.0.50
17
+ Requires-Dist: python-dotenv==1.2.4
18
+ Requires-Dist: psycopg[binary]==3.3.9
19
+ Requires-Dist: nctalk==0.0.4
20
+ Requires-Dist: jinja2==3.1.6
21
+ Dynamic: license-file
22
+
23
+ # API
24
+ This is a custom API, written in Python using FastAPI, to help me accomplish tasks the can be improved through a RESTful API
25
+
26
+ ## Setup
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
+
29
+ ### Environment Vairables
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
+ - `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
+ - `TZ` - Timezone of the container
33
+ - `PGTZ` - Timezone the Postgres container should use
34
+ - `NEXTCLOUD_URL` - Base URL (must be `https://`) of the Nextcloud instance used by the Talk webhooks
35
+ - `NEXTCLOUD_TALK_TOKEN` - Conversation token of the registered [Nextcloud Talk bot](https://nextcloud-talk.readthedocs.io/en/latest/bot-list/) used by `/webhook/databasus`
36
+ - `NEXTCLOUD_TALK_SECRET` - Shared secret of the registered Nextcloud Talk bot used by `/webhook/databasus`
37
+ - `BESZEL_NEXTCLOUD_TALK_TOKEN` - Conversation token for the separate Beszel Talk bot used by `/webhook/beszel`
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
42
+
43
+ ## Webhooks
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": "..."}`
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.
49
+
50
+ ### Beszel setup
51
+
52
+ 1. Register a separate bot named **Beszel** using Nextcloud's [bot management commands](https://nextcloud-talk.readthedocs.io/en/latest/bot-list/) and enable it in the destination Talk conversation.
53
+ 2. Set `NEXTCLOUD_URL`, `BESZEL_NEXTCLOUD_TALK_TOKEN` (the destination conversation token), and `BESZEL_NEXTCLOUD_TALK_SECRET` (the new bot's shared secret) in `.env`, then recreate the API container to load the settings. Beszel credentials are required; this endpoint does not fall back to the Databasus bot.
54
+ 3. In Beszel, open **Settings > Notifications** and add this [generic webhook URL](https://beszel.dev/guide/notifications/generic), replacing the host and API key:
55
+
56
+ ```text
57
+ generic://api.example.com/webhook/beszel?template=json&@X-API-KEY=YOUR_URL_ENCODED_API_KEY
58
+ ```
59
+
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.
61
+ 4. Send a test notification from Beszel, then enable alerts in its systems table.
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
+
68
+ ## How to Access
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"}`
js_api-0.4.0/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # API
2
+ This is a custom API, written in Python using FastAPI, to help me accomplish tasks the can be improved through a RESTful API
3
+
4
+ ## Setup
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
+
7
+ ### Environment Vairables
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
+ - `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
+ - `TZ` - Timezone of the container
11
+ - `PGTZ` - Timezone the Postgres container should use
12
+ - `NEXTCLOUD_URL` - Base URL (must be `https://`) of the Nextcloud instance used by the Talk webhooks
13
+ - `NEXTCLOUD_TALK_TOKEN` - Conversation token of the registered [Nextcloud Talk bot](https://nextcloud-talk.readthedocs.io/en/latest/bot-list/) used by `/webhook/databasus`
14
+ - `NEXTCLOUD_TALK_SECRET` - Shared secret of the registered Nextcloud Talk bot used by `/webhook/databasus`
15
+ - `BESZEL_NEXTCLOUD_TALK_TOKEN` - Conversation token for the separate Beszel Talk bot used by `/webhook/beszel`
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
20
+
21
+ ## Webhooks
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": "..."}`
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.
27
+
28
+ ### Beszel setup
29
+
30
+ 1. Register a separate bot named **Beszel** using Nextcloud's [bot management commands](https://nextcloud-talk.readthedocs.io/en/latest/bot-list/) and enable it in the destination Talk conversation.
31
+ 2. Set `NEXTCLOUD_URL`, `BESZEL_NEXTCLOUD_TALK_TOKEN` (the destination conversation token), and `BESZEL_NEXTCLOUD_TALK_SECRET` (the new bot's shared secret) in `.env`, then recreate the API container to load the settings. Beszel credentials are required; this endpoint does not fall back to the Databasus bot.
32
+ 3. In Beszel, open **Settings > Notifications** and add this [generic webhook URL](https://beszel.dev/guide/notifications/generic), replacing the host and API key:
33
+
34
+ ```text
35
+ generic://api.example.com/webhook/beszel?template=json&@X-API-KEY=YOUR_URL_ENCODED_API_KEY
36
+ ```
37
+
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.
39
+ 4. Send a test notification from Beszel, then enable alerts in its systems table.
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
+
46
+ ## How to Access
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.19"
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"
@@ -0,0 +1,277 @@
1
+ import hmac
2
+ import os
3
+
4
+ from fastapi import APIRouter, HTTPException, Request, Security
5
+ from nctalk import TalkMessenger
6
+ from pydantic import BaseModel, Field, HttpUrl, ValidationError
7
+ from starlette.concurrency import run_in_threadpool
8
+
9
+ from util.auth import get_token_header
10
+ from util.logging import logger
11
+ from util.mail import EmailSender, SMTPConfig, TemplateRenderer
12
+
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
+ )
29
+
30
+
31
+ class NextcloudTalkWebhook(BaseModel):
32
+ header: str = Field(..., min_length=1, max_length=200)
33
+ message: str = Field(..., min_length=1, max_length=32000)
34
+
35
+
36
+ class BeszelWebhook(BaseModel):
37
+ title: str = Field(..., min_length=1, max_length=200)
38
+ message: str = Field(..., min_length=1, max_length=32000)
39
+
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
+
72
+ class PveUpsWebhook(BaseModel):
73
+ subject: str = Field(..., min_length=1, max_length=200)
74
+ body: str = Field(..., min_length=1, max_length=32000)
75
+ severity: str = Field(..., min_length=1, max_length=32000)
76
+ severity_upper: str = Field(..., min_length=1, max_length=32000)
77
+ facts: str = Field(..., min_length=1, max_length=32000)
78
+ timestamp: str = Field(..., min_length=1, max_length=32000)
79
+ version: str = Field(..., min_length=1, max_length=32000)
80
+ to: str = Field(..., min_length=1, max_length=32000)
81
+
82
+
83
+ def send_nextcloud_talk(message: str, config_prefix: str) -> None:
84
+ endpoint_url = os.environ.get("NEXTCLOUD_URL", "").strip()
85
+ token = os.environ.get(f"{config_prefix}_TOKEN", "").strip()
86
+ secret = os.environ.get(f"{config_prefix}_SECRET", "").strip()
87
+
88
+ if not endpoint_url or not token or not secret:
89
+ raise HTTPException(status_code=500, detail="Nextcloud Talk is not configured")
90
+ if not endpoint_url.startswith("https://"):
91
+ raise HTTPException(status_code=500, detail="NEXTCLOUD_URL must use https://")
92
+
93
+ messenger = TalkMessenger(endpoint_url=endpoint_url, token=token, secret=secret)
94
+
95
+ if not messenger.send(message):
96
+ logger.error("Failed to send message to Nextcloud Talk (%s)", config_prefix)
97
+ raise HTTPException(
98
+ status_code=502, detail="Failed to send message to Nextcloud Talk"
99
+ )
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")
144
+ return {"status": "sent"}
145
+
146
+
147
+ @router.post("/beszel", dependencies=[Security(get_token_header)])
148
+ async def beszel(webhook: BeszelWebhook):
149
+ if webhook.title.strip() == "":
150
+ raise HTTPException(status_code=422, detail="title cannot be empty")
151
+ if webhook.message.strip() == "":
152
+ raise HTTPException(status_code=422, detail="message cannot be empty")
153
+
154
+ send_nextcloud_talk(
155
+ f"**{webhook.title}**\n{webhook.message}", "BESZEL_NEXTCLOUD_TALK"
156
+ )
157
+ return {"status": "sent"}
158
+
159
+
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")
165
+
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")
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")
205
+ return {"status": "sent"}
206
+
207
+
208
+ @router.post("/pve-ups", dependencies=[Security(get_token_header)])
209
+ async def pve_ups(webhook: PveUpsWebhook):
210
+ if not os.environ.get("SMTP_HOST") or not os.environ.get("SMTP_PORT"):
211
+ raise HTTPException(status_code=500, detail="SMTP is not configured")
212
+ if not os.environ.get("SMTP_USERNAME") or not os.environ.get("SMTP_PASSWORD"):
213
+ raise HTTPException(
214
+ status_code=500, detail="SMTP credentials are not configured"
215
+ )
216
+
217
+ if webhook.body.strip() == "":
218
+ raise HTTPException(status_code=422, detail="body cannot be empty")
219
+ if webhook.facts.strip() == "":
220
+ raise HTTPException(status_code=422, detail="facts cannot be empty")
221
+ if webhook.timestamp.strip() == "":
222
+ raise HTTPException(status_code=422, detail="timestamp cannot be empty")
223
+ if webhook.subject.strip() == "":
224
+ raise HTTPException(status_code=422, detail="subject cannot be empty")
225
+ if webhook.to.strip() == "":
226
+ raise HTTPException(status_code=422, detail="to cannot be empty")
227
+ if webhook.severity.strip() == "":
228
+ raise HTTPException(status_code=422, detail="severity cannot be empty")
229
+ if webhook.version.strip() == "":
230
+ raise HTTPException(status_code=422, detail="version cannot be empty")
231
+ if webhook.severity_upper.strip() == "":
232
+ raise HTTPException(status_code=422, detail="severity_upper cannot be empty")
233
+
234
+ host = os.environ.get("SMTP_HOST")
235
+ port = int(os.environ.get("SMTP_PORT", "0"))
236
+ username = os.environ.get("SMTP_USERNAME")
237
+ password = os.environ.get("SMTP_PASSWORD")
238
+
239
+ smtp_config = SMTPConfig(host=host, port=port, username=username, password=password)
240
+
241
+ with EmailSender(smtp_config) as sender:
242
+ renderer = TemplateRenderer(templates_dir="templates")
243
+ sender.send_templated(
244
+ renderer=renderer,
245
+ sender_addr="PVE UPS <no-reply@jstockley.com>",
246
+ template="pve_ups_email.html",
247
+ subject=webhook.subject,
248
+ to=[webhook.to],
249
+ context={
250
+ "body": webhook.body,
251
+ "subject": webhook.subject,
252
+ "facts": parse_facts(webhook.facts),
253
+ "timestamp": webhook.timestamp,
254
+ "severity": webhook.severity,
255
+ "severity_upper": webhook.severity.upper(),
256
+ "version": webhook.version,
257
+ },
258
+ )
259
+
260
+ return {"status": "sent"}
261
+
262
+
263
+ def parse_facts(facts_text: str) -> list[dict]:
264
+ """Turn PVE-UPS's rendered 'facts' string into {label, value} rows."""
265
+ facts = []
266
+ for line in facts_text.splitlines():
267
+ line = line.strip()
268
+ if not line:
269
+ continue
270
+ if ":" in line:
271
+ label, _, value = line.partition(":")
272
+ facts.append({"label": label.strip(), "value": value.strip()})
273
+ else:
274
+ facts.append(
275
+ {"label": "", "value": line}
276
+ ) # no colon: show it anyway, don't drop it
277
+ return facts
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: js-api
3
+ Version: 0.4.0
4
+ Summary: Custom API written in Python using FastAPI
5
+ Author-email: Jack Stockley <jack@jstockley.com>
6
+ Project-URL: Homepage, https://github.com/jnstockley/api
7
+ Project-URL: Repository, https://github.com/jnstockley/api.git
8
+ Project-URL: Issues, https://github.com/jnstockley/api/issues
9
+ Keywords: starter,template,python
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: <3.16,>=3.15
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: fastapi[standard]==0.165.0
15
+ Requires-Dist: sqlalchemy==2.1.9
16
+ Requires-Dist: sqlmodel==0.0.50
17
+ Requires-Dist: python-dotenv==1.2.4
18
+ Requires-Dist: psycopg[binary]==3.3.9
19
+ Requires-Dist: nctalk==0.0.4
20
+ Requires-Dist: jinja2==3.1.6
21
+ Dynamic: license-file
22
+
23
+ # API
24
+ This is a custom API, written in Python using FastAPI, to help me accomplish tasks the can be improved through a RESTful API
25
+
26
+ ## Setup
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
+
29
+ ### Environment Vairables
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
+ - `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
+ - `TZ` - Timezone of the container
33
+ - `PGTZ` - Timezone the Postgres container should use
34
+ - `NEXTCLOUD_URL` - Base URL (must be `https://`) of the Nextcloud instance used by the Talk webhooks
35
+ - `NEXTCLOUD_TALK_TOKEN` - Conversation token of the registered [Nextcloud Talk bot](https://nextcloud-talk.readthedocs.io/en/latest/bot-list/) used by `/webhook/databasus`
36
+ - `NEXTCLOUD_TALK_SECRET` - Shared secret of the registered Nextcloud Talk bot used by `/webhook/databasus`
37
+ - `BESZEL_NEXTCLOUD_TALK_TOKEN` - Conversation token for the separate Beszel Talk bot used by `/webhook/beszel`
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
42
+
43
+ ## Webhooks
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": "..."}`
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.
49
+
50
+ ### Beszel setup
51
+
52
+ 1. Register a separate bot named **Beszel** using Nextcloud's [bot management commands](https://nextcloud-talk.readthedocs.io/en/latest/bot-list/) and enable it in the destination Talk conversation.
53
+ 2. Set `NEXTCLOUD_URL`, `BESZEL_NEXTCLOUD_TALK_TOKEN` (the destination conversation token), and `BESZEL_NEXTCLOUD_TALK_SECRET` (the new bot's shared secret) in `.env`, then recreate the API container to load the settings. Beszel credentials are required; this endpoint does not fall back to the Databasus bot.
54
+ 3. In Beszel, open **Settings > Notifications** and add this [generic webhook URL](https://beszel.dev/guide/notifications/generic), replacing the host and API key:
55
+
56
+ ```text
57
+ generic://api.example.com/webhook/beszel?template=json&@X-API-KEY=YOUR_URL_ENCODED_API_KEY
58
+ ```
59
+
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.
61
+ 4. Send a test notification from Beszel, then enable alerts in its systems table.
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
+
68
+ ## How to Access
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"}`
@@ -22,6 +22,7 @@ src/util/docker.py
22
22
  src/util/healthcheck.py
23
23
  src/util/logging.py
24
24
  src/util/mail.py
25
+ tests/test_beszel.py
25
26
  tests/test_docker.py
26
27
  tests/test_health_check.py
27
28
  tests/test_ip.py
@@ -0,0 +1,123 @@
1
+ from unittest.mock import patch
2
+
3
+ import pytest
4
+ from fastapi import FastAPI
5
+ from fastapi.testclient import TestClient
6
+
7
+ from controllers.webhook import router
8
+
9
+
10
+ @pytest.fixture
11
+ def client(monkeypatch):
12
+ monkeypatch.setenv("API_KEY", "testing")
13
+ monkeypatch.setenv("NEXTCLOUD_URL", "https://nextcloud.example.com")
14
+ monkeypatch.setenv("NEXTCLOUD_TALK_TOKEN", "databasus-token")
15
+ monkeypatch.setenv("NEXTCLOUD_TALK_SECRET", "databasus-secret")
16
+ monkeypatch.setenv("BESZEL_NEXTCLOUD_TALK_TOKEN", "beszel-token")
17
+ monkeypatch.setenv("BESZEL_NEXTCLOUD_TALK_SECRET", "beszel-secret")
18
+ app = FastAPI()
19
+ app.include_router(router)
20
+ with TestClient(app) as test_client:
21
+ yield test_client
22
+
23
+
24
+ PAYLOAD = {
25
+ "title": "Server CPU above threshold",
26
+ "message": "CPU averaged 63.53% for the previous 10 minutes.",
27
+ }
28
+ HEADERS = {"X-API-KEY": "testing"}
29
+
30
+
31
+ def test_beszel_sends_using_its_own_bot(client):
32
+ with patch("controllers.webhook.TalkMessenger") as messenger:
33
+ messenger.return_value.send.return_value = True
34
+ response = client.post("/webhook/beszel", headers=HEADERS, json=PAYLOAD)
35
+
36
+ assert response.status_code == 200
37
+ assert response.json() == {"status": "sent"}
38
+ messenger.assert_called_once_with(
39
+ endpoint_url="https://nextcloud.example.com",
40
+ token="beszel-token",
41
+ secret="beszel-secret",
42
+ )
43
+ messenger.return_value.send.assert_called_once_with(
44
+ f"**{PAYLOAD['title']}**\n{PAYLOAD['message']}"
45
+ )
46
+
47
+
48
+ @pytest.mark.parametrize("headers, status", [({}, 422), ({"X-API-KEY": "wrong"}, 401)])
49
+ def test_beszel_requires_api_key(client, headers, status):
50
+ with patch("controllers.webhook.TalkMessenger") as messenger:
51
+ response = client.post("/webhook/beszel", headers=headers, json=PAYLOAD)
52
+ assert response.status_code == status
53
+ messenger.assert_not_called()
54
+
55
+
56
+ @pytest.mark.parametrize(
57
+ "payload",
58
+ [
59
+ {},
60
+ {"title": "title"},
61
+ {"message": "message"},
62
+ {**PAYLOAD, "title": ""},
63
+ {**PAYLOAD, "title": " \t\n"},
64
+ {**PAYLOAD, "message": ""},
65
+ {**PAYLOAD, "message": " \t\n"},
66
+ {**PAYLOAD, "title": "x" * 201},
67
+ {**PAYLOAD, "message": "x" * 32001},
68
+ ],
69
+ )
70
+ def test_beszel_rejects_invalid_payload(client, payload):
71
+ with patch("controllers.webhook.TalkMessenger") as messenger:
72
+ response = client.post("/webhook/beszel", headers=HEADERS, json=payload)
73
+ assert response.status_code == 422
74
+ messenger.assert_not_called()
75
+
76
+
77
+ @pytest.mark.parametrize(
78
+ "variable",
79
+ ["NEXTCLOUD_URL", "BESZEL_NEXTCLOUD_TALK_TOKEN", "BESZEL_NEXTCLOUD_TALK_SECRET"],
80
+ )
81
+ @pytest.mark.parametrize("value", [None, "", " "])
82
+ def test_beszel_requires_configuration(client, monkeypatch, variable, value):
83
+ if value is None:
84
+ monkeypatch.delenv(variable)
85
+ else:
86
+ monkeypatch.setenv(variable, value)
87
+ with patch("controllers.webhook.TalkMessenger") as messenger:
88
+ response = client.post("/webhook/beszel", headers=HEADERS, json=PAYLOAD)
89
+ assert response.status_code == 500
90
+ assert response.json()["detail"] == "Nextcloud Talk is not configured"
91
+ messenger.assert_not_called()
92
+
93
+
94
+ def test_beszel_requires_https(client, monkeypatch):
95
+ monkeypatch.setenv("NEXTCLOUD_URL", "http://nextcloud.example.com")
96
+ with patch("controllers.webhook.TalkMessenger") as messenger:
97
+ response = client.post("/webhook/beszel", headers=HEADERS, json=PAYLOAD)
98
+ assert response.status_code == 500
99
+ messenger.assert_not_called()
100
+
101
+
102
+ def test_beszel_reports_delivery_failure(client):
103
+ with patch("controllers.webhook.TalkMessenger") as messenger:
104
+ messenger.return_value.send.return_value = False
105
+ response = client.post("/webhook/beszel", headers=HEADERS, json=PAYLOAD)
106
+ assert response.status_code == 502
107
+ assert response.json()["detail"] == "Failed to send message to Nextcloud Talk"
108
+
109
+
110
+ def test_databasus_keeps_its_existing_bot(client):
111
+ with patch("controllers.webhook.TalkMessenger") as messenger:
112
+ messenger.return_value.send.return_value = True
113
+ response = client.post(
114
+ "/webhook/databasus",
115
+ headers=HEADERS,
116
+ json={"header": "Backup complete", "message": "Success"},
117
+ )
118
+ assert response.status_code == 200
119
+ messenger.assert_called_once_with(
120
+ endpoint_url="https://nextcloud.example.com",
121
+ token="databasus-token",
122
+ secret="databasus-secret",
123
+ )