Compare commits

...

5 Commits

Author SHA1 Message Date
Fabio Scotto di Santolo
d9cee2effe Add private aria2 RPC gateway for authenticated public access 2026-10-10 16:57:34 +02:00
Fabio Scotto di Santolo
5ebf1c1eb6 Add LAN-only aria2 downloads to Atlas 2026-10-10 16:00:44 +02:00
Fabio Scotto di Santolo
5f3792d603 Prepare qBittorrent for reverse proxy access 2026-10-10 14:05:47 +02:00
Fabio Scotto di Santolo
c8df4dde87 Add Atlas qBittorrent service configuration 2026-10-10 13:49:55 +02:00
Fabio Scotto di Santolo
7d80c57570 Add Nextcloud client to GNOME desktop packages 2026-10-10 13:35:26 +02:00
18 changed files with 1143 additions and 0 deletions

View File

@@ -204,6 +204,26 @@ The dotfile vars follow the same split: `desktop_common_dotfiles` carries mode-i
when it is assigned. After a firewalld reload, restore Prometheus' rootful Podman networking with when it is assigned. After a firewalld reload, restore Prometheus' rootful Podman networking with
`podman network reload --all` so the existing proxy stack retains container DNS. `podman network reload --all` so the existing proxy stack retains container DNS.
- Atlas qBittorrent is selected by `atlas_manage_qbittorrent` and managed with the
`qbittorrent` tag as the admin-owned rootless `atlas-qbittorrent.service` Quadlet.
Its Web UI is `http://192.168.178.55:8090` on the LAN and prepared for the manual
NPM HTTPS domain `torrent.fscotto.co`, trusting only Aegis for forwarded client
addresses. DNS and NPM configuration stay manual. Configuration lives in
`services/data/qbittorrent`, and only `Archive/Downloads` is writable as payload
storage. It uses the home Internet connection, not WireGuard or a VPN; no router
forwarding or published torrent peer port is configured. See `docs/atlas-qbittorrent.md`.
- 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 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. 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 ## Atlas NAS TODO
Completed validation: the existing RAIDZ2 pool and datasets, SELinux, LAN firewall, SSH, Cockpit with Completed validation: the existing RAIDZ2 pool and datasets, SELinux, LAN firewall, SSH, Cockpit with
the selected 45Drives plugins, encrypted SMB3 `Archive`, the Aegis-only NFSv4 `photobook` export, and the the selected 45Drives plugins, encrypted SMB3 `Archive`, the Aegis-only NFSv4 `photobook` export, and the

View File

@@ -42,6 +42,7 @@ fedora_desktop_packages:
- libXft-devel - libXft-devel
- meld - meld
- mpv - mpv
- nextcloud-client
- pdfarranger - pdfarranger
- pinentry-gnome3 - pinentry-gnome3
- plocate - plocate

View File

@@ -257,3 +257,16 @@ host_enabled_services:
- cockpit.socket - cockpit.socket
- pmlogger.service - pmlogger.service
- zfs.target - zfs.target
# Torrent Web UI: LAN and the existing Aegis gateway for the manual NPM proxy.
atlas_manage_qbittorrent: true
atlas_qbittorrent_image: docker.io/qbittorrentofficial/qbittorrent-nox@sha256:92bfd78d731e254ba64f62b77b0696add6447a33642ee5feda106a26b285aa7f
atlas_qbittorrent_reverse_proxy_enabled: true
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

View File

