diff --git a/CHANGELOG.md b/CHANGELOG.md index 01877f1..71a4a39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/user/store/base.js b/lib/user/store/base.js index ab72742..aae5ba0 100644 --- a/lib/user/store/base.js +++ b/lib/user/store/base.js @@ -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 @@ -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') } diff --git a/lib/user/store/elasticsearch.js b/lib/user/store/elasticsearch.js index 9b4514e..2394abb 100644 --- a/lib/user/store/elasticsearch.js +++ b/lib/user/store/elasticsearch.js @@ -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') } diff --git a/lib/user/store/file.js b/lib/user/store/file.js index 9048180..861cbb1 100644 --- a/lib/user/store/file.js +++ b/lib/user/store/file.js @@ -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 diff --git a/lib/user/store/mongodb.js b/lib/user/store/mongodb.js index a5719ef..4dc9a66 100644 --- a/lib/user/store/mongodb.js +++ b/lib/user/store/mongodb.js @@ -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') } diff --git a/lib/user/store/mysql.js b/lib/user/store/mysql.js index f99f196..3eeac79 100644 --- a/lib/user/store/mysql.js +++ b/lib/user/store/mysql.js @@ -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 }))] diff --git a/lib/user/test/index.js b/lib/user/test/index.js index e12a978..e100ecd 100644 --- a/lib/user/test/index.js +++ b/lib/user/test/index.js @@ -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' } @@ -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) + }) +}) diff --git a/lib/user/test/mysql.js b/lib/user/test/mysql.js index 30968b5..cde86d5 100644 --- a/lib/user/test/mysql.js +++ b/lib/user/test/mysql.js @@ -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]) diff --git a/routes/user.js b/routes/user.js index eeef463..a4bb681 100644 --- a/routes/user.js +++ b/routes/user.js @@ -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) { diff --git a/routes/user.test.js b/routes/user.test.js index 0ed4feb..e87f82e 100644 --- a/routes/user.test.js +++ b/routes/user.test.js @@ -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) + }) +})