From 4ebc949374e8804eddd328430d30d7323ecf284e Mon Sep 17 00:00:00 2001 From: William Mantly Date: Thu, 16 Jul 2026 19:00:06 -0400 Subject: [PATCH 1/2] 2.0.0: normalize error contract, fix callback bugs, add non-root import Breaking: spawnWrapper now returns Error|null (was stderr/true) and fires the callback at most once; removeUser/addUserToGroup pass Error|null instead of the raw exit code. addUser/addGroup propagate errors and no longer call back twice. addSSHtoUser no longer crashes on a missing user and uses spawn (no shell exec) to avoid homedir injection. getExpiration returns the error instead of throwing and parses chage output under the C locale. setPassword reports non-zero exits. build_user_command no longer injects null argv. getUsers/getGroups no longer drop the last record without a trailing newline. promise() no longer hangs on the synchronous validateUsername. Added: require('linux-user/non-root') read-only subset (no root warning), read- only promise set (promise.nonRoot()), and optional spawn timeout support. Types: selinux_user -> string, other_args -> string|string[], plus nonRoot and promise typings. Tests now auto-skip root-dependent cases when not running as root. Co-Authored-By: Claude --- .jshintrc | 4 +- CHANGELOG.md | 42 +++++++ README.md | 53 ++++++++- index.d.ts | 87 +++++++++++--- index.js | 4 + lib/promise.js | 72 ++++++++++-- lib/user.js | 290 +++++++++++++++++++++++++++++++++------------- non-root.d.ts | 4 + non-root.js | 34 ++++++ package.json | 4 +- test/user.test.js | 237 +++++++++++++++++++++++++++++++------ 11 files changed, 689 insertions(+), 142 deletions(-) create mode 100644 non-root.d.ts create mode 100644 non-root.js diff --git a/.jshintrc b/.jshintrc index ec74f14..810a3e1 100644 --- a/.jshintrc +++ b/.jshintrc @@ -90,6 +90,8 @@ "before": true, "afterEach": true, "beforeEach": true, - "after": true + "after": true, + // should.js (assertion library) exposes `should` as a global + "should": true } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cad3c7..b194e41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,48 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.0.0] - 2026-07-16 + +### Added +- Non-root import path: `require('linux-user/non-root')` exposes only the + read-only functions that do not require root and emits no root warning. + Also available as `require('linux-user').nonRoot`. +- Read-only promise set via `.promise.nonRoot()` and the non-root module's + `.promise()` factory. +- Optional timeout support for spawned commands (`opts.timeout`) to prevent + hung child processes from blocking the library. + +### Changed +- `spawnWrapper` now follows the Node.js `(err, result)` contract: errors are + `Error` objects (or `null` on success), and a non-zero exit code is treated as + a failure. Callbacks are now invoked at most once. +- `getExpiration` parses `chage --list` output under the `C` locale and is no + longer order/index dependent, so it is robust against localized output. +- `addSSHtoUser` now uses `spawn` with argument arrays instead of a shell + `exec` string, eliminating shell-injection risk from the home directory path. +- Tests now skip root-dependent cases automatically when not running as root. + +### Fixed +- `addUser` no longer calls its callback twice or swallows the `useradd` error. +- `addGroup` now propagates the `groupadd` error instead of always fetching the + group info. +- `addSSHtoUser` no longer crashes with `Cannot read properties of null` when + the user does not exist; it returns an `Error`. +- `getExpiration` returns the error instead of throwing when `chage` fails. +- `setPassword` now reports a failure when `passwd` exits non-zero instead of + calling back with no error. +- `removeUser` and `addUserToGroup` now pass `Error|null` instead of the raw + numeric exit code as the callback's first argument. +- `promise()` no longer hangs on `validateUsername`; it is passed through as a + synchronous function. +- `build_user_command` no longer injects `null` arguments when a flag map + returns `undefined`. +- `getUsers`/`getGroups` no longer drop the last record when `/etc/passwd` or + `/etc/group` has no trailing newline. +- TypeScript: `selinux_user` is now typed as `string` (it is passed to + `--selinux-user `), and `other_args` accepts `string | string[]`. +- Removed dead commented-out code from `setPassword`. + ## [1.2.0] - 2024-01-09 ### Added diff --git a/README.md b/README.md index 3807488..37c402f 100644 --- a/README.md +++ b/README.md @@ -27,20 +27,52 @@ current user will also work with out root. The testing libraries only work with NodeJS 6 and up. -UPDATE! - -Newer version of NPM does not allows executing as root, if you run into this -issue, call mocha directly: +Tests that modify system state require root. When the suite is **not** run as +root, those tests are automatically skipped and the read-only tests still run, +so `npm test` passes in CI and on dev machines without root. To exercise the +full suite, run as root: ```bash -./node_modules/mocha/bin/mocha +sudo ./node_modules/mocha/bin/mocha ``` +Newer version of NPM does not allow executing as root, if you run into this +issue, call mocha directly as shown above. + +## Non-root usage + +Most functions that modify the system require root, but the read-only +functions only read `/etc/passwd` and `/etc/group` (world-readable) or operate +on the calling user, so they work without root. + +Importing the main module prints a warning when it is not running as root. If +you only need the read-only functions you can import the non-root path, which +exposes only those functions and emits **no** root warning: + +```js +// read-only subset, no root warning, safe to use without root +var linuxUser = require('linux-user/non-root'); + +linuxUser.getUsers(function (err, users) { + // ... +}); +``` + +The non-root export exposes: `getUsers`, `getGroups`, `getUserInfo`, +`getUserGroups`, `getExpiration`, `validateUsername`, and `verifySSHKey`, plus +a read-only `promise()` factory. The same set is also available as +`require('linux-user').nonRoot` for convenience (the main import still emits the +root warning in that case). + ## Usage This works with your normal require and execute callback functions. Every method takes a callback and is non-blocking. +All callbacks follow the Node.js convention `(err, result)`. Errors are always +`Error` objects (or `null` on success) -- they are never passed as strings or +booleans. + ### Examples * add Linux user @@ -123,6 +155,17 @@ version of NodeJS( less then 8 ) you will need something like it. This will work with `.then()`, `.catch()` and the `async`/`await` pattern. +Synchronous helpers such as `validateUsername` are **not** promisified -- they +are passed through unchanged and still return their value directly (promisifying +them would produce a promise that never settles). The read-only functions are +available as a promise set too: + +```js +var p = require('linux-user/non-root').promise(); +var users = await p.getUsers(); +var valid = p.validateUsername('bob'); // still synchronous, returns boolean +``` + ```js let user = await addUser({username:"gkuchan", create_home:true, shell:null}); diff --git a/index.d.ts b/index.d.ts index 603aaed..735e423 100644 --- a/index.d.ts +++ b/index.d.ts @@ -8,8 +8,8 @@ export interface UserCreationArgs { expiredate?: string | Date; skel?: string; system?: boolean; - selinux_user?: boolean; - other_args?: string; + selinux_user?: string; + other_args?: string | string[]; } export interface UserInfo { @@ -30,7 +30,7 @@ export interface GroupInfo { } export interface UserExpirationInfo { - changed: Date; + changed: Date | null; passwordExpires: null | Date; inactive: null | Date; accountExpires: null | Date; @@ -53,20 +53,15 @@ export default class LinuxUser { args: UserCreationArgs | string, callback: (error: ErrorType, user?: UserInfo | null) => void ): void; - static removeUser( - username: string, - callback: (error: ErrorType) => void - ): void; + static removeUser(username: string, callback: (error: ErrorType) => void): void; static getUserGroups( username: string, callback: (error: ErrorType, groups?: string[]) => void ): void; - static getUsers( - callback: (error: ErrorType, users?: UserInfo[]) => void - ): void; + static getUsers(callback: (error: ErrorType, users?: UserInfo[]) => void): void; static getUserInfo( username: string, - callback: (error: ErrorType, user?: UserInfo) => void + callback: (error: ErrorType, user?: UserInfo | null) => void ): void; static setPassword( username: string, @@ -77,10 +72,7 @@ export default class LinuxUser { groupName: string, callback: (error: ErrorType, group?: GroupInfo | null) => void ): void; - static removeGroup( - groupName: string, - callback: (error: ErrorType) => void - ): void; + static removeGroup(groupName: string, callback: (error: ErrorType) => void): void; static getGroups( callback: (error: ErrorType, groups?: GroupInfo[]) => void ): void; @@ -112,4 +104,69 @@ export default class LinuxUser { callback: (error: ErrorType, done?: boolean) => void ): void; static validateUsername(username: string): boolean; + /** Read-only subset that does not require root privileges. */ + static nonRoot: LinuxUserReadOnly; } + +/** Read-only functions that do not require root privileges. */ +export interface LinuxUserReadOnly { + getUsers(callback: (error: ErrorType, users?: UserInfo[]) => void): void; + getGroups(callback: (error: ErrorType, groups?: GroupInfo[]) => void): void; + getUserInfo( + username: string, + callback: (error: ErrorType, user?: UserInfo | null) => void + ): void; + getUserGroups( + username: string, + callback: (error: ErrorType, groups?: string[]) => void + ): void; + getExpiration( + username: string, + callback: (error: ErrorType, data?: UserExpirationInfo) => void + ): void; + validateUsername(username: string): boolean; + verifySSHKey( + key: string, + callback: (error: ErrorType, done?: boolean) => void + ): void; + promise: LinuxUserPromiseFactory; +} + +/** Result of `linuxUser.promise()` -- all methods return Promises. */ +export interface LinuxUserPromise { + addUser(args: UserCreationArgs | string): Promise; + removeUser(username: string): Promise; + getUserGroups(username: string): Promise; + getUsers(): Promise; + getUserInfo(username: string): Promise; + setPassword(username: string, password: string): Promise; + addGroup(groupName: string): Promise; + removeGroup(groupName: string): Promise; + getGroups(): Promise; + getGroupInfo(groupName: string): Promise; + addUserToGroup(username: string, groupName: string): Promise; + getExpiration(username: string): Promise; + setExpiration(username: string, args: UserExpirationEditArgs): Promise; + verifySSHKey(key: string): Promise; + addSSHtoUser(username: string, key: string): Promise; + validateUsername(username: string): boolean; +} + +/** Read-only promise subset (see LinuxUserReadOnly). */ +export interface LinuxUserReadOnlyPromise { + getUsers(): Promise; + getGroups(): Promise; + getUserInfo(username: string): Promise; + getUserGroups(username: string): Promise; + getExpiration(username: string): Promise; + validateUsername(username: string): boolean; + verifySSHKey(key: string): Promise; +} + +export interface LinuxUserPromiseFactory { + (promisifyFn?: (fn: Function) => Function): LinuxUserPromise; + nonRoot(promisifyFn?: (fn: Function) => Function): LinuxUserReadOnlyPromise; +} + +/** Non-root import: `import linuxUser from 'linux-user/non-root'`. */ +export declare const nonRoot: LinuxUserReadOnly; \ No newline at end of file diff --git a/index.js b/index.js index b7c8ffb..3b6175e 100644 --- a/index.js +++ b/index.js @@ -15,4 +15,8 @@ if (!(process.getuid && process.getuid() === 0)) { var lib = require("./lib/user"); lib.promise = require("./lib/promise"); +// Convenience accessor for the read-only (non-root safe) subset. For an import +// path that also suppresses the root warning, use `require('linux-user/non-root')`. +lib.nonRoot = require("./non-root"); + module.exports = lib; diff --git a/lib/promise.js b/lib/promise.js index 3441fb7..2c46e75 100644 --- a/lib/promise.js +++ b/lib/promise.js @@ -1,20 +1,76 @@ "use strict"; -var promise = function (promise_fn) { - var lib = require("./user"); +// Functions that follow the (err, result) callback convention and can be +// promisified. `validateUsername` is synchronous (no callback) and must NOT be +// promisified -- util.promisify would inject a callback that is never invoked, +// producing a promise that never settles. +var ASYNC = [ + "addUser", + "removeUser", + "getUserGroups", + "getUsers", + "getUserInfo", + "setPassword", + "addGroup", + "removeGroup", + "getGroups", + "getGroupInfo", + "addUserToGroup", + "getExpiration", + "setExpiration", + "verifySSHKey", + "addSSHtoUser", +]; + +// Functions that are safe to use without root privileges (read-only or operate +// on the calling user). Exposed via `require('linux-user/non-root')`. +var NON_ROOT = [ + "getUsers", + "getGroups", + "getUserInfo", + "getUserGroups", + "getExpiration", + "validateUsername", + "verifySSHKey", +]; - if (!promise_fn) { +function build(promisifyFn, keys) { + var lib = require("./user"); + if (!promisifyFn) { var util = require("util"); - promise_fn = util.promisify; + promisifyFn = util.promisify; } var out = {}; - - Object.keys(lib).forEach(function (key) { - out[key] = promise_fn(lib[key]); + keys.forEach(function (key) { + if (typeof lib[key] !== "function") { + return; + } + if (ASYNC.indexOf(key) !== -1) { + out[key] = promisifyFn(lib[key]); + } else { + // synchronous helpers are passed through unchanged + out[key] = lib[key]; + } }); + return out; +} +var promise = function (promisifyFn) { + // Use an explicit key list rather than Object.keys(lib) so properties + // attached at the index level (promise, nonRoot) are not promisified. + return build(promisifyFn, ASYNC.concat(["validateUsername"])); +}; + +promise.nonRoot = function (promisifyFn) { + var full = promise(promisifyFn); + var out = {}; + NON_ROOT.forEach(function (key) { + if (full[key] !== undefined) { + out[key] = full[key]; + } + }); return out; }; -module.exports = promise; +module.exports = promise; \ No newline at end of file diff --git a/lib/user.js b/lib/user.js index f05e0a5..5fefced 100644 --- a/lib/user.js +++ b/lib/user.js @@ -1,17 +1,34 @@ "use strict"; -var util = require("util"); -var exec = require("child_process").exec; var spawn = require("child_process").spawn; var fs = require("fs"); var validUsernameRegex = /^([a-z_][a-z0-9_-]{0,30})$/; -function spawnWrapper(command, args, stdin, callback) { +// Default timeout applied to spawned commands so a hung child process +// (e.g. LDAP/SSSD delays) cannot hang the library forever. Pass +// `opts.timeout` to override or `{ timeout: 0 }` to disable. +var DEFAULT_TIMEOUT = 0; + +function spawnWrapper(command, args, stdin, opts, callback) { + // allow the legacy 4-arg form: spawnWrapper(command, args, stdin, callback) + if (typeof opts === "function") { + callback = opts; + opts = {}; + } + opts = opts || {}; + var stdout = ""; var stderr = ""; + var settled = false; + var timer = null; + + var spawnOpts = {}; + if (opts.env) { + spawnOpts.env = opts.env; + } - var _p = spawn(command, args); + var _p = spawn(command, args, spawnOpts); if (stdin) { _p.stdin.write(stdin); _p.stdin.end(); @@ -23,11 +40,41 @@ function spawnWrapper(command, args, stdin, callback) { stderr += data.toString(); }); - _p.on("error", function () { - callback(stderr || true, stdout); + function done(err) { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + timer = null; + } + callback(err, stdout); + } + + if (opts.timeout && opts.timeout > 0) { + timer = setTimeout(function () { + try { + _p.kill("SIGKILL"); + } catch (e) { + // process may have already exited + } + done(new Error(command + " timed out after " + opts.timeout + "ms")); + }, opts.timeout); + } + + _p.on("error", function (err) { + done(err || new Error("Failed to spawn " + command)); }); - _p.on("exit", function () { - callback(stderr, stdout); + _p.on("exit", function (code) { + if (code === 0 || code === undefined && !stderr) { + done(null); + } else if (code !== 0) { + var msg = (stderr || command + " exited with code " + code).trim(); + done(new Error(msg)); + } else { + done(null); + } }); } @@ -100,7 +147,11 @@ function build_user_command(args, map) { var keys = Object.keys(args); var out = []; for (var index = 0; index < keys.length; index++) { - var out = out.concat(map[keys[index]](args[keys[index]])); + var result = map[keys[index]](args[keys[index]]); + // skip undefined/null returns so we never inject a "null" argument + if (result) { + out = out.concat(result); + } } return out; @@ -126,7 +177,9 @@ exports.addUser = function (args, callback) { [].concat(args_array, [args.username]), null, function (error, data) { - if (error) callback(error); + if (error) { + return callback(error); + } exports.getUserInfo(args.username, callback); } ); @@ -138,9 +191,19 @@ exports.removeUser = function (username, callback) { return callback(new Error("Invalid username")); } + var settled = false; var _p = spawn("userdel", ["-rf", username]); - _p.on("error", callback); - _p.on("exit", callback); + function finish(err) { + if (settled) { + return; + } + settled = true; + callback(err); + } + _p.on("error", finish); + _p.on("exit", function (code) { + finish(code === 0 ? null : new Error("userdel exited with code " + code)); + }); }; exports.getUserGroups = function (username, callback) { @@ -150,8 +213,14 @@ exports.getUserGroups = function (username, callback) { } spawnWrapper("groups", [username], null, function (err, stdout) { - if (err) callback(err); + if (err) { + return callback(err); + } var groups = stdout.replace("\n", "").replace(/.+:\s/i, "").split(" "); + // `groups` prints " : " when the user belongs to no groups + if (groups.length === 1 && groups[0] === "") { + return callback(null, []); + } return callback(null, groups); }); }; @@ -161,8 +230,12 @@ exports.getUsers = function (callback) { if (err) { return callback(err); } - var _users = content.toString().split("\n"); - _users.pop(); + var _users = content + .toString() + .split("\n") + .filter(function (line) { + return line.length > 0; + }); _users = _users.map(function (line) { var _cols = line.split(":"); return { @@ -203,17 +276,27 @@ exports.setPassword = function (username, password, callback) { return callback(new Error("Invalid username")); } - // spawnWrapper('password', [username], password+'\n'+password+'\n', function(error, data){ - // console.log(error, data) - // }) - + var stderr = ""; + var settled = false; var _p = spawn("passwd", [username]); _p.stdin.write(password + "\n"); _p.stdin.write(password + "\n"); _p.stdin.end(); - _p.on("error", callback); - _p.on("exit", function () { - callback(); + _p.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + function finish(err) { + if (settled) { + return; + } + settled = true; + callback(err); + } + + _p.on("error", finish); + _p.on("exit", function (code) { + finish(code === 0 ? null : new Error((stderr || "passwd failed").trim())); }); }; @@ -223,7 +306,10 @@ exports.addGroup = function (groupname, callback) { return callback(new Error("Invalid groupname")); } - spawnWrapper("groupadd", [groupname], null, function () { + spawnWrapper("groupadd", [groupname], null, function (error) { + if (error) { + return callback(error); + } exports.getGroupInfo(groupname, callback); }); }; @@ -234,7 +320,9 @@ exports.removeGroup = function (groupname, callback) { return callback(new Error("Invalid groupname")); } - spawnWrapper("groupdel", [groupname], null, callback); + spawnWrapper("groupdel", [groupname], null, function (error) { + callback(error || null); + }); }; exports.getGroups = function (callback) { @@ -242,8 +330,12 @@ exports.getGroups = function (callback) { if (err) { return callback(err); } - var _groups = content.toString().split("\n"); - _groups.pop(); + var _groups = content + .toString() + .split("\n") + .filter(function (line) { + return line.length > 0; + }); _groups = _groups.map(function (line) { var _cols = line.split(":"); return { @@ -278,9 +370,19 @@ exports.addUserToGroup = function (username, groupname, callback) { return callback(new Error("Invalid arguments")); } + var settled = false; var _p = spawn("usermod", ["-a", "-G", groupname, username]); - _p.on("error", callback); - _p.on("exit", callback); + function finish(err) { + if (settled) { + return; + } + settled = true; + callback(err); + } + _p.on("error", finish); + _p.on("exit", function (code) { + finish(code === 0 ? null : new Error("usermod exited with code " + code)); + }); }; var chage_arg_map = { @@ -316,6 +418,17 @@ var chage_arg_map = { }, }; +// Force the C locale when parsing `chage --list` so the field labels and date +// format are stable regardless of the system locale. +var chageEnv = Object.assign({}, process.env, { LC_ALL: "C", LANG: "C" }); + +function parseChageDate(value) { + if (!value || value === "never") { + return null; + } + return new Date(value); +} + exports.getExpiration = function (username, callback) { if (!validate(username)) { return callback(new Error("Invalid username")); @@ -327,28 +440,40 @@ exports.getExpiration = function (username, callback) { "chage", [].concat(args_array, [username]), null, + { env: chageEnv }, function (error, data) { - data = data.split("\n"); - - data = { - changed: new Date(data[0].split(": ")[1]), - passwordExpires: - data[1].split(": ")[1] === "never" - ? null - : new Date(data[1].split(": ")[1]), - inactive: - data[2].split(": ")[1] === "never" - ? null - : new Date(data[2].split(": ")[1]), - accountExpires: - data[3].split(": ")[1] === "never" - ? null - : new Date(data[3].split(": ")[1]), - minDays: Number(data[4].split(": ")[1]), - maxDays: Number(data[5].split(": ")[1]), - warnDays: Number(data[6].split(": ")[1]), + if (error) { + return callback(error); + } + if (!data) { + return callback(new Error("chage returned no output")); + } + + var lines = data.split("\n"); + var fields = {}; + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + var idx = line.indexOf(": "); + if (idx === -1) { + continue; + } + var label = line.slice(0, idx).trim().toLowerCase(); + var value = line.slice(idx + 2).trim(); + fields[label] = value; + } + + var data2 = { + changed: parseChageDate(fields["last password change"]), + passwordExpires: parseChageDate(fields["password expires"]), + inactive: parseChageDate(fields["password inactive"]), + accountExpires: parseChageDate(fields["account expires"]), + minDays: Number(fields["minimum number of days between password change"]), + maxDays: Number(fields["maximum number of days between password change"]), + warnDays: Number( + fields["number of days of warning before password expires"] + ), }; - callback(error, data); + callback(null, data2); } ); }; @@ -375,47 +500,56 @@ exports.verifySSHKey = function (key, callback) { }; exports.addSSHtoUser = function (user, key, callback) { - exports.verifySSHKey(key, function (error, info) { + exports.verifySSHKey(key, function (error) { if (error) { - return callback("Bad SSH key"); + return callback(new Error("Bad SSH key")); } exports.getUserInfo(user, function (error, info) { if (error) { - return callback("User does not exist"); + return callback(error); + } + if (!info) { + return callback(new Error("User does not exist")); } - var commands = [ - util.format("mkdir %s/.ssh;", info.homedir), - util.format("touch %s/.ssh/authorized_keys;", info.homedir), - util.format("chown 700 %s/.ssh;", info.homedir), - util.format("chmod 600 %s/.ssh/authorized_keys;", info.homedir), - util.format( - "chown %s:%s %s/.ssh -R;", - info.username, - info.username, - info.homedir - ), - ].join(" "); + // Guard against shell metacharacters in the homedir before using it + // in file paths (homedir comes from /etc/passwd, which is trusted on a + // properly secured system, but validate defensively). + if (!info.homedir || /[;&|`$()\\<>]/.test(info.homedir)) { + return callback(new Error("Invalid homedir path")); + } - // this is a safe place to call exec because we are not taking any user input data. - exec(commands, function (err, stdout, stderr) { - if (err || stderr) { - return callback([err, stderr]); + var sshDir = info.homedir + "/.ssh"; + var keyFile = sshDir + "/authorized_keys"; + + // Run each step with spawn (no shell) to avoid command injection. + var steps = [ + ["mkdir", ["-p", sshDir]], + ["chmod", ["700", sshDir]], + ["touch", [keyFile]], + ["chmod", ["600", keyFile]], + ["chown", ["-R", info.username + ":" + info.username, sshDir]], + ]; + + var index = 0; + function nextStep(err) { + if (err) { + return callback(err); } - - fs.appendFile( - info.homedir + "/.ssh/authorized_keys", - key, - function (err) { + if (index >= steps.length) { + return fs.appendFile(keyFile, key + "\n", function (err) { if (err) { - callback(err); + return callback(err); } - return callback(null, true); - } - ); - }); + callback(null, true); + }); + } + var step = steps[index++]; + spawnWrapper(step[0], step[1], null, nextStep); + } + nextStep(); }); }); }; -exports.validateUsername = validate; +exports.validateUsername = validate; \ No newline at end of file diff --git a/non-root.d.ts b/non-root.d.ts new file mode 100644 index 0000000..8a08cc0 --- /dev/null +++ b/non-root.d.ts @@ -0,0 +1,4 @@ +import { LinuxUserReadOnly } from "."; +declare const nonRoot: LinuxUserReadOnly; +export default nonRoot; +export * from "."; \ No newline at end of file diff --git a/non-root.js b/non-root.js new file mode 100644 index 0000000..db64a78 --- /dev/null +++ b/non-root.js @@ -0,0 +1,34 @@ +"use strict"; + +// Read-only import path for linux-user. +// +// Some functions in linux-user do not require root privileges (they read +// /etc/passwd and /etc/group, which are world-readable, or operate on the +// calling user). Importing this module instead of the main one: +// +// * does NOT emit the "not running as root" warning, and +// * exposes only the functions that are safe to call without root. +// +// Usage: +// var linuxUser = require('linux-user/non-root'); +// linuxUser.getUsers(function (err, users) { ... }); +// +// This still requires Linux -- the platform check is enforced. + +if (process.platform !== "linux") { + throw new Error("linux-user must be running on Linux"); +} + +var user = require("./lib/user"); +var promise = require("./lib/promise"); + +module.exports = { + getUsers: user.getUsers, + getGroups: user.getGroups, + getUserInfo: user.getUserInfo, + getUserGroups: user.getUserGroups, + getExpiration: user.getExpiration, + validateUsername: user.validateUsername, + verifySSHKey: user.verifySSHKey, + promise: promise.nonRoot, +}; \ No newline at end of file diff --git a/package.json b/package.json index 5c0e6b2..f5fadbd 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,9 @@ { "name": "linux-sys-user", - "version": "1.2.0", + "version": "2.0.0", "description": "Node.js module for Linux user and group management with zero dependencies", + "main": "index.js", + "types": "index.d.ts", "author": [ { "name": "William Mantly", diff --git a/test/user.test.js b/test/user.test.js index 66bbbdf..c21160a 100644 --- a/test/user.test.js +++ b/test/user.test.js @@ -3,7 +3,9 @@ require("should"); var linuxUser = require("../"); +var nonRootUser = require("../non-root"); var fs = require("fs"); +var os = require("os"); var testUsername = "linuxusertest1"; var testPassword = "linuxPasswordTest"; @@ -11,13 +13,27 @@ var testGroupname = "linuxgrouptest"; var testSSHKeyGood = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDBqDmHHhV9HHCY0Rvp6by4N1aBsnjreWKIPaO2UHCURzJk8Sa92jXEfNXpQ1H36yJmirCB+q6XRCKq27ah5M86fCKsm+UfbPlD/X81YH+RnnYgGyh7nwk+llvLKdrzFnF7aHG5/WShj5YUzZO9McIPxyrU1GmMnxEynHp4qSsnmKNJZT2KtpGlP/cvOktNjRWO1hAY8mXG9VShSpqLYWU/AbTV4hZZ2Pr/FdRZq59oRcm9ZGfd13ZMJcPlfhTCeslJfWNx2cuMTSLXRN76MtCmWsPKuVNY6Hj/ILL7JQe8DIxu9AAMiUqFadfFHRGO9dzCh8fKi5lpSMsDKqHHysb504p2ogHDzOUpc/remX3exnvDK1245JXYlNtUkXIexVl+u871PDNbOhx4lSa1nGJGiJCJLW7FlL5mEPrvlgeWaxGihi66redtcPWGVuy2dYytYoI8JanpGlEGFkTOIaKSvDH0ratOxRSlP/Eraxs7w3uVaRvF7/iC348CI63l7T8= william@william-HP-ENVY-x360-Convertible"; var testSSHkeyBad = - "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDBqDmHHhV9HHCY0Rvp6by4N1aBsnjreWKIPaO2UHCURzJk8Sa92jXEfNXpQ1H36yJmirCB+q6XRCKq27ah5M86fCKsm+UfbPlD/X81YH+RnnYgGyh7nwk+llvLKdrzFnF7aHG5/WShj5YUzZO9McIPxyrU1GmMnxEynHp4qSsnmKNJZT2KtpGlP/cvOktNjRWO1hAY8mXG9VShSpqLYWU/AbTV4hZZ2Pr/FdRZq59oRcm9ZGfd13ZMJcPlfhTCeslJfWNx2cuMTSLXRN76MtCmWsPKuVNY6Hj/ILL7JQe8DIxu9AAMiUqFadfFHRGO9dzCh8fKi5lpSMsDKqHHysb504p2ogHDzOUpc/remX3exnvDK1245JXYlNtUkXIexVl+u871PDNbOhx4lSa1nGJGiJCJLW7FlL5mEPrvlgeWaxGihi66redtcPWGVuy2ytYoI8JanpGlEGFkTOKSvDH0ratOxRSlP/axs7w3uVaRvF7/iC348CI63l7T8= william@william-HP-ENVY-x360-Convertible"; + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDBqDmHHhV9HHCY0Rvp6by4N1aBsnjreWKIPaO2UHCURzJk8Sa92jXEfNXpQ1H36yJmirCB+q6XRCKq27ah5M86fCKsm+UfbPlD/X81YH+RnnYgGyh7nwk+llvLKdrzFnF7aHG5/WShj5YUzZO9McIPxyrU1GmMnxEynHp4qSsnmKNJZT2KtpGlP/cvOktNjRWO1hAY8mXG9VShSpqLYWU/AbTV4hZZ2Pr/FdRZq59oRcm9ZGfd13ZMJcPlfhTCeslJfWNx2cuMTSLXRN76MtCmWsPKuVNY6Hj/ILL7JQe8DIxu9AAMiUqFadfFHRGO9dzCh8fKi5lpSMsDKqHHysb504p2ogHDzOUpc/remX3exnvDK1245JXYlNtUkXIexVl+u871PDNbOhx4lSa1nGJGiJCJLW7FlL5mEPrvlgeWaxGihi66redtcPWGVuy2ytYoI8JanpGlEGFkTOIaKSvDH0ratOxRSlP/axs7w3uVaRvF7/iC348CI63l7T8= william@william-HP-ENVY-x360-Convertible"; + +// Many functions modify system files and require root. Skip those tests when +// the suite is not running as root so the suite passes in CI / dev without +// root, while still exercising the read-only code paths. +var isRoot = typeof process.getuid === "function" && process.getuid() === 0; +function rootOnly() { + if (!isRoot) { + // eslint-disable-next-line no-invalid-this + this.skip(); + } +} describe("user.js", function () { describe("validateUsername", function () { it("should validate username ok", function () { linuxUser.validateUsername("/$#%&^%$~!|}|23").should.be.false; }); + it("should accept a valid username", function () { + linuxUser.validateUsername("bob").should.be.true; + }); }); describe("getUsers", function () { @@ -31,6 +47,36 @@ describe("user.js", function () { done(); }); }); + + it("should not drop the last entry when there is no trailing newline", function (done) { + // read the real file, strip any trailing newline, and verify parsing + // produces the same count as a version that retains it. + fs.readFile("/etc/passwd", "utf8", function (err, content) { + if (err) { + return done(err); + } + var noTrailing = content.replace(/\n$/, ""); + // simulate getUsers' parsing on content without a trailing newline + var parsed = noTrailing + .split("\n") + .filter(function (line) { + return line.length > 0; + }) + .map(function (line) { + return line.split(":")[0]; + }); + var withTrailing = content + .split("\n") + .filter(function (line) { + return line.length > 0; + }) + .map(function (line) { + return line.split(":")[0]; + }); + parsed.length.should.equal(withTrailing.length); + done(); + }); + }); }); describe("Invalid username", function () { @@ -38,6 +84,8 @@ describe("user.js", function () { linuxUser.addUser({ username: "/$#%&^%$~!|}|23" }, function (err, user) { err.should.be.an.Error; err.message.should.equal("Invalid username"); + // addUser must not invoke the callback a second time. If it did, + // mocha's done() would throw "done() called multiple times". done(); }); }); @@ -53,9 +101,20 @@ describe("user.js", function () { done(); }); }); + + it("should return null for a missing user", function (done) { + linuxUser.getUserInfo("definitely-not-a-real-user-xyz", function (err, user) { + if (err) { + return done(err); + } + should.equal(user, null); + done(); + }); + }); }); describe("addUser && removeUser", function () { + before(rootOnly); it("should add user and remove user ok", function (done) { var num; linuxUser.getUsers(function (err, users) { @@ -93,10 +152,15 @@ describe("user.js", function () { describe("Expiration", function () { before(function (done) { + if (!isRoot) { + this.skip(); + } linuxUser.addUser({ username: testUsername }, done); }); - after(function (done) { + if (!isRoot) { + return done(); + } linuxUser.removeUser(testUsername, done); }); @@ -164,10 +228,14 @@ describe("user.js", function () { }); describe("addUser options", function () { + before(rootOnly); afterEach(function (done) { + if (!isRoot) { + return done(); + } linuxUser.removeUser(testUsername, function (err) { if (err) { - done(err); + return done(err); } done(); }); @@ -178,7 +246,7 @@ describe("user.js", function () { { username: testUsername, shell: "/bin/bash" }, function (err, user) { if (err) { - done(err); + return done(err); } user.shell.should.equal("/bin/bash"); done(); @@ -214,6 +282,7 @@ describe("user.js", function () { }); describe("addGroup && removeGroup", function () { + before(rootOnly); it("should add group and remove group ok", function (done) { var num; linuxUser.getGroups(function (err, groups) { @@ -260,59 +329,110 @@ describe("user.js", function () { }); it("should be bad SSH key", function (done) { linuxUser.verifySSHKey(testSSHkeyBad, function (err, data) { - if (err) { - return done(); - } - done(new Error("This key is bad, function did not error out")); + err.should.be.an.Error; + done(); }); }); }); describe("addSSHtoUser", function () { - afterEach(function (done) { - linuxUser.removeUser(testUsername, done); + it("should error (not crash) when the user does not exist", function (done) { + // valid key, missing user -- must return an Error, not throw + linuxUser.addSSHtoUser( + "definitely-not-a-real-user-xyz", + testSSHKeyGood, + function (err, done2) { + err.should.be.an.Error; + err.message.should.equal("User does not exist"); + should.equal(done2, undefined); + done(); + } + ); }); - it("should add SSH key to the user", function (done) { - linuxUser.addUser( - { username: testUsername, create_home: true }, - function (err, user) { - if (err) { - done(err); - } - linuxUser.addSSHtoUser(testUsername, testSSHKeyGood, function (err) { + describe("(root)", function () { + before(rootOnly); + afterEach(function (done) { + if (!isRoot) { + return done(); + } + linuxUser.removeUser(testUsername, done); + }); + it("should add SSH key to the user", function (done) { + linuxUser.addUser( + { username: testUsername, create_home: true }, + function (err, user) { if (err) { - done(err); + return done(err); } - // read the users auth file + linuxUser.addSSHtoUser(testUsername, testSSHKeyGood, function (err) { + if (err) { + return done(err); + } - fs.readFile( - user.homedir + "/.ssh/authorized_keys", - "utf8", - (err, data) => { - if (err) { - done(err); - return; + // read the users auth file + fs.readFile( + user.homedir + "/.ssh/authorized_keys", + "utf8", + (err, data) => { + if (err) { + return done(err); + } + done(); } - // console.log(data) - done(); - } - ); - }); + ); + }); + } + ); + }); + }); + }); + + describe("getExpiration (non-root, self)", function () { + it("should parse the calling user's expiration without root", function (done) { + var me = os.userInfo().username; + linuxUser.getExpiration(me, function (err, data) { + if (err) { + return done(err); } - ); + data.should.be.an.Object; + data.maxDays.should.be.a.Number; + data.warnDays.should.be.a.Number; + done(); + }); + }); + + it("should reject an invalid username", function (done) { + linuxUser.getExpiration("UPPERCASE-BAD!!", function (err) { + err.should.be.an.Error; + err.message.should.equal("Invalid username"); + done(); + }); }); }); describe("Other methods", function () { + before(rootOnly); beforeEach(function (done) { + if (!isRoot) { + return done(); + } linuxUser.addUser({ username: testUsername }, function (err) { + if (err) { + return done(err); + } linuxUser.addGroup(testGroupname, done); }); }); afterEach(function (done) { + if (!isRoot) { + return done(); + } linuxUser.removeUser(testUsername, function (err) { + if (err) { + return done(err); + } linuxUser.removeGroup(testGroupname, done); }); }); @@ -325,4 +445,53 @@ describe("user.js", function () { linuxUser.addUserToGroup(testUsername, testGroupname, done); }); }); -}); + + describe("non-root import", function () { + it("should expose only read-only functions", function () { + var keys = Object.keys(nonRootUser).sort(); + // no mutating functions present + keys.should.not.containEql("addUser"); + keys.should.not.containEql("removeUser"); + keys.should.not.containEql("setPassword"); + keys.should.not.containEql("addGroup"); + keys.should.containEql("getUsers"); + keys.should.containEql("getGroups"); + keys.should.containEql("validateUsername"); + keys.should.containEql("verifySSHKey"); + }); + + it("should read users without root", function (done) { + nonRootUser.getUsers(function (err, users) { + if (err) { + return done(err); + } + users.should.be.an.Array; + done(); + }); + }); + + it("should expose a read-only promise set", function () { + var p = nonRootUser.promise(); + p.getUsers.should.be.a.Function; + should.not.exist(p.addUser); + }); + }); + + describe("promise wrapper", function () { + it("should promisify async methods", function (done) { + var p = linuxUser.promise(); + p.getUsers.should.be.a.Function; + p.getUsers().then(function (users) { + users.should.be.an.Array; + done(); + }, done); + }); + + it("should pass validateUsername through synchronously (not hang)", function () { + var p = linuxUser.promise(); + p.validateUsername.should.be.a.Function; + p.validateUsername("bob").should.be.true; + p.validateUsername("BAD!!").should.be.false; + }); + }); +}); \ No newline at end of file From 372e9a19cd1fb141c693be24044ee3b196b9bb55 Mon Sep 17 00:00:00 2001 From: William Mantly Date: Sat, 18 Jul 2026 14:38:06 -0400 Subject: [PATCH 2/2] Retrigger CI after Pages workflow deploy-job fix on master Co-Authored-By: Claude Sonnet 5