@@ -297,3 +297,31 @@ atlas_media_quadlet_services:
- atlas-immich-machine-learning.service - atlas-immich-machine-learning.service
- atlas-immich-server.service - atlas-immich-server.service
- atlas-npm.service - atlas-npm.service
atlas_manage_qbittorrent: false
atlas_qbittorrent_image: CHANGEME_PINNED_QBITTORRENT_IMAGE
atlas_qbittorrent_state_dir: "{{ atlas_app_data_mountpoint }}/qbittorrent"
atlas_qbittorrent_downloads_dir: "{{ atlas_archive_mountpoint }}/Downloads"
atlas_qbittorrent_web_port: 8090
atlas_qbittorrent_reverse_proxy_enabled: false
atlas_qbittorrent_public_domain: CHANGEME_QBITTORRENT_DOMAIN
atlas_qbittorrent_web_settings:
- {key: 'WebUI\ServerDomains', value: "{{ atlas_qbittorrent_public_domain }}"}
- {key: 'WebUI\ReverseProxySupportEnabled', value: "true"}
- {key: 'WebUI\TrustedReverseProxiesList', value: "{{ atlas_aegis_ip }}"}
- {key: 'WebUI\HostHeaderValidation', value: "true"}
- {key: 'WebUI\CSRFProtection', value: "true"}
- {key: 'WebUI\LocalHostAuth', value: "true"}
- {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
atlas_ariang_web_port: 8091
atlas_aria2_image: CHANGEME_PINNED_ARIA2_IMAGE
atlas_ariang_image: CHANGEME_PINNED_ARIANG_IMAGE

View 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()

View File

@@ -0,0 +1,205 @@
---
- name: Manage Atlas LAN HTTP downloader
tags: [atlas, aria2]
when: atlas_manage_aria2 | bool
block:
- name: Require isolated state, shared Downloads and pinned images
ansible.builtin.assert:
that:
- atlas_manage_storage | bool
- atlas_aria2_state_dir == atlas_app_data_mountpoint ~ '/aria2'
- atlas_aria2_downloads_dir == atlas_archive_mountpoint ~ '/Downloads'
- atlas_aria2_image is search('@sha256:[0-9a-f]{64}$')
- atlas_ariang_image is search('@sha256:[0-9a-f]{64}$')
- atlas_aria2_rpc_port != atlas_ariang_web_port
- name: Inspect the existing downloader parent datasets
community.general.zfs_facts:
name: "{{ item.dataset }}"
properties: name,mounted,mountpoint
loop:
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_archive }}"
mountpoint: "{{ atlas_archive_mountpoint }}"
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_app_data }}"
mountpoint: "{{ atlas_app_data_mountpoint }}"
register: atlas_aria2_parents
- name: Require mounted downloader parent datasets
ansible.builtin.assert:
that:
- item.ansible_facts.ansible_zfs_datasets | length == 1
- item.ansible_facts.ansible_zfs_datasets[0].mounted == 'yes'
- item.ansible_facts.ansible_zfs_datasets[0].mountpoint == item.item.mountpoint
loop: "{{ atlas_aria2_parents.results }}"
loop_control:
label: "{{ item.item.dataset }}"
- name: Inspect shared Downloads without following links
ansible.builtin.stat:
path: "{{ atlas_aria2_downloads_dir }}"
follow: false
register: atlas_aria2_downloads
- name: Refuse unrelated or symlinked Downloads
ansible.builtin.assert:
that:
- >-
not atlas_aria2_downloads.stat.exists or
(atlas_aria2_downloads.stat.isdir | default(false) and
atlas_aria2_downloads.stat.uid | int == atlas_admin_uid | int)
- name: Create the private aria2 dataset
community.general.zfs:
name: "{{ atlas_zfs_pool }}/services/data/aria2"
state: present
extra_zfs_properties:
compression: zstd
mountpoint: "{{ atlas_aria2_state_dir }}"
- name: Prepare state, downloads and Quadlet directories
ansible.builtin.file:
path: "{{ item.path }}"
state: directory
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "{{ item.mode }}"
loop:
- {path: "{{ atlas_aria2_state_dir }}", mode: "0700"}
- {path: "{{ atlas_aria2_downloads_dir }}", mode: "0770"}
- {path: "{{ atlas_admin_home }}/.config/containers/systemd", mode: "0700"}
- name: Generate a private persistent RPC secret on Atlas only
become_user: "{{ atlas_admin_username }}"
ansible.builtin.command:
argv:
- python3
- -c
- >-
import os, secrets;
fd = os.open('{{ atlas_aria2_state_dir }}/rpc-secret',
os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600);
os.write(fd, (secrets.token_hex(32) + '\n').encode()); os.close(fd)
creates: "{{ atlas_aria2_state_dir }}/rpc-secret"
no_log: true
- name: Read the existing private RPC secret without displaying it
ansible.builtin.slurp:
src: "{{ atlas_aria2_state_dir }}/rpc-secret"
register: atlas_aria2_rpc_secret
no_log: true
when: not ansible_check_mode
- name: Require a strong RPC secret
ansible.builtin.assert:
that:
- atlas_aria2_rpc_secret.content | b64decode | trim is match('^[a-f0-9]{64}$')
no_log: true
when: not ansible_check_mode
- name: Initialize the session file without replacing saved downloads
ansible.builtin.copy:
content: ""
dest: "{{ atlas_aria2_state_dir }}/session"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0600"
force: false
diff: false
no_log: true
- name: Render private aria2 configuration
ansible.builtin.template:
src: atlas-aria2.conf.j2
dest: "{{ atlas_aria2_state_dir }}/aria2.conf"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0600"
register: atlas_aria2_config
no_log: true
diff: false
when: not ansible_check_mode
- name: Allow only the LAN to reach AriaNg and the token-protected API
ansible.posix.firewalld:
zone: "{{ atlas_firewalld_zone }}"
rich_rule: >-
rule family="ipv4" source address="{{ atlas_lan_subnet }}"
port port="{{ item }}" protocol="tcp" accept
permanent: true
immediate: true
state: enabled
loop:
- "{{ atlas_aria2_rpc_port }}"
- "{{ atlas_ariang_web_port }}"
- name: Keep the downloader user manager available at boot
ansible.builtin.command: "loginctl enable-linger {{ atlas_admin_username }}"
args:
creates: "/var/lib/systemd/linger/{{ atlas_admin_username }}"
- name: Render the downloader and static Web UI Quadlets
ansible.builtin.template:
src: "atlas-{{ item }}.container.j2"
dest: "{{ atlas_admin_home }}/.config/containers/systemd/atlas-{{ item }}.container"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0644"
loop: [aria2, ariang]
register: atlas_aria2_quadlets
- name: Reload the user manager after downloader Quadlet changes
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd:
scope: user
daemon_reload: true
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
when:
- atlas_aria2_quadlets.changed
- not ansible_check_mode
- name: Start or update only the changed downloader service
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd:
scope: user
name: "atlas-{{ item.item }}.service"
state: >-
{{ 'restarted' if item.changed or
(item.item == 'aria2' and atlas_aria2_config.changed | default(false))
else 'started' }}
loop: "{{ atlas_aria2_quadlets.results }}"
loop_control:
label: "atlas-{{ item.item }}.service"
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 the LAN Web UI responds
ansible.builtin.uri:
url: "http://{{ ansible_host }}:{{ atlas_ariang_web_port }}/"
status_code: 200
register: atlas_ariang_http
retries: 15
delay: 2
until: atlas_ariang_http is succeeded
when: not ansible_check_mode
- name: Verify the authenticated RPC API
ansible.builtin.uri:
url: "http://{{ ansible_host }}:{{ atlas_aria2_rpc_port }}/jsonrpc"
method: POST
body_format: json
body:
jsonrpc: "2.0"
id: ansible
method: aria2.getVersion
params: ["token:{{ atlas_aria2_rpc_secret.content | b64decode | trim }}"]
return_content: true
register: atlas_aria2_rpc_probe
retries: 15
delay: 2
until: (atlas_aria2_rpc_probe.content | default('{}') | from_json).result.version is defined
no_log: true
when: not ansible_check_mode

