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
28 changes: 28 additions & 0 deletions lib/group/store/base.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { StoreConflictError, StoreInvalidError } from '../../store/error.js'

/**
* Group domain class – pure attributes and business logic.
*
Expand Down Expand Up @@ -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)
}
23 changes: 16 additions & 7 deletions lib/group/store/file.js
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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 = []
Expand All @@ -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)
}
Expand All @@ -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 = {
Expand Down Expand Up @@ -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)
Expand All @@ -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) {
Expand Down
88 changes: 57 additions & 31 deletions lib/group/store/mysql.js
Original file line number Diff line number Diff line change
@@ -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()
Expand All @@ -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`,
Expand All @@ -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,
])
}
}

Expand Down Expand Up @@ -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) {
Expand Down
67 changes: 67 additions & 0 deletions lib/group/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
})
Loading
Loading