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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/).

### Unreleased

- fix: zone record PUT checks the record when its rdata changes
- fix(mysql): an SRV record with priority 0 reads back with its priority
- fix: zone record checks require an address only of types that have one, and use the record's owner
- fix: a user created without names reads back, lists and logs in on mysql
- fix: file stores draw permission ids from one sequence, and renumber repeated ids at startup
- fix: file store user, group and permission reads hide revoked permissions, and a regrant gets a new id
Expand Down
35 changes: 26 additions & 9 deletions lib/zone_record/store/base.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isDeepStrictEqual } from 'node:util'

import * as RR from '@nictool/dns-resource-record'

import { StoreInvalidError } from '../../store/error.js'
Expand Down Expand Up @@ -53,6 +55,11 @@ export function rdataFields(type) {
return (RR[type]?.rdataFields ?? ['address']).map((f) => (Array.isArray(f) ? f[0] : f))
}

// the field a type's rdata can't do without, if it has one
export function mainField(type) {
return RR.getMap(type)?.address ?? (rdataFields(type).includes('address') ? 'address' : undefined)
}

// what a type change takes off the record: the old type's rdata, and the raw
// columns a legacy row can hold without its type mapping them
function retiredFields(type) {
Expand Down Expand Up @@ -95,18 +102,28 @@ export function checkRecord(record) {
if (garbled) throw new StoreInvalidError(`${record.type}: ${garbled} can't be stored as given`)
}
// dns-resource-record 1.x accepts an empty TXT data or CAA value, which no read accepts
const main = RR.getMap(record.type)?.address ?? 'address'
const main = mainField(record.type)
if (typeof main === 'string' && [undefined, null, ''].includes(record[main])) {
throw new StoreInvalidError(`${record.type}: ${main} is required`)
}
}

