import 'dart:convert'; import 'package:core_models/core_models.dart'; import 'package:dio/dio.dart'; import 'auth_interceptor.dart'; import 'dio_factory.dart'; /// How a service's health endpoint should be interpreted. enum _HealthMode { /// Endpoint uses the attached auth (api key / token / query key). /// 2xx → ok, 401/403 → warning (reachable but bad creds), else → error. authed, /// Endpoint is public (no auth needed). 2xx → ok, else → error. publicEndpoint, /// We can't cheaply authenticate in a lightweight probe (cookie/login /// services), so any HTTP response - including 401/403 - proves the host is /// up. Only a transport failure is an error. reachable, /// The probe leaves with no `Authorization` header at all (see /// [anonymousRequestExtra]), because for this service a wrong password /// costs the user more than an unknown one: AdGuard Home locks an address /// out after five. A 2xx means a server with no users, a 401 or 403 means /// one that wants a sign-in; both are up. Anything else is a warning. anonymous, } /// Per-[ServiceKind] health endpoint + interpretation mode. /// /// Keeping this table here (rather than in each service module) lets the /// dashboard probe every instance uniformly without depending on all 11 /// service packages. ({String path, _HealthMode mode}) _config(ServiceKind kind) { switch (kind) { // *arr family: authed REST status endpoints. case ServiceKind.sonarr: case ServiceKind.radarr: return (path: 'api/v3/system/status', mode: _HealthMode.authed); case ServiceKind.lidarr: case ServiceKind.prowlarr: return (path: 'api/v1/system/status', mode: _HealthMode.authed); case ServiceKind.bazarr: return (path: 'api/system/status', mode: _HealthMode.authed); case ServiceKind.seerr: // `status` answers anyone, so it proves no key. `auth/me` refuses a // wrong one. A signed-in instance is probed at `status` instead; see // [_probePath]. return (path: 'api/v1/auth/me', mode: _HealthMode.authed); case ServiceKind.ombi: // Status, about and the request count answer anyone, so none of them // can prove a key works. The smallest protected read is one movie // request. return ( path: 'api/v2/Requests/movie/1/0/requestedDate/desc', mode: _HealthMode.authed, ); case ServiceKind.tracearr: return (path: 'api/v2/public/docs', mode: _HealthMode.authed); case ServiceKind.cleanuparr: return (path: 'api/status', mode: _HealthMode.authed); case ServiceKind.gluetun: // The control server answers whether or not the tunnel is up, so the // answer is read for the VPN status; see the gluetun arm of // [interpretServiceHealthResponse]. return (path: 'v1/vpn/status', mode: _HealthMode.authed); // Query-key services - AuthInterceptor appends the key as a query param. case ServiceKind.tautulli: return ( path: 'api/v2?cmd=get_server_friendly_name', mode: _HealthMode.authed, ); case ServiceKind.sabnzbd: return (path: 'api?mode=version', mode: _HealthMode.authed); // Plex: X-Plex-Token is attached; /identity returns server identity. case ServiceKind.plex: return (path: 'identity', mode: _HealthMode.authed); // Media servers expose an unauthenticated public-info endpoint. case ServiceKind.jellyfin: case ServiceKind.emby: return (path: 'System/Info/Public', mode: _HealthMode.publicEndpoint); // qBittorrent needs a session cookie we don't mint in a probe; any // response means the WebUI is up. case ServiceKind.qbittorrent: return (path: 'api/v2/app/version', mode: _HealthMode.reachable); case ServiceKind.glances: return (path: 'api/4/core', mode: _HealthMode.authed); case ServiceKind.beszel: return (path: 'api/health', mode: _HealthMode.publicEndpoint); case ServiceKind.dashdot: return (path: 'info', mode: _HealthMode.publicEndpoint); case ServiceKind.speedtestTracker: return (path: 'api/v1/results?page[size]=1', mode: _HealthMode.authed); case ServiceKind.nzbget: // JSON-RPC accepts GET for parameterless methods; Basic auth is // attached by the interceptor, so 401 means bad credentials. return (path: 'jsonrpc/version', mode: _HealthMode.authed); case ServiceKind.transmission: // The RPC endpoint answers an unprimed GET with 409 (its CSRF // rejection), which is a distinctive Transmission signature - better // evidence than the 200 a bare web root would give. A probe cannot do // the token handshake, and RPC auth is optional, so any response counts // as up. return (path: 'transmission/rpc', mode: _HealthMode.reachable); case ServiceKind.deluge: // Deluge's login is a POST, so a probe cannot authenticate cheaply. // `/json` answers GET with 405, which is a better liveness signal than // the root path: any web server returns 200 for `/`, but only Deluge's // RPC endpoint is there to refuse the method. return (path: 'json', mode: _HealthMode.reachable); case ServiceKind.rtorrent: // XML-RPC only answers POST - a GET makes the proxy in front return 502 // whether the daemon is alive or dead, which is no signal at all. So this // is the one kind the probe POSTs (see [_probeBody]), and a real // `methodResponse` is required for ok. return (path: '', mode: _HealthMode.authed); case ServiceKind.unraid: // The only API Unraid exposes is GraphQL on one endpoint, so the probe // POSTs the cheapest query there is rather than fetching a status page. return (path: 'graphql', mode: _HealthMode.authed); case ServiceKind.navidrome: // Subsonic's ping, with the credentials the interceptor attaches as // query parameters. `authed` rather than `reachable` because the // response is only worth anything once the envelope has been read; // see the navidrome arm of [interpretServiceHealthResponse]. return (path: 'rest/ping.view', mode: _HealthMode.authed); case ServiceKind.myspeed: return (path: 'api/speedtests', mode: _HealthMode.authed); case ServiceKind.adguardHome: // Any signed route would do for a liveness check, but this one must // not be signed: see [_HealthMode.anonymous]. So the dot cannot tell a // wrong password from a right one, by design. return (path: 'control/status', mode: _HealthMode.anonymous); case ServiceKind.aria2: // aria2's only interface is its JSON-RPC endpoint, so the probe POSTs // a call there. The daemon answers a wrong `--rpc-secret` with HTTP // 400 and an `error` envelope, which the `authed` reading turns into // a warning - the host is up, the secret is not. return (path: 'jsonrpc', mode: _HealthMode.authed); case ServiceKind.slskd: return (path: 'api/v0/application', mode: _HealthMode.authed); case ServiceKind.gotify: // `health` and `version` answer anyone; `current/user` refuses a wrong // token, and an application token too, which cannot read messages. return (path: 'current/user', mode: _HealthMode.authed); } } /// The path to probe [instance] at, where its auth changes it. /// /// A Seerr signed in as a user has no key to send, only a session, and the /// probe must not sign in: it runs on every dashboard refresh, and with a /// wrong password each sign-in reaches Jellyfin or Emby, which lock an /// account after a few. So the probe asks the public `status` and proves only /// that Seerr is up; the Seerr screens report a refused sign-in. String _probePath(Instance instance, String path) => instance.kind == ServiceKind.seerr && instance.auth is! InstanceAuthApiKey ? 'api/v1/status' : path; /// The request body to POST for [instance], or null to probe with a plain GET. /// /// Only rTorrent, Unraid and aria2 need this: none of them has a GET-able /// status endpoint, so the probe sends the cheapest call there is. String? _probeBody(Instance instance) => switch (instance.kind) { ServiceKind.rtorrent => '' 'system.client_version' '', // GraphQL has no status route. `__typename` is the smallest legal query // and answers on any schema, so it costs the server nothing. ServiceKind.unraid => '{"query":"{__typename}"}', ServiceKind.aria2 => _aria2ProbeBody(instance), _ => null, }; /// The JSON-RPC body of an aria2 liveness probe. /// /// `aria2.getVersion` is the cheapest call there is: it touches no download /// and returns the daemon's version. The secret goes in as the first /// parameter, prefixed with `token:`, exactly as the daemon expects - a /// daemon started without `--rpc-secret` answers anyone, so the parameter is /// left out entirely then. String _aria2ProbeBody(Instance instance) { final String secret = switch (instance.auth) { InstanceAuthApiKey(:final String apiKey) => apiKey, InstanceAuthUserPass() || InstanceAuthPlex() || InstanceAuthCookie() => '', }; return jsonEncode({ 'jsonrpc': '2.0', 'id': 'atrium', 'method': 'aria2.getVersion', 'params': secret.isEmpty ? [] : ['token:$secret'], }); } /// Content type for the probe body. /// /// rTorrent speaks XML-RPC; GraphQL refuses anything that is not JSON, so the /// two POST probes cannot share one header. String _probeContentType(ServiceKind kind) => switch (kind) { ServiceKind.unraid => Headers.jsonContentType, ServiceKind.aria2 => Headers.jsonContentType, _ => 'text/xml', }; /// Whether [kind] is probed with no `Authorization` header. /// /// Public for a test that pins it to the one kind that needs it. bool probesAnonymously(ServiceKind kind) => _config(kind).mode == _HealthMode.anonymous; /// Probes the real health of a configured [Instance]. /// /// Unlike a blind `GET /` (which treats a 404 or a login page as "up"), this /// hits the service's own status endpoint with its real auth and returns a /// [Health] the dashboard can trust: /// /// * [Health.ok] - reachable and the credentials work. /// * [Health.warning] - reachable but the API key / token was rejected /// (so the user knows to fix it), the server answered 5xx, or it reports a /// problem of its own, such as Gluetun's VPN being down. /// * [Health.error] - could not reach the server at all. class HealthProbe { HealthProbe({required DioFactory dioFactory}) : _dioFactory = dioFactory; final DioFactory _dioFactory; /// Probes [instance]; see [interpretServiceHealthResponse] for /// [connectionOnly]. Future check(Instance instance, {bool connectionOnly = false}) async { final ({String path, _HealthMode mode}) cfg = _config(instance.kind); Dio? dio; try { dio = await _dioFactory.create(instance); final String? body = _probeBody(instance); final Options options = Options( validateStatus: (_) => true, extra: cfg.mode == _HealthMode.anonymous ? {anonymousRequestExtra: true} : null, receiveTimeout: const Duration(seconds: 8), contentType: body == null ? null : _probeContentType(instance.kind), responseType: body == null ? null : ResponseType.plain, ); final String path = _probePath(instance, cfg.path); final Response resp = body == null ? await dio.get(path, options: options) : await dio.post(path, data: body, options: options); final int status = resp.statusCode ?? 0; return interpretServiceHealthResponse( instance.kind, status, resp.data, contentType: resp.headers.value(Headers.contentTypeHeader), connectionOnly: connectionOnly, ); } on DioException { return Health.error; } on Object { return Health.error; } finally { dio?.close(force: true); } } } /// Interprets a completed HTTP health response without retaining or exposing /// its body. Public for focused tests; callers should normally use /// [HealthProbe]. /// /// With [connectionOnly], only whether the server answered and accepted the /// credentials counts, not what it reports about itself. Test connection /// passes it: a Gluetun whose VPN is stopped still has the right URL and key. Health interpretServiceHealthResponse( ServiceKind kind, int status, Object? data, { String? contentType, bool connectionOnly = false, }) { if (status == 0) { return Health.error; } // A page where an API should be. // // Every health endpoint here answers with JSON, or XML-RPC in rTorrent's // case. None answer with a web page. A forward-auth proxy redirects an // unauthenticated request to its login portal, the probe follows the // redirect as any client would, and the portal returns a perfectly healthy // 200 full of markup. Status alone cannot tell that apart from a working // server, so a login page was being reported as Online. // // Read from the content type rather than the body: Authelia's portal opens // with a licence comment, so looking for a leading = 200 && status < 300 && (contentType?.toLowerCase().contains('text/html') ?? false)) { return Health.warning; } final _HealthMode mode = _config(kind).mode; switch (mode) { case _HealthMode.authed: if (status >= 200 && status < 300) { if (kind == ServiceKind.speedtestTracker && !_isSpeedtestResultsEnvelope(data)) { // The host answered, but not with the authenticated API contract. return Health.warning; } if (kind == ServiceKind.unraid && !'$data'.contains('__typename')) { // GraphQL answers 200 even when it refuses the key, so the status // alone would call a bad key healthy. The echoed __typename is the // proof the query actually ran. return Health.warning; } if (kind == ServiceKind.navidrome && !_subsonicSaysOk(data)) { // Subsonic never reports an error through the HTTP status. A // healthy server, a rejected password and a malformed request all // answer 200 with JSON; only the `status` inside the envelope // tells them apart. Verified against Navidrome 0.64: a wrong // password is 200 with status failed and error code 40, and an // unauthenticated request is 200 with code 10. Without this the // dot stayed green for both. return Health.warning; } if (kind == ServiceKind.gluetun) { final String? vpn = _gluetunVpnStatus(data); if (vpn == null) { // Something answered on the status route, but not with Gluetun's // status object. return Health.warning; } if (!connectionOnly && vpn.toLowerCase() != 'running') { // Gluetun answers 200 whether or not the tunnel is up, so the // status code alone showed a stopped VPN as Online. Everything // routed through Gluetun is cut off while it is down, which is // the one thing this dot should not hide. return Health.warning; } } if (kind == ServiceKind.rtorrent && !'$data'.contains('methodResponse')) { // A 200 from the web UI or a proxy landing page is not the XML-RPC // endpoint, so the URL is pointed at the wrong place. return Health.warning; } if (kind == ServiceKind.aria2 && !_aria2SaysOk(data)) { // If a reverse proxy or RPC gateway returns 200 with an `error` // envelope or missing `result` map rather than the version payload, // ensure it flags a warning rather than falsely reporting healthy. return Health.warning; } return Health.ok; } // 401/403, API-level 4xx, redirects, and 5xx all prove the host answered // while indicating credentials, compatibility, or server health needs // attention. return Health.warning; case _HealthMode.publicEndpoint: return (status >= 200 && status < 300) ? Health.ok : Health.error; case _HealthMode.reachable: return Health.ok; case _HealthMode.anonymous: final bool answeredAsItself = (status >= 200 && status < 300) || status == 401 || status == 403; return answeredAsItself ? Health.ok : Health.warning; } } bool _isSpeedtestResultsEnvelope(Object? data) => data is Map && data['data'] is List; /// Whether an aria2 JSON-RPC answer proves the daemon is there. /// /// The probe asks for `aria2.getVersion`. While aria2 rejects a refused secret /// with HTTP 400, some reverse proxies or RPC gateways reply with HTTP 200 and /// an `error` envelope. `_aria2SaysOk` ensures only a valid `result` envelope /// is accepted as healthy. bool _aria2SaysOk(Object? data) { Object? body = data; if (body is String) { try { body = jsonDecode(body); } on FormatException { return false; } } if (body is! Map) { return false; } if (body['error'] != null) { return false; } return body['result'] is Map; } /// The VPN status in a Gluetun answer, or null if [data] is not one. /// /// Gluetun labels its JSON `text/plain`, so the body normally arrives as a /// string to decode here rather than as a map. String? _gluetunVpnStatus(Object? data) { Object? body = data; if (body is String) { try { body = jsonDecode(body); } on FormatException { return null; } } if (body is! Map) { return null; } final Object? status = body['status']; return status is String ? status : null; } /// Whether a Subsonic reply actually succeeded. /// /// Every response is wrapped in a `subsonic-response` object carrying a /// `status` of `ok` or `failed`. Anything that is not a recognisable envelope /// saying `ok` is treated as a failure, which also covers the case of some /// other server answering on that URL. bool _subsonicSaysOk(Object? data) { if (data is! Map) { return false; } final Object? envelope = data['subsonic-response']; return envelope is Map && envelope['status'] == 'ok'; }