Compare commits

..
19 changed files with 230 additions and 137 deletions

No files matched your search

-2
View File
@@ -63,8 +63,6 @@ UNSAFE_ENABLE_MOCK_INTEGRATION=true
# Public URL contract. Values must be absolute HTTP(S) URLs without credentials, # Public URL contract. Values must be absolute HTTP(S) URLs without credentials,
# query strings, or fragments. Trailing slashes are normalized at startup. # query strings, or fragments. Trailing slashes are normalized at startup.
# Public Homarr origin used by MCP OAuth metadata and redirects behind proxies.
# BASE_URL=https://homarr.example.com
HOMARR_WEBSITE_URL=https://homarr.dev HOMARR_WEBSITE_URL=https://homarr.dev
# PocketBase API used by Homarr and by the standalone documentation site. # PocketBase API used by Homarr and by the standalone documentation site.
# Defaults to HOMARR_WEBSITE_URL. # Defaults to HOMARR_WEBSITE_URL.
@@ -30,7 +30,6 @@ Using the `PUID` and `PGID` will require you to set the correct permissions on t
| `PUID` | User ID to run the container as | Any valid user ID | `0` | | `PUID` | User ID to run the container as | Any valid user ID | `0` |
| `PGID` | Group ID to run the container as | Any valid group ID | `0` | | `PGID` | Group ID to run the container as | Any valid group ID | `0` |
| `LOG_LEVEL` | Log level to use | `debug` / `info` / `warn` / `error` | `info` | | `LOG_LEVEL` | Log level to use | `debug` / `info` / `warn` / `error` | `info` |
| `BASE_URL` | Public Homarr origin used by MCP OAuth metadata and redirects. Set this when a reverse proxy does not preserve the public host and protocol. | HTTP(S) origin without a path | - |
| `NO_EXTERNAL_CONNECTION` | Disables Homarr's internet-backed requests, including update checks, weather, and RSS feeds | `true` or `false` | `false` | | `NO_EXTERNAL_CONNECTION` | Disables Homarr's internet-backed requests, including update checks, weather, and RSS feeds | `true` or `false` | `false` |
| `ENABLE_DNS_CACHING` | Enables dns caching. Enabled by default, but if you experience issues with IPv6 or static IPs, see [#4006](https://github.com/homarr-labs/homarr/issues/4006) or disable this flag | `true` or `false` | `true` | | `ENABLE_DNS_CACHING` | Enables dns caching. Enabled by default, but if you experience issues with IPv6 or static IPs, see [#4006](https://github.com/homarr-labs/homarr/issues/4006) or disable this flag | `true` or `false` | `true` |
| `HOMARR_DISABLE_IPV6` | Disables the IPv6 listener of the internal nginx proxy, even when the host supports IPv6. IPv6 is normally disabled automatically when the host has no IPv6 configured. See [#4596](https://github.com/homarr-labs/homarr/issues/4596) | `true` or `false` | `false` | | `HOMARR_DISABLE_IPV6` | Disables the IPv6 listener of the internal nginx proxy, even when the host supports IPv6. IPv6 is normally disabled automatically when the host has no IPv6 configured. See [#4596](https://github.com/homarr-labs/homarr/issues/4596) | `true` or `false` | `false` |
+1 -1
View File
@@ -40,7 +40,7 @@ services:
volumes: volumes:
- ./homarr/appdata:/appdata - ./homarr/appdata:/appdata
environment: environment:
- BASE_URL=https://your.internal.dns.address.here.com - BASE_URL=your.internal.dns.address.here.com
- SECRET_ENCRYPTION_KEY=your_64_character_hex_string # <--- can be generated with `openssl rand -hex 32` - SECRET_ENCRYPTION_KEY=your_64_character_hex_string # <--- can be generated with `openssl rand -hex 32`
networks: networks:
- proxy - proxy
@@ -202,9 +202,9 @@ Homarr supports multiple authentication options, from internal userbase (credent
| ``AUTH_OIDC_CLIENT_NAME`` | Display name of provider (in login screen) | OIDC | | ``AUTH_OIDC_CLIENT_NAME`` | Display name of provider (in login screen) | OIDC |
| ``AUTH_OIDC_AUTO_LOGIN`` | Automatically redirect to OIDC login | false | | ``AUTH_OIDC_AUTO_LOGIN`` | Automatically redirect to OIDC login | false |
| ``AUTH_OIDC_SCOPE_OVERWRITE`` | Overwrite default scopes (openid, profile, email) | openid email profile groups | | ``AUTH_OIDC_SCOPE_OVERWRITE`` | Overwrite default scopes (openid, profile, email) | openid email profile groups |
| ``AUTH_OIDC_GROUPS_ATTRIBUTE`` | Attribute used for groups (roles) claim | groups | | ``AUTH_OIDC_GROUPS_ATTRIBUTE`` | Attribute used for groups (roles) claim. Dot-separated paths such as `resource_access.homarr.roles` are supported. | groups |
| ``AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT`` | Stop syncing group memberships of OIDC users from the groups claim and manage them locally via the group members page instead | false | | ``AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT`` | Stop syncing group memberships of OIDC users from the groups claim and manage them locally via the group members page instead | false |
| ``AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE`` | Overwrite name attribute. By default it will use preferred_username if it does not contain a `@` and otherwise name. | --- | | ``AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE`` | Overwrite name attribute. Dot-separated paths are supported. By default it will use preferred_username if it does not contain a `@` and otherwise name. | --- |
| ``AUTH_OIDC_FORCE_USERINFO`` | Force userinfo endpoint to be used for user information. | false | | ``AUTH_OIDC_FORCE_USERINFO`` | Force userinfo endpoint to be used for user information. | false |
| ``AUTH_OIDC_ENABLE_DANGEROUS_ACCOUNT_LINKING`` | Enable account linking for OIDC provider. This will link the OIDC accounts by email. Be sure that you have verified emails to prevent stealing accounts. | false | | ``AUTH_OIDC_ENABLE_DANGEROUS_ACCOUNT_LINKING`` | Enable account linking for OIDC provider. This will link the OIDC accounts by email. Be sure that you have verified emails to prevent stealing accounts. | false |
| ``AUTH_OIDC_ENABLE_DANGEROUS_CREDENTIALS_LINKING`` | Link an OIDC identity to an existing credentials user with the same email. The credentials login and existing user data are preserved. Requires the OIDC profile to contain `email_verified: true`. | false | | ``AUTH_OIDC_ENABLE_DANGEROUS_CREDENTIALS_LINKING`` | Link an OIDC identity to an existing credentials user with the same email. The credentials login and existing user data are preserved. Requires the OIDC profile to contain `email_verified: true`. | false |
-4
View File
@@ -54,10 +54,6 @@ The **AI / MCP** tab on Homarr's API page shows the current endpoint, configurat
MCP supports API keys and OAuth 2.1 with PKCE. API keys are simpler for direct client configuration; OAuth is available MCP supports API keys and OAuth 2.1 with PKCE. API keys are simpler for direct client configuration; OAuth is available
for clients that support dynamic authorization. for clients that support dynamic authorization.
When Homarr is behind a reverse proxy that does not preserve the public host and protocol, set `BASE_URL` to the exact
public origin, for example `https://homarr.example.com`. Do not include a path. OAuth clients discover the authorization
server and protected resource through Homarr's `/.well-known/` routes.
Tools use the permissions of the API key owner or authorized user. Creating a key does not grant additional access. Tools use the permissions of the API key owner or authorized user. Creating a key does not grant additional access.
Custom Widget and Workshop authoring tools, prompts, and resources are visible only to administrators. Custom Widget and Workshop authoring tools, prompts, and resources are visible only to administrators.
-9
View File
@@ -65,15 +65,6 @@ const nextConfig: NextConfig = {
}, },
], ],
}, },
async rewrites() {
return [
{ source: "/.well-known/:path*", destination: "/well-known/:path*" },
{
source: "/api/mcp/:transport/.well-known/:path*",
destination: "/well-known/:path*/api/mcp/:transport",
},
];
},
// skipcq: JS-0116 // skipcq: JS-0116
// eslint-disable-next-line @typescript-eslint/require-await,no-restricted-syntax // eslint-disable-next-line @typescript-eslint/require-await,no-restricted-syntax
async headers() { async headers() {
@@ -0,0 +1,33 @@
import { headers } from "next/headers";
import { extractBaseUrlFromHeaders } from "@homarr/common";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "*",
};
export async function GET() {
const baseUrl = extractBaseUrlFromHeaders(await headers());
return Response.json(
{
issuer: baseUrl,
authorization_endpoint: `${baseUrl}/api/mcp/oauth/authorize`,
token_endpoint: `${baseUrl}/api/mcp/oauth/token`,
registration_endpoint: `${baseUrl}/api/mcp/oauth/register`,
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
scopes_supported: ["mcp:tools"],
resource_indicators_supported: true,
},
{ headers: corsHeaders },
);
}
export async function OPTIONS() {
return new Response(null, { status: 204, headers: corsHeaders });
}
@@ -0,0 +1,25 @@
import { headers } from "next/headers";
import { extractBaseUrlFromHeaders } from "@homarr/common";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "*",
};
export async function GET() {
const baseUrl = extractBaseUrlFromHeaders(await headers());
return Response.json(
{
resource: `${baseUrl}/api/mcp`,
authorization_servers: [baseUrl],
},
{ headers: corsHeaders },
);
}
export async function OPTIONS() {
return new Response(null, { status: 204, headers: corsHeaders });
}
@@ -22,10 +22,7 @@ vi.mock("@homarr/auth/api-key", () => ({
API_KEY_HEADER_NAME: "ApiKey", API_KEY_HEADER_NAME: "ApiKey",
getSessionFromApiKeyAsync: mocks.authenticate, getSessionFromApiKeyAsync: mocks.authenticate,
})); }));
vi.mock("@homarr/common", () => ({ vi.mock("@homarr/common", () => ({ extractBaseUrlFromHeaders: () => "http://localhost" }));
extractBaseUrlFromHeaders: () => "http://localhost",
removeTrailingSlash: (value: string) => value.replace(/\/+$/u, ""),
}));
vi.mock("@homarr/common/server", () => ({ ipAddressFromHeaders: mocks.ipAddress })); vi.mock("@homarr/common/server", () => ({ ipAddressFromHeaders: mocks.ipAddress }));
vi.mock("@homarr/core/infrastructure/logs", () => ({ vi.mock("@homarr/core/infrastructure/logs", () => ({
createLogger: () => ({ info: vi.fn(), warn: mocks.loggerWarn, error: vi.fn() }), createLogger: () => ({ info: vi.fn(), warn: mocks.loggerWarn, error: vi.fn() }),
@@ -45,7 +42,6 @@ vi.mock("@homarr/custom-widgets/core", () => ({
getCustomWidgetJsonSchema: () => ({ type: "object", title: "Custom Widget" }), getCustomWidgetJsonSchema: () => ({ type: "object", title: "Custom Widget" }),
})); }));
vi.mock("@homarr/db", () => ({ db: {} })); vi.mock("@homarr/db", () => ({ db: {} }));
vi.mock("~/env", () => ({ env: { BASE_URL: undefined } }));
vi.mock("~/versions/package-reader", () => ({ getPackageVersion: () => "test-version" })); vi.mock("~/versions/package-reader", () => ({ getPackageVersion: () => "test-version" }));
vi.mock("../_extract-tools", () => ({ vi.mock("../_extract-tools", () => ({
extractMcpTools: () => [ extractMcpTools: () => [
-8
View File
@@ -1,8 +0,0 @@
import { extractBaseUrlFromHeaders, removeTrailingSlash } from "@homarr/common";
import { env } from "~/env";
type RequestHeaders = Parameters<typeof extractBaseUrlFromHeaders>[0];
export const getMcpBaseUrl = (headers: RequestHeaders) =>
removeTrailingSlash(env.BASE_URL ?? extractBaseUrlFromHeaders(headers));
+8 -22
View File
@@ -7,7 +7,7 @@ import { z } from "zod/v4";
import type { McpTool } from "@homarr/api/mcp"; import type { McpTool } from "@homarr/api/mcp";
import { createTRPCContext, mcpRouter } from "@homarr/api/mcp"; import { createTRPCContext, mcpRouter } from "@homarr/api/mcp";
import { API_KEY_HEADER_NAME, getSessionFromApiKeyAsync } from "@homarr/auth/api-key"; import { API_KEY_HEADER_NAME, getSessionFromApiKeyAsync } from "@homarr/auth/api-key";
import { removeTrailingSlash } from "@homarr/common"; import { extractBaseUrlFromHeaders } from "@homarr/common";
import { ipAddressFromHeaders } from "@homarr/common/server"; import { ipAddressFromHeaders } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs"; import { createLogger } from "@homarr/core/infrastructure/logs";
import { buildCustomWidgetMcpPrompt } from "@homarr/custom-widgets/authoring-prompt"; import { buildCustomWidgetMcpPrompt } from "@homarr/custom-widgets/authoring-prompt";
@@ -24,7 +24,6 @@ import { db } from "@homarr/db";
import { getPackageVersion } from "~/versions/package-reader"; import { getPackageVersion } from "~/versions/package-reader";
import { getSafeAssistantToolError } from "../assistant/chat/assistant-tool-error"; import { getSafeAssistantToolError } from "../assistant/chat/assistant-tool-error";
import { getMcpBaseUrl } from "./_base-url";
import { extractMcpTools } from "./_extract-tools"; import { extractMcpTools } from "./_extract-tools";
import { createMcpProtocolHandler } from "./_protocol"; import { createMcpProtocolHandler } from "./_protocol";
@@ -247,12 +246,6 @@ function jsonErrorResponse(status: number, body: Record<string, string>, extraHe
}); });
} }
const getOAuthChallenge = (req: NextRequest) => {
const baseUrl = getMcpBaseUrl(req.headers);
const resourcePath = removeTrailingSlash(new URL(req.url).pathname);
return `Bearer resource_metadata="${baseUrl}/.well-known/oauth-protected-resource${resourcePath}"`;
};
export const handleMcpRequest = async (req: NextRequest) => { export const handleMcpRequest = async (req: NextRequest) => {
const pathname = new URL(req.url).pathname; const pathname = new URL(req.url).pathname;
if (pathname.endsWith("/sse") || pathname.endsWith("/message")) { if (pathname.endsWith("/sse") || pathname.endsWith("/message")) {
@@ -276,37 +269,30 @@ export const handleMcpRequest = async (req: NextRequest) => {
if (!apiKeyValue) { if (!apiKeyValue) {
recordAuthFailure(ipAddress); recordAuthFailure(ipAddress);
const baseUrl = extractBaseUrlFromHeaders(req.headers);
return jsonErrorResponse( return jsonErrorResponse(
401, 401,
{ {
error: "unauthorized", error: "unauthorized",
hint: "Authenticate with an ApiKey header or via OAuth at /.well-known/oauth-authorization-server", hint: "Authenticate with an ApiKey header or via OAuth at /.well-known/oauth-authorization-server",
}, },
{ "WWW-Authenticate": getOAuthChallenge(req) }, { "WWW-Authenticate": `Bearer resource_metadata="${baseUrl}/.well-known/oauth-protected-resource"` },
); );
} }
if (!apiKeyValue.includes(".")) { if (!apiKeyValue.includes(".")) {
recordAuthFailure(ipAddress); recordAuthFailure(ipAddress);
return jsonErrorResponse( return jsonErrorResponse(401, { error: "invalid_token", hint: "The token must be in the format '<id>.<token>'." });
401,
{ error: "invalid_token", hint: "The token must be in the format '<id>.<token>'." },
{ "WWW-Authenticate": getOAuthChallenge(req) },
);
} }
const session = await getSessionFromApiKeyAsync(db, apiKeyValue, ipAddress, ua); const session = await getSessionFromApiKeyAsync(db, apiKeyValue, ipAddress, ua);
if (!session) { if (!session) {
recordAuthFailure(ipAddress); recordAuthFailure(ipAddress);
return jsonErrorResponse( return jsonErrorResponse(401, {
401, error: "invalid_token",
{ hint: "The API key was not found or the token is incorrect.",
error: "invalid_token", });
hint: "The API key was not found or the token is incorrect.",
},
{ "WWW-Authenticate": getOAuthChallenge(req) },
);
} }
clearAuthFailures(ipAddress); clearAuthFailures(ipAddress);
@@ -1,8 +1,8 @@
import type { NextRequest } from "next/server"; import type { NextRequest } from "next/server";
import { auth } from "@homarr/auth/next"; import { auth } from "@homarr/auth/next";
import { extractBaseUrlFromHeaders } from "@homarr/common";
import { getMcpBaseUrl } from "../../_base-url";
import { consumePendingAuth, createAuthCode, getClient, storePendingAuth } from "../_store"; import { consumePendingAuth, createAuthCode, getClient, storePendingAuth } from "../_store";
export async function GET(req: NextRequest) { export async function GET(req: NextRequest) {
@@ -83,9 +83,8 @@ export async function GET(req: NextRequest) {
); );
} }
const baseUrl = getMcpBaseUrl(req.headers); const expectedResource = `${extractBaseUrlFromHeaders(req.headers)}/api/mcp`;
const allowedResources = new Set([`${baseUrl}/api/mcp`, `${baseUrl}/api/mcp/mcp`]); if (resource && resource !== expectedResource) {
if (resource && !allowedResources.has(resource)) {
return Response.json( return Response.json(
{ {
error: "invalid_target", error: "invalid_target",
@@ -153,7 +152,7 @@ export async function GET(req: NextRequest) {
); );
} }
const loginUrl = new URL("/auth/login", baseUrl); const loginUrl = new URL("/auth/login", url.origin);
loginUrl.searchParams.set("callbackUrl", `/api/mcp/oauth/authorize?pending=${id}`); loginUrl.searchParams.set("callbackUrl", `/api/mcp/oauth/authorize?pending=${id}`);
return Response.redirect(loginUrl.toString()); return Response.redirect(loginUrl.toString());
} }
@@ -1,51 +0,0 @@
import type { NextRequest } from "next/server";
import { getMcpBaseUrl } from "~/app/api/mcp/_base-url";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "*",
};
export async function GET(req: NextRequest, props: { params: Promise<{ path: string[] }> }) {
const [kind, ...rest] = (await props.params).path;
const baseUrl = getMcpBaseUrl(req.headers);
const identifierPath = rest.join("/");
if (kind === "oauth-authorization-server") {
const issuer = identifierPath ? `${baseUrl}/${identifierPath}` : baseUrl;
return Response.json(
{
issuer,
authorization_endpoint: `${baseUrl}/api/mcp/oauth/authorize`,
token_endpoint: `${baseUrl}/api/mcp/oauth/token`,
registration_endpoint: `${baseUrl}/api/mcp/oauth/register`,
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
scopes_supported: ["mcp:tools"],
resource_indicators_supported: true,
},
{ headers: corsHeaders },
);
}
if (kind === "oauth-protected-resource") {
const resource = identifierPath ? `${baseUrl}/${identifierPath}` : `${baseUrl}/api/mcp`;
return Response.json(
{
resource,
authorization_servers: [baseUrl],
},
{ headers: corsHeaders },
);
}
return Response.json({ error: "not_found" }, { status: 404, headers: corsHeaders });
}
export async function OPTIONS() {
return new Response(null, { status: 204, headers: corsHeaders });
}
-7
View File
@@ -16,15 +16,8 @@ const publicHttpUrl = (variableName: string) =>
} }
}); });
const publicHttpOrigin = (variableName: string) =>
publicHttpUrl(variableName).refine(
(value) => value === new URL(value).origin,
`${variableName} must be an HTTP(S) origin without a path`,
);
export const env = createEnv({ export const env = createEnv({
server: { server: {
BASE_URL: publicHttpOrigin("BASE_URL").optional(),
UNSAFE_ENABLE_MOCK_INTEGRATION: createBooleanSchema(false), UNSAFE_ENABLE_MOCK_INTEGRATION: createBooleanSchema(false),
DEMO_MODE: createBooleanSchema(false), DEMO_MODE: createBooleanSchema(false),
DEMO_READ_ONLY: createBooleanSchema(true), DEMO_READ_ONLY: createBooleanSchema(true),
+5 -10
View File
@@ -9,7 +9,7 @@ import { groupMembers, groups, users } from "@homarr/db/schema";
import { colorSchemeCookieKey, everyoneGroup } from "@homarr/definitions"; import { colorSchemeCookieKey, everyoneGroup } from "@homarr/definitions";
import { env } from "./env"; import { env } from "./env";
import { extractProfileName } from "./providers/oidc/oidc-provider"; import { extractProfileName, getProfileValueByPath } from "./providers/oidc/profile";
const logger = createLogger({ module: "authEvents" }); const logger = createLogger({ module: "authEvents" });
@@ -31,16 +31,11 @@ export const createSignInEventHandler = (db: Database): Exclude<NextAuthConfig["
if (!dbUser) throw new Error("User not found"); if (!dbUser) throw new Error("User not found");
const groupsKey = env.AUTH_OIDC_GROUPS_ATTRIBUTE; const groupsKey = env.AUTH_OIDC_GROUPS_ATTRIBUTE;
const profileGroups = profile ? getProfileValueByPath(profile, groupsKey) : undefined;
// Groups from oidc provider are provided from the profile, it's not typed. // Groups from oidc provider are provided from the profile, it's not typed.
if ( if (!env.AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT && dbUser.provider === "oidc" && Array.isArray(profileGroups)) {
!env.AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT && logger.debug(`Using profile groups (${groupsKey}): ${JSON.stringify(profileGroups)}`);
dbUser.provider === "oidc" && await synchronizeGroupsWithExternalForUserAsync(db, user.id, profileGroups as string[]);
profile &&
groupsKey in profile &&
Array.isArray(profile[groupsKey])
) {
logger.debug(`Using profile groups (${groupsKey}): ${JSON.stringify(profile[groupsKey])}`);
await synchronizeGroupsWithExternalForUserAsync(db, user.id, profile[groupsKey] as string[]);
} }
// In ldap-authroization we return the groups from ldap, it's not typed. // In ldap-authroization we return the groups from ldap, it's not typed.
@@ -7,6 +7,7 @@ import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/h
import { env } from "../../env"; import { env } from "../../env";
import { createRedirectUri } from "../../redirect"; import { createRedirectUri } from "../../redirect";
import { extractProfileName } from "./profile";
import { assertVerifiedEmailForCredentialsLinking } from "./verified-email"; import { assertVerifiedEmailForCredentialsLinking } from "./verified-email";
export const OidcProvider = (headers: ReadonlyHeaders | null): OIDCConfig<Profile> => ({ export const OidcProvider = (headers: ReadonlyHeaders | null): OIDCConfig<Profile> => ({
@@ -76,12 +77,3 @@ export const OidcProvider = (headers: ReadonlyHeaders | null): OIDCConfig<Profil
// @ts-expect-error `undici` has a `duplex` option // @ts-expect-error `undici` has a `duplex` option
[customFetch]: fetchWithTrustedCertificatesAsync, [customFetch]: fetchWithTrustedCertificatesAsync,
}); });
export const extractProfileName = (profile: Profile) => {
if (!env.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE) {
// Use the name as the username if the preferred_username is an email address
return profile.preferred_username?.includes("@") ? profile.name : profile.preferred_username;
}
return profile[env.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE as keyof typeof profile] as string;
};
+23
View File
@@ -0,0 +1,23 @@
import type { Profile } from "@auth/core/types";
import { env } from "../../env";
export const getProfileValueByPath = (profile: Profile, path: string): unknown => {
return path.split(".").reduce<unknown>((value, key) => {
if (typeof value !== "object" || value === null || !Object.hasOwn(value, key)) {
return undefined;
}
return (value as Record<string, unknown>)[key];
}, profile);
};
export const extractProfileName = (profile: Profile): string | undefined => {
if (!env.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE) {
// Use the name as the username if the preferred_username is an email address
return (profile.preferred_username?.includes("@") ? profile.name : profile.preferred_username) ?? undefined;
}
const profileName = getProfileValueByPath(profile, env.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE);
return typeof profileName === "string" ? profileName : undefined;
};
@@ -0,0 +1,96 @@
import type { Profile } from "@auth/core/types";
import { afterEach, describe, expect, test, vi } from "vitest";
const mockEnv = vi.hoisted(() => ({
AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE: undefined as string | undefined,
}));
vi.mock("../../../env", () => ({ env: mockEnv }));
import { extractProfileName, getProfileValueByPath } from "../profile";
afterEach(() => {
mockEnv.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE = undefined;
});
describe("getProfileValueByPath", () => {
const profile = {
sub: "user-id",
resource_access: {
homarr: {
roles: ["admins"],
},
},
} satisfies Profile;
test("returns a top-level claim", () => {
expect(getProfileValueByPath(profile, "sub")).toBe("user-id");
});
test("returns a nested claim", () => {
expect(getProfileValueByPath(profile, "resource_access.homarr.roles")).toEqual(["admins"]);
});
test("returns undefined when the path does not exist", () => {
expect(getProfileValueByPath(profile, "resource_access.missing.roles")).toBeUndefined();
});
});
describe("extractProfileName", () => {
test("uses preferred_username when overwrite is not set", () => {
const profile = {
sub: "user-id",
preferred_username: "johndoe",
} satisfies Profile;
expect(extractProfileName(profile)).toBe("johndoe");
});
test("uses name when preferred_username is an email", () => {
const profile = {
sub: "user-id",
preferred_username: "john@example.com",
name: "John Doe",
} satisfies Profile;
expect(extractProfileName(profile)).toBe("John Doe");
});
test("returns undefined when the fallback name is null", () => {
const profile = {
sub: "user-id",
preferred_username: "john@example.com",
name: null,
} satisfies Profile;
expect(extractProfileName(profile)).toBeUndefined();
});
test("returns undefined when preferred_username is missing", () => {
const profile = {
sub: "user-id",
} satisfies Profile;
expect(extractProfileName(profile)).toBeUndefined();
});
test("uses a nested name claim when configured", () => {
mockEnv.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE = "user.profile.display_name";
const profile = {
sub: "user-id",
user: { profile: { display_name: "Nested User" } },
} satisfies Profile;
expect(extractProfileName(profile)).toBe("Nested User");
});
test("returns undefined when the configured claim is not a string", () => {
mockEnv.AUTH_OIDC_NAME_ATTRIBUTE_OVERWRITE = "user.profile";
const profile = {
sub: "user-id",
user: { profile: { display_name: "Nested User" } },
} satisfies Profile;
expect(extractProfileName(profile)).toBeUndefined();
});
});
+31 -1
View File
@@ -1,7 +1,7 @@
import type { ResponseCookie } from "next/dist/compiled/@edge-runtime/cookies"; import type { ResponseCookie } from "next/dist/compiled/@edge-runtime/cookies";
import type { ReadonlyRequestCookies } from "next/dist/server/web/spec-extension/adapters/request-cookies"; import type { ReadonlyRequestCookies } from "next/dist/server/web/spec-extension/adapters/request-cookies";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { describe, expect, test, vi } from "vitest"; import { afterEach, describe, expect, test, vi } from "vitest";
import { eq } from "@homarr/db"; import { eq } from "@homarr/db";
import type { Database } from "@homarr/db"; import type { Database } from "@homarr/db";
@@ -21,6 +21,12 @@ vi.mock("../env", () => {
env: mockEnv, env: mockEnv,
}; };
}); });
afterEach(() => {
mockEnv.AUTH_OIDC_GROUPS_ATTRIBUTE = "someRandomGroupsKey";
mockEnv.AUTH_OIDC_GROUPS_LOCAL_MANAGEMENT = false;
});
// eslint-disable-next-line @typescript-eslint/consistent-type-imports // eslint-disable-next-line @typescript-eslint/consistent-type-imports
type HeadersExport = typeof import("next/headers"); type HeadersExport = typeof import("next/headers");
vi.mock("next/headers", async (importOriginal) => { vi.mock("next/headers", async (importOriginal) => {
@@ -152,6 +158,30 @@ describe("createSignInEventHandler should create signInEventHandler", () => {
}); });
expect(dbGroupMembers?.groupId).toBe("1"); expect(dbGroupMembers?.groupId).toBe("1");
}); });
test("should add missing group membership from a nested claim", async () => {
// Arrange
mockEnv.AUTH_OIDC_GROUPS_ATTRIBUTE = "resource_access.homarr.roles";
const db = createDb();
await createUserAsync(db, "oidc");
await createGroupAsync(db);
const eventHandler = createSignInEventHandler(db);
// Act
await eventHandler?.({
user: { id: "1", name: "test" },
profile: {
preferred_username: "test",
resource_access: { homarr: { roles: ["test"] } },
},
account: null,
});
// Assert
const dbGroupMembers = await db.query.groupMembers.findFirst({
where: eq(groupMembers.userId, "1"),
});
expect(dbGroupMembers?.groupId).toBe("1");
});
test("should remove group membership", async () => { test("should remove group membership", async () => {
// Arrange // Arrange
const db = createDb(); const db = createDb();