View 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

View File

@@ -26,6 +26,15 @@
- name: Import Atlas iCloudPD storage and boot-started Quadlet tasks - name: Import Atlas iCloudPD storage and boot-started Quadlet tasks
ansible.builtin.import_tasks: icloudpd.yml ansible.builtin.import_tasks: icloudpd.yml
- name: Import Atlas torrent service
ansible.builtin.import_tasks: qbittorrent.yml
- 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 - name: Import Atlas ZFS maintenance tasks
ansible.builtin.import_tasks: zfs_maintenance.yml ansible.builtin.import_tasks: zfs_maintenance.yml

View File

@@ -0,0 +1,186 @@
---
- name: Manage Atlas rootless qBittorrent
tags: [atlas, qbittorrent]
when: atlas_manage_qbittorrent | bool
block:
- name: Require isolated paths and a pinned image
ansible.builtin.assert:
that:
- atlas_manage_storage | bool
- atlas_qbittorrent_state_dir == atlas_app_data_mountpoint ~ '/qbittorrent'
- atlas_qbittorrent_downloads_dir == atlas_archive_mountpoint ~ '/Downloads'
- atlas_qbittorrent_image is search('@sha256:[0-9a-f]{64}$')
- name: Inspect the existing parent datasets
community.general.zfs_facts:
name: "{{ item.dataset }}"
properties: name,mounted,mountpoint
loop:
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_archive }}"
mountpoint: "{{ atlas_archive_mountpoint }}"
- dataset: "{{ atlas_zfs_pool }}/{{ atlas_zfs_dataset_app_data }}"
mountpoint: "{{ atlas_app_data_mountpoint }}"
register: atlas_qbittorrent_parents
- name: Refuse missing or unmounted parent datasets
ansible.builtin.assert:
that:
- item.ansible_facts.ansible_zfs_datasets | length == 1
- item.ansible_facts.ansible_zfs_datasets[0].mounted == 'yes'
- item.ansible_facts.ansible_zfs_datasets[0].mountpoint == item.item.mountpoint
loop: "{{ atlas_qbittorrent_parents.results }}"
loop_control:
label: "{{ item.item.dataset }}"
- name: Inspect the proposed download directory without following links
ansible.builtin.stat:
path: "{{ atlas_qbittorrent_downloads_dir }}"
follow: false
register: atlas_qbittorrent_downloads
- name: Refuse unrelated or symlinked download paths
ansible.builtin.assert:
that:
- >-
not atlas_qbittorrent_downloads.stat.exists or
(atlas_qbittorrent_downloads.stat.isdir | default(false) and
atlas_qbittorrent_downloads.stat.uid | int == atlas_admin_uid | int)
- name: Create the dedicated configuration dataset
community.general.zfs:
name: "{{ atlas_zfs_pool }}/services/data/qbittorrent"
state: present
extra_zfs_properties:
compression: zstd
mountpoint: "{{ atlas_qbittorrent_state_dir }}"
- name: Prepare private state and the SMB download directory
ansible.builtin.file:
path: "{{ item.path }}"
state: directory
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "{{ item.mode }}"
loop:
- {path: "{{ atlas_qbittorrent_state_dir }}", mode: "0700"}
- {path: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config", mode: "0700"}
- {path: "{{ atlas_qbittorrent_downloads_dir }}", mode: "0770"}
- {path: "{{ atlas_admin_home }}/.config/containers/systemd", mode: "0700"}
- name: Seed qBittorrent settings without overwriting application-managed state
ansible.builtin.template:
src: atlas-qbittorrent.conf.j2
dest: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config/qBittorrent.conf"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0600"
force: false
diff: false
- name: Allow only the declared LAN to reach the Web UI
ansible.posix.firewalld:
zone: "{{ atlas_firewalld_zone }}"
rich_rule: >-
rule family="ipv4" source address="{{ atlas_lan_subnet }}"
port port="{{ atlas_qbittorrent_web_port }}" protocol="tcp" accept
permanent: true
immediate: true
state: enabled
- name: Keep the rootless user manager available at boot
ansible.builtin.command: "loginctl enable-linger {{ atlas_admin_username }}"
args:
creates: "/var/lib/systemd/linger/{{ atlas_admin_username }}"
- name: Render the rootless torrent Quadlet
ansible.builtin.template:
src: atlas-qbittorrent.container.j2
dest: "{{ atlas_admin_home }}/.config/containers/systemd/atlas-qbittorrent.container"
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0644"
register: atlas_qbittorrent_quadlet
- name: Reload the user manager after a new or changed Quadlet
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd:
scope: user
daemon_reload: true
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
when:
- atlas_qbittorrent_quadlet.changed
- not ansible_check_mode
- name: Manage the declared qBittorrent reverse-proxy settings
when: atlas_qbittorrent_reverse_proxy_enabled | bool
block:
- name: Require a specific public domain and existing Aegis gateway
ansible.builtin.assert:
that:
- atlas_qbittorrent_public_domain is match('^[a-z0-9]+([.-][a-z0-9]+)+$')
- "'CHANGEME' not in atlas_aegis_ip"
- name: Check whether managed Web settings need an update
community.general.ini_file:
path: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config/qBittorrent.conf"
section: Preferences
option: "{{ item.key }}"
value: "{{ item.value }}"
no_extra_spaces: true
mode: "0600"
loop: "{{ atlas_qbittorrent_web_settings }}"
check_mode: true
register: atlas_qbittorrent_web_probe
no_log: true
diff: false
- name: Stop only qBittorrent before editing its application-managed settings
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd:
name: atlas-qbittorrent.service
scope: user
state: stopped
environment:
XDG_RUNTIME_DIR: "/run/user/{{ atlas_admin_uid }}"
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ atlas_admin_uid }}/bus"
when:
- atlas_qbittorrent_web_probe.changed
- not ansible_check_mode
- name: Preserve credentials and change only the declared Web settings
community.general.ini_file:
path: "{{ atlas_qbittorrent_state_dir }}/qBittorrent/config/qBittorrent.conf"
section: Preferences
option: "{{ item.key }}"
value: "{{ item.value }}"
no_extra_spaces: true
owner: "{{ atlas_admin_username }}"
group: "{{ atlas_admin_group }}"
mode: "0600"
loop: "{{ atlas_qbittorrent_web_settings }}"
when: atlas_qbittorrent_web_probe.changed
no_log: true
diff: false
- name: Start qBittorrent and restart only after a Quadlet change
become_user: "{{ atlas_admin_username }}"
ansible.builtin.systemd:
name: atlas-qbittorrent.service
scope: user
state: "{{ 'restarted' if atlas_qbittorrent_quadlet.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 the Web UI responds on the LAN address
ansible.builtin.uri:
url: "http://{{ ansible_host }}:{{ atlas_qbittorrent_web_port }}/"
status_code: 200
register: atlas_qbittorrent_http
retries: 15
delay: 2
until: atlas_qbittorrent_http is succeeded
when: not ansible_check_mode

