-
Notifications
You must be signed in to change notification settings - Fork 17
feat: auto-detect host DNS resolvers instead of hardcoding Google DNS #1513
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| import { parseResolvConf, detectHostDnsServers, getEffectiveDnsServers, DEFAULT_DNS_SERVERS } from './dns-resolver'; | ||
| import * as fs from 'fs'; | ||
|
|
||
| jest.mock('fs'); | ||
| const mockedFs = fs as jest.Mocked<typeof fs>; | ||
|
|
||
| const mockLogger = { | ||
| debug: jest.fn(), | ||
| info: jest.fn(), | ||
| warn: jest.fn(), | ||
| error: jest.fn(), | ||
| success: jest.fn(), | ||
| setLevel: jest.fn(), | ||
| }; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe('parseResolvConf', () => { | ||
| it('extracts nameservers from standard content', () => { | ||
| const content = `# Generated by systemd-resolved | ||
| nameserver 1.1.1.1 | ||
| nameserver 9.9.9.9 | ||
| search example.com | ||
| `; | ||
| expect(parseResolvConf(content)).toEqual(['1.1.1.1', '9.9.9.9']); | ||
| }); | ||
|
|
||
| it('ignores comments and empty lines', () => { | ||
| const content = ` | ||
| # This is a comment | ||
| ; Another comment style | ||
|
|
||
| nameserver 1.1.1.1 | ||
|
|
||
| # nameserver 2.2.2.2 | ||
| nameserver 8.8.8.8 | ||
| `; | ||
| expect(parseResolvConf(content)).toEqual(['1.1.1.1', '8.8.8.8']); | ||
| }); | ||
|
|
||
| it('skips invalid IPs', () => { | ||
| const content = `nameserver 1.1.1.1 | ||
| nameserver not-an-ip | ||
| nameserver 8.8.8.8 | ||
| `; | ||
| expect(parseResolvConf(content)).toEqual(['1.1.1.1', '8.8.8.8']); | ||
| }); | ||
|
|
||
| it('handles IPv6 nameservers', () => { | ||
| const content = `nameserver 2001:4860:4860::8888 | ||
| nameserver 1.1.1.1 | ||
| nameserver ::1 | ||
| `; | ||
| expect(parseResolvConf(content)).toEqual(['2001:4860:4860::8888', '1.1.1.1', '::1']); | ||
| }); | ||
| }); | ||
|
|
||
| describe('detectHostDnsServers', () => { | ||
| it('filters out 127.0.0.11 (Docker embedded DNS)', () => { | ||
| mockedFs.readFileSync.mockReturnValue( | ||
| 'nameserver 127.0.0.11\nnameserver 1.1.1.1\nnameserver 8.8.8.8\n' | ||
| ); | ||
| const result = detectHostDnsServers(mockLogger as any); | ||
| expect(result).toEqual(['1.1.1.1', '8.8.8.8']); | ||
| }); | ||
|
|
||
| it('filters out 127.0.0.53 and tries secondary file', () => { | ||
| mockedFs.readFileSync.mockImplementation((filePath: any) => { | ||
| if (filePath === '/run/systemd/resolve/resolv.conf') { | ||
| throw new Error('ENOENT'); | ||
| } | ||
| if (filePath === '/etc/resolv.conf') { | ||
| return 'nameserver 127.0.0.53\n'; | ||
| } | ||
| throw new Error('ENOENT'); | ||
| }); | ||
| const result = detectHostDnsServers(mockLogger as any); | ||
| expect(result).toEqual(DEFAULT_DNS_SERVERS); | ||
| expect(mockLogger.warn).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns DEFAULT_DNS_SERVERS when no files are readable', () => { | ||
| mockedFs.readFileSync.mockImplementation(() => { | ||
| throw new Error('ENOENT'); | ||
| }); | ||
| const result = detectHostDnsServers(mockLogger as any); | ||
| expect(result).toEqual(DEFAULT_DNS_SERVERS); | ||
| expect(mockLogger.warn).toHaveBeenCalledWith( | ||
| expect.stringContaining('falling back to') | ||
| ); | ||
| }); | ||
|
|
||
| it('uses first readable file with usable servers', () => { | ||
| mockedFs.readFileSync.mockImplementation((filePath: any) => { | ||
| if (filePath === '/run/systemd/resolve/resolv.conf') { | ||
| return 'nameserver 9.9.9.9\nnameserver 1.1.1.1\n'; | ||
| } | ||
| return 'nameserver 8.8.8.8\n'; | ||
| }); | ||
| const result = detectHostDnsServers(mockLogger as any); | ||
| expect(result).toEqual(['9.9.9.9', '1.1.1.1']); | ||
| expect(mockLogger.info).toHaveBeenCalledWith( | ||
| expect.stringContaining('/run/systemd/resolve/resolv.conf') | ||
| ); | ||
| }); | ||
|
|
||
| it('filters out ::1 IPv6 loopback', () => { | ||
| mockedFs.readFileSync.mockReturnValue( | ||
| 'nameserver ::1\nnameserver 2001:4860:4860::8888\n' | ||
| ); | ||
| const result = detectHostDnsServers(mockLogger as any); | ||
| expect(result).toEqual(['2001:4860:4860::8888']); | ||
| }); | ||
| }); | ||
|
|
||
| describe('getEffectiveDnsServers', () => { | ||
| it('returns explicit servers when provided', () => { | ||
| const result = getEffectiveDnsServers(['1.1.1.1', '9.9.9.9'], mockLogger as any); | ||
| expect(result).toEqual(['1.1.1.1', '9.9.9.9']); | ||
| }); | ||
|
|
||
| it('calls auto-detect when explicit is undefined', () => { | ||
| mockedFs.readFileSync.mockReturnValue('nameserver 9.9.9.9\n'); | ||
| const result = getEffectiveDnsServers(undefined, mockLogger as any); | ||
| expect(result).toEqual(['9.9.9.9']); | ||
| }); | ||
|
|
||
| it('calls auto-detect when explicit is empty array', () => { | ||
| mockedFs.readFileSync.mockImplementation(() => { | ||
| throw new Error('ENOENT'); | ||
| }); | ||
| const result = getEffectiveDnsServers([], mockLogger as any); | ||
| expect(result).toEqual(DEFAULT_DNS_SERVERS); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import * as fs from 'fs'; | ||
| import { isIP } from 'net'; | ||
| import { logger as defaultLogger } from './logger'; | ||
|
|
||
| type Logger = typeof defaultLogger; | ||
|
|
||
| /** Fallback when no usable resolvers are detected on the host */ | ||
| export const DEFAULT_DNS_SERVERS = ['8.8.8.8', '8.8.4.4']; | ||
|
|
||
| /** | ||
| * Paths to try for resolv.conf, in priority order. | ||
| * systemd-resolved's upstream config first (has real upstream servers), | ||
| * then the standard resolv.conf (may contain 127.0.0.53 stub). | ||
| */ | ||
| const RESOLV_CONF_PATHS = ['/run/systemd/resolve/resolv.conf', '/etc/resolv.conf']; | ||
|
|
||
| function isValidIp(ip: string): boolean { | ||
| return isIP(ip) !== 0; | ||
| } | ||
|
|
||
| function isLoopback(ip: string): boolean { | ||
| // 127.0.0.0/8 for IPv4 | ||
| if (ip.startsWith('127.')) return true; | ||
| // ::1 for IPv6 | ||
| if (ip === '::1') return true; | ||
| return false; | ||
| } | ||
|
|
||
| /** | ||
| * Parse nameserver entries from resolv.conf content. | ||
| * Pure function — no I/O. | ||
| */ | ||
| export function parseResolvConf(content: string): string[] { | ||
| const servers: string[] = []; | ||
| for (const line of content.split('\n')) { | ||
| const match = line.match(/^\s*nameserver\s+(\S+)/); | ||
| if (match) { | ||
| const ip = match[1]; | ||
| if (isValidIp(ip)) { | ||
| servers.push(ip); | ||
| } | ||
| } | ||
| } | ||
| return servers; | ||
| } | ||
|
|
||
| /** | ||
| * Detect usable DNS servers from the host's resolv.conf files. | ||
| * Filters out loopback addresses (127.0.0.0/8, ::1) since those point to | ||
| * local stub resolvers that won't be reachable from inside a container. | ||
| * Falls back to DEFAULT_DNS_SERVERS if no usable servers are found. | ||
| */ | ||
| export function detectHostDnsServers(logger?: Logger): string[] { | ||
| const log = logger ?? defaultLogger; | ||
|
|
||
| for (const filePath of RESOLV_CONF_PATHS) { | ||
| let content: string; | ||
| try { | ||
| content = fs.readFileSync(filePath, 'utf-8'); | ||
| } catch { | ||
| log.debug(`DNS auto-detect: could not read ${filePath}, trying next`); | ||
| continue; | ||
| } | ||
|
|
||
| const allServers = parseResolvConf(content); | ||
| const usable = allServers.filter(ip => !isLoopback(ip)); | ||
|
|
||
| if (usable.length > 0) { | ||
| log.info(`Auto-detected DNS servers from ${filePath}: ${usable.join(', ')}`); | ||
| return usable; | ||
| } | ||
|
|
||
| log.debug(`DNS auto-detect: ${filePath} had no usable servers after filtering loopback addresses`); | ||
| } | ||
|
|
||
| log.warn(`Could not detect host DNS servers; falling back to ${DEFAULT_DNS_SERVERS.join(', ')}`); | ||
| return DEFAULT_DNS_SERVERS; | ||
| } | ||
|
|
||
| /** | ||
| * Return the effective DNS server list. | ||
| * If the user explicitly passed --dns-servers, use those. | ||
| * Otherwise, auto-detect from the host. | ||
| */ | ||
| export function getEffectiveDnsServers(explicit: string[] | undefined, logger?: Logger): string[] { | ||
| if (explicit && explicit.length > 0) { | ||
| return explicit; | ||
| } | ||
| return detectHostDnsServers(logger); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
if (options.dnsServers)check treats an explicitly provided empty string (e.g.--dns-servers "") as “not provided” and silently falls back to host auto-detection instead of erroring. Prefer checkingoptions.dnsServers !== undefined(or reusinggetEffectiveDnsServers()so the behavior is centralized and tested).