Compare commits

...

5 commits

Author SHA1 Message Date
Marc
325c546f4b
Merge 49edf0d830 into 46d8744fa4 2024-10-27 05:22:34 +00:00
Louis Lam
46d8744fa4
Fix: Docker Healthcheck is not happy during migration (#5258)
Some checks are pending
Auto Test / auto-test (18, ARM64) (push) Blocked by required conditions
Auto Test / auto-test (18, macos-latest) (push) Blocked by required conditions
Auto Test / auto-test (18, ubuntu-latest) (push) Blocked by required conditions
Auto Test / auto-test (18, windows-latest) (push) Blocked by required conditions
Auto Test / auto-test (20, ARM64) (push) Blocked by required conditions
Auto Test / auto-test (20, macos-latest) (push) Blocked by required conditions
Auto Test / auto-test (20, ubuntu-latest) (push) Blocked by required conditions
Auto Test / auto-test (20, windows-latest) (push) Blocked by required conditions
Auto Test / armv7-simple-test (18, ARMv7) (push) Waiting to run
Auto Test / armv7-simple-test (20, ARMv7) (push) Waiting to run
Auto Test / check-linters (push) Waiting to run
Auto Test / e2e-test (push) Waiting to run
CodeQL / Analyze (push) Waiting to run
Merge Conflict Labeler / Labeling (push) Waiting to run
json-yaml-validate / json-yaml-validate (push) Waiting to run
json-yaml-validate / check-lang-json (push) Waiting to run
2024-10-27 13:22:23 +08:00
Louis Lam
7d8dc55dbe
Fix: the rootless user put in the wrong place (#5257) 2024-10-27 11:47:30 +08:00
Marc Hagen
49edf0d830
[feat] Ability to change username
As there is no user management at the moment.
2024-05-21 22:33:44 +02:00
Marc Hagen
86ee98e0e8
[feat] Adding RemoteUser authentication 2024-05-21 22:33:39 +02:00
11 changed files with 327 additions and 83 deletions

View file

@ -27,7 +27,6 @@ RUN mkdir ./data
# ⭐ Main Image # ⭐ Main Image
############################################ ############################################
FROM $BASE_IMAGE AS release FROM $BASE_IMAGE AS release
USER node
WORKDIR /app WORKDIR /app
LABEL org.opencontainers.image.source="https://github.com/louislam/uptime-kuma" LABEL org.opencontainers.image.source="https://github.com/louislam/uptime-kuma"
@ -46,6 +45,7 @@ CMD ["node", "server/server.js"]
# Rootless Image # Rootless Image
############################################ ############################################
FROM release AS rootless FROM release AS rootless
USER node
############################################ ############################################
# Mark as Nightly # Mark as Nightly

65
extra/change-username.js Normal file
View file

@ -0,0 +1,65 @@
console.log("== Uptime Kuma Change Username Tool ==");
const Database = require("../server/database");
const { R } = require("redbean-node");
const readline = require("readline");
const { initJWTSecret } = require("../server/util-server");
const User = require("../server/model/user");
const args = require("args-parser")(process.argv);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const main = async () => {
console.log("Connecting the database");
Database.init(args);
await Database.connect(false, false, true);
try {
// No need to actually reset the password for testing, just make sure no connection problem. It is ok for now.
if (!process.env.TEST_BACKEND) {
const user = await R.findOne("user");
if (! user) {
throw new Error("user not found, have you installed?");
}
console.log("Found user: " + user.username);
let newUsername = await question("New username: ");
await User.updateUsername(user.id, newUsername);
// Reset all sessions by reset jwt secret
await initJWTSecret();
console.log("Username change successfully.");
}
} catch (e) {
console.error("Error: " + e.message);
}
await Database.close();
rl.close();
console.log("Finished.");
};
/**
* Ask question of user
* @param {string} question Question to ask
* @returns {Promise<string>} Users response
*/
function question(question) {
return new Promise((resolve) => {
rl.question(question, (answer) => {
resolve(answer);
});
});
}
if (!process.env.TEST_BACKEND) {
main();
}
module.exports = {
main,
};

View file

@ -50,6 +50,7 @@
"setup": "git checkout 1.23.14 && npm ci --production && npm run download-dist", "setup": "git checkout 1.23.14 && npm ci --production && npm run download-dist",
"download-dist": "node extra/download-dist.js", "download-dist": "node extra/download-dist.js",
"mark-as-nightly": "node extra/mark-as-nightly.js", "mark-as-nightly": "node extra/mark-as-nightly.js",
"change-username": "node extra/change-username.js",
"reset-password": "node extra/reset-password.js", "reset-password": "node extra/reset-password.js",
"remove-2fa": "node extra/remove-2fa.js", "remove-2fa": "node extra/remove-2fa.js",
"simple-dns-server": "node extra/simple-dns-server.js", "simple-dns-server": "node extra/simple-dns-server.js",

View file

@ -7,6 +7,9 @@ const { loginRateLimiter, apiRateLimiter } = require("./rate-limiter");
const { Settings } = require("./settings"); const { Settings } = require("./settings");
const dayjs = require("dayjs"); const dayjs = require("dayjs");
const remoteAuthEnabled = process.env.REMOTE_AUTH_ENABLED || false;
const remoteAuthHeader = process.env.REMOTE_AUTH_HEADER || "Remote-User";
/** /**
* Login to web app * Login to web app
* @param {string} username Username to login with * @param {string} username Username to login with
@ -133,29 +136,40 @@ function userAuthorizer(username, password, callback) {
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
exports.basicAuth = async function (req, res, next) { exports.basicAuth = async function (req, res, next) {
const disabledAuth = await setting("disableAuth");
if (remoteAuthEnabled) {
const remoteUser = req.headers[remoteAuthHeader.toLowerCase()];
if (remoteUser !== undefined) {
let user = await R.findOne("user", " username = ? AND active = 1 ", [ remoteUser ]);
if (user) {
next();
return;
}
}
}
if (!disabledAuth) {
const middleware = basicAuth({ const middleware = basicAuth({
authorizer: userAuthorizer, authorizer: userAuthorizer,
authorizeAsync: true, authorizeAsync: true,
challenge: true, challenge: true,
}); });
const disabledAuth = await setting("disableAuth");
if (!disabledAuth) {
middleware(req, res, next); middleware(req, res, next);
} else { return;
next();
} }
next();
}; };
/** /**
* Use use API Key if API keys enabled, else use basic auth * Use API Key if API keys enabled, else use basic auth
* @param {express.Request} req Express request object * @param {express.Request} req Express request object
* @param {express.Response} res Express response object * @param {express.Response} res Express response object
* @param {express.NextFunction} next Next handler in chain * @param {express.NextFunction} next Next handler in chain
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
exports.apiAuth = async function (req, res, next) { exports.authMiddleware = async function (req, res, next) {
if (!await Settings.get("disableAuth")) { if (!await Settings.get("disableAuth")) {
let usingAPIKeys = await Settings.get("apiKeysEnabled"); let usingAPIKeys = await Settings.get("apiKeysEnabled");
let middleware; let middleware;

View file

@ -9,6 +9,7 @@ const mysql = require("mysql2/promise");
const { Settings } = require("./settings"); const { Settings } = require("./settings");
const { UptimeCalculator } = require("./uptime-calculator"); const { UptimeCalculator } = require("./uptime-calculator");
const dayjs = require("dayjs"); const dayjs = require("dayjs");
const { SimpleMigrationServer } = require("./utils/simple-migration-server");
/** /**
* Database & App Data Folder * Database & App Data Folder
@ -382,9 +383,11 @@ class Database {
/** /**
* Patch the database * Patch the database
* @param {number} port Start the migration server for aggregate tables on this port if provided
* @param {string} hostname Start the migration server for aggregate tables on this hostname if provided
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
static async patch() { static async patch(port = undefined, hostname = undefined) {
// Still need to keep this for old versions of Uptime Kuma // Still need to keep this for old versions of Uptime Kuma
if (Database.dbConfig.type === "sqlite") { if (Database.dbConfig.type === "sqlite") {
await this.patchSqlite(); await this.patchSqlite();
@ -409,7 +412,7 @@ class Database {
await R.exec("PRAGMA foreign_keys = ON"); await R.exec("PRAGMA foreign_keys = ON");
} }
await this.migrateAggregateTable(); await this.migrateAggregateTable(port, hostname);
} catch (e) { } catch (e) {
// Allow missing patch files for downgrade or testing pr. // Allow missing patch files for downgrade or testing pr.
@ -735,9 +738,11 @@ class Database {
* Normally, it should be in transaction, but UptimeCalculator wasn't designed to be in transaction before that. * Normally, it should be in transaction, but UptimeCalculator wasn't designed to be in transaction before that.
* I don't want to heavily modify the UptimeCalculator, so it is not in transaction. * I don't want to heavily modify the UptimeCalculator, so it is not in transaction.
* Run `npm run reset-migrate-aggregate-table-state` to reset, in case the migration is interrupted. * Run `npm run reset-migrate-aggregate-table-state` to reset, in case the migration is interrupted.
* @param {number} port Start the migration server on this port if provided
* @param {string} hostname Start the migration server on this hostname if provided
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
static async migrateAggregateTable() { static async migrateAggregateTable(port, hostname = undefined) {
log.debug("db", "Enter Migrate Aggregate Table function"); log.debug("db", "Enter Migrate Aggregate Table function");
// Add a setting for 2.0.0-dev users to skip this migration // Add a setting for 2.0.0-dev users to skip this migration
@ -758,6 +763,18 @@ class Database {
throw new Error("Aggregate table migration is already in progress"); throw new Error("Aggregate table migration is already in progress");
} }
/**
* Start migration server for displaying the migration status
* @type {SimpleMigrationServer}
*/
let migrationServer;
let msg;
if (port) {
migrationServer = new SimpleMigrationServer();
await migrationServer.start(port, hostname);
}
await Settings.set("migrateAggregateTableState", "migrating"); await Settings.set("migrateAggregateTableState", "migrating");
log.info("db", "Migrating Aggregate Table"); log.info("db", "Migrating Aggregate Table");
@ -777,6 +794,7 @@ class Database {
let count = countResult.count; let count = countResult.count;
if (count > 0) { if (count > 0) {
log.warn("db", `Aggregate table ${table} is not empty, migration will not be started (Maybe you were using 2.0.0-dev?)`); log.warn("db", `Aggregate table ${table} is not empty, migration will not be started (Maybe you were using 2.0.0-dev?)`);
await migrationServer?.stop();
return; return;
} }
} }
@ -811,7 +829,9 @@ class Database {
`, [ monitor.monitor_id, date.date ]); `, [ monitor.monitor_id, date.date ]);
if (heartbeats.length > 0) { if (heartbeats.length > 0) {
log.info("db", `[DON'T STOP] Migrating monitor data ${monitor.monitor_id} - ${date.date} [${progressPercent.toFixed(2)}%][${i}/${monitors.length}]`); msg = `[DON'T STOP] Migrating monitor data ${monitor.monitor_id} - ${date.date} [${progressPercent.toFixed(2)}%][${i}/${monitors.length}]`;
log.info("db", msg);
migrationServer?.update(msg);
} }
for (let heartbeat of heartbeats) { for (let heartbeat of heartbeats) {
@ -829,9 +849,13 @@ class Database {
i++; i++;
} }
await Database.clearHeartbeatData(true); msg = "Clearing non-important heartbeats";
log.info("db", msg);
migrationServer?.update(msg);
await Database.clearHeartbeatData(true);
await Settings.set("migrateAggregateTableState", "migrated"); await Settings.set("migrateAggregateTableState", "migrated");
await migrationServer?.stop();
if (monitors.length > 0) { if (monitors.length > 0) {
log.info("db", "Aggregate Table Migration Completed"); log.info("db", "Aggregate Table Migration Completed");

View file

@ -48,6 +48,17 @@ class User extends BeanModel {
}, jwtSecret); }, jwtSecret);
} }
/**
* @param {number} userID ID of user to update
* @param {string} newUsername Users new username
* @returns {Promise<void>}
*/
static async updateUsername(userID, newUsername) {
await R.exec("UPDATE `user` SET username = ? WHERE id = ? ", [
newUsername,
userID
]);
}
} }
module.exports = User; module.exports = User;