View File

@@ -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

View File

@@ -0,0 +1,30 @@
# Managed by Ansible. Never expose this file: it contains the RPC secret.
dir=/downloads
input-file=/config/session
save-session=/config/session
save-session-interval=30
auto-save-interval=30
continue=true
allow-overwrite=false
auto-file-renaming=false
max-concurrent-downloads=1
max-connection-per-server=1
split=1
max-tries=20
retry-wait=10
connect-timeout=30
timeout=60
check-certificate=true
file-allocation=none
umask=007
enable-rpc=true
rpc-listen-all=true
rpc-listen-port=6800
rpc-allow-origin-all=true
rpc-secret={{ atlas_aria2_rpc_secret.content | b64decode | trim }}
rpc-max-request-size=2M
enable-dht=false
enable-dht6=false
enable-peer-exchange=false
bt-enable-lpd=false
console-log-level=warn

View File

@@ -0,0 +1,30 @@
# Managed by Ansible. Bypass upstream init, tracker updates and deletion hooks.
[Unit]
Description=Atlas rootless HTTP downloader
RequiresMountsFor={{ atlas_aria2_state_dir }} {{ atlas_aria2_downloads_dir }}
[Container]
ContainerName=atlas-aria2
Image={{ atlas_aria2_image }}
UserNS=keep-id
User={{ atlas_admin_uid }}
Group={{ atlas_admin_gid }}
Entrypoint=/usr/local/bin/aria2c
Exec=--conf-path=/config/aria2.conf
PublishPort={{ ansible_host }}:{{ atlas_aria2_rpc_port }}:6800
Volume={{ atlas_aria2_state_dir }}:/config:Z
Volume={{ atlas_aria2_downloads_dir }}:/downloads:z
ReadOnly=true
Tmpfs=/tmp:rw,nosuid,nodev
NoNewPrivileges=true
DropCapability=all
StopTimeout=60
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
TimeoutStopSec=90
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,22 @@
# Managed by Ansible. Static frontend only; no host data or RPC secret mounted.
[Unit]
Description=Atlas AriaNg LAN Web UI
[Container]
ContainerName=atlas-ariang
Image={{ atlas_ariang_image }}
UserNS=keep-id
User={{ atlas_admin_uid }}
Group={{ atlas_admin_gid }}
PublishPort={{ ansible_host }}:{{ atlas_ariang_web_port }}:6880
ReadOnly=true
NoNewPrivileges=true
DropCapability=all
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
[Install]
WantedBy=default.target

