Use configured local mail broker with restricted SSH rollback
This commit is contained in:
parent
a2f5b8243d
commit
13c2976a24
6 changed files with 141 additions and 6 deletions
|
|
@ -1,3 +1,4 @@
|
|||
import {mailBrokerCommand} from './mail-broker-transport.mjs';
|
||||
import {cacheMailMetadata} from './mail-metadata-cache.mjs';
|
||||
import {reconcileRoyalCompanyMail} from './company-royal-mail.mjs';
|
||||
import {ownCompanyMailbox,ensureCompanyMailbox,reconcileCompanyMail,defaultCompanyMailbox} from './internal-mail-companies.mjs';
|
||||
|
|
@ -25,8 +26,8 @@ export async function initializeInternalMailAccess(db){
|
|||
await db.prepare('INSERT INTO website_settings(setting_key,setting_value,updated_at) VALUES(?,?,?)').bind(key,'complete',Date.now()).run();
|
||||
}
|
||||
export function internalMailBroker(payload){return new Promise((resolve,reject)=>{
|
||||
const dir='/home/dunerealms/.config/';let output=[],bytes=0,done=false;
|
||||
const child=spawn('/usr/bin/ssh',['-T','-i',dir+'staff-mail-broker-key','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','StrictHostKeyChecking=yes','-o','ConnectTimeout=7','-o','UserKnownHostsFile='+dir+'staff-mail-broker-known-hosts','root@2.28.33.142'],{stdio:['pipe','pipe','ignore']});
|
||||
let output=[],bytes=0,done=false;
|
||||
const {command,args}=mailBrokerCommand();const child=spawn(command,args,{stdio:['pipe','pipe','ignore']});
|
||||
const fail=(message='Internal Mail is temporarily unavailable.',code=503)=>{if(done)return;done=true;clearTimeout(timer);child.kill();reject(Object.assign(Error(message),{status:code}));};
|
||||
const timer=setTimeout(()=>fail('Mail operation timed out. Refresh before retrying a send.'),90000);child.on('error',()=>fail());child.stdin.on('error',()=>fail());
|
||||
child.stdout.on('data',chunk=>{bytes+=chunk.length;if(bytes>32*1024*1024)return fail('Mail response exceeds limit.',413);output.push(chunk);});
|
||||
|
|
|
|||
18
website/node/mail-broker-transport.mjs
Normal file
18
website/node/mail-broker-transport.mjs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import {readFileSync} from 'node:fs';
|
||||
|
||||
// Administrator-owned transport settings; never accept these values from HTTP input.
|
||||
export function mailBrokerCommand({file=process.env.DUNE_MAIL_BROKER_SETTINGS||'/etc/dune-mail-broker/settings.json'}={}){
|
||||
const config=JSON.parse(readFileSync(file,'utf8'));
|
||||
if(config.version!==1)throw Error('Unsupported mail broker settings version');
|
||||
const transport=config.transport;
|
||||
if(transport?.mode==='local'){
|
||||
const command=transport.local?.command;
|
||||
if(typeof command!=='string'||!command.startsWith('/')||/[\r\n\0]/.test(command))throw Error('Invalid local mail broker path');
|
||||
return transport.local.sudo===false?{command,args:[]}:{command:'/usr/bin/sudo',args:['-n',command]};
|
||||
}
|
||||
if(transport?.mode!=='ssh')throw Error('Choose local or ssh mail broker transport');
|
||||
const ssh=transport.ssh;
|
||||
if(!ssh||typeof ssh.host!=='string'||!/^[a-z_][a-z0-9_-]*@[a-z0-9][a-z0-9.-]*$/i.test(ssh.host))throw Error('Invalid mail broker SSH host');
|
||||
for(const key of ['identityFile','knownHostsFile'])if(typeof ssh[key]!=='string'||!ssh[key].startsWith('/')||/[\r\n\0]/.test(ssh[key]))throw Error('Invalid mail broker SSH path');
|
||||
return {command:'/usr/bin/ssh',args:['-T','-i',ssh.identityFile,'-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','StrictHostKeyChecking=yes','-o','ConnectTimeout=7','-o','UserKnownHostsFile='+ssh.knownHostsFile,ssh.host]};
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import {mailBrokerCommand} from './mail-broker-transport.mjs';
|
||||
import {spawn} from 'node:child_process';
|
||||
|
||||
const directory='/home/dunerealms/.config/';
|
||||
// The remote key is bound to one source IP and a forced JSON-only root command.
|
||||
// It cannot open a shell, forward a port or select an arbitrary mailbox address.
|
||||
// Administrator settings select the local JSON-only broker or restricted SSH broker.
|
||||
// Request validation and mailbox ownership remain independent of that transport.
|
||||
export async function callMailBroker(payload){
|
||||
if(!payload||!['ensure','status','set_password'].includes(payload.action)||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(payload.userId||''))throw Error('Invalid mailbox request');
|
||||
const request={action:payload.action,userId:payload.userId};
|
||||
|
|
@ -15,7 +15,7 @@ export async function callMailBroker(payload){
|
|||
request.password=payload.password;
|
||||
}
|
||||
return new Promise((resolve,reject)=>{
|
||||
const child=spawn('/usr/bin/ssh',['-T','-i',directory+'staff-mail-broker-key','-o','BatchMode=yes','-o','IdentitiesOnly=yes','-o','StrictHostKeyChecking=yes','-o','ConnectTimeout=7','-o','UserKnownHostsFile='+directory+'staff-mail-broker-known-hosts','root@2.28.33.142'],{stdio:['pipe','pipe','ignore']});
|
||||
const {command,args}=mailBrokerCommand();const child=spawn(command,args,{stdio:['pipe','pipe','ignore']});
|
||||
let output='',finished=false;
|
||||
const fail=message=>{if(finished)return;finished=true;clearTimeout(timer);child.kill();reject(Error(message));};
|
||||
const timer=setTimeout(()=>fail('Mailbox service temporarily unavailable'),15000);
|
||||
|
|
|
|||
68
website/ops/LOCAL-MAIL.md
Normal file
68
website/ops/LOCAL-MAIL.md
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
# Local DuneRealms mailbox transport
|
||||
|
||||
Both named-account provisioning and internal mailbox operations use
|
||||
`node/mail-broker-transport.mjs`. The existing validation, permissions, metadata
|
||||
cache and JSON broker protocol are unchanged. Mail content is stored by Dovecot
|
||||
on the website host; internal read/write/send operations no longer open SSH
|
||||
connections to the controller.
|
||||
|
||||
## Settings
|
||||
|
||||
The administrator-owned `/etc/dune-mail-broker/settings.json` is the single
|
||||
local configuration file. `DUNE_MAIL_BROKER_SETTINGS` can select another file.
|
||||
Use `mail-broker-settings.example.json` as the schema reference. Preserve an
|
||||
existing settings file; update only the intended values. Missing or invalid
|
||||
settings fail closed rather than silently selecting an old host.
|
||||
|
||||
- `transport.mode`: `local` or `ssh`.
|
||||
- `transport.local`: absolute broker command and whether to use `sudo -n`.
|
||||
- `transport.ssh`: pinned host, identity file and known-hosts file for rollback.
|
||||
- `mail`: IMAP/SMTP host and ports used by the installed Python internal broker,
|
||||
plus the existing public webmail URL.
|
||||
- `delivery`: controller address/port, loopback address and website address used
|
||||
to configure Postfix, TLS and the restricted backend listeners.
|
||||
|
||||
The settings file contains no passwords and is root-owned, readable by the
|
||||
application group. Database credentials, encrypted generated-mailbox credentials,
|
||||
password hashes and TLS private keys remain root-private. The application can
|
||||
run only `/usr/local/sbin/dune-mail-broker` through its dedicated sudo rule.
|
||||
|
||||
The controller keeps its non-secret domain routing settings separately at
|
||||
`/etc/dune-mail-router/settings.json`. Other domains retain their existing
|
||||
configuration. Its Dovecot authenticates Dune logins against the backend over
|
||||
verified TLS; SMTP SASL also checks the backend password. Postfix routes the
|
||||
Dune domain to the backend and verifies recipients there. Controller SMTP
|
||||
trust is restricted to the website source. The local submission policy rejects
|
||||
external recipients from internal identities before approved alias forwarding.
|
||||
|
||||
The JSON broker reads settings for each invocation. After changing delivery
|
||||
addresses or ports, regenerate the affected service configuration/firewall/TLS
|
||||
certificate and reload those services; editing JSON alone does not reconfigure
|
||||
Postfix or Dovecot. The Node consumers require a process reload only when code
|
||||
changes. Do not change unrelated integration settings.
|
||||
|
||||
## Installed operation, 19 November 2026
|
||||
|
||||
The owner authorized direct live installation before committing this change.
|
||||
Two active personal named accounts were copied with their existing password
|
||||
hashes and central identity mappings. No message migration was requested;
|
||||
automatic/shared mailboxes regenerate through the existing reconciliation.
|
||||
Old controller mailbox data was retained for rollback.
|
||||
|
||||
Storage: `/var/vmail` points to
|
||||
`/mnt/HC_Volume_107481500/dunegit/mail/vmail`. Managed internal mailboxes retain
|
||||
the existing 100 MB quota and 30-day purge through
|
||||
`dune-internal-mail-purge.timer`. Backend IMAPS/SMTP listeners are restricted to
|
||||
loopback and the controller by `dune-mail-firewall.service`; submission is
|
||||
loopback-only. No public backend mail credentials were introduced.
|
||||
|
||||
Verification: both personal password hashes matched the source; local internal
|
||||
provision/list/send/read/Sent succeeded; the unchanged public IMAP endpoint
|
||||
reached the backend and rejected an incorrect password; internal external-compose
|
||||
was rejected at SMTP RCPT. Verification messages were removed. No external
|
||||
test message was sent. No full website rebuild was used for these live checks.
|
||||
|
||||
Rollback is an operator procedure: select the restricted SSH transport, restore
|
||||
the controller domain routing/configuration from its root-private `before`
|
||||
directory, and reload services. Reconcile messages created after cutover before
|
||||
rolling storage back; switching transport alone does not move those messages.
|
||||
14
website/ops/mail-broker-settings.example.json
Normal file
14
website/ops/mail-broker-settings.example.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"version": 1,
|
||||
"transport": {
|
||||
"mode": "local",
|
||||
"local": {"command": "/usr/local/sbin/dune-mail-broker", "sudo": true},
|
||||
"ssh": {
|
||||
"host": "root@mail-controller.example.invalid",
|
||||
"identityFile": "/home/dunerealms/.config/staff-mail-broker-key",
|
||||
"knownHostsFile": "/home/dunerealms/.config/staff-mail-broker-known-hosts"
|
||||
}
|
||||
},
|
||||
"mail": {"host": "localhost", "imapPort": 993, "smtpPort": 587, "webmailUrl": "https://www.lgbbenelux.org/webmail/"},
|
||||
"delivery": {"gatewayHost": "mail-controller.example.invalid", "gatewayPort": 25, "localAddress": "127.0.0.1", "siteAddress": "site.example.invalid"}
|
||||
}
|
||||
34
website/tests/mail-broker-transport.test.mjs
Normal file
34
website/tests/mail-broker-transport.test.mjs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdtempSync,writeFileSync,rmSync} from 'node:fs';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join} from 'node:path';
|
||||
import {mailBrokerCommand} from '../node/mail-broker-transport.mjs';
|
||||
|
||||
function configured(config,check){
|
||||
const directory=mkdtempSync(join(tmpdir(),'dune-mail-transport-'));
|
||||
const file=join(directory,'settings.json');
|
||||
try{writeFileSync(file,JSON.stringify(config));check(()=>mailBrokerCommand({file}));}
|
||||
finally{rmSync(directory,{recursive:true,force:true});}
|
||||
}
|
||||
test('local mail uses only the narrowly allowed local broker command',()=>{
|
||||
configured({version:1,transport:{mode:'local',local:{command:'/usr/local/sbin/dune-mail-broker',sudo:true}}},read=>{
|
||||
assert.deepEqual(read(),{command:'/usr/bin/sudo',args:['-n','/usr/local/sbin/dune-mail-broker']});
|
||||
});
|
||||
});
|
||||
test('SSH rollback uses configured addresses and pinned host keys',()=>{
|
||||
configured({version:1,transport:{mode:'ssh',ssh:{host:'broker@mail.example.invalid',identityFile:'/private/key',knownHostsFile:'/private/known-hosts'}}},read=>{
|
||||
const result=read();assert.equal(result.command,'/usr/bin/ssh');
|
||||
assert.equal(result.args.at(-1),'broker@mail.example.invalid');
|
||||
assert.ok(result.args.includes('StrictHostKeyChecking=yes'));
|
||||
assert.ok(result.args.includes('UserKnownHostsFile=/private/known-hosts'));
|
||||
});
|
||||
});
|
||||
test('invalid transport settings fail closed without silently using another server',()=>{
|
||||
for(const config of [
|
||||
{version:2,transport:{mode:'local'}},
|
||||
{version:1,transport:{mode:'other'}},
|
||||
{version:1,transport:{mode:'local',local:{command:'relative-command'}}},
|
||||
{version:1,transport:{mode:'ssh',ssh:{host:'-oProxyCommand=bad',identityFile:'/key',knownHostsFile:'/known'}}}
|
||||
])configured(config,read=>assert.throws(read));
|
||||
});
|
||||
Loading…
Reference in a new issue

Staff