Adaugă codul complet al proiectului underchat-ircd

This commit is contained in:
mihaiitdata committed 2026-02-13 00:04:12 +02:00
1 parent caba5224bf
commit 5fdc1cc27c
462 files changed
+164488

No files matched your search

+204
View File
@@ -0,0 +1,204 @@
/**
* Tests for auth configuration parsing
*/
import { describe, it, expect } from 'vitest';
import { parseAuthConfig, convertSASLDB } from '../../src/auth/config.js';
describe('Auth Config Parsing', () => {
describe('parseAuthConfig', () => {
it('should return null if provider is missing', () => {
const result = parseAuthConfig('path=/etc/users');
expect(result).toBeNull();
});
it('should parse file provider config', () => {
const result = parseAuthConfig('provider=file path=/etc/iauth/users');
expect(result).toEqual({
provider: 'file',
path: '/etc/iauth/users',
priority: undefined,
});
});
it('should parse file provider with priority', () => {
const result = parseAuthConfig('provider=file path=/etc/users priority=50');
expect(result).toEqual({
provider: 'file',
path: '/etc/users',
priority: 50,
});
});
it('should return null for file provider without path', () => {
const result = parseAuthConfig('provider=file');
expect(result).toBeNull();
});
it('should parse LDAP direct bind config', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldap://ldap.example.com:389 mode=direct userdn=uid=%s,ou=users,dc=example,dc=com'
);
expect(result).toEqual({
provider: 'ldap',
uri: 'ldap://ldap.example.com:389',
mode: 'direct',
userdn: 'uid=%s,ou=users,dc=example,dc=com',
priority: undefined,
timeout: undefined,
accountattr: undefined,
});
});
it('should parse LDAP search mode config', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldaps://ldap.example.com:636 mode=search ' +
'basedn=ou=users,dc=example,dc=com ' +
'binddn=cn=admin,dc=example,dc=com ' +
'bindpass=secret ' +
'userfilter=(uid=%s)'
);
expect(result).toEqual({
provider: 'ldap',
uri: 'ldaps://ldap.example.com:636',
mode: 'search',
basedn: 'ou=users,dc=example,dc=com',
binddn: 'cn=admin,dc=example,dc=com',
bindpass: 'secret',
userfilter: '(uid=%s)',
groupdn: undefined,
priority: undefined,
timeout: undefined,
accountattr: undefined,
});
});
it('should parse LDAP config with groupdn', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldaps://ldap.example.com mode=search ' +
'basedn=ou=users,dc=example,dc=com ' +
'binddn=cn=admin,dc=example,dc=com ' +
'bindpass=secret ' +
'userfilter=(uid=%s) ' +
'groupdn=cn=ircusers,ou=groups,dc=example,dc=com'
);
expect(result?.provider).toBe('ldap');
if (result?.provider === 'ldap') {
expect(result.groupdn).toBe('cn=ircusers,ou=groups,dc=example,dc=com');
}
});
it('should parse LDAP config with timeout and priority', () => {
const result = parseAuthConfig(
'provider=ldap uri=ldap://server mode=direct userdn=uid=%s,dc=test timeout=10000 priority=25'
);
expect(result?.provider).toBe('ldap');
if (result?.provider === 'ldap') {
expect(result.timeout).toBe(10000);
expect(result.priority).toBe(25);
}
});
it('should return null for LDAP without uri', () => {
const result = parseAuthConfig('provider=ldap mode=direct');
expect(result).toBeNull();
});
it('should return null for LDAP without mode', () => {
const result = parseAuthConfig('provider=ldap uri=ldap://server');
expect(result).toBeNull();
});
it('should return null for unknown provider', () => {
const result = parseAuthConfig('provider=unknown');
expect(result).toBeNull();
});
it('should handle quoted values with spaces', () => {
const result = parseAuthConfig('provider=file path="/path/with spaces/users"');
expect(result).toEqual({
provider: 'file',
path: '/path/with spaces/users',
priority: undefined,
});
});
it('should handle single-quoted values', () => {
const result = parseAuthConfig("provider=file path='/path/with spaces/users'");
expect(result).toEqual({
provider: 'file',
path: '/path/with spaces/users',
priority: undefined,
});
});
it('should parse Keycloak config', () => {
const result = parseAuthConfig(
'provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client'
);
expect(result).toEqual({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'myrealm',
clientid: 'irc-client',
clientsecret: undefined,
accountattr: undefined,
timeout: undefined,
priority: undefined,
});
});
it('should parse Keycloak config with clientsecret', () => {
const result = parseAuthConfig(
'provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client clientsecret=mysecret'
);
expect(result?.provider).toBe('keycloak');
if (result?.provider === 'keycloak') {
expect(result.clientsecret).toBe('mysecret');
}
});
it('should parse Keycloak config with all options', () => {
const result = parseAuthConfig(
'provider=keycloak url=https://keycloak.example.com realm=myrealm clientid=irc-client ' +
'clientsecret=mysecret accountattr=irc_nick timeout=10000 priority=25'
);
expect(result?.provider).toBe('keycloak');
if (result?.provider === 'keycloak') {
expect(result.url).toBe('https://keycloak.example.com');
expect(result.realm).toBe('myrealm');
expect(result.clientid).toBe('irc-client');
expect(result.clientsecret).toBe('mysecret');
expect(result.accountattr).toBe('irc_nick');
expect(result.timeout).toBe(10000);
expect(result.priority).toBe(25);
}
});
it('should return null for Keycloak without url', () => {
const result = parseAuthConfig('provider=keycloak realm=test clientid=test');
expect(result).toBeNull();
});
it('should return null for Keycloak without realm', () => {
const result = parseAuthConfig('provider=keycloak url=https://kc.example.com clientid=test');
expect(result).toBeNull();
});
it('should return null for Keycloak without clientid', () => {
const result = parseAuthConfig('provider=keycloak url=https://kc.example.com realm=test');
expect(result).toBeNull();
});
});
describe('convertSASLDB', () => {
it('should convert SASLDB path to file provider config', () => {
const result = convertSASLDB('/etc/iauth/users');
expect(result).toEqual({
provider: 'file',
path: '/etc/iauth/users',
priority: 100,
});
});
});
});
+184
View File
@@ -0,0 +1,184 @@
/**
* Tests for FileAuthProvider
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { FileAuthProvider } from '../../src/auth/providers/file.js';
import { generateHash } from '../../src/sasl.js';
describe('FileAuthProvider', () => {
let tempDir: string;
let usersFile: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile = join(tempDir, 'users');
});
afterEach(() => {
try {
unlinkSync(usersFile);
} catch {
// Ignore if file doesn't exist
}
});
describe('initialization', () => {
it('should initialize with empty users file', async () => {
writeFileSync(usersFile, '');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
expect(provider.getUserCount()).toBe(0);
});
it('should initialize with non-existent file', async () => {
const provider = new FileAuthProvider({
provider: 'file',
path: '/nonexistent/path/users',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
expect(provider.getUserCount()).toBe(0);
});
it('should load users from file', async () => {
writeFileSync(usersFile, 'testuser:plainpassword\nadmin:adminpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
expect(provider.getUserCount()).toBe(2);
});
it('should use default priority of 100', async () => {
writeFileSync(usersFile, '');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
expect(provider.priority).toBe(100);
});
it('should use custom priority', async () => {
writeFileSync(usersFile, '');
const provider = new FileAuthProvider({
provider: 'file',
path: usersFile,
priority: 50,
});
expect(provider.priority).toBe(50);
});
});
describe('authentication', () => {
it('should authenticate valid user with plain password', async () => {
writeFileSync(usersFile, 'testuser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'testpass');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should authenticate with SHA-256 hash', async () => {
const hash = generateHash('secretpass', 'sha256');
writeFileSync(usersFile, `testuser:${hash}\n`);
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'secretpass');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should authenticate with SHA-512 hash', async () => {
const hash = generateHash('secretpass', 'sha512');
writeFileSync(usersFile, `testuser:${hash}\n`);
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'secretpass');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should reject invalid password', async () => {
writeFileSync(usersFile, 'testuser:correctpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('testuser', 'wrongpass');
expect(result.success).toBe(false);
expect(result.error).toBe('Invalid credentials');
});
it('should reject unknown user', async () => {
writeFileSync(usersFile, 'testuser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('unknownuser', 'testpass');
expect(result.success).toBe(false);
});
it('should be case-insensitive for usernames', async () => {
writeFileSync(usersFile, 'TestUser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
const result = await provider.authenticate('TESTUSER', 'testpass');
expect(result.success).toBe(true);
});
it('should return error if not initialized', async () => {
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
// Don't call initialize
const result = await provider.authenticate('testuser', 'testpass');
expect(result.success).toBe(false);
expect(result.error).toBe('Users database not loaded');
});
});
describe('reload', () => {
it('should reload users file', async () => {
writeFileSync(usersFile, 'user1:pass1\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.getUserCount()).toBe(1);
// Modify file
writeFileSync(usersFile, 'user1:pass1\nuser2:pass2\n');
await provider.reload();
expect(provider.getUserCount()).toBe(2);
});
it('should detect file modifications during auth', async () => {
writeFileSync(usersFile, 'user1:pass1\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
// File is automatically reloaded if modified
// Wait a bit to ensure mtime changes
await new Promise((r) => setTimeout(r, 100));
writeFileSync(usersFile, 'user1:newpass\n');
// Auth should use new password after auto-reload
const result = await provider.authenticate('user1', 'newpass');
expect(result.success).toBe(true);
});
});
describe('shutdown', () => {
it('should mark provider as unhealthy after shutdown', async () => {
writeFileSync(usersFile, 'testuser:testpass\n');
const provider = new FileAuthProvider({ provider: 'file', path: usersFile });
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
await provider.shutdown();
expect(provider.isHealthy()).toBe(false);
});
});
});
+415
View File
@@ -0,0 +1,415 @@
/**
* Tests for KeycloakAuthProvider
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { KeycloakAuthProvider } from '../../src/auth/providers/keycloak.js';
// Mock fetch globally
const mockFetch = vi.fn();
vi.stubGlobal('fetch', mockFetch);
describe('KeycloakAuthProvider', () => {
beforeEach(() => {
mockFetch.mockReset();
});
afterEach(() => {
vi.clearAllMocks();
});
/**
* Create a mock JWT access token
*/
function createMockToken(payload: Record<string, unknown>): string {
const header = Buffer.from(JSON.stringify({ alg: 'RS256', typ: 'JWT' })).toString('base64url');
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
const signature = 'mock-signature';
return `${header}.${body}.${signature}`;
}
describe('initialization', () => {
it('should throw if url is missing', async () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: '',
realm: 'test',
clientid: 'myclient',
});
await expect(provider.initialize()).rejects.toThrow('requires url');
});
it('should throw if realm is missing', async () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: '',
clientid: 'myclient',
});
await expect(provider.initialize()).rejects.toThrow('requires realm');
});
it('should throw if clientid is missing', async () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: '',
});
await expect(provider.initialize()).rejects.toThrow('requires clientid');
});
it('should initialize successfully with valid config', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ issuer: 'https://keycloak.example.com/realms/test' }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
});
it('should use default priority of 100', () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
expect(provider.priority).toBe(100);
});
it('should use custom priority', () => {
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
priority: 50,
});
expect(provider.priority).toBe(50);
});
});
describe('authentication', () => {
it('should authenticate valid user', async () => {
const accessToken = createMockToken({
sub: 'user-uuid',
preferred_username: 'testuser',
email: 'test@example.com',
});
// Mock well-known endpoint
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({}),
});
// Mock token endpoint
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () =>
JSON.stringify({
access_token: accessToken,
token_type: 'Bearer',
expires_in: 300,
scope: 'openid profile email',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password123');
expect(result.success).toBe(true);
expect(result.account).toBe('testuser');
});
it('should use clientsecret for confidential clients', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
clientsecret: 'secret123',
});
await provider.initialize();
await provider.authenticate('testuser', 'password123');
// Check that client_secret was included in the request
const tokenCall = mockFetch.mock.calls[1];
expect(tokenCall[1].body).toContain('client_secret=secret123');
});
it('should reject invalid credentials', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: false,
status: 401,
text: async () =>
JSON.stringify({
error: 'invalid_grant',
error_description: 'Invalid user credentials',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'wrongpass');
expect(result.success).toBe(false);
expect(result.error).toBe('Invalid credentials');
});
it('should handle disabled account', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: false,
status: 400,
text: async () =>
JSON.stringify({
error: 'invalid_grant',
error_description: 'Account disabled',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('disableduser', 'password');
expect(result.success).toBe(false);
expect(result.error).toBe('Account disabled');
});
it('should handle client misconfiguration', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: false,
status: 401,
text: async () =>
JSON.stringify({
error: 'unauthorized_client',
error_description: 'Client not allowed for direct access grants',
}),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'misconfigured-client',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(false);
expect(result.error).toContain('Client error');
});
it('should extract account from custom attribute', async () => {
const accessToken = createMockToken({
sub: 'user-uuid',
preferred_username: 'testuser',
irc_account: 'CustomNick',
});
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
accountattr: 'irc_account',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(true);
expect(result.account).toBe('CustomNick');
});
it('should fall back to sub if preferred_username not available', async () => {
const accessToken = createMockToken({
sub: 'user-uuid-12345',
});
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(true);
expect(result.account).toBe('user-uuid-12345');
});
});
describe('token endpoint URL', () => {
it('should build correct token endpoint URL', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'myrealm',
clientid: 'myclient',
});
await provider.initialize();
await provider.authenticate('testuser', 'password');
// Check the token endpoint URL
const tokenCall = mockFetch.mock.calls[1];
expect(tokenCall[0]).toBe(
'https://keycloak.example.com/realms/myrealm/protocol/openid-connect/token'
);
});
it('should handle trailing slash in URL', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com/', // Trailing slash
realm: 'myrealm',
clientid: 'myclient',
});
await provider.initialize();
await provider.authenticate('testuser', 'password');
const tokenCall = mockFetch.mock.calls[1];
expect(tokenCall[0]).toBe(
'https://keycloak.example.com/realms/myrealm/protocol/openid-connect/token'
);
});
});
describe('health status', () => {
it('should mark as unhealthy on connection failure', async () => {
mockFetch.mockRejectedValueOnce(new Error('Connection refused'));
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(false);
});
it('should mark as healthy after successful auth', async () => {
const accessToken = createMockToken({ preferred_username: 'testuser' });
// Initialize fails
mockFetch.mockRejectedValueOnce(new Error('Connection refused'));
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(false);
// Auth succeeds
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => JSON.stringify({ access_token: accessToken }),
});
const result = await provider.authenticate('testuser', 'password');
expect(result.success).toBe(true);
expect(provider.isHealthy()).toBe(true);
});
});
describe('shutdown', () => {
it('should mark provider as unhealthy after shutdown', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({}) });
const provider = new KeycloakAuthProvider({
provider: 'keycloak',
url: 'https://keycloak.example.com',
realm: 'test',
clientid: 'myclient',
});
await provider.initialize();
expect(provider.isHealthy()).toBe(true);
await provider.shutdown();
expect(provider.isHealthy()).toBe(false);
});
});
});
+191
View File
@@ -0,0 +1,191 @@
/**
* Tests for AuthManager
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { AuthManager } from '../../src/auth/manager.js';
import type { AuthProviderConfig } from '../../src/auth/types.js';
describe('AuthManager', () => {
let tempDir: string;
let usersFile1: string;
let usersFile2: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile1 = join(tempDir, 'users1');
usersFile2 = join(tempDir, 'users2');
});
afterEach(() => {
try {
unlinkSync(usersFile1);
unlinkSync(usersFile2);
} catch {
// Ignore if files don't exist
}
});
describe('initialization', () => {
it('should initialize with no providers', async () => {
const manager = new AuthManager([]);
await manager.initialize();
expect(manager.hasProviders()).toBe(false);
expect(manager.getProviderCount()).toBe(0);
});
it('should initialize single file provider', async () => {
writeFileSync(usersFile1, 'testuser:testpass\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
expect(manager.hasProviders()).toBe(true);
expect(manager.getProviderCount()).toBe(1);
});
it('should initialize multiple providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 50 },
{ provider: 'file', path: usersFile2, priority: 100 },
];
const manager = new AuthManager(configs);
await manager.initialize();
expect(manager.getProviderCount()).toBe(2);
});
it('should sort providers by priority', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 100 },
{ provider: 'file', path: usersFile2, priority: 50 },
];
const manager = new AuthManager(configs);
await manager.initialize();
const info = manager.getProviderInfo();
expect(info[0].priority).toBe(50);
expect(info[1].priority).toBe(100);
});
});
describe('authentication with fallback chain', () => {
it('should authenticate against first matching provider', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 50 },
{ provider: 'file', path: usersFile2, priority: 100 },
];
const manager = new AuthManager(configs);
await manager.initialize();
const result = await manager.authenticate('user1', 'pass1');
expect(result.success).toBe(true);
expect(result.account).toBe('user1');
});
it('should fallback to second provider if first fails', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1, priority: 50 },
{ provider: 'file', path: usersFile2, priority: 100 },
];
const manager = new AuthManager(configs);
await manager.initialize();
// user2 is only in the second file
const result = await manager.authenticate('user2', 'pass2');
expect(result.success).toBe(true);
expect(result.account).toBe('user2');
});
it('should fail if no provider matches', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
writeFileSync(usersFile2, 'user2:pass2\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
{ provider: 'file', path: usersFile2 },
];
const manager = new AuthManager(configs);
await manager.initialize();
const result = await manager.authenticate('unknownuser', 'anypass');
expect(result.success).toBe(false);
});
it('should return error if not initialized', async () => {
const manager = new AuthManager([]);
// Don't call initialize
const result = await manager.authenticate('user', 'pass');
expect(result.success).toBe(false);
expect(result.error).toBe('AuthManager not initialized');
});
it('should return error if no providers configured', async () => {
const manager = new AuthManager([]);
await manager.initialize();
const result = await manager.authenticate('user', 'pass');
expect(result.success).toBe(false);
expect(result.error).toBe('No auth providers configured');
});
});
describe('provider health', () => {
it('should report healthy providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
expect(manager.hasHealthyProviders()).toBe(true);
const info = manager.getProviderInfo();
expect(info[0].healthy).toBe(true);
});
});
describe('reload', () => {
it('should reload all providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
// Modify file
writeFileSync(usersFile1, 'user1:newpass\n');
await manager.reload();
// Should now use new password
const result = await manager.authenticate('user1', 'newpass');
expect(result.success).toBe(true);
});
});
describe('shutdown', () => {
it('should shutdown all providers', async () => {
writeFileSync(usersFile1, 'user1:pass1\n');
const configs: AuthProviderConfig[] = [
{ provider: 'file', path: usersFile1 },
];
const manager = new AuthManager(configs);
await manager.initialize();
await manager.shutdown();
expect(manager.hasProviders()).toBe(false);
});
});
});
+184
View File
@@ -0,0 +1,184 @@
/**
* Unit tests for configuration parser
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { readConfigFile } from '../src/config.js';
describe('Config Parser', () => {
let tempDir: string;
let configPath: string;
beforeAll(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
configPath = join(tempDir, 'test.conf');
});
afterAll(() => {
try {
unlinkSync(configPath);
} catch {}
});
it('should parse POLICY directive', () => {
writeFileSync(configPath, '#IAUTH POLICY RTAWUwFr\n');
const { config } = readConfigFile(configPath);
expect(config.policy).toBe('RTAWUwFr');
});
it('should parse CACHETIME directive', () => {
writeFileSync(configPath, '#IAUTH CACHETIME 3600\n');
const { config } = readConfigFile(configPath);
expect(config.cacheTime).toBe(3600);
});
it('should parse DNSTIMEOUT directive', () => {
writeFileSync(configPath, '#IAUTH DNSTIMEOUT 10\n');
const { config } = readConfigFile(configPath);
expect(config.dnsTimeout).toBe(10);
});
it('should parse BLOCKMSG directive', () => {
writeFileSync(configPath, '#IAUTH BLOCKMSG Your connection has been rejected.\n');
const { config } = readConfigFile(configPath);
expect(config.blockMsg).toBe('Your connection has been rejected.');
});
it('should parse DEBUG directive', () => {
writeFileSync(configPath, '#IAUTH DEBUG\n');
const { config } = readConfigFile(configPath);
expect(config.debug).toBe(true);
});
it('should parse simple DNSBL directive', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls).toHaveLength(1);
expect(config.dnsbls[0].server).toBe('dnsbl.example.com');
});
it('should parse DNSBL with index', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com index=2,3,4\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].index).toBe('2,3,4');
});
it('should parse DNSBL with bitmask', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com bitmask=128\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].bitmask).toBe('128');
});
it('should parse DNSBL with mark', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com mark=baduser\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].mark).toBe('baduser');
});
it('should parse DNSBL with block=all', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com block=all\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].block).toBe('all');
});
it('should parse DNSBL with block=anonymous', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com block=anonymous\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].block).toBe('anonymous');
});
it('should parse DNSBL with whitelist', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=whitelist.example.com whitelist\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].whitelist).toBe(true);
});
it('should parse DNSBL with class', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com class=Trusted\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].class).toBe('Trusted');
});
it('should parse DNSBL with cachetime override', () => {
writeFileSync(configPath, '#IAUTH DNSBL server=dnsbl.example.com cachetime=7200\n');
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].cacheTime).toBe(7200);
});
it('should parse multiple DNSBL directives', () => {
writeFileSync(configPath, `
#IAUTH DNSBL server=dnsbl1.example.com index=2,3 mark=bl1
#IAUTH DNSBL server=dnsbl2.example.com index=4,5 mark=bl2 block=anonymous
#IAUTH DNSBL server=whitelist.example.com whitelist
`);
const { config } = readConfigFile(configPath);
expect(config.dnsbls).toHaveLength(3);
expect(config.dnsbls[0].server).toBe('dnsbl1.example.com');
expect(config.dnsbls[1].server).toBe('dnsbl2.example.com');
expect(config.dnsbls[1].block).toBe('anonymous');
expect(config.dnsbls[2].whitelist).toBe(true);
});
it('should parse full config with all directives', () => {
writeFileSync(configPath, `
# This is a comment
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIME 86400
#IAUTH DNSTIMEOUT 5
#IAUTH BLOCKMSG Sorry! Your connection has been rejected.
#IAUTH DNSBL server=dnsbl.sorbs.net index=2,3,4,5 mark=sorbs block=anonymous
#IAUTH DNSBL server=rbl.efnetrbl.org index=4 mark=tor
# Some other config lines that should be ignored
General {
name = "test.server";
};
`);
const { config, configLines } = readConfigFile(configPath);
expect(config.policy).toBe('RTAWUwFr');
expect(config.cacheTime).toBe(86400);
expect(config.dnsTimeout).toBe(5);
expect(config.blockMsg).toBe('Sorry! Your connection has been rejected.');
expect(config.dnsbls).toHaveLength(2);
expect(configLines).toHaveLength(6);
});
it('should use defaults when directives are missing', () => {
writeFileSync(configPath, '# Empty config\n');
const { config } = readConfigFile(configPath);
expect(config.policy).toBe('RTAWUwFr');
expect(config.cacheTime).toBe(86400);
expect(config.dnsTimeout).toBe(5);
expect(config.debug).toBe(false);
expect(config.dnsbls).toHaveLength(0);
});
it('should ignore non-IAUTH lines', () => {
writeFileSync(configPath, `
# Regular comment
General { name = "test"; };
#IAUTH POLICY RTAW
#NOTIAUTHPOLICY test
`);
const { config } = readConfigFile(configPath);
expect(config.policy).toBe('RTAW');
});
it('should assign incrementing cfgNum to DNSBLs', () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=first.example.com
#IAUTH DNSBL server=second.example.com
#IAUTH DNSBL server=third.example.com
`);
const { config } = readConfigFile(configPath);
expect(config.dnsbls[0].cfgNum).toBe(2);
expect(config.dnsbls[1].cfgNum).toBe(3);
expect(config.dnsbls[2].cfgNum).toBe(4);
});
});
@@ -0,0 +1,641 @@
/**
* DNSBL Integration Tests with Mocked DNS
*
* Tests the full pipeline: client connect → DNSBL lookup → decision
* Uses mock DNS responses to test all matching modes and edge cases.
*
* Based on real-world AfterNET production config.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { spawn, ChildProcess } from 'node:child_process';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createInterface } from 'node:readline';
/**
* Mock DNS responses for testing
* Maps reversed-IP.dnsbl-server to response IP(s)
*/
const mockDnsResponses: Map<string, string[]> = new Map();
/**
* Set up a mock DNS response
*/
function mockDns(clientIp: string, dnsblServer: string, responses: string[]): void {
const reversed = clientIp.split('.').reverse().join('.');
const query = `${reversed}.${dnsblServer}`;
mockDnsResponses.set(query, responses);
}
/**
* Clear all mock DNS responses
*/
function clearMockDns(): void {
mockDnsResponses.clear();
}
interface TestHarness {
proc: ChildProcess;
output: string[];
send: (line: string) => void;
waitFor: (pattern: RegExp, timeout?: number) => Promise<string>;
getMarks: (clientId: number) => string[];
wasAccepted: (clientId: number) => boolean;
wasRejected: (clientId: number) => boolean;
close: () => Promise<void>;
}
/**
* Create a test harness with mock DNS injection
*/
async function createHarness(configPath: string): Promise<TestHarness> {
const output: string[] = [];
// Create a wrapper script that injects our mock DNS module
const wrapperPath = join(tmpdir(), `dns-mock-${Date.now()}.mjs`);
const mockResponses = JSON.stringify(Array.from(mockDnsResponses.entries()));
writeFileSync(wrapperPath, `
import { promises as dns } from 'node:dns';
// Mock DNS responses
const mockResponses = new Map(${mockResponses});
// Override dns.resolve4
const originalResolve4 = dns.resolve4.bind(dns);
dns.resolve4 = async (hostname) => {
const mock = mockResponses.get(hostname);
if (mock !== undefined) {
if (mock.length === 0) {
const err = new Error('NXDOMAIN');
err.code = 'ENOTFOUND';
throw err;
}
return mock;
}
// For non-mocked queries, return NXDOMAIN (not listed)
const err = new Error('NXDOMAIN');
err.code = 'ENOTFOUND';
throw err;
};
// Now import and run the actual daemon
import('${join(import.meta.dirname, '..', 'src', 'index.ts').replace(/\\/g, '/')}');
`);
const proc = spawn('npx', ['tsx', wrapperPath, '-v', '-c', configPath], {
cwd: join(import.meta.dirname, '..'),
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env },
});
const rl = createInterface({ input: proc.stdout! });
rl.on('line', (line) => output.push(line));
proc.stderr?.on('data', (data) => {
// Uncomment for debugging:
// console.error('stderr:', data.toString());
});
const send = (line: string) => {
proc.stdin!.write(line + '\n');
};
const waitFor = (pattern: RegExp, timeout = 5000): Promise<string> => {
return new Promise((resolve, reject) => {
// Check existing output
for (const line of output) {
if (pattern.test(line)) {
resolve(line);
return;
}
}
const startLen = output.length;
const interval = setInterval(() => {
for (let i = startLen; i < output.length; i++) {
if (pattern.test(output[i])) {
clearInterval(interval);
clearTimeout(timer);
resolve(output[i]);
return;
}
}
}, 10);
const timer = setTimeout(() => {
clearInterval(interval);
reject(new Error(`Timeout waiting for: ${pattern}\nOutput was:\n${output.join('\n')}`));
}, timeout);
});
};
const getMarks = (clientId: number): string[] => {
const marks: string[] = [];
const pattern = new RegExp(`^m ${clientId} .* MARK (\\S+)`);
for (const line of output) {
const match = line.match(pattern);
if (match) {
marks.push(match[1]);
}
}
return marks;
};
const wasAccepted = (clientId: number): boolean => {
return output.some(line => line.startsWith(`D ${clientId} `));
};
const wasRejected = (clientId: number): boolean => {
return output.some(line => line.startsWith(`k ${clientId} `));
};
const close = async (): Promise<void> => {
try { unlinkSync(wrapperPath); } catch {}
return new Promise((resolve) => {
proc.on('close', () => resolve());
proc.stdin!.end();
setTimeout(() => {
proc.kill('SIGTERM');
resolve();
}, 1000);
});
};
// Wait for startup
await waitFor(/^S iauthd-ts/);
await new Promise(r => setTimeout(r, 100));
return { proc, output, send, waitFor, getMarks, wasAccepted, wasRejected, close };
}
/**
* Simulate a full client connection flow
*/
async function connectClient(
harness: TestHarness,
clientId: number,
ip: string,
options: { authenticated?: string } = {}
): Promise<void> {
harness.send(`${clientId} C ${ip} ${10000 + clientId} 10.0.0.1 6667`);
if (options.authenticated) {
harness.send(`${clientId} R ${options.authenticated}`);
}
// Small delay to let lookups start
await new Promise(r => setTimeout(r, 50));
harness.send(`${clientId} H Users`);
// Wait for decision
await harness.waitFor(new RegExp(`^[Dk] ${clientId} `), 3000);
}
describe('DNSBL Integration Tests', () => {
let tempDir: string;
let configPath: string;
let harness: TestHarness;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-dnsbl-test-'));
configPath = join(tempDir, 'test.conf');
clearMockDns();
});
afterEach(async () => {
await harness?.close();
try { unlinkSync(configPath); } catch {}
});
describe('Index Matching', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl index=2,3,4 mark=testbl block=all
`);
});
it('should block when index matches exactly', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
expect(harness.wasAccepted(0)).toBe(false);
});
it('should block when any configured index matches', async () => {
mockDns('192.168.1.101', 'test.dnsbl', ['127.0.0.4']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should pass when index does not match', async () => {
mockDns('192.168.1.102', 'test.dnsbl', ['127.0.0.5']); // index=5 not in 2,3,4
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.102');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.wasRejected(0)).toBe(false);
});
it('should pass when not listed (NXDOMAIN)', async () => {
// No mock = NXDOMAIN
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.103');
expect(harness.wasAccepted(0)).toBe(true);
});
});
describe('Bitmask Matching', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl bitmask=2,4 mark=testbl block=all
`);
});
it('should block when bitmask matches (bit 1 set)', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']); // 2 = 0010
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block when bitmask matches (bit 2 set)', async () => {
mockDns('192.168.1.101', 'test.dnsbl', ['127.0.0.4']); // 4 = 0100
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block when multiple bits match', async () => {
mockDns('192.168.1.102', 'test.dnsbl', ['127.0.0.6']); // 6 = 0110 (bits 1 and 2)
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.102');
expect(harness.wasRejected(0)).toBe(true);
});
it('should pass when no bitmask bits match', async () => {
mockDns('192.168.1.103', 'test.dnsbl', ['127.0.0.1']); // 1 = 0001 (bit 0 only)
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.103');
expect(harness.wasAccepted(0)).toBe(true);
});
});
describe('Block Modes', () => {
describe('block=all', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl index=2 mark=testbl block=all
`);
});
it('should block unauthenticated users', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block authenticated users too', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100', { authenticated: 'testuser' });
expect(harness.wasRejected(0)).toBe(true);
});
});
describe('block=anonymous', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH BLOCKMSG You must authenticate to connect.
#IAUTH DNSBL server=test.dnsbl index=2 mark=testbl block=anonymous
`);
});
it('should block unauthenticated users', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
it('should allow SASL-authenticated users', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100', { authenticated: 'gooduser' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.wasRejected(0)).toBe(false);
});
it('should mark authenticated users even though not blocked', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100', { authenticated: 'gooduser' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('testbl');
});
});
describe('mark only (no block)', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=test.dnsbl index=2 mark=infomark
`);
});
it('should accept client but apply mark', async () => {
mockDns('192.168.1.100', 'test.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('infomark');
});
});
});
describe('Whitelist', () => {
beforeEach(async () => {
// Whitelist first, then blocking DNSBLs - mimics AfterNET config
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=whitelist.dnsbl index=2 mark=whitelist whitelist
#IAUTH DNSBL server=blocklist.dnsbl index=2 mark=blocked block=all
`);
});
it('should not block whitelisted clients even if they match blocking DNSBL', async () => {
mockDns('192.168.1.100', 'whitelist.dnsbl', ['127.0.0.2']); // Whitelisted
mockDns('192.168.1.100', 'blocklist.dnsbl', ['127.0.0.2']); // Also on blocklist
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.wasRejected(0)).toBe(false);
});
it('should block non-whitelisted clients that match blocking DNSBL', async () => {
// Not on whitelist, but on blocklist
mockDns('192.168.1.101', 'blocklist.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should apply whitelist mark', async () => {
mockDns('192.168.1.100', 'whitelist.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.getMarks(0)).toContain('whitelist');
});
});
describe('Multiple DNSBLs', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=dnsbl1.test index=2 mark=list1
#IAUTH DNSBL server=dnsbl2.test index=2 mark=list2
#IAUTH DNSBL server=dnsbl3.test index=2 mark=list3 block=anonymous
`);
});
it('should accumulate marks from multiple DNSBLs', async () => {
mockDns('192.168.1.100', 'dnsbl1.test', ['127.0.0.2']);
mockDns('192.168.1.100', 'dnsbl2.test', ['127.0.0.2']);
// Not on dnsbl3
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
const marks = harness.getMarks(0);
expect(marks).toContain('list1');
expect(marks).toContain('list2');
expect(marks).not.toContain('list3');
});
it('should block if any blocking DNSBL matches', async () => {
mockDns('192.168.1.100', 'dnsbl3.test', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasRejected(0)).toBe(true);
});
});
describe('Same Server, Different Indices (AfterNET pattern)', () => {
beforeEach(async () => {
// Mimics AfterNET's dnsbl.afternet.org with different indices
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=dnsbl.example.org index=2 mark=whitelist whitelist
#IAUTH DNSBL server=dnsbl.example.org index=250 mark=rbl block=anonymous
#IAUTH DNSBL server=dnsbl.example.org index=251 mark=cloud block=anonymous
`);
});
it('should whitelist on index=2', async () => {
mockDns('192.168.1.100', 'dnsbl.example.org', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('whitelist');
});
it('should block anonymous on index=250', async () => {
mockDns('192.168.1.101', 'dnsbl.example.org', ['127.0.0.250']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101');
expect(harness.wasRejected(0)).toBe(true);
});
it('should block anonymous on index=251', async () => {
mockDns('192.168.1.102', 'dnsbl.example.org', ['127.0.0.251']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.102');
expect(harness.wasRejected(0)).toBe(true);
});
it('should allow authenticated on index=250', async () => {
mockDns('192.168.1.101', 'dnsbl.example.org', ['127.0.0.250']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.101', { authenticated: 'user' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('rbl');
});
});
describe('Real-world AfterNET Config Simulation', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIMEOUT 21600
#IAUTH DNSTIMEOUT 5
#IAUTH BLOCKMSG Sorry! Your connection has been rejected due to poor reputation.
#IAUTH DNSBL server=dnsbl.afternet.org index=2 mark=whitelist whitelist
#IAUTH DNSBL server=dnsbl.afternet.org index=250 mark=afternetrbl block=anonymous
#IAUTH DNSBL server=dnsbl.afternet.org index=251 mark=cloud block=anonymous
#IAUTH DNSBL server=dnsbl.sorbs.net index=2,3,4,5,6,7,9 mark=sorbs block=anonymous
#IAUTH DNSBL server=dnsbl.dronebl.org index=2,3,5,6,7,8,9,10,13,14,15 mark=dronebl block=anonymous
#IAUTH DNSBL server=rbl.efnetrbl.org index=4 mark=tor block=anonymous
#IAUTH DNSBL server=rbl.efnetrbl.org index=1,2,3,5 mark=efnetrbl block=anonymous
#IAUTH DNSBL server=dnsbl-2.uceprotect.net index=2 mark=uce-2
#IAUTH DNSBL server=cbl.abuseat.org index=2 mark=cbl
`);
});
it('should accept clean clients', async () => {
harness = await createHarness(configPath);
await connectClient(harness, 0, '8.8.8.8');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toHaveLength(0);
});
it('should whitelist AfterNET trusted IPs', async () => {
mockDns('10.0.0.50', 'dnsbl.afternet.org', ['127.0.0.2']);
mockDns('10.0.0.50', 'dnsbl.dronebl.org', ['127.0.0.5']); // Also on dronebl!
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.50');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('whitelist');
});
it('should block drones unless authenticated', async () => {
mockDns('10.0.0.60', 'dnsbl.dronebl.org', ['127.0.0.5']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.60');
expect(harness.wasRejected(0)).toBe(true);
});
it('should allow authenticated drones', async () => {
mockDns('10.0.0.60', 'dnsbl.dronebl.org', ['127.0.0.5']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.60', { authenticated: 'droneuser' });
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('dronebl');
});
it('should block Tor exit nodes unless authenticated', async () => {
mockDns('10.0.0.70', 'rbl.efnetrbl.org', ['127.0.0.4']); // index=4 = tor
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.70');
expect(harness.wasRejected(0)).toBe(true);
});
it('should mark UCE-2 but not block', async () => {
mockDns('10.0.0.80', 'dnsbl-2.uceprotect.net', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.80');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('uce-2');
});
it('should mark CBL but not block', async () => {
mockDns('10.0.0.90', 'cbl.abuseat.org', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.90');
expect(harness.wasAccepted(0)).toBe(true);
expect(harness.getMarks(0)).toContain('cbl');
});
it('should accumulate multiple marks', async () => {
mockDns('10.0.0.95', 'dnsbl-2.uceprotect.net', ['127.0.0.2']);
mockDns('10.0.0.95', 'cbl.abuseat.org', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '10.0.0.95');
expect(harness.wasAccepted(0)).toBe(true);
const marks = harness.getMarks(0);
expect(marks).toContain('uce-2');
expect(marks).toContain('cbl');
});
});
describe('Class Assignment', () => {
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=trusted.dnsbl index=2 class=Trusted mark=trusted
#IAUTH DNSBL server=limited.dnsbl index=2 class=Limited mark=limited
`);
});
it('should assign class from matching DNSBL', async () => {
mockDns('192.168.1.100', 'trusted.dnsbl', ['127.0.0.2']);
harness = await createHarness(configPath);
await connectClient(harness, 0, '192.168.1.100');
expect(harness.wasAccepted(0)).toBe(true);
// Check the D message includes the class
const acceptLine = harness.output.find(l => l.startsWith('D 0 '));
expect(acceptLine).toContain('Trusted');
});
});
});
+228
View File
@@ -0,0 +1,228 @@
/**
* Unit tests for DNSBL functions
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
reverseIPv4,
isIPv4,
getCacheEntry,
setCacheEntry,
getCacheSize,
matchesDNSBL,
parseQuery,
} from '../src/dnsbl.js';
import type { DNSBLConfig } from '../src/types.js';
describe('DNSBL Functions', () => {
describe('reverseIPv4', () => {
it('should reverse a valid IPv4 address', () => {
expect(reverseIPv4('192.168.1.10')).toBe('10.1.168.192');
});
it('should handle 127.0.0.1', () => {
expect(reverseIPv4('127.0.0.1')).toBe('1.0.0.127');
});
it('should handle 0.0.0.0', () => {
expect(reverseIPv4('0.0.0.0')).toBe('0.0.0.0');
});
it('should handle 255.255.255.255', () => {
expect(reverseIPv4('255.255.255.255')).toBe('255.255.255.255');
});
it('should return null for invalid IPv4', () => {
expect(reverseIPv4('not-an-ip')).toBeNull();
});
it('should return null for IPv6 addresses', () => {
expect(reverseIPv4('::1')).toBeNull();
expect(reverseIPv4('2001:db8::1')).toBeNull();
});
it('should return null for partial IPs', () => {
expect(reverseIPv4('192.168.1')).toBeNull();
expect(reverseIPv4('192.168')).toBeNull();
});
it('should return null for IPs with invalid octets', () => {
expect(reverseIPv4('192.168.1.256')).toBeNull();
expect(reverseIPv4('192.168.1.1000')).toBeNull();
});
});
describe('isIPv4', () => {
it('should return true for valid IPv4 addresses', () => {
expect(isIPv4('192.168.1.1')).toBe(true);
expect(isIPv4('127.0.0.1')).toBe(true);
expect(isIPv4('0.0.0.0')).toBe(true);
expect(isIPv4('255.255.255.255')).toBe(true);
});
it('should return false for IPv6 addresses', () => {
expect(isIPv4('::1')).toBe(false);
expect(isIPv4('2001:db8::1')).toBe(false);
});
it('should return false for invalid strings', () => {
expect(isIPv4('not-an-ip')).toBe(false);
expect(isIPv4('')).toBe(false);
expect(isIPv4('192.168.1')).toBe(false);
});
});
describe('Cache functions', () => {
beforeEach(() => {
// Clear cache by setting entries and letting them expire
// Note: In a real implementation, we'd want a clearCache() function
});
it('should store and retrieve cache entries', () => {
const query = 'test-cache-1.dnsbl.example.com';
setCacheEntry(query, ['127.0.0.2']);
const entry = getCacheEntry(query, 3600);
expect(entry).not.toBeNull();
expect(entry?.result).toEqual(['127.0.0.2']);
});
it('should return null for non-existent entries', () => {
const entry = getCacheEntry('nonexistent.query.com', 3600);
expect(entry).toBeNull();
});
it('should expire old entries', () => {
const query = 'test-cache-expire.dnsbl.example.com';
setCacheEntry(query, ['127.0.0.2']);
// With cacheTime of 0, entry should be expired
const entry = getCacheEntry(query, 0);
expect(entry).toBeNull();
});
it('should track cache size', () => {
const initialSize = getCacheSize();
const query = `test-cache-size-${Date.now()}.dnsbl.example.com`;
setCacheEntry(query, ['127.0.0.2']);
expect(getCacheSize()).toBeGreaterThanOrEqual(initialSize);
});
it('should handle null results (pending lookups)', () => {
const query = 'test-cache-null.dnsbl.example.com';
setCacheEntry(query, null);
const entry = getCacheEntry(query, 3600);
expect(entry).not.toBeNull();
expect(entry?.result).toBeNull();
});
});
describe('matchesDNSBL', () => {
it('should match by index', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '2,3,4',
};
expect(matchesDNSBL(['127.0.0.2'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.3'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.4'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.5'], config)).toBe(false);
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(false);
});
it('should match by bitmask', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
bitmask: '2', // Binary: 010
};
expect(matchesDNSBL(['127.0.0.2'], config)).toBe(true); // 010 & 010 = 010
expect(matchesDNSBL(['127.0.0.3'], config)).toBe(true); // 011 & 010 = 010
expect(matchesDNSBL(['127.0.0.6'], config)).toBe(true); // 110 & 010 = 010
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(false); // 001 & 010 = 000
expect(matchesDNSBL(['127.0.0.4'], config)).toBe(false); // 100 & 010 = 000
});
it('should match multiple bitmasks', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
bitmask: '2,4', // Match if bit 1 or bit 2 set
};
expect(matchesDNSBL(['127.0.0.2'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.4'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.6'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(false);
});
it('should match any result if no index or bitmask', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
};
expect(matchesDNSBL(['127.0.0.1'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.255'], config)).toBe(true);
});
it('should not match empty results', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '2',
};
expect(matchesDNSBL([], config)).toBe(false);
});
it('should match if any result matches (multiple results)', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '4',
};
expect(matchesDNSBL(['127.0.0.2', '127.0.0.4'], config)).toBe(true);
expect(matchesDNSBL(['127.0.0.1', '127.0.0.2'], config)).toBe(false);
});
it('should handle invalid result IPs gracefully', () => {
const config: DNSBLConfig = {
cfgNum: 1,
server: 'dnsbl.example.com',
index: '2',
};
expect(matchesDNSBL(['invalid', '127.0.0.2'], config)).toBe(true);
expect(matchesDNSBL(['invalid'], config)).toBe(false);
});
});
describe('parseQuery', () => {
it('should parse a valid DNSBL query', () => {
const result = parseQuery('10.1.168.192.dnsbl.example.com');
expect(result).not.toBeNull();
expect(result?.ip).toBe('192.168.1.10');
expect(result?.server).toBe('dnsbl.example.com');
});
it('should handle multi-part server names', () => {
const result = parseQuery('1.0.0.127.zen.spamhaus.org');
expect(result).not.toBeNull();
expect(result?.ip).toBe('127.0.0.1');
expect(result?.server).toBe('zen.spamhaus.org');
});
it('should return null for invalid queries', () => {
expect(parseQuery('invalid')).toBeNull();
expect(parseQuery('dnsbl.example.com')).toBeNull();
expect(parseQuery('')).toBeNull();
});
});
});
+474
View File
@@ -0,0 +1,474 @@
/**
* Integration tests for IAuth protocol
* Tests the full protocol communication by spawning the daemon
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';
import { spawn, ChildProcess } from 'node:child_process';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createInterface } from 'node:readline';
interface IAuthTestHarness {
process: ChildProcess;
output: string[];
send: (line: string) => void;
waitForOutput: (pattern: RegExp, timeout?: number) => Promise<string>;
waitForLines: (count: number, timeout?: number) => Promise<string[]>;
close: () => Promise<void>;
}
async function createTestHarness(configPath: string): Promise<IAuthTestHarness> {
const output: string[] = [];
const proc = spawn('npx', ['tsx', 'src/index.ts', '-v', '-c', configPath], {
cwd: join(import.meta.dirname, '..'),
stdio: ['pipe', 'pipe', 'pipe'],
});
const rl = createInterface({ input: proc.stdout! });
rl.on('line', (line) => {
output.push(line);
});
// Also capture stderr for debugging
proc.stderr?.on('data', (data) => {
console.error('stderr:', data.toString());
});
const send = (line: string) => {
proc.stdin!.write(line + '\n');
};
const waitForOutput = (pattern: RegExp, timeout = 5000): Promise<string> => {
return new Promise((resolve, reject) => {
// First check existing output
for (const line of output) {
if (pattern.test(line)) {
resolve(line);
return;
}
}
const startLen = output.length;
const checkInterval = setInterval(() => {
for (let i = startLen; i < output.length; i++) {
if (pattern.test(output[i])) {
clearInterval(checkInterval);
clearTimeout(timeoutId);
resolve(output[i]);
return;
}
}
}, 10);
const timeoutId = setTimeout(() => {
clearInterval(checkInterval);
reject(new Error(`Timeout waiting for pattern: ${pattern}`));
}, timeout);
});
};
const waitForLines = (count: number, timeout = 5000): Promise<string[]> => {
return new Promise((resolve, reject) => {
const startLen = output.length;
const checkInterval = setInterval(() => {
if (output.length >= startLen + count) {
clearInterval(checkInterval);
clearTimeout(timeoutId);
resolve(output.slice(startLen, startLen + count));
}
}, 10);
const timeoutId = setTimeout(() => {
clearInterval(checkInterval);
resolve(output.slice(startLen)); // Return what we have
}, timeout);
});
};
const close = (): Promise<void> => {
return new Promise((resolve) => {
proc.on('close', () => resolve());
proc.stdin!.end();
setTimeout(() => {
proc.kill('SIGTERM');
resolve();
}, 1000);
});
};
// Wait for startup - wait for stats output which comes last
await waitForOutput(/^S iauthd-ts/);
// Small delay to ensure all startup output is captured
await new Promise(r => setTimeout(r, 100));
return { process: proc, output, send, waitForOutput, waitForLines, close };
}
describe('IAuth Protocol Integration', () => {
let tempDir: string;
let configPath: string;
beforeAll(() => {
tempDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
configPath = join(tempDir, 'test.conf');
});
afterAll(() => {
try {
unlinkSync(configPath);
} catch {}
});
describe('Startup Messages', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH CACHETIME 3600
#IAUTH BLOCKMSG Test rejection message
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should send G (protocol version request) on startup', () => {
expect(harness.output).toContain('G 1');
});
it('should send V (version) on startup', () => {
const versionLine = harness.output.find(l => l.startsWith('V :'));
expect(versionLine).toBeDefined();
expect(versionLine).toContain('iauthd-ts');
});
it('should send O (policy) on startup', () => {
expect(harness.output).toContain('O RTAWUwFr');
});
it('should send a (new config) on startup', () => {
expect(harness.output).toContain('a');
});
it('should send A (config info) lines on startup', () => {
const configLines = harness.output.filter(l => l.startsWith('A *'));
expect(configLines.length).toBeGreaterThan(0);
});
it('should send s (stats start) on startup', () => {
expect(harness.output).toContain('s');
});
it('should send S (stats) lines on startup', () => {
const statsLines = harness.output.filter(l => l.startsWith('S '));
expect(statsLines.length).toBeGreaterThan(0);
});
});
describe('Client Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
// Config with no DNSBLs - clients should pass immediately
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should accept a client with no DNSBLs configured', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 H Users');
const doneLine = await harness.waitForOutput(/^D 0 192\.168\.1\.10 12345/);
expect(doneLine).toBeDefined();
});
it('should handle client disconnect', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 D');
// Should see debug message about disconnect
await harness.waitForOutput(/disconnected/i, 1000).catch(() => {});
// No error should occur
});
it('should handle multiple concurrent clients', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('1 C 192.168.1.11 12346 10.0.0.1 6667');
harness.send('2 C 192.168.1.12 12347 10.0.0.1 6667');
harness.send('0 H Users');
harness.send('1 H Users');
harness.send('2 H Users');
// All three should be accepted (longer timeout for concurrent processing)
await harness.waitForOutput(/^D 0/, 10000);
await harness.waitForOutput(/^D 1/, 10000);
await harness.waitForOutput(/^D 2/, 10000);
}, 15000);
});
describe('SASL/LOC Authentication', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
// Config that blocks anonymous but allows authenticated
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH BLOCKMSG Blocked for testing
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should track authenticated account', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 R testuser');
harness.send('0 H Users');
// Should see debug about auth
const authLine = await harness.waitForOutput(/authed as testuser/i);
expect(authLine).toBeDefined();
});
});
describe('SASL PLAIN Authentication', () => {
let harness: IAuthTestHarness;
let usersPath: string;
beforeEach(async () => {
// Create users file with test user (password: testpass)
usersPath = join(tempDir, 'users');
// Plain text password for testing
writeFileSync(usersPath, 'testuser:testpass\n');
// Config with SASL enabled (S in policy) and users file
writeFileSync(configPath, `
#IAUTH POLICY SRTAWUwFr
#IAUTH SASLDB ${usersPath}
#IAUTH SASLFAILMSG Authentication failed
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
try {
unlinkSync(usersPath);
} catch {}
});
it('should respond with challenge when SASL PLAIN is requested', async () => {
// IRCd introduces a client
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// IRCd sends SASL start with mechanism
// Format: <id> A S :<mechanism>
harness.send('0 A S :PLAIN');
// iauthd should respond with empty challenge ('+' means ready)
// Format: c <id> <ip> <port> :<challenge>
const challengeLine = await harness.waitForOutput(/^c 0 192\.168\.1\.10 12345 :\+$/);
expect(challengeLine).toBeDefined();
});
it('should send L and Z messages on successful authentication', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 A S :PLAIN');
await harness.waitForOutput(/^c 0/);
// Send SASL continuation with credentials
// Format: <id> a :<base64_data>
// Base64 of "\0testuser\0testpass" (SASL PLAIN format)
const credentials = Buffer.from('\0testuser\0testpass').toString('base64');
harness.send(`0 a :${credentials}`);
// iauthd should respond with L (login success) then Z (SASL complete)
// Format: L <id> <ip> <port> <account>
const loginLine = await harness.waitForOutput(/^L 0 192\.168\.1\.10 12345 testuser$/);
expect(loginLine).toBeDefined();
// Format: Z <id> <ip> <port>
const completeLine = await harness.waitForOutput(/^Z 0 192\.168\.1\.10 12345$/);
expect(completeLine).toBeDefined();
});
it('should send f message on failed authentication', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 A S :PLAIN');
await harness.waitForOutput(/^c 0/);
// Send wrong credentials
const credentials = Buffer.from('\0testuser\0wrongpass').toString('base64');
harness.send(`0 a :${credentials}`);
// iauthd should respond with f (auth failed)
// Format: f <id> <ip> <port>
const failLine = await harness.waitForOutput(/^f 0 192\.168\.1\.10 12345$/);
expect(failLine).toBeDefined();
});
it('should handle SASL host info message', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// IRCd sends host info with SASL start
// Format: <id> A H :<user@host:ip>
harness.send('0 A H :user@testhost.example.com:192.168.1.10');
// Should see debug about host info
const hostLine = await harness.waitForOutput(/SASL host info.*testhost/i);
expect(hostLine).toBeDefined();
});
it('should handle mechanism with certfp', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// Format with certfp: <id> A S <mechanism> :<certfp>
harness.send('0 A S PLAIN :abc123fingerprint');
// Should respond with challenge
const challengeLine = await harness.waitForOutput(/^c 0/);
expect(challengeLine).toBeDefined();
});
it('should send mechanism list for unsupported mechanism', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
// Request unsupported mechanism
harness.send('0 A S :EXTERNAL');
// Should respond with mechanism list
// Format: l <id> <ip> <port> :<mechanisms>
const mechLine = await harness.waitForOutput(/^l 0 192\.168\.1\.10 12345 :PLAIN$/);
expect(mechLine).toBeDefined();
});
it('should complete full SASL flow then accept client', async () => {
harness.send('0 C 192.168.1.10 12345 10.0.0.1 6667');
harness.send('0 A S :PLAIN');
await harness.waitForOutput(/^c 0/);
const credentials = Buffer.from('\0testuser\0testpass').toString('base64');
harness.send(`0 a :${credentials}`);
await harness.waitForOutput(/^L 0/);
await harness.waitForOutput(/^Z 0/);
// Now hurry up to finish connection
harness.send('0 H Users');
// Should accept the client with D message
const doneLine = await harness.waitForOutput(/^D 0 192\.168\.1\.10 12345/);
expect(doneLine).toBeDefined();
});
});
describe('WEBIRC Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should ignore untrusted WEBIRC (capital W)', async () => {
harness.send('0 C 10.0.0.100 12345 10.0.0.1 6667');
harness.send('0 W password user host.example.com 192.168.1.10');
await harness.waitForOutput(/untrusted WEBIRC/i);
});
it('should process trusted WEBIRC (lowercase w)', async () => {
harness.send('0 C 10.0.0.100 12345 10.0.0.1 6667');
harness.send('0 w password user host.example.com 192.168.1.10');
harness.send('0 H Users');
// Should accept with new IP
const doneLine = await harness.waitForOutput(/^D 0 192\.168\.1\.10/);
expect(doneLine).toBeDefined();
});
});
describe('Error Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should handle malformed client intro gracefully', async () => {
harness.send('0 C'); // Missing IP and ports
// Should not crash, might log an error
await new Promise(r => setTimeout(r, 100));
expect(harness.process.exitCode).toBeNull(); // Still running
});
it('should handle unknown message types gracefully', async () => {
harness.send('0 Z some unknown message');
await harness.waitForOutput(/unknown message/i, 1000).catch(() => {});
expect(harness.process.exitCode).toBeNull(); // Still running
});
it('should handle Hurry for unknown client gracefully', async () => {
harness.send('99 H Users'); // Client 99 was never introduced
await harness.waitForOutput(/ERROR.*hurry/i, 1000).catch(() => {});
expect(harness.process.exitCode).toBeNull(); // Still running
});
});
describe('IPv6 Handling', () => {
let harness: IAuthTestHarness;
beforeEach(async () => {
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSBL server=dnsbl.example.com index=2
`);
harness = await createTestHarness(configPath);
});
afterEach(async () => {
await harness?.close();
});
it('should skip DNSBL lookups for IPv6 and accept client', async () => {
harness.send('0 C 2001:db8::1 12345 ::1 6667');
harness.send('0 H Users');
// Should accept (IPv6 skips DNSBL lookups)
const doneLine = await harness.waitForOutput(/^D 0/);
expect(doneLine).toBeDefined();
});
});
});
+273
View File
@@ -0,0 +1,273 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
parseUsersFile,
verifyPassword,
generateHash,
decodeSASLPlain,
authenticatePlain,
} from '../src/sasl.js';
describe('SASL Module', () => {
describe('generateHash', () => {
it('should generate SHA-256 hash with $5$ prefix', () => {
const hash = generateHash('password', 'sha256');
expect(hash).toMatch(/^\$5\$[A-Za-z0-9]+\$[A-Za-z0-9+/]+$/);
});
it('should generate SHA-512 hash with $6$ prefix', () => {
const hash = generateHash('password', 'sha512');
expect(hash).toMatch(/^\$6\$[A-Za-z0-9]+\$[A-Za-z0-9+/]+$/);
});
it('should generate MD5 hash with $1$ prefix', () => {
const hash = generateHash('password', 'md5');
expect(hash).toMatch(/^\$1\$[A-Za-z0-9]+\$[A-Za-z0-9+/]+$/);
});
it('should generate different hashes for different passwords', () => {
const hash1 = generateHash('password1', 'sha256');
const hash2 = generateHash('password2', 'sha256');
expect(hash1).not.toBe(hash2);
});
it('should generate different hashes for same password (different salt)', () => {
const hash1 = generateHash('password', 'sha256');
const hash2 = generateHash('password', 'sha256');
// Salts are random, so hashes should be different
expect(hash1).not.toBe(hash2);
});
});
describe('verifyPassword', () => {
it('should verify SHA-256 hashed password', () => {
const hash = generateHash('testpass', 'sha256');
expect(verifyPassword('testpass', hash)).toBe(true);
expect(verifyPassword('wrongpass', hash)).toBe(false);
});
it('should verify SHA-512 hashed password', () => {
const hash = generateHash('testpass', 'sha512');
expect(verifyPassword('testpass', hash)).toBe(true);
expect(verifyPassword('wrongpass', hash)).toBe(false);
});
it('should verify MD5 hashed password', () => {
const hash = generateHash('testpass', 'md5');
expect(verifyPassword('testpass', hash)).toBe(true);
expect(verifyPassword('wrongpass', hash)).toBe(false);
});
it('should verify plain text password', () => {
expect(verifyPassword('plainpass', 'plainpass')).toBe(true);
expect(verifyPassword('wrongpass', 'plainpass')).toBe(false);
});
it('should reject invalid hash format', () => {
expect(verifyPassword('pass', '$invalid$format')).toBe(false);
expect(verifyPassword('pass', '$99$salt$hash')).toBe(false);
});
it('should handle empty password', () => {
const hash = generateHash('', 'sha256');
expect(verifyPassword('', hash)).toBe(true);
expect(verifyPassword('notempty', hash)).toBe(false);
});
});
describe('decodeSASLPlain', () => {
it('should decode valid SASL PLAIN data', () => {
// Format: base64(authzid \0 authcid \0 password)
const data = Buffer.from('\0testuser\0testpass').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authzid).toBe('');
expect(result?.authcid).toBe('testuser');
expect(result?.password).toBe('testpass');
});
it('should decode with authzid', () => {
const data = Buffer.from('authzid\0authcid\0password').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authzid).toBe('authzid');
expect(result?.authcid).toBe('authcid');
expect(result?.password).toBe('password');
});
it('should return null for invalid base64', () => {
const result = decodeSASLPlain('not-valid-base64!!!');
// Actually base64 decode may not fail, it will just produce garbage
// Let's test with wrong number of parts
});
it('should return null for wrong number of parts', () => {
// Only 2 parts instead of 3
const data = Buffer.from('user\0pass').toString('base64');
const result = decodeSASLPlain(data);
expect(result).toBeNull();
});
it('should handle empty fields', () => {
const data = Buffer.from('\0\0').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authzid).toBe('');
expect(result?.authcid).toBe('');
expect(result?.password).toBe('');
});
it('should handle special characters', () => {
const data = Buffer.from('\0user@example.com\0p@ss:word!').toString('base64');
const result = decodeSASLPlain(data);
expect(result).not.toBeNull();
expect(result?.authcid).toBe('user@example.com');
expect(result?.password).toBe('p@ss:word!');
});
});
describe('parseUsersFile', () => {
let tmpDir: string;
let usersFile: string;
beforeAll(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile = join(tmpDir, 'users');
});
afterAll(() => {
try {
unlinkSync(usersFile);
} catch {}
});
it('should parse simple users file', () => {
writeFileSync(usersFile, 'testuser:testpass\nadmin:adminpass\n');
const db = parseUsersFile(usersFile);
expect(db.users.size).toBe(2);
expect(db.users.get('testuser')?.passwordHash).toBe('testpass');
expect(db.users.get('admin')?.passwordHash).toBe('adminpass');
});
it('should skip comments and empty lines', () => {
writeFileSync(usersFile, '# Comment\n\nuser:pass\n \n# Another comment\n');
const db = parseUsersFile(usersFile);
expect(db.users.size).toBe(1);
expect(db.users.get('user')?.passwordHash).toBe('pass');
});
it('should lowercase usernames', () => {
writeFileSync(usersFile, 'TestUser:pass\nADMIN:pass2\n');
const db = parseUsersFile(usersFile);
expect(db.users.has('testuser')).toBe(true);
expect(db.users.has('admin')).toBe(true);
expect(db.users.has('TestUser')).toBe(false);
});
it('should handle passwords with colons', () => {
writeFileSync(usersFile, 'user:pass:with:colons\n');
const db = parseUsersFile(usersFile);
expect(db.users.get('user')?.passwordHash).toBe('pass:with:colons');
});
it('should handle crypt-style hashes', () => {
const hash = '$5$salt$hashvalue';
writeFileSync(usersFile, `user:${hash}\n`);
const db = parseUsersFile(usersFile);
expect(db.users.get('user')?.passwordHash).toBe(hash);
});
it('should return empty db for non-existent file', () => {
const db = parseUsersFile('/nonexistent/file');
expect(db.users.size).toBe(0);
});
it('should skip lines without colon', () => {
writeFileSync(usersFile, 'validuser:pass\ninvalidline\nanotheruser:anotherpass\n');
const db = parseUsersFile(usersFile);
expect(db.users.size).toBe(2);
expect(db.users.has('validuser')).toBe(true);
expect(db.users.has('anotheruser')).toBe(true);
});
});
describe('authenticatePlain', () => {
let tmpDir: string;
let usersFile: string;
beforeAll(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'iauthd-test-'));
usersFile = join(tmpDir, 'users');
// Create users file with various hash types
const sha256Hash = generateHash('sha256pass', 'sha256');
const sha512Hash = generateHash('sha512pass', 'sha512');
writeFileSync(usersFile, [
`plainuser:plainpass`,
`sha256user:${sha256Hash}`,
`sha512user:${sha512Hash}`,
].join('\n'));
});
afterAll(() => {
try {
unlinkSync(usersFile);
} catch {}
});
it('should authenticate with plain text password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'plainuser', 'plainpass');
expect(result).toBe('plainuser');
});
it('should authenticate with SHA-256 hashed password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'sha256user', 'sha256pass');
expect(result).toBe('sha256user');
});
it('should authenticate with SHA-512 hashed password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'sha512user', 'sha512pass');
expect(result).toBe('sha512user');
});
it('should reject wrong password', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'plainuser', 'wrongpass');
expect(result).toBeNull();
});
it('should reject non-existent user', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'nouser', 'anypass');
expect(result).toBeNull();
});
it('should be case-insensitive for username', () => {
const db = parseUsersFile(usersFile);
const result = authenticatePlain(db, 'PlainUser', 'plainpass');
expect(result).toBe('plainuser');
});
});
});
+313
View File
@@ -0,0 +1,313 @@
#!/usr/bin/env npx tsx
/**
* Memory stress test for iauthd-ts
*
* Simulates thousands of client connections to verify:
* 1. Memory doesn't leak (client map cleanup)
* 2. DNS cache doesn't grow unbounded
* 3. Performance remains stable under load
*
* Usage:
* npm run stress
* npm run stress -- --clients=10000 --duration=60
*/
import { spawn, ChildProcess } from 'node:child_process';
import { writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createInterface } from 'node:readline';
import { parseArgs } from 'node:util';
interface StressOptions {
clients: number; // Total clients to simulate
concurrent: number; // Max concurrent connections
duration: number; // Max duration in seconds
verbose: boolean; // Verbose output
}
interface Stats {
clientsSent: number;
clientsAccepted: number;
clientsRejected: number;
startTime: number;
lastHeapUsed: number;
maxHeapUsed: number;
samples: Array<{ time: number; heap: number; clients: number; cache: number }>;
}
function parseOptions(): StressOptions {
const { values } = parseArgs({
options: {
clients: { type: 'string', short: 'n', default: '5000' },
concurrent: { type: 'string', short: 'c', default: '100' },
duration: { type: 'string', short: 'd', default: '120' },
verbose: { type: 'boolean', short: 'v', default: false },
},
strict: true,
});
return {
clients: parseInt(values.clients!, 10),
concurrent: parseInt(values.concurrent!, 10),
duration: parseInt(values.duration!, 10),
verbose: values.verbose!,
};
}
function generateRandomIP(): string {
const a = Math.floor(Math.random() * 223) + 1; // 1-223 (avoid 0 and 224+)
const b = Math.floor(Math.random() * 256);
const c = Math.floor(Math.random() * 256);
const d = Math.floor(Math.random() * 256);
return `${a}.${b}.${c}.${d}`;
}
async function runStressTest(options: StressOptions): Promise<void> {
console.log('='.repeat(60));
console.log('iauthd-ts Memory Stress Test');
console.log('='.repeat(60));
console.log(`Clients to simulate: ${options.clients}`);
console.log(`Max concurrent: ${options.concurrent}`);
console.log(`Max duration: ${options.duration}s`);
console.log('='.repeat(60));
console.log();
// Create temp config
const tempDir = mkdtempSync(join(tmpdir(), 'iauthd-stress-'));
const configPath = join(tempDir, 'stress.conf');
// Use a DNSBL that will respond quickly (or use a fake one)
// For stress testing, we want quick responses so we use short timeout
writeFileSync(configPath, `
#IAUTH POLICY RTAWUwFr
#IAUTH DNSTIMEOUT 1
#IAUTH CACHETIME 60
#IAUTH BLOCKMSG Stress test rejection
#IAUTH DNSBL server=zen.spamhaus.org index=2,3,4,5,6,7 mark=spamhaus block=anonymous
`);
const stats: Stats = {
clientsSent: 0,
clientsAccepted: 0,
clientsRejected: 0,
startTime: Date.now(),
lastHeapUsed: 0,
maxHeapUsed: 0,
samples: [],
};
// Spawn the daemon with memory tracking
const proc = spawn('node', [
'--expose-gc',
'--max-old-space-size=256', // Limit heap to catch leaks faster
'dist/index.js',
'-c', configPath,
], {
cwd: join(import.meta.dirname, '..'),
stdio: ['pipe', 'pipe', 'pipe'],
env: {
...process.env,
NODE_OPTIONS: '--expose-gc',
},
});
let cacheSize = 0;
let activeClients = 0;
const rl = createInterface({ input: proc.stdout! });
rl.on('line', (line) => {
if (options.verbose) {
console.log('< ' + line);
}
if (line.startsWith('D ')) {
stats.clientsAccepted++;
activeClients--;
} else if (line.startsWith('k ')) {
stats.clientsRejected++;
activeClients--;
} else if (line.includes('Cache size:')) {
const match = line.match(/Cache size: (\d+)/);
if (match) {
cacheSize = parseInt(match[1], 10);
}
}
});
proc.stderr?.on('data', (data) => {
if (options.verbose) {
console.error('stderr:', data.toString());
}
});
const send = (line: string) => {
if (options.verbose) {
console.log('> ' + line);
}
proc.stdin!.write(line + '\n');
};
// Wait for startup
await new Promise<void>((resolve) => {
const checkStartup = setInterval(() => {
// Check if we've seen the startup messages
if (stats.clientsSent === 0) {
clearInterval(checkStartup);
resolve();
}
}, 100);
setTimeout(() => {
clearInterval(checkStartup);
resolve();
}, 2000);
});
console.log('Daemon started. Beginning stress test...\n');
// Send server info
send('-1 M stress.test.server 65535');
const startTime = Date.now();
const endTime = startTime + (options.duration * 1000);
let clientId = 0;
// Progress reporting
const progressInterval = setInterval(() => {
const elapsed = (Date.now() - startTime) / 1000;
const rate = stats.clientsSent / elapsed;
const heapUsed = process.memoryUsage().heapUsed / 1024 / 1024;
stats.samples.push({
time: elapsed,
heap: heapUsed,
clients: activeClients,
cache: cacheSize,
});
if (heapUsed > stats.maxHeapUsed) {
stats.maxHeapUsed = heapUsed;
}
stats.lastHeapUsed = heapUsed;
process.stdout.write(
`\rSent: ${stats.clientsSent} | Accepted: ${stats.clientsAccepted} | ` +
`Rejected: ${stats.clientsRejected} | Active: ${activeClients} | ` +
`Cache: ${cacheSize} | Rate: ${rate.toFixed(1)}/s | ` +
`Elapsed: ${elapsed.toFixed(1)}s `
);
}, 1000);
// Main send loop
const sendBatch = () => {
const now = Date.now();
if (now >= endTime || stats.clientsSent >= options.clients) {
return false;
}
// Send up to concurrent limit
while (activeClients < options.concurrent && stats.clientsSent < options.clients) {
const ip = generateRandomIP();
const port = 10000 + (clientId % 55535);
send(`${clientId} C ${ip} ${port} 10.0.0.1 6667`);
send(`${clientId} H Users`);
stats.clientsSent++;
activeClients++;
clientId++;
}
return true;
};
// Run the send loop
while (sendBatch()) {
await new Promise(r => setTimeout(r, 10));
}
// Wait for remaining clients to be processed
console.log('\n\nWaiting for remaining clients to be processed...');
const drainStart = Date.now();
while (activeClients > 0 && (Date.now() - drainStart) < 30000) {
await new Promise(r => setTimeout(r, 100));
}
clearInterval(progressInterval);
// Cleanup
proc.stdin!.end();
await new Promise<void>((resolve) => {
proc.on('close', () => resolve());
setTimeout(() => {
proc.kill('SIGTERM');
resolve();
}, 2000);
});
try {
rmSync(tempDir, { recursive: true });
} catch {}
// Print results
const totalTime = (Date.now() - startTime) / 1000;
console.log('\n');
console.log('='.repeat(60));
console.log('STRESS TEST RESULTS');
console.log('='.repeat(60));
console.log(`Total clients sent: ${stats.clientsSent}`);
console.log(`Total clients accepted: ${stats.clientsAccepted}`);
console.log(`Total clients rejected: ${stats.clientsRejected}`);
console.log(`Unprocessed clients: ${stats.clientsSent - stats.clientsAccepted - stats.clientsRejected}`);
console.log(`Total time: ${totalTime.toFixed(2)}s`);
console.log(`Average rate: ${(stats.clientsSent / totalTime).toFixed(2)} clients/s`);
console.log(`Final cache size: ${cacheSize}`);
console.log('');
// Memory analysis
console.log('MEMORY ANALYSIS');
console.log('-'.repeat(60));
if (stats.samples.length > 1) {
const firstSample = stats.samples[0];
const lastSample = stats.samples[stats.samples.length - 1];
const heapGrowth = lastSample.heap - firstSample.heap;
const heapGrowthPercent = (heapGrowth / firstSample.heap) * 100;
console.log(`Initial heap: ${firstSample.heap.toFixed(2)} MB`);
console.log(`Final heap: ${lastSample.heap.toFixed(2)} MB`);
console.log(`Max heap: ${stats.maxHeapUsed.toFixed(2)} MB`);
console.log(`Heap growth: ${heapGrowth.toFixed(2)} MB (${heapGrowthPercent.toFixed(1)}%)`);
// Check for memory leak indicators
console.log('');
if (heapGrowthPercent > 100) {
console.log('⚠️ WARNING: Significant heap growth detected. Possible memory leak.');
} else if (heapGrowthPercent > 50) {
console.log('⚠️ NOTICE: Moderate heap growth. Monitor in production.');
} else {
console.log('✅ Memory usage appears stable.');
}
// Check if all clients were processed
const unprocessed = stats.clientsSent - stats.clientsAccepted - stats.clientsRejected;
if (unprocessed > 0) {
console.log(`⚠️ WARNING: ${unprocessed} clients were not processed. Possible state leak.`);
} else {
console.log('✅ All clients were processed correctly.');
}
// Check cache growth
const clientsPerCacheEntry = stats.clientsSent / Math.max(cacheSize, 1);
console.log(`Cache efficiency: ${clientsPerCacheEntry.toFixed(1)} clients per cache entry`);
}
console.log('='.repeat(60));
}
// Run the test
const options = parseOptions();
runStressTest(options).catch(console.error);