View file

@ -104,12 +104,14 @@ log.debug("server", "Importing Background Jobs");
const { initBackgroundJobs, stopBackgroundJobs } = require("./jobs"); const { initBackgroundJobs, stopBackgroundJobs } = require("./jobs");
const { loginRateLimiter, twoFaRateLimiter } = require("./rate-limiter"); const { loginRateLimiter, twoFaRateLimiter } = require("./rate-limiter");
const { apiAuth } = require("./auth"); const { authMiddleware } = require("./auth");
const { login } = require("./auth"); const { login } = require("./auth");
const passwordHash = require("./password-hash"); const passwordHash = require("./password-hash");
const hostname = config.hostname; const remoteAuthEnabled = process.env.REMOTE_AUTH_ENABLED || false;
const remoteAuthHeader = process.env.REMOTE_AUTH_HEADER || "Remote-User";
const hostname = config.hostname;
if (hostname) { if (hostname) {
log.info("server", "Custom hostname: " + hostname); log.info("server", "Custom hostname: " + hostname);
} }
@ -292,7 +294,7 @@ let needSetup = false;
// Prometheus API metrics /metrics // Prometheus API metrics /metrics
// With Basic Auth using the first user's username/password // With Basic Auth using the first user's username/password
app.get("/metrics", apiAuth, prometheusAPIMetrics()); app.get("/metrics", authMiddleware, prometheusAPIMetrics());
app.use("/", expressStaticGzip("dist", { app.use("/", expressStaticGzip("dist", {
enableBrotli: true, enableBrotli: true,
@ -1583,10 +1585,26 @@ let needSetup = false;
// *************************** // ***************************
log.debug("auth", "check auto login"); log.debug("auth", "check auto login");
if (await setting("disableAuth")) { if (await Settings.get("disableAuth")) {
log.info("auth", "Disabled Auth: auto login to admin"); log.info("auth", "Disabled Auth: auto login to admin");
await afterLogin(socket, await R.findOne("user")); await afterLogin(socket, await R.findOne("user"));
socket.emit("autoLogin"); socket.emit("autoLogin");
} else if (remoteAuthEnabled) {
log.debug("auth", socket.handshake.headers);
const remoteUser = socket.handshake.headers[remoteAuthHeader.toLowerCase()];
if (remoteUser !== undefined) {
const user = await R.findOne("user", " username = ? AND active = 1 ", [ remoteUser ]);
if (user) {
log.info("auth", `Login by remote-user header. IP=${await server.getClientIP(socket)}`);
log.debug("auth", `Remote user ${remoteUser} exists, found user ${user.username}`);
afterLogin(socket, user);
socket.emit("autoLoginRemoteHeader", user.username);
} else {
log.debug("auth", `Remote user ${remoteUser} doesn't exist`);
}
} else {
log.debug("auth", "Remote user header set but not found in headers");
}
} else { } else {
socket.emit("loginRequired"); socket.emit("loginRequired");
log.debug("auth", "need auth"); log.debug("auth", "need auth");
@ -1716,7 +1734,7 @@ async function initDatabase(testMode = false) {
log.info("server", "Connected to the database"); log.info("server", "Connected to the database");
// Patch the database // Patch the database
await Database.patch(); await Database.patch(port, hostname);
let jwtSecretBean = await R.findOne("setting", " `key` = ? ", [ let jwtSecretBean = await R.findOne("setting", " `key` = ? ", [
"jwtSecret", "jwtSecret",

View file

@ -0,0 +1,84 @@
const express = require("express");
const http = require("node:http");
const { log } = require("../../src/util");
/**
* SimpleMigrationServer
* For displaying the migration status of the server
* Also, it is used to let Docker healthcheck know the status of the server, as the main server is not started yet, healthcheck will think the server is down incorrectly.
*/
class SimpleMigrationServer {
/**
* Express app instance
* @type {?Express}
*/
app;
/**
* Server instance
* @type {?Server}
*/
server;
/**
* Response object
* @type {?Response}
*/
response;
/**
* Start the server
* @param {number} port Port
* @param {string} hostname Hostname
* @returns {Promise<void>}
*/
start(port, hostname) {
this.app = express();
this.server = http.createServer(this.app);
this.app.get("/", (req, res) => {
res.set("Content-Type", "text/plain");
res.write("Migration is in progress, listening message...\n");
if (this.response) {
this.response.write("Disconnected\n");
this.response.end();
}
this.response = res;
// never ending response
});
return new Promise((resolve) => {
this.server.listen(port, hostname, () => {
if (hostname) {
log.info("migration", `Migration server is running on http://${hostname}:${port}`);
} else {
log.info("migration", `Migration server is running on http://localhost:${port}`);
}
resolve();
});
});
}
/**
* Update the message
* @param {string} msg Message to update
* @returns {void}
*/
update(msg) {
this.response?.write(msg + "\n");
}
/**
* Stop the server
* @returns {Promise<void>}
*/
async stop() {
this.response?.write("Finished, please refresh this page.\n");
this.response?.end();
await this.server?.close();
}
}
module.exports = {
SimpleMigrationServer,
};

View file

@ -5,9 +5,9 @@
<template v-if="!settings.disableAuth"> <template v-if="!settings.disableAuth">
<p> <p>
{{ $t("Current User") }}: <strong>{{ $root.username }}</strong> {{ $t("Current User") }}: <strong>{{ $root.username }}</strong>
<button v-if="! settings.disableAuth" id="logout-btn" class="btn btn-danger ms-4 me-2 mb-2" @click="$root.logout">{{ $t("Logout") }}</button> <button v-if="$root.socket.token.startsWith('autoLogin') === false" id="logout-btn" class="btn btn-danger ms-4 me-2 mb-2" @click="$root.logout">{{ $t("Logout") }}</button>
</p> </p>
<template v-if="$root.socket.token.startsWith('autoLogin') === false">
<h5 class="my-4 settings-subheading">{{ $t("Change Password") }}</h5> <h5 class="my-4 settings-subheading">{{ $t("Change Password") }}</h5>
<form class="mb-3" @submit.prevent="savePassword"> <form class="mb-3" @submit.prevent="savePassword">
<div class="mb-3"> <div class="mb-3">
@ -63,8 +63,9 @@
</div> </div>
</form> </form>
</template> </template>
</template>
<div v-if="! settings.disableAuth" class="mt-5 mb-3"> <div v-if="$root.socket.token.startsWith('autoLogin') === false" class="mt-5 mb-3">
<h5 class="my-4 settings-subheading"> <h5 class="my-4 settings-subheading">
{{ $t("Two Factor Authentication") }} {{ $t("Two Factor Authentication") }}
</h5> </h5>

View file

@ -69,7 +69,7 @@
</a> </a>
</li> </li>
<li v-if="$root.loggedIn && $root.socket.token !== 'autoLogin'"> <li v-if="$root.loggedIn && $root.socket.token.startsWith('autoLogin') === false">
<button class="dropdown-item" @click="$root.logout"> <button class="dropdown-item" @click="$root.logout">
<font-awesome-icon icon="sign-out-alt" /> <font-awesome-icon icon="sign-out-alt" />
{{ $t("Logout") }} {{ $t("Logout") }}

View file

@ -119,17 +119,25 @@ export default {
this.info = info; this.info = info;
}); });
socket.on("setup", (monitorID, data) => { socket.on("setup", () => {
this.$router.push("/setup"); this.$router.push("/setup");
}); });
socket.on("autoLogin", (monitorID, data) => { socket.on("autoLogin", () => {
this.loggedIn = true; this.loggedIn = true;
this.storage().token = "autoLogin"; this.storage().token = "autoLogin";
this.socket.token = "autoLogin"; this.socket.token = "autoLogin";
this.allowLoginDialog = false; this.allowLoginDialog = false;
}); });
socket.on("autoLoginRemoteHeader", (username) => {
this.loggedIn = true;
this.username = username;
this.storage().token = "autoLoginRemoteHeader";
this.socket.token = "autoLoginRemoteHeader";
this.allowLoginDialog = false;
});
socket.on("loginRequired", () => { socket.on("loginRequired", () => {
let token = this.storage().token; let token = this.storage().token;
if (token && token !== "autoLogin") { if (token && token !== "autoLogin") {
@ -275,6 +283,24 @@ export default {
this.clearData(); this.clearData();
} }
let token = this.storage().token;
if (token) {
if (token.startsWith("autoLogin") === false) {
this.loginByToken(token);
} else {
// Timeout if it is not actually auto login
setTimeout(() => {
if (! this.loggedIn) {
this.allowLoginDialog = true;
this.$root.storage().removeItem("token");
}
}, 5000);
}
} else {
this.allowLoginDialog = true;
}
this.socket.firstConnect = false; this.socket.firstConnect = false;
}); });
@ -326,7 +352,7 @@ export default {
getJWTPayload() { getJWTPayload() {
const jwtToken = this.$root.storage().token; const jwtToken = this.$root.storage().token;
if (jwtToken && jwtToken !== "autoLogin") { if (jwtToken && jwtToken.startsWith("autoLogin") === false) {
return jwtDecode(jwtToken); return jwtDecode(jwtToken);
} }
return undefined; return undefined;