View File

@@ -0,0 +1,17 @@
; Seeded once by Ansible. Subsequent settings are managed through the Web UI.
[BitTorrent]
Session\DefaultSavePath=/downloads
Session\TempPath=/downloads/.incomplete
Session\TempPathEnabled=true
Session\Port=6881
[Meta]
MigrationVersion=9999
[Network]
PortForwardingEnabled=false
[Preferences]
WebUI\Port={{ atlas_qbittorrent_web_port }}
WebUI\LocalHostAuth=true
WebUI\AuthSubnetWhitelistEnabled=false
WebUI\CSRFProtection=true
WebUI\ClickjackingProtection=true
WebUI\HostHeaderValidation=true

View File

@@ -0,0 +1,33 @@
# Managed by Ansible. No VPN, host networking or router port forwarding.
[Unit]
Description=Atlas rootless qBittorrent
RequiresMountsFor={{ atlas_qbittorrent_state_dir }} {{ atlas_qbittorrent_downloads_dir }}
[Container]
ContainerName=atlas-qbittorrent
Image={{ atlas_qbittorrent_image }}
UserNS=keep-id
User={{ atlas_admin_uid }}
Group={{ atlas_admin_gid }}
PublishPort={{ ansible_host }}:{{ atlas_qbittorrent_web_port }}:{{ atlas_qbittorrent_web_port }}
Environment=QBT_LEGAL_NOTICE=confirm
Environment=QBT_WEBUI_PORT={{ atlas_qbittorrent_web_port }}
Environment=XDG_CACHE_HOME=/tmp/cache
Environment=TZ={{ atlas_timezone }}
Environment=UMASK=007
Volume={{ atlas_qbittorrent_state_dir }}:/config:Z
Volume={{ atlas_qbittorrent_downloads_dir }}:/downloads:z
ReadOnly=true
Tmpfs=/tmp:rw,nosuid,nodev
NoNewPrivileges=true
DropCapability=all
StopTimeout=1800
[Service]
Restart=on-failure
RestartSec=10
TimeoutStartSec=900
TimeoutStopSec=1900
[Install]
WantedBy=default.target

