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
38 changes: 25 additions & 13 deletions lib/group/store/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import FileStore, { claimId, removeRows, serialize } from '../../store/file.js'
import { idConflict } from '../../store/error.js'

import GroupBase from './base.js'
import { groupNameTaken } from '../../user/store/base.js'
import PermissionRepoFile from '../../permission/store/file.js'

import { cascade } from '../../references.js'
Expand All @@ -22,6 +23,7 @@ class GroupRepoFile extends GroupBase {
constructor(args = {}) {
super(args)
this.file = new FileStore('group')
this.userFile = new FileStore('user')
}

async _load() {
Expand Down Expand Up @@ -72,6 +74,8 @@ class GroupRepoFile extends GroupBase {
}

args.id = claimId(groups, data, args.id)
if (!args.deleted)
groupNameTaken(await this.userFile.load('user'), [...groups, args], args.id, args.name)

const gid = args.id
args.permissions = {
Expand Down Expand Up @@ -130,25 +134,33 @@ class GroupRepoFile extends GroupBase {
const usable_ns = args.usable_ns
delete args.usable_ns

return this.file.mutate('group', (groups) => {
const idx = groups.findIndex((g) => g.id === id)
if (idx === -1) return false
return serialize('permission create', () =>
this.file.mutate('group', async (groups) => {
const idx = groups.findIndex((g) => g.id === id)
if (idx === -1) return false

if (usable_ns !== undefined && groups[idx].permissions && !groups[idx].permissions.deleted) {
groups[idx].permissions.nameserver = {
...groups[idx].permissions.nameserver,
usable: Array.isArray(usable_ns) ? usable_ns : [],
const next = { ...groups[idx], ...args }
if ((args.name !== undefined || args.deleted !== undefined) && !next.deleted) {
groupNameTaken(await this.userFile.load('user'), groups, id, next.name)
}
}

if (Object.keys(args).length > 0) {
groups[idx] = { ...groups[idx], ...args }
}
return true
})
if (usable_ns !== undefined && groups[idx].permissions && !groups[idx].permissions.deleted) {
groups[idx].permissions.nameserver = {
...groups[idx].permissions.nameserver,
usable: Array.isArray(usable_ns) ? usable_ns : [],
}
}

if (Object.keys(args).length > 0) {
groups[idx] = { ...groups[idx], ...args }
}
return true
}),
)
}

async delete(args) {
if (!(args.deleted ?? true)) return this.put({ id: args.id, deleted: false })
return this.file.mutate('group', (groups) => {
const row = groups.find((g) => g.id === args.id)
if (!row) return false
Expand Down
52 changes: 36 additions & 16 deletions lib/group/store/mysql.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import GroupBase 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'

const groupDbMap = { id: 'nt_group_id', parent_gid: 'parent_group_id' }
const boolFields = ['deleted']
Expand All @@ -24,7 +25,16 @@ class Group extends GroupBase {

const parent_gid = args.parent_gid ?? 0

const insertId = await Mysql.execute(...Mysql.insert(`nt_group`, mapToDbColumn(args, groupDbMap)))
// 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
})
// 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).
Expand Down Expand Up @@ -147,25 +157,35 @@ class Group extends GroupBase {
const usable_ns = args.usable_ns
delete args.usable_ns

if (usable_ns !== undefined) {
const perm = await Permission.get({ gid: id })
if (perm) {
await Permission.put({
id: perm.id,
nameserver: { usable: Array.isArray(usable_ns) ? usable_ns : [] },
})
const columns = Object.keys(args).length > 0
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

// 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,
])
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 (Object.keys(args).length === 0) return true

const r = await Mysql.execute(
...Mysql.update(`nt_group`, { nt_group_id: id }, mapToDbColumn(args, groupDbMap)),
)
return r.changedRows === 1
const changed = columns ? (await tx.execute(...update)).changedRows === 1 : true
if (usable_ns !== undefined) {
await tx.execute(
`UPDATE nt_perm SET usable_ns = ?
WHERE nt_group_id = ? AND (nt_user_id IS NULL OR nt_user_id = 0) AND deleted = 0`,
[(Array.isArray(usable_ns) ? usable_ns : []).join(','), id],
)
}
return changed
})
}

async delete(args) {
if (!(args.deleted ?? true)) return this.put({ id: args.id, deleted: false })
const r = await Mysql.execute(
...Mysql.update(
`nt_group`,
Expand Down
10 changes: 9 additions & 1 deletion lib/store/file.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ describe('file store', () => {
it(`keeps ${type} users created while a permission is added to a user`, async (t) => {
process.env.NICTOOL_DATA_STORE = type
fs.rmSync(path.join(tmp, `user.${type}`), { force: true })
await seed(new FileStore('group'), 'group', [{ id: 1, name: 'one.example' }])
const users = new UserRepoFile()
const uid = await users.create({ gid: 1, username: 'holder', email: 'holder@example.com' })

Expand Down Expand Up @@ -205,6 +206,9 @@ describe('file store', () => {
assert.equal(stored.find((user) => user.id === uid).permissions.id, permId)
})

// a user needs its group to exist
const groupOne = () => seed(new FileStore('group'), 'group', [{ id: 1, name: 'one.example' }])

for (const [entity, Repo, make, changes] of [
['group', GroupRepoFile, (i) => ({ name: `racer-${i}.example` }), { put: { name: 'renamed.example' } }],
['nameserver', NameserverRepoFile, (i) => ({ gid: 1, name: `ns${i}.example.` }), { put: { ttl: 7 } }],
Expand Down Expand Up @@ -243,6 +247,7 @@ describe('file store', () => {
it(`keeps ${type} ${entity} rows created during a ${label}`, async (t) => {
process.env.NICTOOL_DATA_STORE = type
fs.rmSync(path.join(tmp, `${entity}.${type}`), { force: true })
if (entity === 'user') await groupOne()
const repo = new Repo()
const id = await repo.create(make('target'))

Expand Down Expand Up @@ -271,6 +276,7 @@ describe('file store', () => {
it(`gives a ${type} user fresh permissions when it goes explicit after a revoke`, async () => {
process.env.NICTOOL_DATA_STORE = type
fs.rmSync(path.join(tmp, `user.${type}`), { force: true })
await groupOne()
const users = new UserRepoFile()
const permissions = new PermissionRepoFile()
const uid = await users.create({ gid: 1, username: 'again', email: 'again@example.com' })
Expand All @@ -288,6 +294,7 @@ describe('file store', () => {
it(`keeps a live ${type} permission's id when its user goes explicit`, async () => {
process.env.NICTOOL_DATA_STORE = type
fs.rmSync(path.join(tmp, `user.${type}`), { force: true })
await groupOne()
const users = new UserRepoFile()
const permissions = new PermissionRepoFile()
const uid = await users.create({ gid: 1, username: 'live', email: 'live@example.com' })
Expand All @@ -304,6 +311,7 @@ describe('file store', () => {
for (const name of ['user', 'group', 'permission']) {
fs.rmSync(path.join(tmp, `${name}.${type}`), { force: true })
}
await groupOne()
const users = new UserRepoFile()
const permissions = new PermissionRepoFile()
const first = await users.create({ gid: 1, username: 'first', email: 'first@example.com' })
Expand Down Expand Up @@ -336,7 +344,7 @@ describe('file store', () => {
[
'user create',
'user',
[],
[[new FileStore('group'), 'group', [{ id: 1, name: 'one.example' }]]],
() => new UserRepoFile().create({ gid: 1, username: 'one', inherit_group_permissions: false }),
],
[
Expand Down
41 changes: 41 additions & 0 deletions lib/user/store/base.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { StoreConflictError, StoreInvalidError } from '../../store/error.js'

/**
* Base user repository – the persistence contract
*
Expand Down Expand Up @@ -52,3 +54,42 @@ class UserBase {
}

export default UserBase

// login is username@groupname, so a username can't repeat across live groups of one name
export function usernameConflict(username, groupName) {
return new StoreConflictError('user', undefined, `username ${username}@${groupName} is not unique`)
}

export function missingGroup(gid) {
return new StoreInvalidError(gid === undefined ? 'a user needs a gid' : `group ${gid} doesn't exist`)
}

export function requireGroup(groups, gid) {
const group = groups.find((g) => g.id === gid)
if (!group) throw missingGroup(gid)
return group
}

// a deleted group's users only meet the other groups when it is restored
export function usernameTaken(users, groups, user) {
const group = requireGroup(groups, user.gid)
const named = new Set(
group.deleted ? [group.id] : groups.filter((g) => g.name === group.name && !g.deleted).map((g) => g.id),
)
const taken = users.some(
(u) => u.id !== user.id && !u.deleted && u.username === user.username && named.has(u.gid),
)
if (taken) throw usernameConflict(user.username, group.name)
}

export function groupNameTaken(users, groups, gid, name) {
const named = new Set(
groups.filter((g) => g.id === gid || (g.name === name && !g.deleted)).map((g) => g.id),
)
const count = new Map()
for (const u of users) {
if (!u.deleted && named.has(u.gid)) count.set(u.username, (count.get(u.username) ?? 0) + 1)
}
const clash = users.find((u) => u.gid === gid && !u.deleted && count.get(u.username) > 1)
if (clash) throw usernameConflict(clash.username, name)
}
11 changes: 10 additions & 1 deletion lib/user/store/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import FileStore, { claimId, removeRows, serialize } from '../../store/file.js'
import { idConflict } from '../../store/error.js'
import Config from '../../config.js'
import Credentials from '../credentials.js'
import UserBase from './base.js'
import UserBase, { requireGroup, usernameTaken } from './base.js'
import PermissionRepoFile from '../../permission/store/file.js'
import { splitQualifiedUsername } from '../qualified.js'

Expand Down Expand Up @@ -156,6 +156,9 @@ class UserRepoFile extends UserBase {
return keep(idConflict('user', args.id, options))
}

const groups = await this.groupFile.load('group')
if (args.deleted) requireGroup(groups, args.gid)
else usernameTaken(users, groups, args)
args.id = claimId(users, data, args.id)

if (inherit === false) {
Expand Down Expand Up @@ -185,6 +188,11 @@ class UserRepoFile extends UserBase {
const idx = users.findIndex((u) => u.id === args.id)
if (idx === -1) return false

const next = { ...users[idx], ...args }
const claimsName = args.username !== undefined || args.gid !== undefined || args.deleted !== undefined
if (claimsName && !next.deleted) usernameTaken(users, await this.groupFile.load('group'), next)
else if (args.gid !== undefined) requireGroup(await this.groupFile.load('group'), args.gid)

if (inherit === true) {
delete users[idx].permissions
} else if (inherit === false && (!users[idx].permissions || users[idx].permissions.deleted)) {
Expand All @@ -208,6 +216,7 @@ class UserRepoFile extends UserBase {
}

async delete(args) {
if (!(args.deleted ?? true)) return this.put({ id: args.id, deleted: false })
return this.file.mutate('user', (users) => {
const row = users.find((u) => u.id === args.id)
if (!row) return false
Expand Down
Loading
Loading