From 449bb6fd6aac9f87a9302bdbcc84f6e2b59f1009 Mon Sep 17 00:00:00 2001 From: Gabriel20xx Date: Thu, 3 Sep 2026 21:46:53 +0200 Subject: [PATCH] Auto-detect scheme for AUTHGUARD_URL instead of always assuming https A bare host:port (e.g. a LAN AuthGuard reachable only over plain HTTP) was always defaulting to https, so a TLS handshake against a plain-HTTP AuthGuard failed at the transport level. Now a loopback, RFC1918/RFC4193 private, or link-local host (or a .local name) defaults to http instead; an explicit http:// or https:// is still always honored as-is. Co-Authored-By: Claude Sonnet 5 --- backend/authclient/client.go | 37 +++++++++++- backend/authclient/client_test.go | 18 ++++-- .../gabriel20xx/shared/auth/AuthClient.java | 59 +++++++++++++++++-- .../shared/auth/AuthClientTest.java | 23 +++++++- packages/node-backend/src/authclient.js | 50 ++++++++++++++-- packages/node-backend/test/authclient.test.js | 21 ++++++- .../src/shared_backend/authclient.py | 41 +++++++++++-- .../python-backend/tests/test_authclient.py | 19 +++++- 8 files changed, 241 insertions(+), 27 deletions(-) diff --git a/backend/authclient/client.go b/backend/authclient/client.go index 9ad727b..7cb10d8 100644 --- a/backend/authclient/client.go +++ b/backend/authclient/client.go @@ -20,6 +20,7 @@ import ( "errors" "fmt" "io" + "net" "net/http" "strings" "time" @@ -77,9 +78,11 @@ func WithCookieName(name string) Option { // New creates a Client for the AuthServer instance at baseURL. baseURL may // be given without a scheme (e.g. "auth.example.com" or "192.168.1.50:8080") -// - "https://" is assumed in that case, so a deployment only needs to name -// the host, not repeat the scheme; an explicit "http://" (for a plain-HTTP -// local/LAN AuthServer) is left as-is. +// - the scheme is then inferred from the host: a loopback, RFC1918/RFC4193 +// private, or link-local address, or a ".local" name, defaults to "http://" +// (a plain-HTTP AuthServer on a local network is the common case for those), +// anything else defaults to "https://". An explicit "http://" or "https://" +// is always left as-is, overriding the inference. func New(baseURL string, opts ...Option) *Client { c := &Client{ baseURL: normalizeBaseURL(baseURL), @@ -101,9 +104,37 @@ func normalizeBaseURL(baseURL string) string { if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") { return trimmed } + if isPrivateHost(trimmed) { + return "http://" + trimmed + } return "https://" + trimmed } +// isPrivateHost reports whether hostport (a bare "host" or "host:port", no +// scheme) names a loopback, RFC1918/RFC4193 private, or link-local address, +// or a ".local" mDNS name -- the kind of host a plain-HTTP AuthServer is +// typically reachable at on a local network, as opposed to a public hostname +// expected to terminate TLS itself. Never performs DNS resolution: only +// literal IPs and the "localhost"/".local" names are recognized, so a real +// public hostname that merely happens to resolve to a private address still +// defaults to https. +func isPrivateHost(hostport string) bool { + host := hostport + if h, _, err := net.SplitHostPort(hostport); err == nil { + host = h + } + host = strings.Trim(host, "[]") + lower := strings.ToLower(host) + if lower == "localhost" || strings.HasSuffix(lower, ".local") { + return true + } + ip := net.ParseIP(host) + if ip == nil { + return false + } + return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() +} + // Validate calls AuthServer's GET /api/session/validate with token as a // Bearer credential and returns the resolved user. It returns // ErrInvalidSession (wrapped) when AuthServer reports the session as not diff --git a/backend/authclient/client_test.go b/backend/authclient/client_test.go index 0d8cbe9..2cd2a54 100644 --- a/backend/authclient/client_test.go +++ b/backend/authclient/client_test.go @@ -14,10 +14,20 @@ func TestNewNormalizesBaseURL(t *testing.T) { input string want string }{ - {name: "bare host gets https", input: "auth.example.com", want: "https://auth.example.com"}, - {name: "bare host:port gets https", input: "192.168.1.50:8080", want: "https://192.168.1.50:8080"}, - {name: "explicit http is left alone", input: "http://auth.example.com", want: "http://auth.example.com"}, - {name: "explicit https is left alone", input: "https://auth.example.com", want: "https://auth.example.com"}, + {name: "bare public host gets https", input: "auth.example.com", want: "https://auth.example.com"}, + {name: "bare private host:port gets http", input: "192.168.1.50:8080", want: "http://192.168.1.50:8080"}, + {name: "bare public host:port gets https", input: "auth.example.com:8080", want: "https://auth.example.com:8080"}, + {name: "loopback IPv4 gets http", input: "127.0.0.1:8080", want: "http://127.0.0.1:8080"}, + {name: "10/8 private range gets http", input: "10.1.2.3:8080", want: "http://10.1.2.3:8080"}, + {name: "172.16/12 private range gets http", input: "172.20.0.5:8080", want: "http://172.20.0.5:8080"}, + {name: "172.x outside the 16-31 private range gets https", input: "172.32.0.5:8080", want: "https://172.32.0.5:8080"}, + {name: "link-local IPv4 gets http", input: "169.254.1.1:8080", want: "http://169.254.1.1:8080"}, + {name: "localhost name gets http", input: "localhost:8080", want: "http://localhost:8080"}, + {name: ".local mDNS name gets http", input: "authguard.local:8080", want: "http://authguard.local:8080"}, + {name: "loopback IPv6 gets http", input: "[::1]:8080", want: "http://[::1]:8080"}, + {name: "unique-local IPv6 gets http", input: "[fd00::1]:8080", want: "http://[fd00::1]:8080"}, + {name: "explicit http is left alone even for a public host", input: "http://auth.example.com", want: "http://auth.example.com"}, + {name: "explicit https is left alone even for a private host", input: "https://192.168.1.50:8080", want: "https://192.168.1.50:8080"}, {name: "scheme match is case-insensitive", input: "HTTP://auth.example.com", want: "HTTP://auth.example.com"}, {name: "trailing slash stripped before scheme check", input: "auth.example.com/", want: "https://auth.example.com"}, {name: "surrounding whitespace trimmed", input: " auth.example.com ", want: "https://auth.example.com"}, diff --git a/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java b/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java index 2831cc5..5165c6a 100644 --- a/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java +++ b/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/AuthClient.java @@ -681,10 +681,13 @@ public final class AuthClient { /** * Trims {@code baseUrl}, strips a trailing slash, and - if the result has - * no scheme - assumes {@code https://}, so a deployment only needs to - * name the host (e.g. {@code "auth.example.com"} or - * {@code "192.168.1.50:8080"}), not repeat the scheme. An explicit - * {@code http://} (for a plain-HTTP local/LAN AuthGuard) is left as-is. + * no scheme - infers one from the host: a loopback, RFC1918/RFC4193 + * private, or link-local address, or a {@code ".local"} name, defaults to + * {@code http://} (a plain-HTTP AuthGuard on a local network is the + * common case for those); anything else, including a plain hostname like + * {@code "auth.example.com"}, defaults to {@code https://}. An explicit + * {@code http://} or {@code https://} is always left as-is, overriding + * the inference. */ private static String normalizeBaseUrl(String baseUrl) { String trimmed = baseUrl == null ? "" : baseUrl.trim(); @@ -698,7 +701,53 @@ public final class AuthClient { if (lower.startsWith("http://") || lower.startsWith("https://")) { return trimmed; } - return "https://" + trimmed; + return (isPrivateHost(trimmed) ? "http://" : "https://") + trimmed; + } + + private static final Pattern IPV4_PATTERN = Pattern.compile("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"); + private static final Pattern IPV6_UNIQUE_LOCAL_PATTERN = Pattern.compile("^f[cd][0-9a-f]{2}:.*$"); + + /** + * Reports whether {@code hostPort} (a bare {@code "host"} or + * {@code "host:port"}, no scheme) names a loopback, RFC1918/RFC4193 + * private, or link-local address, or a {@code ".local"} mDNS name - the + * kind of host a plain-HTTP AuthGuard is typically reachable at on a + * local network, as opposed to a public hostname expected to terminate + * TLS itself. Never performs DNS resolution: only literal IPs and the + * {@code "localhost"}/{@code ".local"} names are recognized, so a real + * public hostname that merely happens to resolve to a private address + * still defaults to https. + */ + private static boolean isPrivateHost(String hostPort) { + String host = hostPort; + if (host.startsWith("[")) { + int end = host.indexOf(']'); + if (end != -1) { + host = host.substring(1, end); + } + } else { + int idx = host.indexOf(':'); + if (idx != -1 && idx == host.lastIndexOf(':')) { + String portPart = host.substring(idx + 1); + if (!portPart.isEmpty() && portPart.chars().allMatch(Character::isDigit)) { + host = host.substring(0, idx); + } + } + } + String lower = host.toLowerCase(Locale.ROOT); + if (lower.equals("localhost") || lower.endsWith(".local")) { + return true; + } + Matcher ipv4Matcher = IPV4_PATTERN.matcher(lower); + if (ipv4Matcher.matches()) { + int a = Integer.parseInt(ipv4Matcher.group(1)); + int b = Integer.parseInt(ipv4Matcher.group(2)); + return a == 127 || a == 10 || (a == 172 && b >= 16 && b <= 31) || (a == 192 && b == 168) || (a == 169 && b == 254); + } + if (lower.equals("::1")) { + return true; + } + return lower.startsWith("fe80:") || IPV6_UNIQUE_LOCAL_PATTERN.matcher(lower).matches(); } private static String readAll(InputStream in) throws IOException { diff --git a/packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java b/packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java index ccfc7bb..0815359 100644 --- a/packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java +++ b/packages/java-backend/src/test/java/com/gabriel20xx/shared/auth/AuthClientTest.java @@ -38,9 +38,27 @@ class AuthClientTest { } @Test - void constructorAssumesHttpsForABareHost() { + void constructorAssumesHttpsForABarePublicHost() { assertEquals("https://auth.example.com", new AuthClient("auth.example.com").baseUrlForTest()); - assertEquals("https://192.168.1.50:8080", new AuthClient("192.168.1.50:8080").baseUrlForTest()); + assertEquals("https://auth.example.com:8080", new AuthClient("auth.example.com:8080").baseUrlForTest()); + } + + @Test + void constructorAssumesHttpForABarePrivateHost() { + assertEquals("http://192.168.1.50:8080", new AuthClient("192.168.1.50:8080").baseUrlForTest()); + assertEquals("http://10.1.2.3:8080", new AuthClient("10.1.2.3:8080").baseUrlForTest()); + assertEquals("http://172.20.0.5:8080", new AuthClient("172.20.0.5:8080").baseUrlForTest()); + assertEquals("http://127.0.0.1:8080", new AuthClient("127.0.0.1:8080").baseUrlForTest()); + assertEquals("http://169.254.1.1:8080", new AuthClient("169.254.1.1:8080").baseUrlForTest()); + assertEquals("http://localhost:8080", new AuthClient("localhost:8080").baseUrlForTest()); + assertEquals("http://authguard.local:8080", new AuthClient("authguard.local:8080").baseUrlForTest()); + assertEquals("http://[::1]:8080", new AuthClient("[::1]:8080").baseUrlForTest()); + assertEquals("http://[fd00::1]:8080", new AuthClient("[fd00::1]:8080").baseUrlForTest()); + } + + @Test + void constructorAssumesHttpsFor172RangeOutsidePrivateBlock() { + assertEquals("https://172.32.0.5:8080", new AuthClient("172.32.0.5:8080").baseUrlForTest()); } @Test @@ -48,6 +66,7 @@ class AuthClientTest { assertEquals("http://auth.example.com", new AuthClient("http://auth.example.com").baseUrlForTest()); assertEquals("https://auth.example.com", new AuthClient("https://auth.example.com").baseUrlForTest()); assertEquals("HTTP://auth.example.com", new AuthClient("HTTP://auth.example.com").baseUrlForTest()); + assertEquals("https://192.168.1.50:8080", new AuthClient("https://192.168.1.50:8080").baseUrlForTest()); } @Test diff --git a/packages/node-backend/src/authclient.js b/packages/node-backend/src/authclient.js index 70bcf32..81f0f82 100644 --- a/packages/node-backend/src/authclient.js +++ b/packages/node-backend/src/authclient.js @@ -58,9 +58,11 @@ export class AuthClient { /** * @param {string} baseUrl - AuthGuard's base URL (e.g. from AUTHGUARD_URL), no trailing slash required. * May be given without a scheme (e.g. "auth.example.com" or "192.168.1.50:8080") - - * "https://" is assumed in that case, so a deployment only needs to name the - * host, not repeat the scheme; an explicit "http://" (for a plain-HTTP - * local/LAN AuthGuard) is left as-is. + * the scheme is then inferred from the host: a loopback, RFC1918/RFC4193 private, + * or link-local address, or a ".local" name, defaults to "http://" (a plain-HTTP + * AuthGuard on a local network is the common case for those), anything else + * defaults to "https://". An explicit "http://" or "https://" is always left + * as-is, overriding the inference. * @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options] */ constructor(baseUrl, options = {}) { @@ -73,7 +75,47 @@ export class AuthClient { static _normalizeBaseUrl(baseUrl) { const trimmed = String(baseUrl ?? '').trim().replace(/\/+$/, ''); if (!trimmed) return trimmed; - return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`; + if (/^https?:\/\//i.test(trimmed)) return trimmed; + return AuthClient._isPrivateHost(trimmed) ? `http://${trimmed}` : `https://${trimmed}`; + } + + /** + * Reports whether hostport (a bare "host" or "host:port", no scheme) names + * a loopback, RFC1918/RFC4193 private, or link-local address, or a + * ".local" mDNS name - the kind of host a plain-HTTP AuthGuard is + * typically reachable at on a local network, as opposed to a public + * hostname expected to terminate TLS itself. Never performs DNS + * resolution: only literal IPs and the "localhost"/".local" names are + * recognized, so a real public hostname that merely happens to resolve to + * a private address still defaults to https. + */ + static _isPrivateHost(hostport) { + let host = hostport; + if (host.startsWith('[')) { + const end = host.indexOf(']'); + if (end !== -1) host = host.slice(1, end); + } else { + const parts = host.split(':'); + if (parts.length === 2 && /^\d+$/.test(parts[1])) host = parts[0]; + } + host = host.toLowerCase(); + if (host === 'localhost' || host.endsWith('.local')) return true; + const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); + if (ipv4) { + const a = Number(ipv4[1]); + const b = Number(ipv4[2]); + return ( + a === 127 || + a === 10 || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) || + (a === 169 && b === 254) + ); + } + if (host === '::1') return true; + if (/^fe80:/.test(host)) return true; + if (/^f[cd][0-9a-f]{2}:/.test(host)) return true; + return false; } // --- session validation (the original, minimal surface) ----------------- diff --git a/packages/node-backend/test/authclient.test.js b/packages/node-backend/test/authclient.test.js index 5db2c75..071ae35 100644 --- a/packages/node-backend/test/authclient.test.js +++ b/packages/node-backend/test/authclient.test.js @@ -31,15 +31,32 @@ function recordingFetch(responses) { return wrapped; } -test('constructor assumes https for a bare host', () => { +test('constructor assumes https for a bare public host', () => { assert.equal(new AuthClient('auth.example.com').baseUrl, 'https://auth.example.com'); - assert.equal(new AuthClient('192.168.1.50:8080').baseUrl, 'https://192.168.1.50:8080'); + assert.equal(new AuthClient('auth.example.com:8080').baseUrl, 'https://auth.example.com:8080'); +}); + +test('constructor assumes http for a bare private/loopback/link-local host', () => { + assert.equal(new AuthClient('192.168.1.50:8080').baseUrl, 'http://192.168.1.50:8080'); + assert.equal(new AuthClient('10.1.2.3:8080').baseUrl, 'http://10.1.2.3:8080'); + assert.equal(new AuthClient('172.20.0.5:8080').baseUrl, 'http://172.20.0.5:8080'); + assert.equal(new AuthClient('127.0.0.1:8080').baseUrl, 'http://127.0.0.1:8080'); + assert.equal(new AuthClient('169.254.1.1:8080').baseUrl, 'http://169.254.1.1:8080'); + assert.equal(new AuthClient('localhost:8080').baseUrl, 'http://localhost:8080'); + assert.equal(new AuthClient('authguard.local:8080').baseUrl, 'http://authguard.local:8080'); + assert.equal(new AuthClient('[::1]:8080').baseUrl, 'http://[::1]:8080'); + assert.equal(new AuthClient('[fd00::1]:8080').baseUrl, 'http://[fd00::1]:8080'); +}); + +test('constructor assumes https for a 172.x address outside the 16-31 private range', () => { + assert.equal(new AuthClient('172.32.0.5:8080').baseUrl, 'https://172.32.0.5:8080'); }); test('constructor leaves an explicit scheme alone', () => { assert.equal(new AuthClient('http://auth.example.com').baseUrl, 'http://auth.example.com'); assert.equal(new AuthClient('https://auth.example.com').baseUrl, 'https://auth.example.com'); assert.equal(new AuthClient('HTTP://auth.example.com').baseUrl, 'HTTP://auth.example.com'); + assert.equal(new AuthClient('https://192.168.1.50:8080').baseUrl, 'https://192.168.1.50:8080'); }); test('constructor strips a trailing slash before checking the scheme', () => { diff --git a/packages/python-backend/src/shared_backend/authclient.py b/packages/python-backend/src/shared_backend/authclient.py index 175ee50..a886f76 100644 --- a/packages/python-backend/src/shared_backend/authclient.py +++ b/packages/python-backend/src/shared_backend/authclient.py @@ -49,6 +49,7 @@ concrete Response object and knows how to attach headers to it. from __future__ import annotations import asyncio +import ipaddress import json import urllib.error import urllib.request @@ -67,7 +68,34 @@ def _normalize_base_url(base_url: str) -> str: return trimmed if trimmed.lower().startswith(("http://", "https://")): return trimmed - return f"https://{trimmed}" + return f"http://{trimmed}" if _is_private_host(trimmed) else f"https://{trimmed}" + + +def _is_private_host(hostport: str) -> bool: + """Reports whether hostport (a bare "host" or "host:port", no scheme) + names a loopback, RFC1918/RFC4193 private, or link-local address, or a + ".local" mDNS name -- the kind of host a plain-HTTP AuthGuard is + typically reachable at on a local network, as opposed to a public + hostname expected to terminate TLS itself. Never performs DNS + resolution: only literal IPs and the "localhost"/".local" names are + recognized, so a real public hostname that merely happens to resolve to + a private address still defaults to https. + """ + host = hostport + if host.startswith("["): + end = host.find("]") + if end != -1: + host = host[1:end] + elif host.count(":") == 1: + host = host.split(":", 1)[0] + host = host.strip().lower() + if host == "localhost" or host.endswith(".local"): + return True + try: + ip = ipaddress.ip_address(host) + except ValueError: + return False + return ip.is_loopback or ip.is_private or ip.is_link_local class InvalidSessionError(Exception): @@ -180,10 +208,13 @@ class AuthClient: ) -> None: """base_url is AuthGuard's base URL, e.g. "https://auth.example.com" (no trailing slash required). May be given without a scheme (e.g. - "auth.example.com" or "192.168.1.50:8080") -- "https://" is assumed - in that case, so a deployment only needs to name the host, not repeat - the scheme; an explicit "http://" (for a plain-HTTP local/LAN - AuthGuard) is left as-is. cookie_name is the cookie + "auth.example.com" or "192.168.1.50:8080") -- the scheme is then + inferred from the host: a loopback, RFC1918/RFC4193 private, or + link-local address, or a ".local" name, defaults to "http://" (a + plain-HTTP AuthGuard on a local network is the common case for + those), anything else defaults to "https://". An explicit "http://" + or "https://" is always left as-is, overriding the inference. + cookie_name is the cookie token_from_request looks for when there is no Authorization header; it must match AuthGuard's SessionCookieName. timeout is the request timeout in seconds for the underlying blocking HTTP call.""" diff --git a/packages/python-backend/tests/test_authclient.py b/packages/python-backend/tests/test_authclient.py index 52acf04..8dfbfe5 100644 --- a/packages/python-backend/tests/test_authclient.py +++ b/packages/python-backend/tests/test_authclient.py @@ -50,14 +50,29 @@ def _fake_http_error(status: int, payload: dict) -> urllib.error.HTTPError: class AuthClientBaseUrlTests(unittest.TestCase): - def test_bare_host_assumes_https(self) -> None: + def test_bare_public_host_assumes_https(self) -> None: self.assertEqual(AuthClient("auth.example.com").base_url, "https://auth.example.com") - self.assertEqual(AuthClient("192.168.1.50:8080").base_url, "https://192.168.1.50:8080") + self.assertEqual(AuthClient("auth.example.com:8080").base_url, "https://auth.example.com:8080") + + def test_bare_private_host_assumes_http(self) -> None: + self.assertEqual(AuthClient("192.168.1.50:8080").base_url, "http://192.168.1.50:8080") + self.assertEqual(AuthClient("10.1.2.3:8080").base_url, "http://10.1.2.3:8080") + self.assertEqual(AuthClient("172.20.0.5:8080").base_url, "http://172.20.0.5:8080") + self.assertEqual(AuthClient("127.0.0.1:8080").base_url, "http://127.0.0.1:8080") + self.assertEqual(AuthClient("169.254.1.1:8080").base_url, "http://169.254.1.1:8080") + self.assertEqual(AuthClient("localhost:8080").base_url, "http://localhost:8080") + self.assertEqual(AuthClient("authguard.local:8080").base_url, "http://authguard.local:8080") + self.assertEqual(AuthClient("[::1]:8080").base_url, "http://[::1]:8080") + self.assertEqual(AuthClient("[fd00::1]:8080").base_url, "http://[fd00::1]:8080") + + def test_172_range_outside_private_block_assumes_https(self) -> None: + self.assertEqual(AuthClient("172.32.0.5:8080").base_url, "https://172.32.0.5:8080") def test_explicit_scheme_left_alone(self) -> None: self.assertEqual(AuthClient("http://auth.example.com").base_url, "http://auth.example.com") self.assertEqual(AuthClient("https://auth.example.com").base_url, "https://auth.example.com") self.assertEqual(AuthClient("HTTP://auth.example.com").base_url, "HTTP://auth.example.com") + self.assertEqual(AuthClient("https://192.168.1.50:8080").base_url, "https://192.168.1.50:8080") def test_trailing_slash_stripped_before_scheme_check(self) -> None: self.assertEqual(AuthClient("auth.example.com/").base_url, "https://auth.example.com")