Files
caprover/tests/ShadowConfigStore.test.ts

321 lines
12 KiB
TypeScript

import fs = require('node:fs')
import os = require('node:os')
import path = require('node:path')
import Configstore = require('configstore')
import CaptainConstants from '../src/utils/CaptainConstants'
import EnvVars from '../src/utils/EnvVars'
import JsonFileStore from '../src/datastore/JsonFileStore'
import ShadowConfigStore, {
takeShadowReport,
} from '../src/datastore/ShadowConfigStore'
import { runDataStoreMigrations } from '../src/datastore/DataStore'
import { AnalyticsLogger } from '../src/user/events/emitter/AnalyticsLogger'
import { CapRoverEventType } from '../src/user/events/ICapRoverEvent'
import ProManager from '../src/user/pro/ProManager'
let dir: string
let file: string
let shadow: string
const originalBase = CaptainConstants.captainBaseDirectory
const disabled = EnvVars.CAPROVER_DISABLE_DATASTORE_SHADOW
const analytics = EnvVars.CAPROVER_DISABLE_ANALYTICS
const start = () => new ShadowConfigStore('test', file)
const contents = (name: string) => JSON.parse(fs.readFileSync(name, 'utf8'))
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'shadow-store-'))
CaptainConstants.captainBaseDirectory = dir
file = path.join(dir, 'data/config-captain.json')
shadow = path.join(dir, 'datastore-shadow/config-captain.json')
fs.mkdirSync(path.dirname(file))
EnvVars.CAPROVER_DISABLE_DATASTORE_SHADOW = false
takeShadowReport()
})
afterEach(() => {
jest.restoreAllMocks()
jest.useRealTimers()
CaptainConstants.captainBaseDirectory = originalBase
EnvVars.CAPROVER_DISABLE_DATASTORE_SHADOW = disabled
EnvVars.CAPROVER_DISABLE_ANALYTICS = analytics
fs.rmSync(dir, { recursive: true, force: true })
})
test('seeds before migration and reuses a matching shadow across startups', () => {
fs.writeFileSync(
file,
JSON.stringify({ appDefinitions: { 123: { name: '123' } }, extra: 3 })
)
const store = start()
expect(contents(shadow)).toEqual(contents(file))
runDataStoreMigrations(store)
expect(contents(shadow)).toEqual(contents(file))
expect(contents(file).appDefinitions['123'].isLegacyAppName).toBe(true)
expect(fs.statSync(path.dirname(shadow)).mode & 0o777).toBe(0o700)
const inode = fs.statSync(shadow).ino
start()
expect(fs.statSync(shadow).ino).toBe(inode)
fs.writeFileSync(file, '{"restored":true}')
expect(start().get('restored')).toBe(true)
expect(takeShadowReport()).toMatchObject({
preExistingDivergence: 1,
resynchronizations: 1,
sets: 2,
})
})
test('reconciles external edits before reads and writes and counts successful comparisons', () => {
const store = start()
expect(contents(shadow)).toEqual({})
fs.writeFileSync(file, '{"edited":0}')
expect(store.get('edited')).toBe(0)
fs.writeFileSync(file, '{"restored":false}')
store.set({ 'nested.0': true })
store.set('missing', undefined)
store.delete('restored')
expect(store.get('nested')).toEqual({ '0': true })
expect(contents(shadow)).toEqual(contents(file))
expect(takeShadowReport()).toMatchObject({
sets: 2,
deletes: 1,
reads: 1,
preExistingDivergence: 2,
resynchronizations: 2,
mutationMismatches: 0,
readMismatches: 0,
})
})
test('a wrong reader and destructive shadow mutation leave production results and unrelated fields intact', () => {
const store = start()
store.set('account', { name: 'existing' })
jest.spyOn(JsonFileStore.prototype, 'get').mockReturnValueOnce('wrong')
expect(store.get('account')).toEqual({ name: 'existing' })
jest.spyOn(JsonFileStore.prototype, 'delete').mockImplementationOnce(
function (this: JsonFileStore) {
this.replace({ destroyed: true })
}
)
expect(store.delete('other')).toBeUndefined()
expect(contents(file)).toEqual({ account: { name: 'existing' } })
expect(contents(shadow)).toEqual(contents(file))
expect(takeShadowReport()).toMatchObject({
readMismatches: 1,
mutationMismatches: 1,
resynchronizations: 2,
})
})
test('concurrent external edits during replay are counted separately', () => {
const store = start()
jest.spyOn(JsonFileStore.prototype, 'set').mockImplementationOnce(() =>
fs.writeFileSync(file, '{"external":true}')
)
store.set('a', 1)
expect(contents(shadow)).toEqual({ external: true })
expect(takeShadowReport()).toMatchObject({
concurrentChanges: 1,
skippedComparisons: 1,
mutationMismatches: 0,
})
})
test('shadow failures never retry authoritative writes and a failed reset disables comparison', () => {
const store = start()
const writes = jest.spyOn(Configstore.prototype, 'set')
jest.spyOn(JsonFileStore.prototype, 'set').mockImplementation(() => {
throw new Error('broken')
})
store.set('a', 1)
expect(contents(shadow)).toEqual({ a: 1 })
jest.spyOn(JsonFileStore.prototype, 'replace').mockImplementation(() => {
throw new Error('broken reset')
})
store.set('b', 2)
const reads = jest.spyOn(JsonFileStore.prototype, 'get')
expect(store.get('a')).toBe(1)
expect(reads).not.toHaveBeenCalled()
expect(store.set('b', 3)).toBeUndefined()
expect(contents(file)).toEqual({ a: 1, b: 3 })
expect(writes).toHaveBeenCalledTimes(3)
expect(takeShadowReport()).toMatchObject({
executionErrors: 2,
resynchronizations: 1,
resynchronizationErrors: 1,
})
})
test('replay cannot mutate caller-owned inputs or execute a value getter twice', () => {
const store = start()
const value = { name: 'kept' }
jest.spyOn(JsonFileStore.prototype, 'set').mockImplementationOnce(
(...args) => {
Object.assign(args[1] as object, { name: 'changed' })
}
)
store.set('app', value)
expect(value.name).toBe('kept')
let calls = 0
store.set('custom', {
get number() {
return ++calls
},
})
expect(calls).toBe(1)
expect(contents(file)).toEqual({
app: { name: 'kept' },
custom: { number: 1 },
})
expect(contents(shadow)).toEqual(contents(file))
})
test('an unusable shadow from first startup preserves the vanilla migration and subsequent writes', () => {
const control = new Configstore(
'control',
{},
{ configPath: path.join(dir, 'control.json') }
)
control.set('appDefinitions.001', { name: '001' })
fs.copyFileSync(control.path, file)
for (const method of ['get', 'set', 'delete', 'read', 'replace'] as const) {
jest.spyOn(JsonFileStore.prototype, method).mockImplementation(() => {
throw new Error('unavailable')
})
}
const store = start()
for (const participant of [control, store]) {
runDataStoreMigrations(participant)
participant.set('falseValue', false)
participant.delete('unused')
}
expect(store.get('appDefinitions')).toEqual(control.get('appDefinitions'))
expect(fs.readFileSync(file)).toEqual(fs.readFileSync(control.path))
expect(takeShadowReport()).toMatchObject({
initializationErrors: 1,
resynchronizationErrors: 1,
sets: 0,
reads: 0,
})
})
test.each(['symlink', 'hard link'])(
'rejects a live shadow %s to the authoritative file',
(kind) => {
const store = start()
fs.unlinkSync(shadow)
if (kind === 'symlink') fs.symlinkSync(file, shadow)
else fs.linkSync(file, shadow)
const replay = jest.spyOn(JsonFileStore.prototype, 'set')
store.set('verified', 17)
expect(contents(file)).toEqual({ verified: 17 })
expect(replay).not.toHaveBeenCalled()
expect(takeShadowReport().resynchronizationErrors).toBe(1)
}
)
test('propagates the identical authoritative error and skips replay', () => {
const store = start()
const error = new Error('failed')
jest.spyOn(Configstore.prototype, 'set').mockImplementationOnce(() => {
throw error
})
const replay = jest.spyOn(JsonFileStore.prototype, 'set')
let caught
try {
store.set('a', 1)
} catch (e) {
caught = e
}
expect(caught).toBe(error)
expect(replay).not.toHaveBeenCalled()
})
test.each([
'directory symlink',
'file symlink',
'hard link',
'directory as file',
'ordinary file as directory',
])('isolates %s at initialization or runtime', (kind) => {
const store = start()
fs.unlinkSync(shadow)
const victim = path.join(dir, 'data/victim')
fs.writeFileSync(victim, '{"saved":true}', { mode: 0o644 })
const victimMode = fs.statSync(victim).mode
if (kind === 'directory symlink' || kind === 'ordinary file as directory') {
fs.rmdirSync(path.dirname(shadow))
if (kind === 'directory symlink')
fs.symlinkSync(path.dirname(file), path.dirname(shadow))
else fs.writeFileSync(path.dirname(shadow), 'unexpected')
} else if (kind === 'file symlink') fs.symlinkSync(victim, shadow)
else if (kind === 'hard link') fs.linkSync(victim, shadow)
else fs.mkdirSync(shadow)
store.set('runtime', 1)
const restarted = start()
restarted.set('again', 2)
expect(contents(file)).toEqual({ runtime: 1, again: 2 })
expect(contents(victim)).toEqual({ saved: true })
expect(fs.statSync(victim).mode).toBe(victimMode)
expect(takeShadowReport().initializationErrors).toBeGreaterThan(0)
})
test('malformed shadow is repaired on restart and disabled mode never opens it', () => {
start()
fs.writeFileSync(shadow, 'invalid')
start()
expect(contents(shadow)).toEqual({})
fs.rmSync(path.dirname(shadow), { recursive: true })
EnvVars.CAPROVER_DISABLE_DATASTORE_SHADOW = true
const store = start()
store.set('a', false)
expect(store.get('a')).toBe(false)
store.delete('a')
expect(fs.existsSync(path.dirname(shadow))).toBe(false)
})
test.each(['CAPROVER_DISABLE_ANALYTICS', 'DO_NOT_TRACK'])(
'%s opts out of daily reporting',
(flag) => {
const previous = process.env[flag]
try {
process.env[flag] = '1'
jest.isolateModules(() => {
const interval = jest.spyOn(global, 'setInterval')
const Logger =
require('../src/user/events/emitter/AnalyticsLogger').AnalyticsLogger
expect(
new Logger({}).isEventApplicable({
eventType: CapRoverEventType.ConfigStoreShadowReport,
})
).toBe(false)
expect(interval).not.toHaveBeenCalled()
})
} finally {
if (previous === undefined) delete process.env[flag]
else process.env[flag] = previous
}
}
)
test('reports only numeric counters daily, even when header lookups read the store and delivery rejects', async () => {
jest.useFakeTimers()
EnvVars.CAPROVER_DISABLE_ANALYTICS = false
const store = start()
store.set('secret', 'private')
const reportUnAuthAnalyticsEvent = jest.fn(async () => {
store.get('secret')
throw new Error('sensitive!')
})
new AnalyticsLogger({ reportUnAuthAnalyticsEvent } as unknown as ProManager)
await jest.advanceTimersByTimeAsync(86400000)
expect(reportUnAuthAnalyticsEvent).toHaveBeenCalledTimes(1)
const payload = (
reportUnAuthAnalyticsEvent.mock.calls as unknown[][]
)[0][0] as { eventMetadata: Record<string, number> }
expect(payload.eventMetadata.sets).toBe(1)
expect(
Object.values(payload.eventMetadata).every((v) => typeof v === 'number')
).toBe(true)
expect(JSON.stringify(payload)).not.toMatch(/secret|private|sensitive/)
await jest.advanceTimersByTimeAsync(86400000)
expect(reportUnAuthAnalyticsEvent).toHaveBeenCalledTimes(2)
})