160
docs/atlas-aria2.md Normal file
View File

@@ -0,0 +1,160 @@
# Atlas HTTP downloader: aria2 + AriaNg
Ansible manages two admin-owned rootless Quadlets, `atlas-aria2.service` and
`atlas-ariang.service`, with pinned images. The third-party aria2 image is used
only for its binary: its init scripts, tracker updates and automatic deletion
hooks are bypassed. The static frontend has no host-data or credential mounts.
- Web UI (LAN only): `http://192.168.178.55:8091`.
- RPC (LAN only, mandatory secret): `http://192.168.178.55:6800/jsonrpc`.
- Payloads: `/zpool/archive/Downloads`, shared with qBittorrent and SMB Archive.
- Private state: `zpool/services/data/aria2`, mounted at `/zpool/services/data/aria2`.
- The persistent 256-bit RPC secret is generated only on Atlas; it is not committed
or printed by Ansible. It is not a username/password: AriaNg passes it as an
RPC token. Whoever has it can control the downloader.
- No DNS/NPM/public exposure or WireGuard changes are performed. Never publish
the bare RPC port on the Internet. LAN HTTP does not encrypt the token; use
only a trusted LAN or an SSH tunnel.
## Deploy
From the repository root:
```sh
ansible-playbook ansible/site.yml --limit atlas --tags aria2 --check
ansible-playbook ansible/site.yml --limit atlas --tags aria2
```
Check mode validates storage and Quadlet/firewall changes but skips generation,
reading and rendering of secret-dependent configuration and runtime probes.
Boot startup uses admin lingering plus `WantedBy=default.target`; a host reboot
must be tested separately.
## First use
Open the LAN Web UI. In **AriaNg Settings -> RPC**, use:
- Protocol: HTTP (JSON-RPC)
- Host/address: `192.168.178.55`
- Port: `6800`
- Interface/path: `jsonrpc`
- Secret: privately read it in your terminal with:
```sh
ssh admin@192.168.178.55 'cat /zpool/services/data/aria2/rpc-secret'
```
Do not paste it into chat or share exported AriaNg settings, which may include
it. After saving settings the status should be Connected. Select **New**, add
one or more actual file URLs and start the download. One download/connection at
a time is the default, to reduce load and avoid excessive requests to Apple.
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
payloads and `.aria2` control files for resume. Restarting restores pending tasks.
Resume requires server support and a valid link. Expired Apple links must be
refreshed; some downloads also require authenticated cookies or headers. Never
share full signed URLs or cookie files. Apple exports have not been tested until
new links are available. TLS certificate verification remains enabled.
No completion/error deletion hooks are enabled. Cancelling a task does not
implicitly clean payloads. Downloads remain inside the existing Archive backup
scope, including incomplete files. Session files contain URLs and are kept
private; their dataset inherits existing recursive backup/snapshot coverage.
References:
- <https://github.com/aria2/aria2>
- <https://github.com/mayswind/AriaNg>
- <https://github.com/P3TERX/Aria2-Pro-Docker>
## Verified on 2026-10-10
The pinned aria2 binary reports 1.36.0. The Web UI and authenticated RPC are
operational; RPC requests without a token are rejected. A second targeted
Ansible application reported `changed=0`, `failed=0`.
A real HTTPS smoke test downloaded the official curl 8.10.1 source archive
(2,726,748 bytes). After pausing at 1,048,576 bytes and restarting only
`atlas-aria2.service`, the saved task and partial progress were restored. The
completed file matched an independently downloaded reference by SHA-256.
Only the exact smoke-test task and its temporary payload/control files were
removed. A host reboot and authenticated Apple export downloads are not claimed.

120
docs/atlas-qbittorrent.md Normal file
View File

@@ -0,0 +1,120 @@
# Atlas qBittorrent
Atlas runs the official qBittorrent-nox image, pinned by digest, in the
admin-owned rootless `atlas-qbittorrent.service` Quadlet. No VPN is involved:
outbound traffic uses Atlas' normal home-network default route. Existing
WireGuard configuration is unchanged.
- LAN Web UI: `http://192.168.178.55:8090` (LAN-only firewalld rule,
already including Aegis at `192.168.178.54`).
- Prepared public domain: `torrent.fscotto.co`, through NPM on Prometheus.
DNS and the NPM Proxy Host remain manual operations.
- Downloads: `/zpool/archive/Downloads`, available through SMB `Archive`.
- Private configuration dataset: `zpool/services/data/qbittorrent`.
- Only configuration and Downloads are mounted in the container.
- UPnP/NAT-PMP is disabled in the initial settings. No torrent peer port is
published and no router port forwarding is configured. Outbound connections
work; inbound peer connectivity and seeding are consequently limited.
- The Web UI keeps authentication and CSRF/Host-header protection enabled.
Initial settings are seeded only once. Ansible owns only the declared Web
domain, reverse-proxy support, trusted Aegis source, and authentication/CSRF/Host
protections; it stops only qBittorrent before changing these settings and
preserves credentials and unrelated application settings.
## Deployment
From the repository root:
```sh
ansible-playbook ansible/site.yml --limit atlas --tags qbittorrent --check --diff
ansible-playbook ansible/site.yml --limit atlas --tags qbittorrent
```
The service starts at boot through `WantedBy=default.target` and admin lingering.
A real reboot must be verified separately. Only a changed Quadlet restarts the
service on subsequent playbook runs.
## First login
Username: `admin`. The application generates a temporary password at startup.
Read it privately on Atlas, without pasting it into chat:
```sh
ssh admin@192.168.178.55 'podman logs atlas-qbittorrent 2>&1 | grep "temporary password" | tail -1'
```
Set a permanent password immediately under Web UI settings. Temporary passwords
change after restarting until a permanent password is saved. LAN access uses
HTTP; do not expose this port to the Internet. An SSH tunnel may be used instead
for encrypted access.
Downloads are inside Archive and inherit its existing snapshot, Borg and offline
USB backup scope. Large downloads and incomplete files therefore affect backup
capacity. No backup exclusions or automatic deletion are introduced.
Official image documentation:
<https://github.com/qbittorrent/docker-qbittorrent-nox>
## Verified on 2026-10-10
The pinned image reports qBittorrent v5.2.4. Targeted deployment succeeded and a
second application reported `changed=0`, `failed=0`. LAN HTTP returned 200 from
Ikaros; unauthenticated API access returned 403. Authenticated API checks verified
the download paths, required authentication, Host-header/CSRF protection, and
port forwarding disabled, including after a qBittorrent service restart. Existing
Gitea, Navidrome, Syncthing and iCloudPD services remained active.
A real torrent download and a host reboot have not been tested. The initial
WebUI port mapping was corrected to use 8090 internally and externally, preserving
Host-header validation. qBittorrent 5.2 uses `[Network] PortForwardingEnabled=false`
for its persistent UPnP/NAT-PMP option.
## Manual public endpoint setup
Atlas is prepared for `torrent.fscotto.co`, with reverse-proxy support enabled
and only `192.168.178.54` (the Aegis source-NAT gateway) trusted for forwarded
client addresses. Existing LAN access remains available. No new firewall opening
is required because the existing `192.168.178.0/24` rule includes Aegis.
Before publishing, set a strong permanent Web UI password. A temporary startup
password is not suitable for a public endpoint. Do not bypass authentication for
the reverse proxy or disable CSRF/Host validation.
Namecheap:
- Type: A Record; Host: `torrent`; Value: `179.237.102.172` (Prometheus).
- Do not point this record to Atlas' private LAN address.
NPM on Prometheus:
- Domain Names: `torrent.fscotto.co`
- Scheme: `http`
- Forward Hostname/IP: `192.168.178.55`
- Forward Port: `8090`
- SSL: request/select a certificate for the domain and enable Force SSL.
- No custom Advanced configuration is needed for the currently deployed NPM:
its standard include sets `Host $host`, `X-Forwarded-Proto`, and
`X-Forwarded-For`. Host has no explicit external port, avoiding the Web UI's
internal-port validation. Do not replace it with `Host $http_host` when the
latter includes `:443`.
Reference: <https://github.com/qbittorrent/qBittorrent/wiki/NGINX-Reverse-Proxy-for-Web-UI>.
Public DNS, TLS and end-to-end login remain unverified until the manual setup is
complete. Preparing the Web proxy does not change torrent peer connectivity.
### Reverse-proxy preparation verified on 2026-10-10
The previous live domain `downloads.fscotto.co` was verified with HTTPS forwarded headers from the NPM
container on Prometheus through Aegis (HTTP 200). Unauthenticated API access is
still denied (403), and an unrelated Host is rejected (401). No DNS record,
NPM Proxy Host, certificate, router forwarding or WireGuard configuration was
changed. The existing LAN firewall rule already permits Aegis. A permanent
Web UI password still needs to be configured before public exposure.
The domain change to `torrent.fscotto.co` was subsequently applied to Atlas with
the targeted `qbittorrent` playbook tag. The old live Host allowlist caused HTTP
401 (Unauthorized) on the new public domain. After deployment, public HTTPS
returned 200 and unauthenticated API access remained denied (403). Credentials,
Host validation and CSRF protection were preserved; all existing Atlas services
remained active. DNS and NPM were not modified by this deployment.

View 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()