From d9cee2effe0da21d9cea19c935af4576688ef2a3 Mon Sep 17 00:00:00 2001 From: Fabio Scotto di Santolo Date: Sat, 10 Oct 2026 16:57:34 +0200 Subject: [PATCH] Add private aria2 RPC gateway for authenticated public access --- AGENTS.md | 8 +- ansible/inventory/host_vars/atlas.yml | 2 + ansible/roles/profile_atlas/defaults/main.yml | 3 + .../files/atlas-aria2-rpc-gateway.py | 131 ++++++++++++++++++ .../profile_atlas/tasks/aria2_gateway.yml | 81 +++++++++++ ansible/roles/profile_atlas/tasks/main.yml | 3 + .../templates/atlas-aria2-gateway.service.j2 | 17 +++ docs/atlas-aria2.md | 74 ++++++++++ tests/test_aria2_rpc_gateway.py | 40 ++++++ 9 files changed, 357 insertions(+), 2 deletions(-) create mode 100644 ansible/roles/profile_atlas/files/atlas-aria2-rpc-gateway.py create mode 100644 ansible/roles/profile_atlas/tasks/aria2_gateway.yml create mode 100644 ansible/roles/profile_atlas/templates/atlas-aria2-gateway.service.j2 create mode 100644 tests/test_aria2_rpc_gateway.py diff --git a/AGENTS.md b/AGENTS.md index 9ddc50e..cbb0af9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/ansible/inventory/host_vars/atlas.yml b/ansible/inventory/host_vars/atlas.yml index bbd262f..d2015dd 100644 --- a/ansible/inventory/host_vars/atlas.yml +++ b/ansible/inventory/host_vars/atlas.yml @@ -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 diff --git a/ansible/roles/profile_atlas/defaults/main.yml b/ansible/roles/profile_atlas/defaults/main.yml index 958587e..29e869d 100644 --- a/ansible/roles/profile_atlas/defaults/main.yml +++ b/ansible/roles/profile_atlas/defaults/main.yml @@ -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 diff --git a/ansible/roles/profile_atlas/files/atlas-aria2-rpc-gateway.py b/ansible/roles/profile_atlas/files/atlas-aria2-rpc-gateway.py new file mode 100644 index 0000000..63ad9c5 --- /dev/null +++ b/ansible/roles/profile_atlas/files/atlas-aria2-rpc-gateway.py @@ -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() diff --git a/ansible/roles/profile_atlas/tasks/aria2_gateway.yml b/ansible/roles/profile_atlas/tasks/aria2_gateway.yml new file mode 100644 index 0000000..cfac535 --- /dev/null +++ b/ansible/roles/profile_atlas/tasks/aria2_gateway.yml @@ -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 diff --git a/ansible/roles/profile_atlas/tasks/main.yml b/ansible/roles/profile_atlas/tasks/main.yml index 2d146e9..4ce8e11 100644 --- a/ansible/roles/profile_atlas/tasks/main.yml +++ b/ansible/roles/profile_atlas/tasks/main.yml @@ -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 diff --git a/ansible/roles/profile_atlas/templates/atlas-aria2-gateway.service.j2 b/ansible/roles/profile_atlas/templates/atlas-aria2-gateway.service.j2 new file mode 100644 index 0000000..aedc429 --- /dev/null +++ b/ansible/roles/profile_atlas/templates/atlas-aria2-gateway.service.j2 @@ -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 diff --git a/docs/atlas-aria2.md b/docs/atlas-aria2.md index 8007bbc..10c136a 100644 --- a/docs/atlas-aria2.md +++ b/docs/atlas-aria2.md @@ -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 diff --git a/tests/test_aria2_rpc_gateway.py b/tests/test_aria2_rpc_gateway.py new file mode 100644 index 0000000..62ec2b6 --- /dev/null +++ b/tests/test_aria2_rpc_gateway.py @@ -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()