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 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Sonnet 5 committed 2026-09-03 21:48:08 +02:00
1 parent c29520fcd3
commit 40578f5392
8 files changed
+241 -27

No files matched your search

@@ -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 {
@@ -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
+46 -4
View File
@@ -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) -----------------
@@ -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', () => {
@@ -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."""
@@ -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")