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

### Unreleased

- fix: PUT /user asks a non-admin editor for the target user's current password
- fix(json, toml): zone record create checks the record, and an unchanged PUT answers false, as on mysql
- fix: zone record checks take an RRSIG with a type number or times in seconds
- fix: zone record PUT checks the record when its rdata changes
Expand Down
10 changes: 10 additions & 0 deletions lib/user/store/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { StoreConflictError, StoreInvalidError } from '../../store/error.js'
*
* Repo contract:
* authenticate(authTry) → { user, group } | undefined
* isAdmin(id) → boolean
* checkPassword(args) → boolean | undefined (undefined: no such user)
* get(args) → object[]
* create(args, options) → number (userId)
* put(args) → boolean
Expand All @@ -32,6 +34,14 @@ class UserBase {
throw new Error('authenticate() not implemented by this repo')
}

async isAdmin(_id) {
throw new Error('isAdmin() not implemented by this repo')
}

async checkPassword(_args) {
throw new Error('checkPassword() not implemented by this repo')
}

async get(_args) {
throw new Error('get() not implemented by this repo')
}
Expand Down
8 changes: 8 additions & 0 deletions lib/user/store/elasticsearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ class UserRepoElasticsearch extends UserBase {
throw new Error('UserRepoElasticsearch is not yet implemented')
}

async isAdmin(_id) {
throw new Error('UserRepoElasticsearch is not yet implemented')
}

async checkPassword(_args) {
throw new Error('UserRepoElasticsearch is not yet implemented')
}

async get(_args) {
throw new Error('UserRepoElasticsearch is not yet implemented')
}
Expand Down
12 changes: 12 additions & 0 deletions lib/user/store/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,18 @@ class UserRepoFile extends UserBase {
}
}

async isAdmin(id) {
const user = (await this._load()).find((u) => u.id === id && !u.deleted)
if (!user?.is_admin) return false
return (await this.groupFile.load('group')).some((g) => g.id === user.gid && !g.deleted)
}

async checkPassword({ id, password }) {
const user = (await this._load()).find((u) => u.id === id)
if (!user) return undefined
return (await Credentials.validPassword(password, user.password, user.username, user.pass_salt)).valid
}

async get(args) {
args = JSON.parse(JSON.stringify(args))
const deletedArg = args.deleted ?? false
Expand Down
8 changes: 8 additions & 0 deletions lib/user/store/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ class UserRepoMongoDB extends UserBase {
throw new Error('UserRepoMongoDB is not yet implemented')
}

async isAdmin(_id) {
throw new Error('UserRepoMongoDB is not yet implemented')
}

async checkPassword(_args) {
throw new Error('UserRepoMongoDB is not yet implemented')
}

async get(_args) {
throw new Error('UserRepoMongoDB is not yet implemented')
}
Expand Down
18 changes: 18 additions & 0 deletions lib/user/store/mysql.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,24 @@ class UserRepoMySQL extends UserBase {
}
}

async isAdmin(id) {
const [row] = await Mysql.execute(
`SELECT u.is_admin FROM nt_user u JOIN nt_group g ON g.nt_group_id = u.nt_group_id
WHERE u.nt_user_id = ? AND u.deleted = 0 AND g.deleted = 0`,
[id],
)
return row?.is_admin === 1
}

async checkPassword({ id, password }) {
const [u] = await Mysql.execute(
'SELECT username, password, pass_salt FROM nt_user WHERE nt_user_id = ?',
[id],
)
if (!u) return undefined
return (await Credentials.validPassword(password, u.password, u.username, u.pass_salt)).valid
}

async create(args, options) {
if (args.id !== undefined) {
const u = [...(await this.get({ id: args.id })), ...(await this.get({ id: args.id, deleted: true }))]
Expand Down
50 changes: 50 additions & 0 deletions lib/user/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { describe, it, after, before } from 'node:test'
import User from '../index.js'
import Group from '../../group/index.js'
import Credentials from '../credentials.js'
import UserBase from '../store/base.js'

import userJson from './user.json' with { type: 'json' }
import groupJson from '../../group/test/group.json' with { type: 'json' }
Expand Down Expand Up @@ -328,3 +329,52 @@ describe('user', function () {
})
})
})

describe('user store base', () => {
it('leaves the password check to its backends', async () => {
const base = new UserBase()
await assert.rejects(base.isAdmin(1), /not implemented/)
await assert.rejects(base.checkPassword({ id: 1, password: 'x' }), /not implemented/)
})
})

describe('isAdmin', () => {
const adminGroup = { ...groupJson, id: 9033, name: 'is-admin.example.com' }
const admin = {
...userJson,
id: 9033,
gid: 9033,
username: 'is-admin',
email: 'is-admin@example.com',
is_admin: true,
}

before(async () => {
await User.destroy({ id: admin.id })
await Group.destroy({ id: adminGroup.id })
await Group.create(adminGroup)
await User.create(admin)
})

after(async () => {
await User.destroy({ id: admin.id })
await Group.destroy({ id: adminGroup.id })
})

it('reads the flag of a live user in a live group', async () => {
assert.equal(await User.isAdmin(admin.id), true)
assert.equal(await User.isAdmin(userCase.id), false)
})

it('is false once the group is deleted', async () => {
await Group.delete({ id: adminGroup.id })
assert.equal(await User.isAdmin(admin.id), false)
await Group.delete({ id: adminGroup.id, deleted: 0 })
assert.equal(await User.isAdmin(admin.id), true)
})

it('is false once the user is deleted', async () => {
await User.delete({ id: admin.id })
assert.equal(await User.isAdmin(admin.id), false)
})
})
15 changes: 15 additions & 0 deletions lib/user/test/mysql.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,21 @@ describe('user (mysql)', function () {
})
})

