A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.
feat(auth): log client IP on failed logins (#7242)
Josh Bazar7fc93ebf0c1d
diff --git a/packages/auth/providers/credentials/authorization/basic-authorization.ts b/packages/auth/providers/credentials/authorization/basic-authorization.tsindex 2a6b96a31..277544521 100644--- a/packages/auth/providers/credentials/authorization/basic-authorization.ts+++ b/packages/auth/providers/credentials/authorization/basic-authorization.ts@@ -13,13 +13,14 @@ const logger = createLogger({ module: "basicAuthorization" });export const authorizeWithBasicCredentialsAsync = async (db: Database,credentials: z.infer<typeof userSignInSchema>,+ ipAddress: string,) => {const user = await db.query.users.findFirst({where: and(eq(users.name, credentials.name.toLowerCase()), eq(users.provider, "credentials")),});if (!user?.password) {- logger.info("User not found", { userName: credentials.name });+ logger.warn("User not found", { userName: credentials.name, ipAddress });return null;}@@ -27,7 +28,7 @@ export const authorizeWithBasicCredentialsAsync = async (const isValidPassword = await comparePasswordsAsync(credentials.password, user.password);if (!isValidPassword) {- logger.warn("Password for user was incorrect", { userName: user.name });+ logger.warn("Password for user was incorrect", { userName: user.name, ipAddress });return null;}diff --git a/packages/auth/providers/credentials/authorization/ldap-authorization.ts b/packages/auth/providers/credentials/authorization/ldap-authorization.tsindex 75ce78874..b1990f7b3 100644--- a/packages/auth/providers/credentials/authorization/ldap-authorization.ts+++ b/packages/auth/providers/credentials/authorization/ldap-authorization.ts@@ -18,6 +18,7 @@ const logger = createLogger({ module: "ldapAuthorization" });export const authorizeWithLdapCredentialsAsync = async (db: Database,credentials: z.infer<typeof ldapSignInSchema>,+ ipAddress: string,) => {logger.info("User is trying to log in using LDAP. Connecting to LDAP server...", { userName: credentials.name });const client = new LdapClient();@@ -57,6 +58,7 @@ export const authorizeWithLdapCredentialsAsync = async (});if (!ldapUser) {+ logger.warn("User not found", { userName: credentials.name, ipAddress });throw new CredentialsSignin(`User not found in LDAP username="${credentials.name}"`);}@@ -80,7 +82,7 @@ export const authorizeWithLdapCredentialsAsync = async (password: credentials.password,}).catch(() => {- logger.warn("Wrong credentials for user", { userName: credentials.name });+ logger.warn("Wrong credentials for user", { userName: credentials.name, ipAddress });throw new CredentialsSignin();});await userClient.disconnectAsync();diff --git a/packages/auth/providers/credentials/credentials-provider.ts b/packages/auth/providers/credentials/credentials-provider.tsindex 9de08da14..43b2c8459 100644--- a/packages/auth/providers/credentials/credentials-provider.ts+++ b/packages/auth/providers/credentials/credentials-provider.ts@@ -1,5 +1,6 @@import type Credentials from "@auth/core/providers/credentials";+import { resolveRequestIdentity } from "@homarr/common/server";import type { Database } from "@homarr/db";import { ldapSignInSchema, userSignInSchema } from "@homarr/validation/user";@@ -14,10 +15,11 @@ export const createCredentialsConfiguration = (db: Database) =>type: "credentials",name: "Credentials",// eslint-disable-next-line no-restricted-syntax- async authorize(credentials) {+ async authorize(credentials, request) {const data = await userSignInSchema.parseAsync(credentials);+ const ipAddress = resolveRequestIdentity(request.headers).address ?? "unknown";- return await authorizeWithBasicCredentialsAsync(db, data);+ return await authorizeWithBasicCredentialsAsync(db, data, ipAddress);},}) satisfies CredentialsConfiguration;@@ -27,8 +29,9 @@ export const createLdapConfiguration = (db: Database) =>type: "credentials",name: "Ldap",// eslint-disable-next-line no-restricted-syntax- async authorize(credentials) {+ async authorize(credentials, request) {const data = await ldapSignInSchema.parseAsync(credentials);- return await authorizeWithLdapCredentialsAsync(db, data).catch(() => null);+ const ipAddress = resolveRequestIdentity(request.headers).address ?? "unknown";+ return await authorizeWithLdapCredentialsAsync(db, data, ipAddress).catch(() => null);},}) satisfies CredentialsConfiguration;diff --git a/packages/auth/providers/test/basic-authorization.spec.ts b/packages/auth/providers/test/basic-authorization.spec.tsindex 6188729c7..133c2eac4 100644--- a/packages/auth/providers/test/basic-authorization.spec.ts+++ b/packages/auth/providers/test/basic-authorization.spec.ts@@ -1,4 +1,4 @@-import { describe, expect, test } from "vitest";+import { describe, expect, test, vi } from "vitest";import { createId } from "@homarr/common";import { users } from "@homarr/db/schema";@@ -7,7 +7,16 @@ import { createDb } from "@homarr/db/test";import { hashPasswordAsync } from "../../security";import { authorizeWithBasicCredentialsAsync } from "../credentials/authorization/basic-authorization";+const mocks = vi.hoisted(() => ({+ logger: { info: vi.fn(), warn: vi.fn() },+}));++vi.mock("@homarr/core/infrastructure/logs", () => ({+ createLogger: () => mocks.logger,+}));+const defaultUserId = createId();+const ipAddress = "203.0.113.7";describe("authorizeWithBasicCredentials", () => {test("should authorize user with correct credentials", async () => {@@ -20,10 +29,14 @@ describe("authorizeWithBasicCredentials", () => {});// Act- const result = await authorizeWithBasicCredentialsAsync(db, {- name: "test",- password: "test",- });+ const result = await authorizeWithBasicCredentialsAsync(+ db,+ {+ name: "test",+ password: "test",+ },+ ipAddress,+ );// Assertexpect(result).toEqual({ id: defaultUserId, name: "test" });@@ -39,13 +52,18 @@ describe("authorizeWithBasicCredentials", () => {});// Act- const result = await authorizeWithBasicCredentialsAsync(db, {- name: "test",- password: "wrong",- });+ const result = await authorizeWithBasicCredentialsAsync(+ db,+ {+ name: "test",+ password: "wrong",+ },+ ipAddress,+ );// Assertexpect(result).toBeNull();+ expect(mocks.logger.warn).toHaveBeenCalledWith("Password for user was incorrect", { userName: "test", ipAddress });});test("should not authorize user with incorrect username", async () => {@@ -58,13 +76,18 @@ describe("authorizeWithBasicCredentials", () => {});// Act- const result = await authorizeWithBasicCredentialsAsync(db, {- name: "wrong",- password: "test",- });+ const result = await authorizeWithBasicCredentialsAsync(+ db,+ {+ name: "wrong",+ password: "test",+ },+ ipAddress,+ );// Assertexpect(result).toBeNull();+ expect(mocks.logger.warn).toHaveBeenCalledWith("User not found", { userName: "wrong", ipAddress });});test("should not authorize user when password is not set", async () => {@@ -76,10 +99,14 @@ describe("authorizeWithBasicCredentials", () => {});// Act- const result = await authorizeWithBasicCredentialsAsync(db, {- name: "test",- password: "test",- });+ const result = await authorizeWithBasicCredentialsAsync(+ db,+ {+ name: "test",+ password: "test",+ },+ ipAddress,+ );// Assertexpect(result).toBeNull();diff --git a/packages/auth/providers/test/ldap-authorization.spec.ts b/packages/auth/providers/test/ldap-authorization.spec.tsindex 65c52fa2e..d43e7f666 100644--- a/packages/auth/providers/test/ldap-authorization.spec.ts+++ b/packages/auth/providers/test/ldap-authorization.spec.ts@@ -26,6 +26,16 @@ vi.mock("../../env", () => ({},}));+const mocks = vi.hoisted(() => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));++vi.mock("@homarr/core/infrastructure/logs", () => ({+ createLogger: () => mocks.logger,+}));++const ipAddress = "203.0.113.7";+describe("authorizeWithLdapCredentials", () => {test("requests the group lookup attribute and preserves literal filter values", async () => {const memberAttribute = vi.spyOn(env, "AUTH_LDAP_GROUP_MEMBER_USER_ATTRIBUTE", "get");@@ -45,7 +55,11 @@ describe("authorizeWithLdapCredentials", () => {});try {- const result = await authorizeWithLdapCredentialsAsync(createDb(), { name: username, password: "test" });+ const result = await authorizeWithLdapCredentialsAsync(+ createDb(),+ { name: username, password: "test" },+ ipAddress,+ );const userSearch = search.mock.calls[0]?.[0];const groupSearch = search.mock.calls[1]?.[0];expect(userSearch.options.attributes).toContain("distinguishedName");@@ -72,10 +86,14 @@ describe("authorizeWithLdapCredentials", () => {// Actconst act = () =>- authorizeWithLdapCredentialsAsync(null as unknown as Database, {- name: "test",- password: "test",- });+ authorizeWithLdapCredentialsAsync(+ null as unknown as Database,+ {+ name: "test",+ password: "test",+ },+ ipAddress,+ );// Assertawait expect(act()).rejects.toThrow(CredentialsSignin);@@ -93,13 +111,18 @@ describe("authorizeWithLdapCredentials", () => {// Actconst act = () =>- authorizeWithLdapCredentialsAsync(null as unknown as Database, {- name: "test",- password: "test",- });+ authorizeWithLdapCredentialsAsync(+ null as unknown as Database,+ {+ name: "test",+ password: "test",+ },+ ipAddress,+ );// Assertawait expect(act()).rejects.toThrow(CredentialsSignin);+ expect(mocks.logger.warn).toHaveBeenCalledWith("User not found", { userName: "test", ipAddress });});test("should fail when user has invalid email", async () => {@@ -121,10 +144,14 @@ describe("authorizeWithLdapCredentials", () => {// Actconst act = () =>- authorizeWithLdapCredentialsAsync(null as unknown as Database, {- name: "test",- password: "test",- });+ authorizeWithLdapCredentialsAsync(+ null as unknown as Database,+ {+ name: "test",+ password: "test",+ },+ ipAddress,+ );// Assertawait expect(act()).rejects.toThrow(CredentialsSignin);@@ -152,14 +179,19 @@ describe("authorizeWithLdapCredentials", () => {// Actconst act = () =>- authorizeWithLdapCredentialsAsync(null as unknown as Database, {- name: "test",- password: "test",- });+ authorizeWithLdapCredentialsAsync(+ null as unknown as Database,+ {+ name: "test",+ password: "test",+ },+ ipAddress,+ );// Assertawait expect(act()).rejects.toThrow(CredentialsSignin);expect(searchSpy).toHaveBeenCalledTimes(1);+ expect(mocks.logger.warn).toHaveBeenCalledWith("Wrong credentials for user", { userName: "test", ipAddress });});test("should authorize user with correct credentials and create user", async () => {@@ -182,10 +214,14 @@ describe("authorizeWithLdapCredentials", () => {});// Act- const result = await authorizeWithLdapCredentialsAsync(db, {- name: "test",- password: "test",- });+ const result = await authorizeWithLdapCredentialsAsync(+ db,+ {+ name: "test",+ password: "test",+ },+ ipAddress,+ );// Assertexpect(result.name).toBe("test");@@ -226,10 +262,14 @@ describe("authorizeWithLdapCredentials", () => {});// Act- const result = await authorizeWithLdapCredentialsAsync(db, {- name: "test",- password: "test",- });+ const result = await authorizeWithLdapCredentialsAsync(+ db,+ {+ name: "test",+ password: "test",+ },+ ipAddress,+ );// Assertexpect(result.name).toBe("test");@@ -280,10 +320,14 @@ describe("authorizeWithLdapCredentials", () => {});// Act- const result = await authorizeWithLdapCredentialsAsync(db, {- name: "test",- password: "test",- });+ const result = await authorizeWithLdapCredentialsAsync(+ db,+ {+ name: "test",+ password: "test",+ },+ ipAddress,+ );// Assertexpect(result).toEqual({ id: userId, name: "test", groups: [] });@@ -339,10 +383,14 @@ describe("authorizeWithLdapCredentials", () => {});// Act- const result = await authorizeWithLdapCredentialsAsync(db, {- name: "test",- password: "test",- });+ const result = await authorizeWithLdapCredentialsAsync(+ db,+ {+ name: "test",+ password: "test",+ },+ ipAddress,+ );// Assertexpect(result).toEqual({ id: userId, name: "test", groups: ["homarr_example"] });diff --git a/packages/auth/providers/test/ldap-sign-in.spec.ts b/packages/auth/providers/test/ldap-sign-in.spec.tsindex d5d42e822..27b17439e 100644--- a/packages/auth/providers/test/ldap-sign-in.spec.ts+++ b/packages/auth/providers/test/ldap-sign-in.spec.ts@@ -4,6 +4,7 @@ import { afterEach, beforeEach, expect, test, vi } from "vitest";const userDn = "uid=alice,ou=people,dc=example,dc=com";const userPassword = "fixture-user-password";const directoryCredentials = new Map<string, string>();+const request = new Request("http://localhost");beforeEach(() => {vi.resetModules();@@ -62,7 +63,7 @@ test("signs in through anonymous directory lookup when environment validation isconst { createLdapConfiguration } = await import("../credentials/credentials-provider");const provider = createLdapConfiguration(createDb());- const user = await provider.authorize({ name: "alice", password: userPassword });+ const user = await provider.authorize({ name: "alice", password: userPassword }, request);expect(user).toMatchObject({ name: "alice", groups: ["homarr-users"] });});@@ -76,7 +77,7 @@ test.each([undefined, ""])(const { createLdapConfiguration } = await import("../credentials/credentials-provider");const provider = createLdapConfiguration(createDb());- const user = await provider.authorize({ name: "alice", password: userPassword });+ const user = await provider.authorize({ name: "alice", password: userPassword }, request);expect(user).toMatchObject({ name: "alice", groups: ["homarr-users"] });},@@ -93,7 +94,7 @@ test("still signs in when directory searches require configured service credenticonst { createLdapConfiguration } = await import("../credentials/credentials-provider");const provider = createLdapConfiguration(createDb());- const user = await provider.authorize({ name: "alice", password: userPassword });+ const user = await provider.authorize({ name: "alice", password: userPassword }, request);expect(user).toMatchObject({ name: "alice", groups: ["homarr-users"] });});@@ -103,7 +104,7 @@ test("rejects an incorrect user password after anonymous directory lookup", asynconst { createLdapConfiguration } = await import("../credentials/credentials-provider");const provider = createLdapConfiguration(createDb());- await expect(provider.authorize({ name: "alice", password: "incorrect" })).resolves.toBeNull();+ await expect(provider.authorize({ name: "alice", password: "incorrect" }, request)).resolves.toBeNull();});test("rejects an empty user password when the directory allows anonymous lookup", async () => {@@ -111,5 +112,5 @@ test("rejects an empty user password when the directory allows anonymous lookup"const { createLdapConfiguration } = await import("../credentials/credentials-provider");const provider = createLdapConfiguration(createDb());- await expect(provider.authorize({ name: "alice", password: "" })).rejects.toThrow();+ await expect(provider.authorize({ name: "alice", password: "" }, request)).rejects.toThrow();});