mirror of
https://github.com/fscotto/infra.git
synced 2026-11-26 13:49:52 +00:00
Add private aria2 RPC gateway for authenticated public access
This commit is contained in:
@@ -215,10 +215,14 @@ The dotfile vars follow the same split: `desktop_common_dotfiles` carries mode-i
|
||||
|
||||
- Atlas HTTP downloads use the admin-owned rootless `atlas-aria2.service` and
|
||||
`atlas-ariang.service` Quadlets, gated by `atlas_manage_aria2` and the `aria2` tag.
|
||||
AriaNg is LAN-only at `http://192.168.178.55:8091`; RPC is LAN-only on TCP/6800
|
||||
AriaNg binds the LAN at `http://192.168.178.55:8091`; direct RPC is LAN-only on TCP/6800
|
||||
and requires a private target-generated token. State lives in `services/data/aria2`,
|
||||
with payloads in `Archive/Downloads`; do not expose RPC through the existing
|
||||
qBittorrent `torrent.fscotto.co` endpoint. See `docs/atlas-aria2.md`.
|
||||
qBittorrent `torrent.fscotto.co` endpoint. Public `downloads.fscotto.co` uses
|
||||
a manual NPM Access List for both UI and `/jsonrpc`. The `aria2_gateway` tag
|
||||
manages an admin user service on TCP/8092, accessible only through Aegis,
|
||||
injecting the private token for JSON-RPC POST clients; keep this route
|
||||
authenticated and never expose the gateway directly. See `docs/atlas-aria2.md`.
|
||||
|
||||
## Atlas NAS TODO
|
||||
Completed validation: the existing RAIDZ2 pool and datasets, SELinux, LAN firewall, SSH, Cockpit with
|
||||
|
||||
@@ -266,5 +266,7 @@ atlas_qbittorrent_public_domain: torrent.fscotto.co
|
||||
|
||||
# LAN-only HTTP downloader; RPC secret is generated and retained privately on Atlas.
|
||||
atlas_manage_aria2: true
|
||||
atlas_aria2_gateway_enabled: true
|
||||
atlas_aria2_public_domain: downloads.fscotto.co
|
||||
atlas_aria2_image: docker.io/p3terx/aria2-pro@sha256:086d1a37c586edb07ec0fb956bf9edd89d1d38d138ad5309ff96d510c8c9a011
|
||||
atlas_ariang_image: docker.io/p3terx/ariang@sha256:73849cf75fe9f959229222622e887310df505cbf868eb9c735e2af376523c010
|
||||
|
||||
@@ -316,6 +316,9 @@ atlas_qbittorrent_web_settings:
|
||||
- {key: 'WebUI\AuthSubnetWhitelistEnabled', value: "false"}
|
||||
|
||||
atlas_manage_aria2: false
|
||||
atlas_aria2_gateway_enabled: false
|
||||
atlas_aria2_gateway_port: 8092
|
||||
atlas_aria2_public_domain: CHANGEME_ARIA2_DOMAIN
|
||||
atlas_aria2_state_dir: "{{ atlas_app_data_mountpoint }}/aria2"
|
||||
atlas_aria2_downloads_dir: "{{ atlas_archive_mountpoint }}/Downloads"
|
||||
atlas_aria2_rpc_port: 6800
|
||||
|
||||
131
ansible/roles/profile_atlas/files/atlas-aria2-rpc-gateway.py
Normal file
131
ansible/roles/profile_atlas/files/atlas-aria2-rpc-gateway.py
Normal file
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/python3
|
||||
"""Private NPM-only JSON-RPC adapter. Never serves the secret to browsers."""
|
||||
import argparse
|
||||
import copy
|
||||
import http.client
|
||||
import json
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
import threading
|
||||
|
||||
MAX_BODY = 2 * 1024 * 1024
|
||||
|
||||
|
||||
def inject(request, token, depth=0):
|
||||
if depth > 4 or not isinstance(request, dict):
|
||||
raise ValueError('Invalid RPC request')
|
||||
result = copy.deepcopy(request)
|
||||
method = result.get('method', result.get('methodName'))
|
||||
params = result.setdefault('params', [])
|
||||
if not isinstance(method, str) or not isinstance(params, list):
|
||||
raise ValueError('Invalid RPC method or params')
|
||||
if method == 'system.multicall':
|
||||
if len(params) != 1 or not isinstance(params[0], list) or len(params[0]) > 128:
|
||||
raise ValueError('Invalid multicall')
|
||||
result['params'] = [[inject(item, token, depth + 1) for item in params[0]]]
|
||||
elif method.startswith('aria2.'):
|
||||
if params and isinstance(params[0], str) and params[0].startswith('token:'):
|
||||
params.pop(0)
|
||||
# Keep RPC security configuration owned by Ansible, not remote callers.
|
||||
if method in ('aria2.changeGlobalOption', 'aria2.changeOption'):
|
||||
for value in params:
|
||||
if isinstance(value, dict) and any(key.startswith('rpc-') for key in value):
|
||||
raise ValueError('RPC security options are not editable')
|
||||
params.insert(0, 'token:' + token)
|
||||
elif method not in ('system.listMethods', 'system.listNotifications'):
|
||||
raise ValueError('Unsupported RPC method')
|
||||
return result
|
||||
|
||||
|
||||
def sanitize(value, token):
|
||||
if isinstance(value, dict):
|
||||
return {key: sanitize(item, token) for key, item in value.items()
|
||||
if key not in ('rpc-secret', 'rpc-passwd', 'rpc-user')}
|
||||
if isinstance(value, list):
|
||||
return [sanitize(item, token) for item in value]
|
||||
if isinstance(value, str):
|
||||
return value.replace(token, '[redacted]')
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--listen', required=True)
|
||||
parser.add_argument('--port', type=int, required=True)
|
||||
parser.add_argument('--upstream-port', type=int, required=True)
|
||||
parser.add_argument('--peer', required=True)
|
||||
parser.add_argument('--domain', required=True)
|
||||
parser.add_argument('--secret-file', required=True)
|
||||
args = parser.parse_args()
|
||||
token = Path(args.secret_file).read_text().strip()
|
||||
if len(token) != 64 or any(char not in '0123456789abcdef' for char in token):
|
||||
raise ValueError('Invalid private RPC secret')
|
||||
slots = threading.BoundedSemaphore(16)
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def setup(self):
|
||||
super().setup()
|
||||
self.connection.settimeout(15)
|
||||
|
||||
def log_message(self, *_):
|
||||
pass # No credentials, download URLs or request payloads in logs.
|
||||
|
||||
def reply(self, status, value):
|
||||
body = json.dumps(value).encode()
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.send_header('Content-Length', str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_POST(self):
|
||||
if self.client_address[0] not in (args.peer, args.listen):
|
||||
return self.reply(403, {'error': 'Forbidden'})
|
||||
if self.path != '/jsonrpc' or self.headers.get('Host') not in (args.domain, args.domain + ':443'):
|
||||
return self.reply(403, {'error': 'Forbidden'})
|
||||
origin = self.headers.get('Origin')
|
||||
if origin and origin != 'https://' + args.domain:
|
||||
return self.reply(403, {'error': 'Forbidden origin'})
|
||||
if self.headers.get('Transfer-Encoding') or self.headers.get('Content-Type', '').split(';')[0].strip() not in ('application/json', 'application/json-rpc'):
|
||||
return self.reply(415, {'error': 'JSON POST required'})
|
||||
if not slots.acquire(blocking=False):
|
||||
return self.reply(503, {'error': 'Busy'})
|
||||
connection = None
|
||||
try:
|
||||
length = int(self.headers.get('Content-Length', '0'))
|
||||
if not 0 < length <= MAX_BODY:
|
||||
return self.reply(413, {'error': 'Invalid request size'})
|
||||
request = json.loads(self.rfile.read(length))
|
||||
if isinstance(request, list):
|
||||
if not 0 < len(request) <= 128:
|
||||
raise ValueError('Invalid batch')
|
||||
request = [inject(item, token) for item in request]
|
||||
else:
|
||||
request = inject(request, token)
|
||||
body = json.dumps(request).encode()
|
||||
if len(body) > MAX_BODY:
|
||||
return self.reply(413, {'error': 'Request too large'})
|
||||
connection = http.client.HTTPConnection(args.listen, args.upstream_port, timeout=30)
|
||||
connection.request('POST', '/jsonrpc', body, {'Content-Type': 'application/json'})
|
||||
response = connection.getresponse()
|
||||
payload = response.read(MAX_BODY + 1)
|
||||
if len(payload) > MAX_BODY:
|
||||
return self.reply(502, {'error': 'Upstream response too large'})
|
||||
self.reply(response.status, sanitize(json.loads(payload), token))
|
||||
except (ValueError, TypeError, KeyError):
|
||||
self.reply(400, {'error': 'Invalid RPC request'})
|
||||
except (OSError, http.client.HTTPException):
|
||||
self.reply(502, {'error': 'RPC upstream unavailable'})
|
||||
finally:
|
||||
if connection:
|
||||
connection.close()
|
||||
slots.release()
|
||||
|
||||
server = ThreadingHTTPServer((args.listen, args.port), Handler)
|
||||
server.daemon_threads = True
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
81
ansible/roles/profile_atlas/tasks/aria2_gateway.yml
Normal file
81
ansible/roles/profile_atlas/tasks/aria2_gateway.yml
Normal file
@@ -0,0 +1,81 @@
|
||||
---
|
||||
- name: Manage the private NPM aria2 adapter
|
||||
tags: [atlas, aria2_gateway]
|
||||
when:
|
||||
- atlas_manage_aria2 | bool
|
||||
- atlas_aria2_gateway_enabled | bool
|
||||
block:
|
||||
- name: Require a dedicated gateway and explicit public domain
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- atlas_aria2_gateway_port not in [atlas_aria2_rpc_port, atlas_ariang_web_port]
|
||||
- atlas_aria2_public_domain is match('^[a-z0-9][a-z0-9.-]+[.][a-z]{2,}$')
|
||||
- not atlas_aria2_public_domain.startswith('CHANGEME')
|
||||
|
||||
- name: Install the private JSON-RPC adapter
|
||||
ansible.builtin.copy:
|
||||
src: atlas-aria2-rpc-gateway.py
|
||||
dest: "{{ atlas_aria2_state_dir }}/rpc-gateway.py"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0600"
|
||||
register: atlas_aria2_gateway_script
|
||||
|
||||
- name: Prepare the user unit directory
|
||||
ansible.builtin.file:
|
||||
path: "{{ atlas_admin_home }}/.config/systemd/user"
|
||||
state: directory
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0700"
|
||||
|
||||
- name: Install the user gateway unit
|
||||
ansible.builtin.template:
|
||||
src: atlas-aria2-gateway.service.j2
|
||||
dest: "{{ atlas_admin_home }}/.config/systemd/user/atlas-aria2-gateway.service"
|
||||
owner: "{{ atlas_admin_username }}"
|
||||
group: "{{ atlas_admin_group }}"
|
||||
mode: "0644"
|
||||
register: atlas_aria2_gateway_unit
|
||||
|
||||
- name: Allow only Aegis to reach the credential-injecting adapter
|
||||
ansible.posix.firewalld:
|
||||
zone: "{{ atlas_firewalld_zone }}"
|
||||
rich_rule: >-
|
||||
rule family="ipv4" source address="{{ atlas_aegis_ip }}"
|
||||
port port="{{ atlas_aria2_gateway_port }}" protocol="tcp" accept
|
||||
permanent: true
|
||||
immediate: true
|
||||
state: enabled
|
||||
|
||||
- name: Enable and start the private gateway
|
||||
become_user: "{{ atlas_admin_username }}"
|
||||
ansible.builtin.systemd_service:
|
||||
scope: user
|
||||
name: atlas-aria2-gateway.service
|
||||
daemon_reload: "{{ atlas_aria2_gateway_unit.changed }}"
|
||||
enabled: true
|
||||
state: "{{ 'restarted' if atlas_aria2_gateway_script.changed or atlas_aria2_gateway_unit.changed else 'started' }}"
|
||||
environment:
|
||||
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
|
||||
when: not ansible_check_mode
|
||||
|
||||
- name: Verify token-free requests through the private adapter
|
||||
ansible.builtin.uri:
|
||||
url: "http://{{ ansible_host }}:{{ atlas_aria2_gateway_port }}/jsonrpc"
|
||||
headers:
|
||||
Host: "{{ atlas_aria2_public_domain }}"
|
||||
method: POST
|
||||
body_format: json
|
||||
body:
|
||||
jsonrpc: "2.0"
|
||||
id: ansible-gateway
|
||||
method: aria2.getVersion
|
||||
params: []
|
||||
return_content: true
|
||||
register: atlas_aria2_gateway_probe
|
||||
retries: 10
|
||||
delay: 2
|
||||
until: atlas_aria2_gateway_probe.json.result.version is defined
|
||||
when: not ansible_check_mode
|
||||
@@ -32,6 +32,9 @@
|
||||
- name: Import Atlas LAN HTTP downloader
|
||||
ansible.builtin.import_tasks: aria2.yml
|
||||
|
||||
- name: Import Atlas private aria2 RPC gateway
|
||||
ansible.builtin.import_tasks: aria2_gateway.yml
|
||||
|
||||
- name: Import Atlas ZFS maintenance tasks
|
||||
ansible.builtin.import_tasks: zfs_maintenance.yml
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Managed by Ansible. NPM authenticates callers; this private adapter adds RPC credentials.
|
||||
[Unit]
|
||||
Description=Atlas private aria2 RPC gateway
|
||||
After=atlas-aria2.service
|
||||
Requires=atlas-aria2.service
|
||||
PartOf=atlas-aria2.service
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/bin/python3 {{ atlas_aria2_state_dir }}/rpc-gateway.py --listen {{ ansible_host }} --port {{ atlas_aria2_gateway_port }} --upstream-port {{ atlas_aria2_rpc_port }} --peer {{ atlas_aegis_ip }} --domain {{ atlas_aria2_public_domain }} --secret-file {{ atlas_aria2_state_dir }}/rpc-secret
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
NoNewPrivileges=true
|
||||
UMask=0077
|
||||
RestrictAddressFamilies=AF_INET AF_UNIX
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
@@ -53,6 +53,80 @@ The UI may store the secret in browser-local settings. There is no additional
|
||||
login for the static page; the RPC token protects the actual service. Do not
|
||||
publish this interface on the qBittorrent endpoint (`torrent.fscotto.co`).
|
||||
|
||||
## Public access: downloads.fscotto.co
|
||||
|
||||
NPM on Prometheus manages the public endpoint separately from the Atlas
|
||||
playbook. Atlas' existing LAN rules already admit the Aegis gateway; do not
|
||||
publish port 6800 on the router or Prometheus firewall.
|
||||
|
||||
Create an NPM Access List before enabling the Proxy Host:
|
||||
|
||||
- Add a unique username and strong password in the Authorization tab.
|
||||
- Leave Satisfy Any and Pass Auth to Host disabled. Do not add an IP-based
|
||||
authentication bypass.
|
||||
- Keep these credentials private; they are separate from the aria2 RPC secret.
|
||||
|
||||
Create the Proxy Host with that Access List selected:
|
||||
|
||||
- Domain: `downloads.fscotto.co`; DNS A record points to `179.237.102.172`.
|
||||
- Scheme: HTTP; Forward Host: `192.168.178.55`; Forward Port: `8091`.
|
||||
- Custom Location `/jsonrpc`: HTTP, `192.168.178.55`, port `8092` (private gateway).
|
||||
Leave its forwarding path unchanged so `/jsonrpc` reaches aria2.
|
||||
- Request a Let's Encrypt certificate and enable Force SSL.
|
||||
- Use HTTPS JSON-RPC (POST) in AriaNg: host `downloads.fscotto.co`, port `443`,
|
||||
path `jsonrpc`, with the RPC secret field empty. Never embed either secret in
|
||||
URLs or static frontend files.
|
||||
|
||||
Use NPM's Custom Locations UI rather than a hand-written unprotected location:
|
||||
the deployed NPM templates include Access List authentication in both the
|
||||
default location and custom locations. Verify this in the rendered host config.
|
||||
Both `/` and `/jsonrpc` must return 401 without proxy credentials; direct aria2
|
||||
RPC on port 6800 still requires its separate token. Validate before considering public
|
||||
access complete.
|
||||
|
||||
On 2026-10-10 NPM-to-AriaNg connectivity returned HTTP 200. After operator
|
||||
creation of the Access List and saving the Proxy Host, public DNS resolved to
|
||||
Prometheus and valid HTTPS returned 401 with a Basic authentication challenge
|
||||
for both `/` and `/jsonrpc`. The rendered NPM configuration confirmed both
|
||||
locations use the same Access List, with Satisfy All and no upstream forwarding
|
||||
of Basic credentials. Authenticated browser/RPC operation remains to be
|
||||
confirmed by the operator; no passwords were read or reset.
|
||||
|
||||
### Server-side token gateway
|
||||
|
||||
`atlas_aria2_gateway_enabled` enables the Ansible-managed admin user service
|
||||
`atlas-aria2-gateway.service` (tag `aria2_gateway`). Python's installed standard
|
||||
library implements HTTP JSON-RPC POST, batch and `system.multicall`; WebSocket,
|
||||
JSONP and XML-RPC are not supported. It reads the existing private `rpc-secret`
|
||||
only on Atlas and inserts it into RPC parameters. It filters credential-bearing
|
||||
response fields and rejects RPC security-option edits. Requests have size,
|
||||
timeout and concurrency limits; bodies and URLs are not logged.
|
||||
|
||||
The adapter binds Atlas' LAN IP on port 8092 and admits only Aegis through
|
||||
firewalld. Application checks admit Aegis and Atlas itself (local validation),
|
||||
require the declared public Host and reject foreign browser Origins. Its
|
||||
security boundary relies on Aegis and the authenticated NPM Custom Location:
|
||||
never open this adapter to the whole LAN or create an unauthenticated proxy
|
||||
route to it. It does not independently authenticate NPM users.
|
||||
|
||||
On each browser, use HTTPS `downloads.fscotto.co:443/jsonrpc`, POST and an empty
|
||||
RPC secret. The normal NPM username/password login remains required. Direct LAN
|
||||
clients using port 6800 still need the token. No token is embedded in static
|
||||
AriaNg assets, URLs or NPM configuration.
|
||||
|
||||
Validation: `python3 -B tests/test_aria2_rpc_gateway.py`; then
|
||||
`ansible-playbook ansible/site.yml --limit atlas --tags aria2_gateway`.
|
||||
|
||||
Gateway deployment on 2026-10-10 passed syntax/check validation and a second
|
||||
steady-state run reported `changed=0`, `failed=0`. Six offline regression tests
|
||||
passed. From the NPM container, token-free multicall returned version and global
|
||||
stats; an Atlas-local batch verified credential response filtering. Foreign
|
||||
Origins returned 403, direct Ikaros-to-gateway access was blocked, and both
|
||||
public UI and RPC remained 401 without Basic credentials. NPM host 16 now
|
||||
forwards `/jsonrpc` to 8092 with the same Access List. `nginx -t` passed;
|
||||
aria2, AriaNg, gateway and qBittorrent remained active. Public authenticated
|
||||
browser operation and an actual host reboot remain operator verification.
|
||||
|
||||
## Interrupted downloads and iCloud
|
||||
|
||||
The queue is saved every 30 seconds and on graceful shutdown. Keep both partial
|
||||
|
||||
40
tests/test_aria2_rpc_gateway.py
Normal file
40
tests/test_aria2_rpc_gateway.py
Normal file
@@ -0,0 +1,40 @@
|
||||
"""Offline regression tests for the private RPC adapter (no real credentials)."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
path = Path(__file__).resolve().parents[1] / 'ansible/roles/profile_atlas/files/atlas-aria2-rpc-gateway.py'
|
||||
spec = importlib.util.spec_from_file_location('gateway', path)
|
||||
gateway = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(gateway)
|
||||
|
||||
|
||||
class GatewayTests(unittest.TestCase):
|
||||
def test_insert_without_mutating(self):
|
||||
request = {'method': 'aria2.getVersion', 'params': []}
|
||||
self.assertEqual(gateway.inject(request, 'test')['params'], ['token:test'])
|
||||
self.assertEqual(request['params'], [])
|
||||
|
||||
def test_replace_stale_token(self):
|
||||
self.assertEqual(gateway.inject({'method': 'aria2.tellActive', 'params': ['token:old']}, 'test')['params'], ['token:test'])
|
||||
|
||||
def test_multicall(self):
|
||||
request = {'method': 'system.multicall', 'params': [[{'methodName': 'aria2.getVersion', 'params': []}]]}
|
||||
self.assertEqual(gateway.inject(request, 'test')['params'][0][0]['params'], ['token:test'])
|
||||
|
||||
def test_security_option_edits_rejected(self):
|
||||
for method in ('aria2.changeOption', 'aria2.changeGlobalOption'):
|
||||
with self.assertRaises(ValueError):
|
||||
gateway.inject({'method': method, 'params': [{'rpc-secret': 'new'}]}, 'test')
|
||||
|
||||
def test_malformed_requests_rejected(self):
|
||||
for request in (None, {}, {'method': 'bad'}, {'method': 'system.multicall', 'params': []}, {'method': 'aria2.getVersion', 'params': {}}):
|
||||
with self.assertRaises(ValueError):
|
||||
gateway.inject(request, 'test')
|
||||
|
||||
def test_response_secret_filtering(self):
|
||||
self.assertEqual(gateway.sanitize({'result': [{'rpc-secret': 'test', 'rpc-user': 'user', 'rpc-passwd': 'pw', 'value': 'token:test'}]}, 'test'), {'result': [{'value': 'token:[redacted]'}]})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user