// A type change, or a change to fields packed into one column, must leave a
// valid record. The placeholder owner lets a legacy relative owner through.
export function checkPut(fromType, record, changes) {
const packed = Object.values(RR.getMap(record.type) ?? {})
.filter(Array.isArray)
.flat()
if (record.type === fromType && !packed.some((f) => f in changes)) return
checkRecord({ ...record, owner: 'put.invalid.', ttl: record.ttl ?? 0 })
async function zoneName(zid) {
const { default: Zone } = await import('../../zone/index.js')
return (await Zone.get({ id: zid }))[0]?.zone
}

// A relative owner sits under its zone. The placeholder stands in when the zone is gone.
function asStored(record, zone) {
let owner = record.owner
if (!owner?.endsWith('.')) owner = zone ? `${owner}.${zone}.` : 'put.invalid.'
return { ...record, owner, ttl: record.ttl ?? 0 }
}

// A type change, or a change to any rdata field, must leave a valid record.
export async function checkPut(current, record, changes, zoneOf = zoneName) {
const changed = (f) => f in changes && !isDeepStrictEqual(changes[f], current[f])
if (record.type === current.type && !rdataFields(record.type).some(changed)) return
const zone = record.owner?.endsWith('.') ? undefined : await zoneOf(record.zid)
checkRecord(asStored(record, zone))
}
49 changes: 49 additions & 0 deletions lib/zone_record/store/base.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import fs from 'node:fs'

import assert from 'node:assert/strict'
import { describe, it } from 'node:test'

import * as RR from '@nictool/dns-resource-record'

import { checkPut, mergeChanges } from './base.js'

async function put(current, changes, zone) {
const target = mergeChanges(current, changes)
await checkPut(current, target, changes, async () => zone)
return target
}

describe('zone_record checkPut', () => {
// as the API takes it: the covered type and times as text
const rrsig = {
...new RR.RRSIG(null).getCanonical(),
'type covered': 'A',
'signature expiration': '20030212123200',
'signature inception': '20030113123200',
}
delete rrsig.class

it('checks an RRSIG edit against its own owner', async () => {
assert.equal((await put(rrsig, { signature: 'BAUG' })).signature, 'BAUG')
await assert.rejects(put(rrsig, { 'signers name': 'other.example.' }), { code: 'STORE_INVALID' })
})

it('checks an RRSIG edit against a relative owner under its zone', async () => {
const www = { ...rrsig, owner: 'www', labels: 3 }
assert.equal((await put(www, { signature: 'BAUG' }, 'example.com')).signature, 'BAUG')
await assert.rejects(put(www, { 'signers name': 'other.example.' }, 'example.com'), {
code: 'STORE_INVALID',
})
})

it('takes rdata sent back as stored, even when it is invalid', async () => {
const a = { id: 1, zid: 1, owner: 'a.example.com.', ttl: 300, type: 'A', address: '1.2.3' }
assert.equal((await put(a, { ...a, ttl: 600 })).ttl, 600)
await assert.rejects(put(a, { ...a, address: '1.2.4' }), { code: 'STORE_INVALID' })
})

it('refuses the text "undefined" for a field the record lacks', async () => {
const { flags, ...naptr } = JSON.parse(fs.readFileSync('lib/zone_record/test/rrs/naptr.json'))
await assert.rejects(put(naptr, { flags: 'undefined' }), { code: 'STORE_INVALID' })
})
})
4 changes: 2 additions & 2 deletions lib/zone_record/store/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,12 @@ class ZoneRecordRepoFile extends ZoneRecordBase {

async put(args) {
if (!args.id) return false
return this.file.mutate('zone_record', (records) => {
return this.file.mutate('zone_record', async (records) => {
const idx = records.findIndex((r) => r.id === args.id)
if (idx === -1) return false

const target = mergeChanges(records[idx], args)
checkPut(records[idx].type, target, args)
await checkPut(records[idx], target, args)
records[idx] = target
return true
})
Expand Down
17 changes: 13 additions & 4 deletions lib/zone_record/store/mysql.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as RR from '@nictool/dns-resource-record'
import { applyMap, getMap, unApplyMap } from '@nictool/dns-resource-record'
import ZoneRecordBase, { checkPut, checkRecord, mergeChanges } from './base.js'
import ZoneRecordBase, { checkPut, checkRecord, mainField, mergeChanges } from './base.js'

import Mysql from '../../mysql.js'
import { idConflict, StoreConflictError } from '../../store/error.js'
import { idConflict, StoreConflictError, StoreInvalidError } from '../../store/error.js'
import { mapToDbColumn } from '../../util.js'

const zrDbMap = { id: 'nt_zone_record_id', zid: 'nt_zone_id', owner: 'name' }
Expand All @@ -24,7 +24,14 @@ const columns = new Set([
])
const boolFields = ['deleted']
const keepZeroWeightFor = new Set(['SRV', 'URI'])
const keepZeroPriorityFor = new Set(['HTTPS', 'SVCB', 'URI'])
const keepZeroPriorityFor = new Set(['HTTPS', 'SRV', 'SVCB', 'URI'])

// a type with no rdata in the address column has no columns here to hold it
function checkStorable(type) {
if (mainField(type) === undefined) {
throw new StoreInvalidError(`${type} records can't be stored in mysql`)
}
}

const sortByColumn = { id: 'nt_zone_record_id', owner: 'name', type: 'type_id', ttl: 'ttl' }

Expand All @@ -49,6 +56,7 @@ class ZoneRecordMySQL extends ZoneRecordBase {
}

checkRecord(args.ttl === undefined ? { ...args, default: { ttl: 0 } } : args)
checkStorable(args.type)

args = objectToDb(args)

Expand Down Expand Up @@ -146,7 +154,8 @@ class ZoneRecordMySQL extends ZoneRecordBase {

const type = changes.type ?? current.type
const target = mergeChanges(current, changes)
checkPut(current.type, target, changes)
await checkPut(current, target, changes)
if (type !== current.type) checkStorable(type)
const before = objectToDb(current)
// Several fields can share a column, so pack the whole merged record.
const after = objectToDb(target)
Expand Down
33 changes: 33 additions & 0 deletions lib/zone_record/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,42 @@ describe('zone_record', function () {
await ZoneRecord.destroy({ id: base.id })
await ZoneRecord.create(soa)
await assert.rejects(ZoneRecord.put({ id: base.id, serial: 'abc' }), { code: 'STORE_INVALID' })
await assert.rejects(ZoneRecord.put({ id: base.id, serial: [soa.serial] }), { code: 'STORE_INVALID' })
assert.equal((await ZoneRecord.get({ id: base.id }))[0].serial, soa.serial)
})

it('takes a whole SOA sent back with only a new ttl', async () => {
const [stored] = await ZoneRecord.get({ id: base.id })
assert.ok(await ZoneRecord.put({ ...stored, ttl: stored.ttl + 1 }))
assert.equal((await ZoneRecord.get({ id: base.id }))[0].ttl, stored.ttl + 1)
})

it('refuses an address the type cannot hold', async () => {
await ZoneRecord.destroy({ id: base.id })
await ZoneRecord.create({ ...base, type: 'A', address: '203.0.113.7' })
await assert.rejects(ZoneRecord.put({ id: base.id, address: '1.2.3' }), { code: 'STORE_INVALID' })
assert.equal((await ZoneRecord.get({ id: base.id }))[0].address, '203.0.113.7')
})

it('takes the whole record sent back with only a new ttl', async () => {
await ZoneRecord.destroy({ id: base.id })
await ZoneRecord.create({ ...base, type: 'A', address: '203.0.113.7' })
const [stored] = await ZoneRecord.get({ id: base.id })
assert.ok(await ZoneRecord.put({ ...stored, ttl: 600 }))
assert.equal((await ZoneRecord.get({ id: base.id }))[0].ttl, 600)
})

it('reads back an SRV with priority 0 and refuses an IP as its target', async () => {
const srv = { ...base, type: 'SRV', priority: 0, weight: 0, port: 5060, target: 'sip.example.com.' }
await ZoneRecord.destroy({ id: base.id })
await ZoneRecord.create(srv)
const [stored] = await ZoneRecord.get({ id: base.id })
assert.equal(stored.priority, 0)
assert.equal(stored.weight, 0)
await assert.rejects(ZoneRecord.put({ id: base.id, target: '1.2.3.4' }), { code: 'STORE_INVALID' })
assert.equal((await ZoneRecord.get({ id: base.id }))[0].target, 'sip.example.com.')
})

it('takes a NAPTR with an empty regexp', async () => {
const [before] = await ZoneRecord.get({ id: naptr.id })
const { regexp, ...rest } = before
Expand Down
48 changes: 46 additions & 2 deletions lib/zone_record/test/mysql.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
import assert from 'node:assert/strict'
import { describe, it, before, after } from 'node:test'

import * as RR from '@nictool/dns-resource-record'

import ZoneRecord from '../index.js'
import { checkRecord, mainField } from '../store/base.js'

const id = 60303
const record = { id, zid: 4096, owner: 'legacy.example.com.', ttl: 300, type: 'A', address: '203.0.113.10' }

// valid rdata of a type the library maps nothing into address for, while one is left
function unheldRdata() {
for (const type of Object.keys(RR.typeMap).filter((t) => isNaN(t) && RR[t])) {
if (mainField(type) !== undefined) continue
const rdata = new RR[type](null).getCanonical()
for (const f of ['owner', 'ttl', 'class']) delete rdata[f]
try {
checkRecord({ ...rdata, owner: record.owner, ttl: record.ttl })
return rdata
} catch {
// a type its own rules refuse here can't show the mysql refusal
}
}
}

before(async () => {
await ZoneRecord.destroy({ id })
await ZoneRecord.create(record)
Expand All @@ -17,6 +35,18 @@ after(async () => {
})

describe('zone_record (mysql)', function () {
it('edits a legacy relative owner, checked under its zone', async () => {
await ZoneRecord.mysql.execute('UPDATE nt_zone_record SET name = ? WHERE nt_zone_record_id = ?', [
'legacy',
id,
])
assert.ok(await ZoneRecord.put({ id, address: '203.0.113.11' }))
const [zr] = await ZoneRecord.get({ id })
assert.equal(zr.owner, 'legacy')
assert.equal(zr.address, '203.0.113.11')
await ZoneRecord.put({ id, owner: record.owner, address: record.address })
})

it('drops a legacy priority on a type change', async () => {
await ZoneRecord.mysql.execute('UPDATE nt_zone_record SET priority = 5 WHERE nt_zone_record_id = ?', [id])
assert.ok(await ZoneRecord.put({ id, type: 'MX', preference: 10, exchange: 'mail.example.com.' }))
Expand All @@ -25,6 +55,12 @@ describe('zone_record (mysql)', function () {
assert.equal(zr.preference, 10)
})

it('refuses a type change into a type mysql cannot hold', async (t) => {
const rdata = unheldRdata()
if (!rdata) return t.skip('every type has a column map')
await assert.rejects(ZoneRecord.put({ id, ...rdata }), /can't be stored in mysql/)
})

it('refuses a create with incomplete rdata as invalid', async () => {
await assert.rejects(ZoneRecord.create({ ...record, id: id + 1, type: 'MX' }), { code: 'STORE_INVALID' })
})
Expand Down Expand Up @@ -76,12 +112,20 @@ describe('zone_record (mysql)', function () {
assert.equal(zr.params, undefined)
})

it('edits a legacy SRV whose priority is NULL', async () => {
it('edits a stored SRV whose priority is NULL only into a valid record', async () => {
await ZoneRecord.put({ id, type: 'SRV', priority: 5, weight: 5, port: 5060, target: 'sip.example.com.' })
await ZoneRecord.mysql.execute('UPDATE nt_zone_record SET priority = NULL WHERE nt_zone_record_id = ?', [
id,
])
assert.ok(await ZoneRecord.put({ id, port: 5061 }))
const [stored] = await ZoneRecord.get({ id })
assert.ok(await ZoneRecord.put({ id, ttl: stored.ttl + 1 }))
assert.equal((await ZoneRecord.get({ id }))[0].ttl, stored.ttl + 1)
assert.ok(await ZoneRecord.put({ ...stored, ttl: stored.ttl + 2 }))
const [edited] = await ZoneRecord.get({ id })
assert.equal(edited.ttl, stored.ttl + 2)
assert.equal(edited.priority, stored.priority)
await assert.rejects(ZoneRecord.put({ id, port: 5061 }), { code: 'STORE_INVALID' })
assert.ok(await ZoneRecord.put({ id, priority: 5, port: 5061 }))
assert.equal((await ZoneRecord.get({ id }))[0].port, 5061)
})

Expand Down
26 changes: 26 additions & 0 deletions routes/zone_record.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,32 @@ describe('zone_record routes', () => {
assert.equal((await ZoneRecord.get({ id: testZoneRecordId }))[0].type, 'A')
})

it(`PUT /zone_record/${testZoneRecordId} refuses an address the type can't hold`, async () => {
const res = await server.inject({
method: 'PUT',
url: `/zone_record/${testZoneRecordId}`,
headers: auth.headers,
payload: { address: '1.2.3' },
})

assert.equal(res.statusCode, 400)
assert.equal((await ZoneRecord.get({ id: testZoneRecordId }))[0].address, '198.51.100.99')
})

it(`PUT /zone_record/${testZoneRecordId} takes the record as the web UI sends it`, async () => {
const [stored] = await ZoneRecord.get({ id: testZoneRecordId })
const { zid, owner, type, address } = stored
const res = await server.inject({
method: 'PUT',
url: `/zone_record/${testZoneRecordId}`,
headers: auth.headers,
payload: { zid, owner, type, ttl: stored.ttl + 1, address },
})

assert.equal(res.statusCode, 200)
assert.equal((await ZoneRecord.get({ id: testZoneRecordId }))[0].ttl, stored.ttl + 1)
})

it(`PUT /zone_record/${testZoneRecordId} refuses a TXT with no data`, async () => {
const res = await server.inject({
method: 'PUT',
Expand Down
Loading