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:
1 parent
730bf0463f
commit
449bb6fd6a
8 files changed
+241
-27
No files matched your search
@@ -20,6 +20,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -77,9 +78,11 @@ func WithCookieName(name string) Option {
|
|||||||
|
|
||||||
// New creates a Client for the AuthServer instance at baseURL. baseURL may
|
// 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")
|
// 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 scheme is then inferred from the host: a loopback, RFC1918/RFC4193
|
||||||
// the host, not repeat the scheme; an explicit "http://" (for a plain-HTTP
|
// private, or link-local address, or a ".local" name, defaults to "http://"
|
||||||
// local/LAN AuthServer) is left as-is.
|
// (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 {
|
func New(baseURL string, opts ...Option) *Client {
|
||||||
c := &Client{
|
c := &Client{
|
||||||
baseURL: normalizeBaseURL(baseURL),
|
baseURL: normalizeBaseURL(baseURL),
|
||||||
@@ -101,9 +104,37 @@ func normalizeBaseURL(baseURL string) string {
|
|||||||
if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") {
|
if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") {
|
||||||
return trimmed
|
return trimmed
|
||||||
}
|
}
|
||||||
|
if isPrivateHost(trimmed) {
|
||||||
|
return "http://" + trimmed
|
||||||
|
}
|
||||||
return "https://" + 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
|
// Validate calls AuthServer's GET /api/session/validate with token as a
|
||||||
// Bearer credential and returns the resolved user. It returns
|
// Bearer credential and returns the resolved user. It returns
|
||||||
// ErrInvalidSession (wrapped) when AuthServer reports the session as not
|
// ErrInvalidSession (wrapped) when AuthServer reports the session as not
|
||||||
|
|||||||
@@ -14,10 +14,20 @@ func TestNewNormalizesBaseURL(t *testing.T) {
|
|||||||
input string
|
input string
|
||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{name: "bare host gets https", input: "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 host:port gets https", input: "192.168.1.50:8080", want: "https://192.168.1.50:8080"},
|
{name: "bare private host:port gets http", input: "192.168.1.50:8080", want: "http://192.168.1.50:8080"},
|
||||||
{name: "explicit http is left alone", input: "http://auth.example.com", want: "http://auth.example.com"},
|
{name: "bare public host:port gets https", input: "auth.example.com:8080", want: "https://auth.example.com:8080"},
|
||||||
{name: "explicit https is left alone", input: "https://auth.example.com", want: "https://auth.example.com"},
|
{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: "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: "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"},
|
{name: "surrounding whitespace trimmed", input: " auth.example.com ", want: "https://auth.example.com"},
|
||||||
|
|||||||
@@ -681,10 +681,13 @@ public final class AuthClient {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Trims {@code baseUrl}, strips a trailing slash, and - if the result has
|
* Trims {@code baseUrl}, strips a trailing slash, and - if the result has
|
||||||
* no scheme - assumes {@code https://}, so a deployment only needs to
|
* no scheme - infers one from the host: a loopback, RFC1918/RFC4193
|
||||||
* name the host (e.g. {@code "auth.example.com"} or
|
* private, or link-local address, or a {@code ".local"} name, defaults to
|
||||||
* {@code "192.168.1.50:8080"}), not repeat the scheme. An explicit
|
* {@code http://} (a plain-HTTP AuthGuard on a local network is the
|
||||||
* {@code http://} (for a plain-HTTP local/LAN AuthGuard) is left as-is.
|
* 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) {
|
private static String normalizeBaseUrl(String baseUrl) {
|
||||||
String trimmed = baseUrl == null ? "" : baseUrl.trim();
|
String trimmed = baseUrl == null ? "" : baseUrl.trim();
|
||||||
@@ -698,7 +701,53 @@ public final class AuthClient {
|
|||||||
if (lower.startsWith("http://") || lower.startsWith("https://")) {
|
if (lower.startsWith("http://") || lower.startsWith("https://")) {
|
||||||
return trimmed;
|
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 {
|
private static String readAll(InputStream in) throws IOException {
|
||||||
|
|||||||
+21
-2
@@ -38,9 +38,27 @@ class AuthClientTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void constructorAssumesHttpsForABareHost() {
|
void constructorAssumesHttpsForABarePublicHost() {
|
||||||
assertEquals("https://auth.example.com", new AuthClient("auth.example.com").baseUrlForTest());
|
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
|
@Test
|
||||||
@@ -48,6 +66,7 @@ class AuthClientTest {
|
|||||||
assertEquals("http://auth.example.com", new AuthClient("http://auth.example.com").baseUrlForTest());
|
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("https://auth.example.com", new AuthClient("https://auth.example.com").baseUrlForTest());
|
||||||
assertEquals("HTTP://auth.example.com", new AuthClient("HTTP://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
|
@Test
|
||||||
|
|||||||
@@ -58,9 +58,11 @@ export class AuthClient {
|
|||||||
/**
|
/**
|
||||||
* @param {string} baseUrl - AuthGuard's base URL (e.g. from AUTHGUARD_URL), no trailing slash required.
|
* @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") -
|
* 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
|
* the scheme is then inferred from the host: a loopback, RFC1918/RFC4193 private,
|
||||||
* host, not repeat the scheme; an explicit "http://" (for a plain-HTTP
|
* or link-local address, or a ".local" name, defaults to "http://" (a plain-HTTP
|
||||||
* local/LAN AuthGuard) is left as-is.
|
* 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]
|
* @param {{cookieName?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} [options]
|
||||||
*/
|
*/
|
||||||
constructor(baseUrl, options = {}) {
|
constructor(baseUrl, options = {}) {
|
||||||
@@ -73,7 +75,47 @@ export class AuthClient {
|
|||||||
static _normalizeBaseUrl(baseUrl) {
|
static _normalizeBaseUrl(baseUrl) {
|
||||||
const trimmed = String(baseUrl ?? '').trim().replace(/\/+$/, '');
|
const trimmed = String(baseUrl ?? '').trim().replace(/\/+$/, '');
|
||||||
if (!trimmed) return trimmed;
|
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) -----------------
|
// --- session validation (the original, minimal surface) -----------------
|
||||||
|
|||||||
@@ -31,15 +31,32 @@ function recordingFetch(responses) {
|
|||||||
return wrapped;
|
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('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', () => {
|
test('constructor leaves an explicit scheme alone', () => {
|
||||||
assert.equal(new AuthClient('http://auth.example.com').baseUrl, 'http://auth.example.com');
|
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('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('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', () => {
|
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
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import ipaddress
|
||||||
import json
|
import json
|
||||||
import urllib.error
|
import urllib.error
|
||||||
import urllib.request
|
import urllib.request
|
||||||
@@ -67,7 +68,34 @@ def _normalize_base_url(base_url: str) -> str:
|
|||||||
return trimmed
|
return trimmed
|
||||||
if trimmed.lower().startswith(("http://", "https://")):
|
if trimmed.lower().startswith(("http://", "https://")):
|
||||||
return trimmed
|
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):
|
class InvalidSessionError(Exception):
|
||||||
@@ -180,10 +208,13 @@ class AuthClient:
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""base_url is AuthGuard's base URL, e.g. "https://auth.example.com"
|
"""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.
|
(no trailing slash required). May be given without a scheme (e.g.
|
||||||
"auth.example.com" or "192.168.1.50:8080") -- "https://" is assumed
|
"auth.example.com" or "192.168.1.50:8080") -- the scheme is then
|
||||||
in that case, so a deployment only needs to name the host, not repeat
|
inferred from the host: a loopback, RFC1918/RFC4193 private, or
|
||||||
the scheme; an explicit "http://" (for a plain-HTTP local/LAN
|
link-local address, or a ".local" name, defaults to "http://" (a
|
||||||
AuthGuard) is left as-is. cookie_name is the cookie
|
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;
|
token_from_request looks for when there is no Authorization header;
|
||||||
it must match AuthGuard's SessionCookieName. timeout is the request
|
it must match AuthGuard's SessionCookieName. timeout is the request
|
||||||
timeout in seconds for the underlying blocking HTTP call."""
|
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):
|
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("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:
|
def test_explicit_scheme_left_alone(self) -> None:
|
||||||
self.assertEqual(AuthClient("http://auth.example.com").base_url, "http://auth.example.com")
|
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("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("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:
|
def test_trailing_slash_stripped_before_scheme_check(self) -> None:
|
||||||
self.assertEqual(AuthClient("auth.example.com/").base_url, "https://auth.example.com")
|
self.assertEqual(AuthClient("auth.example.com/").base_url, "https://auth.example.com")
|
||||||
|
|||||||
Reference in new issue
Block a user