diff --git a/lib/group/store/base.js b/lib/group/store/base.js index e8cfee9..fe7c174 100644 --- a/lib/group/store/base.js +++ b/lib/group/store/base.js @@ -1,3 +1,5 @@ +import { StoreConflictError, StoreInvalidError } from '../../store/error.js' + /** * Group domain class – pure attributes and business logic. * @@ -51,3 +53,29 @@ class GroupBase { } export default GroupBase + +export function siblingNameConflict(name, parentGid) { + return new StoreConflictError('group', undefined, `group ${name} already exists in group ${parentGid}`) +} + +// mysql compares names with trailing spaces stripped +export function sameGroupName(a, b) { + return padless(a ?? '') === padless(b ?? '') +} + +function padless(name) { + let end = name.length + while (end > 0 && name[end - 1] === ' ') end-- + return name.slice(0, end) +} + +export function missingParent(parentGid) { + return new StoreInvalidError(`group ${parentGid} does not exist`) +} + +export function siblingNameTaken(groups, id, parentGid, name) { + const taken = groups.some( + (g) => g.id !== id && !g.deleted && (g.parent_gid ?? 0) === parentGid && sameGroupName(g.name, name), + ) + if (taken) throw siblingNameConflict(name, parentGid) +} diff --git a/lib/group/store/file.js b/lib/group/store/file.js index fae1832..ec0525d 100644 --- a/lib/group/store/file.js +++ b/lib/group/store/file.js @@ -1,7 +1,7 @@ import FileStore, { claimId, removeRows, serialize } from '../../store/file.js' import { idConflict } from '../../store/error.js' -import GroupBase from './base.js' +import GroupBase, { missingParent, sameGroupName, siblingNameTaken } from './base.js' import { groupNameTaken } from '../../user/store/base.js' import PermissionRepoFile from '../../permission/store/file.js' @@ -33,6 +33,7 @@ class GroupRepoFile extends GroupBase { _postProcess(row, deletedArg) { const r = JSON.parse(JSON.stringify(row)) r.deleted = Boolean(r.deleted) + r.parent_gid ??= 0 if (r.permissions?.deleted) delete r.permissions if (r.permissions?.nameserver && !Array.isArray(r.permissions.nameserver.usable)) { r.permissions.nameserver.usable = [] @@ -48,7 +49,7 @@ class GroupRepoFile extends GroupBase { while (queue.length) { const cur = queue.shift() for (const g of groups) { - if (g.parent_gid === cur && !ids.includes(g.id)) { + if ((g.parent_gid ?? 0) === cur && !ids.includes(g.id)) { ids.push(g.id) queue.push(g.id) } @@ -73,9 +74,15 @@ class GroupRepoFile extends GroupBase { return keep(idConflict('group', args.id, options)) } + args.parent_gid ??= 0 + if (args.parent_gid !== 0 && !groups.some((g) => g.id === args.parent_gid)) { + throw missingParent(args.parent_gid) + } args.id = claimId(groups, data, args.id) - if (!args.deleted) + if (!args.deleted) { groupNameTaken(await this.userFile.load('user'), [...groups, args], args.id, args.name) + siblingNameTaken(groups, args.id, args.parent_gid, args.name) + } const gid = args.id args.permissions = { @@ -115,8 +122,8 @@ class GroupRepoFile extends GroupBase { } } - if (args.parent_gid !== undefined) groups = groups.filter((g) => g.parent_gid === args.parent_gid) - if (args.name !== undefined) groups = groups.filter((g) => g.name === args.name) + if (args.parent_gid !== undefined) groups = groups.filter((g) => (g.parent_gid ?? 0) === args.parent_gid) + if (args.name !== undefined) groups = groups.filter((g) => sameGroupName(g.name, args.name)) if (deletedArg === false) groups = groups.filter((g) => !g.deleted) else if (deletedArg !== undefined) @@ -140,8 +147,10 @@ class GroupRepoFile extends GroupBase { if (idx === -1) return false const next = { ...groups[idx], ...args } - if ((args.name !== undefined || args.deleted !== undefined) && !next.deleted) { - groupNameTaken(await this.userFile.load('user'), groups, id, next.name) + const claimsName = args.name !== undefined || args.deleted !== undefined + if ((claimsName || args.parent_gid !== undefined) && !next.deleted) { + if (claimsName) groupNameTaken(await this.userFile.load('user'), groups, id, next.name) + siblingNameTaken(groups, id, next.parent_gid ?? 0, next.name) } if (usable_ns !== undefined && groups[idx].permissions && !groups[idx].permissions.deleted) { diff --git a/lib/group/store/mysql.js b/lib/group/store/mysql.js index 0467791..fde4043 100644 --- a/lib/group/store/mysql.js +++ b/lib/group/store/mysql.js @@ -1,13 +1,40 @@ import Mysql from '../../mysql.js' -import GroupBase from './base.js' +import GroupBase, { missingParent, siblingNameConflict } from './base.js' import Permission from '../../permission/index.js' import { idConflict } from '../../store/error.js' import { mapToDbColumn } from '../../util.js' -import { assertGroupNameAvailable } from '../../user/store/mysql.js' +import { assertGroupNameAvailable, lockGroupName } from '../../user/store/mysql.js' const groupDbMap = { id: 'nt_group_id', parent_gid: 'parent_group_id' } const boolFields = ['deleted'] +// callers hold the group name lock +async function assertSiblingNameAvailable(tx, id, parentGid, name) { + const [taken] = await tx.execute( + `SELECT 1 FROM nt_group + WHERE deleted = 0 AND parent_group_id = ? AND name = ? AND nt_group_id <> ? LIMIT 1`, + [parentGid, name, id], + ) + if (taken) throw siblingNameConflict(name, parentGid) +} + +// Ahead of the name lock, the order a rename takes its row and name in. +async function lockAncestors(tx, parentGid) { + const ancestors = [] + for (let gid = parentGid; gid !== 0 && !ancestors.includes(gid);) { + const [row] = await tx.execute( + 'SELECT parent_group_id AS parent, deleted FROM nt_group WHERE nt_group_id = ? LOCK IN SHARE MODE', + [gid], + ) + if (!row && gid === parentGid) throw missingParent(gid) + if (!row) break + ancestors.push(gid) + if (row.deleted) break + gid = row.parent + } + return ancestors +} + class Group extends GroupBase { constructor() { super() @@ -27,23 +54,22 @@ class Group extends GroupBase { // an explicit id can meet users left behind by a destroyed group const insert = Mysql.insert(`nt_group`, mapToDbColumn(args, groupDbMap)) - const insertId = - args.deleted === true || args.deleted === 1 - ? await Mysql.execute(...insert) - : await Mysql.transaction(async (tx) => { - const inserted = await tx.execute(...insert) - await assertGroupNameAvailable(tx, args.id ?? inserted, args.name) - return inserted - }) + const insertId = await Mysql.transaction(async (tx) => { + const ancestors = await lockAncestors(tx, parent_gid) + const inserted = await tx.execute(...insert) + const id = args.id ?? inserted + if (!(args.deleted === true || args.deleted === 1)) { + await assertGroupNameAvailable(tx, id, args.name) + await assertSiblingNameAvailable(tx, id, parent_gid, args.name) + } + if (id) await this.addToSubgroups(tx, id, ancestors) + return inserted + }) // MySQL 8.0 returns insertId 0 for an explicit-id insert into an // AUTO_INCREMENT column, so fall back to the supplied id; otherwise the // subgroup + permission wiring below runs against the wrong gid (or is skipped). const gid = args.id ?? insertId - if (gid && parent_gid !== 0) { - await this.addToSubgroups(gid, parent_gid) - } - await Permission.create({ gid, name: `Group ${args.name} perms`, @@ -53,20 +79,15 @@ class Group extends GroupBase { return gid } - async addToSubgroups(gid, parent_gid, rank = 1000) { - if (!parent_gid || parent_gid === 0) return - + async addToSubgroups(tx, gid, ancestors) { // `rank` is a reserved word in MySQL 8.0+, so it must be backticked; the // generic Mysql.insert helper doesn't quote column names. - await Mysql.execute('INSERT INTO nt_group_subgroups (nt_group_id,nt_subgroup_id,`rank`) VALUES(?,?,?)', [ - parent_gid, - gid, - rank, - ]) - - const parent = await this.get({ id: parent_gid }) - if (parent.length === 1 && parent[0].parent_gid !== 0) { - await this.addToSubgroups(gid, parent[0].parent_gid, rank - 1) + for (const [i, ancestor] of ancestors.entries()) { + await tx.execute('INSERT INTO nt_group_subgroups (nt_group_id,nt_subgroup_id,`rank`) VALUES(?,?,?)', [ + ancestor, + gid, + 1000 - i, + ]) } } @@ -161,16 +182,21 @@ class Group extends GroupBase { if (!columns && usable_ns === undefined) return true const update = Mysql.update(`nt_group`, { nt_group_id: id }, mapToDbColumn(args, groupDbMap)) const claimsName = args.name !== undefined || args.deleted !== undefined + const claimsSlot = claimsName || args.parent_gid !== undefined // the group permission row changes with the rename, so a refused rename leaves both alone return Mysql.transaction(async (tx) => { - const [row] = await tx.execute('SELECT name, deleted FROM nt_group WHERE nt_group_id = ? FOR UPDATE', [ - id, - ]) + const [row] = await tx.execute( + 'SELECT name, parent_group_id, deleted FROM nt_group WHERE nt_group_id = ? FOR UPDATE', + [id], + ) if (!row) return false const deleted = args.deleted ?? row.deleted - if (claimsName && !(deleted === true || deleted === 1)) { - await assertGroupNameAvailable(tx, id, args.name ?? row.name) + if (claimsSlot && !(deleted === true || deleted === 1)) { + const name = args.name ?? row.name + if (claimsName) await assertGroupNameAvailable(tx, id, name) + else await lockGroupName(tx, name) + await assertSiblingNameAvailable(tx, id, args.parent_gid ?? row.parent_group_id, name) } const changed = columns ? (await tx.execute(...update)).changedRows === 1 : true if (usable_ns !== undefined) { diff --git a/lib/group/test/index.js b/lib/group/test/index.js index ca657a1..c4f198b 100644 --- a/lib/group/test/index.js +++ b/lib/group/test/index.js @@ -59,4 +59,71 @@ describe('group', function () { g = await Group.get({ id: testCase.id }) assert.equal(g[0].deleted, undefined) }) + + describe('sibling names', function () { + const sib = { ...groupJson, id: 4092, parent_gid: testCase.id, name: 'sibling.example.com' } + const other = { ...groupJson, id: 4093, parent_gid: testCase.id, name: 'other.example.com' } + const loose = { ...sib, id: 4094, parent_gid: 0 } + const conflict = { + code: 'STORE_CONFLICT', + message: `group ${sib.name} already exists in group ${testCase.id}`, + } + + before(async () => { + for (const g of [sib, other, loose]) await Group.destroy({ id: g.id }) + for (const g of [sib, other]) await Group.create(g) + }) + + after(async () => { + for (const g of [sib, other, loose]) await Group.destroy({ id: g.id }) + }) + + it('is unique among live siblings', async () => { + await assert.rejects(Group.create({ ...loose, parent_gid: testCase.id }), conflict) + await assert.rejects(Group.create({ ...loose, parent_gid: testCase.id, name: `${sib.name} ` }), { + code: 'STORE_CONFLICT', + }) + const [found] = await Group.get({ parent_gid: testCase.id, name: `${sib.name} ` }) + assert.equal(found?.id, sib.id) + for (const deleted of [false, true]) assert.deepEqual(await Group.get({ id: loose.id, deleted }), []) + assert.ok(await Group.create(loose)) + await Group.destroy({ id: loose.id }) + }) + + it('refuses a missing parent', async () => { + const orphan = { ...loose, id: 4097, parent_gid: 4099 } + await assert.rejects(Group.create(orphan), { + code: 'STORE_INVALID', + message: 'group 4099 does not exist', + }) + assert.deepEqual(await Group.get({ id: orphan.id, deleted: undefined }), []) + }) + + it('puts a group created without a parent at the top level', async () => { + assert.ok(await Group.create({ id: loose.id, name: loose.name })) + assert.equal((await Group.get({ parent_gid: 0, name: loose.name })).length, 1) + await Group.destroy({ id: loose.id }) + }) + + it('refuses a rename or a move onto a sibling', async () => { + await assert.rejects(Group.put({ id: other.id, name: sib.name }), conflict) + assert.equal((await Group.get({ id: other.id }))[0].name, other.name) + assert.ok(await Group.create(loose)) + await assert.rejects(Group.put({ id: loose.id, parent_gid: testCase.id }), conflict) + assert.equal((await Group.get({ id: loose.id }))[0].parent_gid, 0) + await Group.destroy({ id: loose.id }) + }) + + it('is free while the sibling is deleted', async () => { + await Group.delete({ id: sib.id }) + try { + assert.ok(await Group.put({ id: other.id, name: sib.name })) + await assert.rejects(Group.delete({ id: sib.id, deleted: 0 }), conflict) + assert.ok(await Group.put({ id: other.id, name: other.name })) + } finally { + await Group.delete({ id: sib.id, deleted: 0 }) + } + assert.equal((await Group.get({ id: sib.id }))[0].name, sib.name) + }) + }) }) diff --git a/lib/group/test/mysql.js b/lib/group/test/mysql.js new file mode 100644 index 0000000..7949c57 --- /dev/null +++ b/lib/group/test/mysql.js @@ -0,0 +1,99 @@ +import assert from 'node:assert/strict' +import { describe, it, before, after } from 'node:test' + +import Group from '../index.js' + +import groupJson from './group.json' with { type: 'json' } + +const parent = { ...groupJson, id: 9020, name: 'grouptest-mysql.example.com' } +const ids = [9021, 9022, 9023, 9024] +const racer = (id) => ({ ...groupJson, id, parent_gid: parent.id, name: 'racer.example.com' }) +const settled = (results) => results.filter((r) => r.status === 'fulfilled').length + +const shared = { ...groupJson, id: 9025, parent_gid: parent.id, name: 'shared.example.com' } +const twin = { ...shared, id: 9026, parent_gid: 0 } +const late = { ...groupJson, id: 9030, parent_gid: parent.id, name: 'late-parent.example.com' } +const orphan = { ...groupJson, id: 9029, parent_gid: late.id, name: 'orphan.example.com' } +const selfish = { ...groupJson, id: 9031, parent_gid: 9031, name: 'selfish.example.com' } + +async function cleanup() { + await Group.mysql.execute('DELETE FROM nt_user WHERE nt_user_id IN (9027, 9028)') + for (const id of [shared.id, twin.id, ...ids, orphan.id, late.id, selfish.id, parent.id]) + await Group.destroy({ id }) +} + +before(async () => { + await cleanup() + await Group.create(parent) +}) + +after(async () => { + await cleanup() + Group.disconnect() +}) + +describe('mysql group name races', () => { + it('lets one of several concurrent creates of a name win', async () => { + const results = await Promise.allSettled(ids.map((id) => Group.create(racer(id)))) + assert.equal(settled(results), 1) + for (const r of results) if (r.status === 'rejected') assert.equal(r.reason.code, 'STORE_CONFLICT') + assert.equal((await Group.get({ parent_gid: parent.id, name: 'racer.example.com' })).length, 1) + for (const id of ids) await Group.destroy({ id }) + }) + + it('lets a create or a rename onto the same name win, not both', async () => { + assert.ok(await Group.create({ ...racer(ids[0]), name: 'renamer.example.com' })) + const results = await Promise.allSettled([ + Group.create(racer(ids[1])), + Group.put({ id: ids[0], name: 'racer.example.com' }), + ]) + assert.equal(settled(results), 1) + for (const r of results) if (r.status === 'rejected') assert.equal(r.reason.code, 'STORE_CONFLICT') + assert.equal((await Group.get({ parent_gid: parent.id, name: 'racer.example.com' })).length, 1) + }) +}) + +describe('mysql group moves', () => { + it('leave the logins of an upgraded db alone', async () => { + for (const g of [shared, twin]) await Group.create(g) + // two live groups of one name sharing a login, as a v2 db can hold + for (const [id, gid] of [ + [9027, shared.id], + [9028, twin.id], + ]) { + await Group.mysql.execute( + 'INSERT INTO nt_user (nt_user_id, nt_group_id, username, password, email) VALUES (?, ?, ?, ?, ?)', + [id, gid, 'amy', 'x', `amy${id}@example.com`], + ) + } + assert.ok(await Group.put({ id: shared.id, parent_gid: twin.id })) + await assert.rejects(Group.put({ id: shared.id, name: 'shared.example.com', parent_gid: parent.id }), { + message: 'username amy@shared.example.com is not unique', + }) + }) +}) + +describe('mysql group create', () => { + it('keeps nothing when the parent is missing', async () => { + await assert.rejects(Group.create(orphan), { + code: 'STORE_INVALID', + message: `group ${late.id} does not exist`, + }) + assert.deepEqual(await Group.get({ id: orphan.id, deleted: undefined }), []) + await Group.create(late) + assert.equal(await Group.create(orphan), orphan.id) + const links = await Group.mysql.execute( + 'SELECT nt_group_id AS gid FROM nt_group_subgroups WHERE nt_subgroup_id = ? ORDER BY `rank`', + [orphan.id], + ) + assert.deepEqual( + links.map((l) => l.gid), + [parent.id, late.id], + ) + }) + + it('refuses a group as its own parent', async () => { + await assert.rejects(Group.create(selfish), { code: 'STORE_INVALID' }) + assert.deepEqual(await Group.get({ id: selfish.id, deleted: undefined }), []) + }) +}) diff --git a/lib/store/file.test.js b/lib/store/file.test.js index 2c446e9..03836c0 100644 --- a/lib/store/file.test.js +++ b/lib/store/file.test.js @@ -745,6 +745,26 @@ describe('file store', () => { assert.equal(await groups.create({ name: 'next.example' }), 21) }) + it(`reads a ${type} group stored without a parent as top level`, async () => { + process.env.NICTOOL_DATA_STORE = type + fs.rmSync(path.join(tmp, `group.${type}`), { force: true }) + await seed(new FileStore('group'), 'group', [ + { id: 7, name: 'parentless.example' }, + { id: 8, parent_gid: 7, name: 'child.example' }, + ]) + const groups = new GroupRepoFile() + assert.equal((await groups.get({ id: 7 }))[0].parent_gid, 0) + assert.equal((await groups.get({ parent_gid: 0 }))[0].parent_gid, 0) + assert.deepEqual(await groups.subgroupGids(0), [0, 7, 8]) + }) + + it(`creates a ${type} group beside a nameless one`, async () => { + process.env.NICTOOL_DATA_STORE = type + fs.rmSync(path.join(tmp, `group.${type}`), { force: true }) + await seed(new FileStore('group'), 'group', [{ id: 7, parent_gid: 0 }]) + assert.equal(await new GroupRepoFile().create({ name: 'named.example' }), 8) + }) + it(`refuses a ${type} permission with no user or group`, async () => { process.env.NICTOOL_DATA_STORE = type await assert.rejects(new PermissionRepoFile().create({ name: 'no target' }), /needs a user or group/) diff --git a/lib/user/test/mysql.js b/lib/user/test/mysql.js index bbd3d3c..30968b5 100644 --- a/lib/user/test/mysql.js +++ b/lib/user/test/mysql.js @@ -187,7 +187,7 @@ describe('user (mysql)', function () { }) describe('mysql username races', () => { - const second = { ...groupJson, id: 9003, name: 'usertest-mysql-2.example.com' } + const second = { ...groupJson, id: 9003, parent_gid: groupCase.id, name: 'usertest-mysql-2.example.com' } const ids = [9010, 9011, 9012, 9013] const racer = (id, gid) => ({ id, @@ -223,7 +223,10 @@ describe('mysql username races', () => { Group.put({ id: second.id, name: groupCase.name }), ]) assert.equal(settled(results), 1) - for (const r of results) if (r.status === 'rejected') assert.equal(r.reason.code, 'STORE_CONFLICT') + for (const r of results) { + if (r.status === 'rejected') + assert.equal(r.reason.message, `username racer@${groupCase.name} is not unique`) + } await User.destroy({ id: ids[0] }) await Group.put({ id: second.id, name: second.name }) }) diff --git a/routes/zone_record.test.js b/routes/zone_record.test.js index a9f1467..05ad8c8 100644 --- a/routes/zone_record.test.js +++ b/routes/zone_record.test.js @@ -15,6 +15,7 @@ let server const createdZoneRecordIds = [] const testGroupId = 5094 +const testGroupName = 'route-zr.example.com' const testZoneId = 5095 const testZoneRecordId = 5096 const bystanderId = 5097 @@ -40,7 +41,7 @@ before(async () => { await ZoneRecord.destroy({ id: bystanderId }) await Zone.destroy({ id: testZoneId }) - const testGroup = { ...groupCase, id: testGroupId } + const testGroup = { ...groupCase, id: testGroupId, name: testGroupName } const testUser = { ...userCase, id: testGroupId, @@ -49,8 +50,10 @@ before(async () => { username: `route-zr-delete-${testGroupId}`, } - await Group.create(testGroup, { ifExists: 'return' }) - await User.create(testUser, { ifExists: 'return' }) + await User.destroy({ id: testGroupId }) + await Group.destroy({ id: testGroupId }) + await Group.create(testGroup) + await User.create(testUser) await Zone.create(testZone) await ZoneRecord.create(testZoneRecord) await ZoneRecord.create({ @@ -70,6 +73,8 @@ after(async () => { await ZoneRecord.destroy({ id: testZoneRecordId }) await ZoneRecord.destroy({ id: bystanderId }) await Zone.destroy({ id: testZoneId }) + await User.destroy({ id: testGroupId }) + await Group.destroy({ id: testGroupId }) // a failed before() leaves no server, and an open db connection keeps node running if (server) await server.stop() else await ZoneRecord.disconnect() @@ -83,7 +88,7 @@ describe('zone_record routes', () => { method: 'POST', url: '/session', payload: { - username: `route-zr-delete-${testGroupId}@${groupCase.name}`, + username: `route-zr-delete-${testGroupId}@${testGroupName}`, password: userCase.password, }, }) diff --git a/test/fixtures.js b/test/fixtures.js index 788be8e..c75fc92 100644 --- a/test/fixtures.js +++ b/test/fixtures.js @@ -65,6 +65,9 @@ async function teardown() { await User.destroy({ id: userCaseR.id }) await Group.destroy({ id: groupCase.id }) await Group.destroy({ id: groupCaseR.id }) + // older zone_record route runs left group 5094 holding groupCaseR's name + await User.destroy({ id: 5094 }) + await Group.destroy({ id: 5094 }) await User.disconnect() await Group.disconnect() process.exit(0)