describe('checkPassword', function () {
after(async () => {
await User.destroy({ id: upgradeUserId })
})

it('reads a legacy SHA1 hash keyed on the bare username, and leaves it', async () => {
const sha1Hash = crypto.createHmac('sha1', upgradeUser.username).update(testPass).digest('hex')
await seedUser(sha1Hash, null)

assert.equal(await User.checkPassword({ id: upgradeUserId, password: testPass }), true)
assert.equal(await User.checkPassword({ id: upgradeUserId, password: 'wrong' }), false)
assert.equal((await storedCredentials()).password, sha1Hash)
})
})

it('rolls back the move when its permission change fails', async (t) => {
await seedUser(testPass, null)
await User.mysql.execute('DELETE FROM nt_perm WHERE nt_user_id = ?', [upgradeUserId])
Expand Down
13 changes: 12 additions & 1 deletion routes/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,18 @@ function UserRoutes(server) {
},
handler: async (request, h) => {
const id = parseInt(request.params.id, 10)
const args = { ...request.payload, id }
const { current_password: currentPassword, ...payload } = request.payload ?? {}
const args = { ...payload, id }

if (args.password && !(await User.isAdmin(request.auth.credentials.user.id))) {
const refuse = (msg) => h.response({ meta: { api: meta.api, msg } }).code(400)
if (currentPassword === undefined) return refuse('current password is required')
const valid = await User.checkPassword({ id, password: currentPassword })
if (valid === undefined) {
return h.response({ meta: { api: meta.api, msg: `user not found` } }).code(404)
}
if (!valid) return refuse('current password is incorrect')
}

// no salt passed: a password change always gets a fresh one
if (args.password) {
Expand Down
91 changes: 91 additions & 0 deletions routes/user.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,94 @@ describe('user routes', () => {
assert.equal(res.statusCode, 200)
})
})

describe('PUT /user/{id} password change', () => {
const pass = 'Wh@tA-Decent#P6ssw0rd'
const newPass = 'An0ther-Decent#Passw0rd'
const pwUser = (id, username, extra = {}) => ({
id,
gid: groupCase.id,
username,
email: `${username}@example.com`,
password: pass,
...extra,
})
const self = pwUser(9030, 'pw-self')
const other = pwUser(9031, 'pw-other')
const admin = pwUser(9032, 'pw-admin', { is_admin: true })
const headers = {}

async function login(user, password) {
return server.inject({
method: 'POST',
url: '/session',
payload: { username: `${user.username}@${groupCase.name}`, password },
})
}

async function put(as, id, payload) {
return server.inject({ method: 'PUT', url: `/user/${id}`, headers: headers[as], payload })
}

before(async () => {
for (const u of [self, other, admin]) {
await User.destroy({ id: u.id })
await User.create(u)
const res = await login(u, pass)
headers[u.username] = { Authorization: `Bearer ${res.result.session.token}` }
}
})

after(async () => {
for (const u of [self, other, admin]) await User.destroy({ id: u.id })
})

it('wants the current password from a non-admin', async () => {
const res = await put('pw-self', self.id, { password: newPass })
assert.equal(res.statusCode, 400)
assert.equal(res.result.meta.msg, 'current password is required')
})

it('refuses a wrong current password', async () => {
const res = await put('pw-self', self.id, { password: newPass, current_password: 'wrong' })
assert.equal(res.statusCode, 400)
assert.equal(res.result.meta.msg, 'current password is incorrect')
assert.equal((await login(self, pass)).statusCode, 200)
})

it('changes the password with the right current one', async () => {
const res = await put('pw-self', self.id, { password: newPass, current_password: pass })
assert.equal(res.statusCode, 200)
assert.equal((await login(self, newPass)).statusCode, 200)
assert.equal((await login(self, pass)).statusCode, 401)
})

it("wants the target user's password when a non-admin edits another user", async () => {
const mine = await put('pw-self', other.id, { password: newPass, current_password: newPass })
assert.equal(mine.statusCode, 400)
assert.equal(mine.result.meta.msg, 'current password is incorrect')

const theirs = await put('pw-self', other.id, { password: newPass, current_password: pass })
assert.equal(theirs.statusCode, 200)
assert.equal((await login(other, newPass)).statusCode, 200)
})

it('lets an admin change a password without the current one', async () => {
const res = await put('pw-admin', other.id, { password: pass })
assert.equal(res.statusCode, 200)
assert.equal((await login(other, pass)).statusCode, 200)
})

it('answers 404 for a user that does not exist', async () => {
const res = await put('pw-self', 9039, { password: newPass, current_password: pass })
assert.equal(res.statusCode, 404)
})

it('does not store current_password', async () => {
const res = await put('pw-self', self.id, { first_name: 'Kept', current_password: 'anything' })
assert.equal(res.statusCode, 200)
const [stored] = await User.get({ id: self.id })
assert.equal(stored.first_name, 'Kept')
assert.equal(stored.current_password, undefined)
})
})
Loading