diff --git a/.changeset/cli-env-file-private-permissions.md b/.changeset/cli-env-file-private-permissions.md new file mode 100644 index 000000000..b31b30400 --- /dev/null +++ b/.changeset/cli-env-file-private-permissions.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +fix(cli): keep the .env file private to its owner + +`nostream setup` and `nostream config env set` wrote `.env` with the default file mode, which under the usual umask makes it readable by every local account that can reach the project directory. The file holds `SECRET`, which signs the admin session tokens, and other credentials. The CLI now creates `.env` readable by its owner only (mode 0600), including when it starts from `.env.example`, and restricts an existing `.env` to the owner whenever it writes to it. An existing `.env` that setup does not need to change is left as it is. Where the permissions cannot be changed, for example on a file system without Unix permissions, the write still succeeds. diff --git a/src/cli/commands/setup.ts b/src/cli/commands/setup.ts index 1bc84fe22..3bf4b1d0f 100644 --- a/src/cli/commands/setup.ts +++ b/src/cli/commands/setup.ts @@ -3,7 +3,7 @@ import { randomBytes } from 'crypto' import { intro, outro, confirm, text, isCancel, cancel } from '@clack/prompts' import { ensureConfigBootstrap } from '../utils/bootstrap' -import { getUnsafeSecretReason, stripQuotes } from '../utils/env-config' +import { getUnsafeSecretReason, stripQuotes, writeEnvFile } from '../utils/env-config' import { getProjectPath } from '../utils/paths' import { runStart } from './start' @@ -172,11 +172,8 @@ const ensureEnvFile = async (assumeYes: boolean): Promise => { const envExamplePath = getProjectPath('.env.example') if (!fs.existsSync(envPath)) { - if (fs.existsSync(envExamplePath)) { - fs.copyFileSync(envExamplePath, envPath) - } else { - fs.writeFileSync(envPath, '', 'utf-8') - } + // Written with writeEnvFile rather than copied, so the new file is private from the start. + writeEnvFile(envPath, fs.existsSync(envExamplePath) ? fs.readFileSync(envExamplePath, 'utf-8') : '') } const current = fs.readFileSync(envPath, 'utf-8') @@ -204,7 +201,7 @@ const ensureEnvFile = async (assumeYes: boolean): Promise => { } process.env.SECRET = secret - fs.writeFileSync(envPath, upsertSecret(current, secret), 'utf-8') + writeEnvFile(envPath, upsertSecret(current, secret)) return true } diff --git a/src/cli/utils/env-config.ts b/src/cli/utils/env-config.ts index d35cc1ef7..1bb546f88 100644 --- a/src/cli/utils/env-config.ts +++ b/src/cli/utils/env-config.ts @@ -202,6 +202,32 @@ export const readEnvValues = (): Record => { return values } +// .env holds SECRET, which signs the admin session tokens, and other credentials, so only its owner should read +// it. With the usual umask a file created with the default mode is readable by every local account. +const PRIVATE_FILE_MODE = 0o600 + +/** Writes the .env file readable by its owner only, whether it exists already or not. */ +export const writeEnvFile = (envPath: string, content: string): void => { + // The mode option of the write only applies when the file is created, so a file that exists already is restricted + // first, before the new content is written into it. A file that does not exist yet fails here, which is fine. + restrictEnvFile(envPath) + + // A new file is created with the private mode, so it is never readable by others, not even briefly. + fs.writeFileSync(envPath, content, { encoding: 'utf-8', mode: PRIVATE_FILE_MODE }) + + // Sets exactly the private mode on a new file as well, in case the umask left it with fewer bits. + restrictEnvFile(envPath) +} + +const restrictEnvFile = (envPath: string): void => { + try { + fs.chmodSync(envPath, PRIVATE_FILE_MODE) + } catch { + // Best effort: a missing file, a file system without Unix permissions, or a file we do not own must not stop + // the write. + } +} + export const upsertEnvValue = (key: string, value: string): void => { const envPath = getEnvFilePath() const { lines, parsed } = parseEnvFile() @@ -218,7 +244,7 @@ export const upsertEnvValue = (key: string, value: string): void => { lines.push(replacement) } - fs.writeFileSync(envPath, lines.join('\n').replace(/\n?$/, '\n'), 'utf-8') + writeEnvFile(envPath, lines.join('\n').replace(/\n?$/, '\n')) } export const validateEnvValues = (values: Record): EnvValidationIssue[] => { diff --git a/test/unit/cli/env-file.spec.ts b/test/unit/cli/env-file.spec.ts new file mode 100644 index 000000000..1397c7fa3 --- /dev/null +++ b/test/unit/cli/env-file.spec.ts @@ -0,0 +1,110 @@ +import { expect } from 'chai' +import fs from 'fs' +import os from 'os' +import path from 'path' + +import { upsertEnvValue, writeEnvFile } from '../../../src/cli/utils/env-config' + +describe('the permissions of the .env file written by the CLI', function () { + // File modes mean nothing on Windows. + before(function () { + if (process.platform === 'win32') { + this.skip() + } + }) + + const originalCwd = process.cwd() + let tempDir: string + let originalUmask: number + + const envPath = () => path.join(tempDir, '.env') + const modeOf = (file: string) => fs.statSync(file).mode & 0o777 + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nostream-env-')) + process.chdir(tempDir) + // The usual umask, under which a file created with the default mode is readable by every local account. + originalUmask = process.umask(0o022) + }) + + afterEach(() => { + process.umask(originalUmask) + process.chdir(originalCwd) + fs.rmSync(tempDir, { recursive: true, force: true }) + }) + + describe('writeEnvFile', () => { + it('creates a new file readable by its owner only', () => { + writeEnvFile(envPath(), 'SECRET=abc\n') + + expect(modeOf(envPath())).to.equal(0o600) + expect(fs.readFileSync(envPath(), 'utf-8')).to.equal('SECRET=abc\n') + }) + + it('restricts a file that exists already and replaces its content', () => { + fs.writeFileSync(envPath(), 'OLD=1\n') + fs.chmodSync(envPath(), 0o644) + + writeEnvFile(envPath(), 'SECRET=abc\n') + + expect(modeOf(envPath())).to.equal(0o600) + expect(fs.readFileSync(envPath(), 'utf-8')).to.equal('SECRET=abc\n') + }) + + it('restricts an existing file before the new content is written into it', () => { + fs.writeFileSync(envPath(), 'OLD=1\n') + fs.chmodSync(envPath(), 0o644) + + // What another account could read at the moment the new content arrives. + let modeWhenWritten: number | undefined + const write = fs.writeFileSync + ;(fs as any).writeFileSync = (...args: Parameters) => { + modeWhenWritten = modeOf(envPath()) + return write(...args) + } + + try { + writeEnvFile(envPath(), 'SECRET=abc\n') + } finally { + ;(fs as any).writeFileSync = write + } + + expect(modeWhenWritten).to.equal(0o600) + expect(fs.readFileSync(envPath(), 'utf-8')).to.equal('SECRET=abc\n') + }) + + it('does not fail when the permissions cannot be changed', () => { + const chmod = fs.chmodSync + ;(fs as any).chmodSync = () => { + throw Object.assign(new Error('EPERM'), { code: 'EPERM' }) + } + + try { + expect(() => writeEnvFile(envPath(), 'SECRET=abc\n')).not.to.throw() + } finally { + ;(fs as any).chmodSync = chmod + } + + expect(fs.readFileSync(envPath(), 'utf-8')).to.equal('SECRET=abc\n') + }) + }) + + describe('upsertEnvValue (nostream config env set)', () => { + it('creates .env readable by its owner only when it did not exist', () => { + upsertEnvValue('SECRET', 'abc') + + expect(modeOf(envPath())).to.equal(0o600) + expect(fs.readFileSync(envPath(), 'utf-8')).to.equal('SECRET=abc\n') + }) + + it('restricts an existing .env and keeps its other values', () => { + fs.writeFileSync(envPath(), 'FOO=bar\n') + fs.chmodSync(envPath(), 0o644) + + upsertEnvValue('SECRET', 'abc') + + expect(modeOf(envPath())).to.equal(0o600) + expect(fs.readFileSync(envPath(), 'utf-8')).to.equal('FOO=bar\n\nSECRET=abc\n') + }) + }) +}) diff --git a/test/unit/cli/setup.spec.ts b/test/unit/cli/setup.spec.ts index 58c432b11..33196dcb1 100644 --- a/test/unit/cli/setup.spec.ts +++ b/test/unit/cli/setup.spec.ts @@ -262,6 +262,70 @@ describe('runSetup', () => { }) }) + describe('the permissions of .env', function () { + // File modes mean nothing on Windows. + before(function () { + if (process.platform === 'win32') { + this.skip() + } + }) + + const modeOf = (file: string) => fs.statSync(file).mode & 0o777 + const envPath = () => path.join(tempDir, '.env') + let originalUmask: number + + beforeEach(() => { + // The usual umask, under which a file created with the default mode is readable by every local account. + originalUmask = process.umask(0o022) + }) + + afterEach(() => { + process.umask(originalUmask) + }) + + it('creates .env from .env.example readable by its owner only', async () => { + fs.writeFileSync(path.join(tempDir, '.env.example'), 'SECRET=change_me_to_something_long_and_random\nFOO=bar\n') + fs.chmodSync(path.join(tempDir, '.env.example'), 0o644) + process.env.SECRET = 'replacement-secret' + + expect(await setupCommand.runSetup({ yes: true })).to.equal(0) + + expect(modeOf(envPath())).to.equal(0o600) + expect(readEnv()).to.include('SECRET=replacement-secret') + expect(readEnv()).to.include('FOO=bar') + }) + + it('creates .env readable by its owner only when there is no .env.example', async () => { + process.env.SECRET = 'replacement-secret' + + expect(await setupCommand.runSetup({ yes: true })).to.equal(0) + + expect(modeOf(envPath())).to.equal(0o600) + expect(readEnv()).to.include('SECRET=replacement-secret') + }) + + it('restricts an existing .env when it stores the secret', async () => { + fs.writeFileSync(envPath(), 'SECRET=change_me_to_something_long_and_random\nFOO=bar\n') + fs.chmodSync(envPath(), 0o644) + process.env.SECRET = 'replacement-secret' + + expect(await setupCommand.runSetup({ yes: true })).to.equal(0) + + expect(modeOf(envPath())).to.equal(0o600) + expect(readEnv()).to.include('FOO=bar') + }) + + it('does not touch an existing .env that already has a secret and needs no write', async () => { + fs.writeFileSync(envPath(), 'SECRET=real-secret\n') + fs.chmodSync(envPath(), 0o640) + + expect(await setupCommand.runSetup({ yes: true })).to.equal(0) + + expect(modeOf(envPath())).to.equal(0o640) + expect(readEnv()).to.equal('SECRET=real-secret\n') + }) + }) + describe('a secret that is accepted', () => { const safe = [ 'plain-hex-0123456789abcdef',