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:
@@ -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
|
||||
Reference in New Issue
Block a user