Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion lib/AgentManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
31 changes: 31 additions & 0 deletions test/unit/lib/AgentManager_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading