diff --git a/lib/AgentManager.js b/lib/AgentManager.js index b496bd72..cf6eb0ed 100644 --- a/lib/AgentManager.js +++ b/lib/AgentManager.js @@ -500,7 +500,15 @@ class AgentManager { // 'w' flag definition: https://nodejs.org/docs/latest-v16.x/api/fs.html#file-system-flags // Open the file for writing. The file is created // (if it does not exist) or truncated (if it exists). - const fn = fs.openSync(deviceFile, 'w') + // The mode only applies when the file is created. + const fn = fs.openSync(deviceFile, 'w', 0o600) + try { + // A file truncated in place keeps its old mode + fs.fchmodSync(fn, 0o600) + } catch (error) { + // fails with EPERM when the file is owned by another user + debug(`Error setting mode on device file '${deviceFile}': ${error.message}`) + } fs.writeFileSync(fn, deviceYAML, { encoding: 'utf8' }) fs.closeSync(fn) } catch (error) { diff --git a/test/unit/lib/AgentManager_spec.js b/test/unit/lib/AgentManager_spec.js index 33ee7f7b..022ec9e2 100644 --- a/test/unit/lib/AgentManager_spec.js +++ b/test/unit/lib/AgentManager_spec.js @@ -202,6 +202,37 @@ my_data: AgentManager._provisionDevice.restore() } }) + describe('Device file mode', function () { + const provisioningData = { + id: 'device-hash-id', + forgeURL: 'http://localhost:3000', + credentials: { token: 'i-am-token', credentialSecret: 'cred-secret' } + } + before(function () { + if (process.platform === 'win32') { + this.skip() + } + }) + it('writes a new device file readable only by its owner', async function () { + const deviceFile = path.join(configDir, 'project', 'device.yml') + await fs.writeFile(deviceFile, 'forgeURL: http://localhost:9000\n', { mode: 0o644 }) + AgentManager.init({ deviceFile }) + await AgentManager._provisionDevice(provisioningData) + const stat = await fs.stat(deviceFile) + ;(stat.mode & 0o777).should.equal(0o600) + }) + it('restricts the mode when the device file is rewritten in place', async function () { + const deviceFile = path.join(configDir, 'project', 'device.yml') + await fs.writeFile(deviceFile, 'forgeURL: http://localhost:9000\n', { mode: 0o644 }) + sinon.stub(require('fs'), 'renameSync').throws(new Error('EBUSY')) + AgentManager.init({ deviceFile }) + await AgentManager._provisionDevice(provisioningData) + const stat = await fs.stat(deviceFile) + ;(stat.mode & 0o777).should.equal(0o600) + const deviceConfig = await fs.readFile(deviceFile, 'utf8') + deviceConfig.should.match(/deviceId: device-hash-id/) + }) + }) it('Agent Manager should request config from FlowFuse when started in Quick Connect mode', async function () { const deviceFile = path.join(configDir, 'project', 'device.yml') // setup a web server to mock the FlowFuse server