Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix: require AUTH_SECRET and gate project visibility changes

Andrej Acevski156b72b3b664
diff --git a/ENVIRONMENT_SETUP.md b/ENVIRONMENT_SETUP.md
index 6c5c60538..65def7f8b 100644
--- a/ENVIRONMENT_SETUP.md
+++ b/ENVIRONMENT_SETUP.md
@@ -25,7 +25,7 @@ For development, you'll need at minimum:
- `KANEO_CLIENT_URL` - The URL of the web application (e.g., `http://localhost:5173`)
- `KANEO_API_URL` - The URL of the API (e.g., `http://localhost:1337`)
-- `AUTH_SECRET` - Secret key for JWT token generation (**must be at least 32 characters long**; use a long, random value in production)
+- `AUTH_SECRET` - **Required.** Secret key for JWT token generation (**must be at least 32 characters long**; use a long, random value in production). The API refuses to start without it, because an unset secret would fall back to a publicly known default and make every session cookie forgeable. The Docker entrypoint generates a random one per session if you do not set it, so sessions will not survive a restart until you do. Generate one with `openssl rand -hex 32`.
- `DEVICE_AUTH_CLIENT_IDS` - **Optional.** Comma-separated list of allowed device-flow OAuth client IDs. When unset, Kaneo implicitly allows `kaneo-cli` and `kaneo-mcp` by default (no extra configuration for the CLI or MCP). Override only when you need additional trusted clients, for example `kaneo-cli,kaneo-mcp,my-desktop-app`.
- `DATABASE_URL` - PostgreSQL connection string
- `POSTGRES_DB` - PostgreSQL database name
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index cebe15ac9..3ffc2bc6f 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -43,6 +43,7 @@ import { syncWorkspaceSeats } from "./billing/controllers/sync-seats";
import db, { schema } from "./database";
import { publishEvent } from "./events";
import deleteAccountData from "./user/controllers/delete-account-data";
+import { resolveAuthSecret } from "./utils/auth-secret";
import { checkRegistrationAllowed } from "./utils/check-registration-allowed";
import { checkWorkspaceName } from "./utils/check-workspace-name";
import { mapCustomOAuthProfileToUser } from "./utils/custom-oauth-profile";
@@ -99,12 +100,14 @@ const baseURLWithoutPath = (() => {
}
})();
-if (process.env.AUTH_SECRET && process.env.AUTH_SECRET.length < 32) {
- console.error(
- "AUTH_SECRET is less than 32 characters, please generate a new one.",
- );
- process.exit(1);
-}
+const authSecret = (() => {
+ try {
+ return resolveAuthSecret();
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+ }
+})();
async function getUserLocale(email: string) {
const [user] = await db
@@ -175,7 +178,7 @@ function getDeviceAuthVerificationUri(): string {
export const auth = betterAuth({
baseURL: baseURLWithoutPath,
trustedOrigins,
- secret: process.env.AUTH_SECRET || "",
+ secret: authSecret,
basePath: "/api/auth",
database: drizzleAdapter(db, {
provider: "pg",
diff --git a/apps/api/src/project/controllers/update-project.ts b/apps/api/src/project/controllers/update-project.ts
index 722de1266..887c8aac4 100644
--- a/apps/api/src/project/controllers/update-project.ts
+++ b/apps/api/src/project/controllers/update-project.ts
@@ -11,6 +11,7 @@ async function updateProject(
description: string,
isPublic: boolean,
workspaceId: string,
+ canShare: boolean,
) {
const [existingProject] = await db
.select()
@@ -19,15 +20,20 @@ async function updateProject(
and(eq(projectTable.id, id), eq(projectTable.workspaceId, workspaceId)),
);
- const isProjectExisting = Boolean(existingProject);
-
- if (!isProjectExisting) {
+ if (!existingProject) {
throw new HTTPException(404, {
message:
"Project doesn't exist or doesn't belong to the specified workspace",
});
}
+ if (isPublic !== existingProject.isPublic && !canShare) {
+ throw new HTTPException(403, {
+ message:
+ "Changing project visibility requires the project:share permission",
+ });
+ }
+
const [updatedWorkspace] = await db
.update(projectTable)
.set({
diff --git a/apps/api/src/project/index.ts b/apps/api/src/project/index.ts
index b0228f14e..1595d2dc6 100644
--- a/apps/api/src/project/index.ts
+++ b/apps/api/src/project/index.ts
@@ -7,7 +7,10 @@ import {
jsonResponse,
z,
} from "../openapi";
-import { requireWorkspacePermission } from "../utils/require-workspace-permission";
+import {
+ hasWorkspacePermission,
+ requireWorkspacePermission,
+} from "../utils/require-workspace-permission";
import { workspaceAccess } from "../utils/workspace-access-middleware";
import archiveProjectCtrl from "./controllers/archive-project";
import createProjectCtrl from "./controllers/create-project";
@@ -143,7 +146,7 @@ const updateProjectRoute = createRoute({
200: jsonResponse("The updated project", projectSchema),
400: errorResponse("Invalid body, or unknown project"),
403: errorResponse(
- "No workspace access, or missing project:update permission",
+ "No workspace access, missing project:update, or missing project:share when visibility changes",
),
},
});
@@ -259,6 +262,7 @@ const project = apiRouter<BaseVariables & { workspaceId: string }>()
description,
isPublic,
workspaceId,
+ await hasWorkspacePermission(c, { project: ["share"] }),
);
return c.json(updatedProject, 200);
})
diff --git a/apps/api/src/utils/auth-secret.ts b/apps/api/src/utils/auth-secret.ts
new file mode 100644
index 000000000..9999e489d
--- /dev/null
+++ b/apps/api/src/utils/auth-secret.ts
@@ -0,0 +1,18 @@
+export const MIN_AUTH_SECRET_LENGTH = 32;
+
+// An unset secret is not merely a weak one: Better Auth substitutes a published
+// default, which makes every session cookie forgeable offline.
+export function resolveAuthSecret(raw = process.env.AUTH_SECRET): string {
+ const secret = raw ?? "";
+ if (!secret) {
+ throw new Error(
+ "AUTH_SECRET is not set. Generate one with: openssl rand -hex 32",
+ );
+ }
+ if (secret.length < MIN_AUTH_SECRET_LENGTH) {
+ throw new Error(
+ "AUTH_SECRET is less than 32 characters, please generate a new one.",
+ );
+ }
+ return secret;
+}
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index e97adbd73..d1654731a 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -6532,7 +6532,7 @@
"description": "Missing or invalid credentials"
},
"403": {
- "description": "No workspace access, or missing project:update permission",
+ "description": "No workspace access, missing project:update, or missing project:share when visibility changes",
"content": {
"text/plain": {
"schema": {
diff --git a/scripts/openapi/check.mjs b/scripts/openapi/check.mjs
index f21363571..444cff8d2 100644
--- a/scripts/openapi/check.mjs
+++ b/scripts/openapi/check.mjs
@@ -22,6 +22,13 @@ if (!packageManager) {
}
const RUN = {
stdio: ["ignore", "ignore", "inherit"],
+ // The exporter boots the app to serialize route metadata. It never issues or
+ // verifies a token, but the app refuses to start without a secret.
+ env: {
+ ...process.env,
+ AUTH_SECRET:
+ process.env.AUTH_SECRET ?? "openapi-export-only-secret-not-for-serving",
+ },
};
function generate(into) {
diff --git a/tests/api-integration/project-visibility-scope.test.ts b/tests/api-integration/project-visibility-scope.test.ts
new file mode 100644
index 000000000..6b666b28f
--- /dev/null
+++ b/tests/api-integration/project-visibility-scope.test.ts
@@ -0,0 +1,118 @@
+import { createHash, randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+beforeEach(resetTestDatabase);
+
+async function fixture(permissions: Record<string, string[]>) {
+ const member = await createWorkspaceMember({ role: "limited" });
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ await db.insert(schema.workspaceRoleTable).values({
+ workspaceId: member.workspace.id,
+ role: "limited",
+ permission: JSON.stringify(permissions),
+ });
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const put = (body: Record<string, unknown>) =>
+ app.request(`/api/project/${project.id}`, {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ name: project.name,
+ icon: project.icon ?? "Layout",
+ slug: project.slug,
+ description: project.description ?? "",
+ ...body,
+ }),
+ });
+ const stored = async () =>
+ (
+ await db
+ .select({ isPublic: schema.projectTable.isPublic })
+ .from(schema.projectTable)
+ .where(eq(schema.projectTable.id, project.id))
+ )[0]?.isPublic;
+ return { put, stored, project };
+}
+
+describe("project visibility authorization", () => {
+ it("refuses to publish a private project without project:share", async () => {
+ const { put, stored } = await fixture({ project: ["read", "update"] });
+ const response = await put({ isPublic: true });
+ expect(response.status).toBe(403);
+ expect(await stored()).toBe(false);
+ });
+
+ it("allows an unrelated edit without project:share", async () => {
+ const { put, stored } = await fixture({ project: ["read", "update"] });
+ const response = await put({ name: "Renamed", isPublic: false });
+ expect(response.status).toBe(200);
+ expect(await stored()).toBe(false);
+ });
+
+ it("allows publishing with project:share", async () => {
+ const { put, stored } = await fixture({
+ project: ["read", "update", "share"],
+ });
+ expect((await put({ isPublic: true })).status).toBe(200);
+ expect(await stored()).toBe(true);
+ });
+
+ it("refuses to unpublish a public project without project:share", async () => {
+ const { put, stored, project } = await fixture({
+ project: ["read", "update"],
+ });
+ await db
+ .update(schema.projectTable)
+ .set({ isPublic: true })
+ .where(eq(schema.projectTable.id, project.id));
+ expect((await put({ isPublic: false })).status).toBe(403);
+ expect(await stored()).toBe(true);
+ });
+
+ it("applies the same rule to a scoped API key", async () => {
+ const member = await createWorkspaceMember({ role: "admin" });
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ mockAnonymousSession();
+ const key = `kaneo_test_${randomUUID()}`;
+ await db.insert(schema.apikeyTable).values({
+ referenceId: member.user.id,
+ userId: member.user.id,
+ key: createHash("sha256").update(key).digest("base64url"),
+ name: "update-only key",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ permissions: JSON.stringify({ project: ["read", "update"] }),
+ enabled: true,
+ });
+ const { app } = createApp();
+ const response = await app.request(`/api/project/${project.id}`, {
+ method: "PUT",
+ headers: {
+ "content-type": "application/json",
+ Authorization: `Bearer ${key}`,
+ },
+ body: JSON.stringify({
+ name: project.name,
+ icon: project.icon ?? "Layout",
+ slug: project.slug,
+ description: project.description ?? "",
+ isPublic: true,
+ }),
+ });
+ expect(response.status).toBe(403);
+ });
+});
diff --git a/tests/api/auth-secret.test.ts b/tests/api/auth-secret.test.ts
new file mode 100644
index 000000000..ec8a6dae4
--- /dev/null
+++ b/tests/api/auth-secret.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+import { resolveAuthSecret } from "../../apps/api/src/utils/auth-secret";
+
+const valid = "a".repeat(32);
+
+describe("AUTH_SECRET resolution", () => {
+ it.each([undefined, ""])(
+ "refuses to start when AUTH_SECRET is %p",
+ (value) => {
+ // Better Auth would otherwise fall back to its published default secret,
+ // which makes every session cookie forgeable offline.
+ expect(() => resolveAuthSecret(value)).toThrow(/AUTH_SECRET is not set/);
+ },
+ );
+
+ it("never returns Better Auth's default secret", () => {
+ expect(() =>
+ resolveAuthSecret("better-auth-secret-12345678901234567890"),
+ ).not.toThrow();
+ expect(resolveAuthSecret(valid)).not.toBe(
+ "better-auth-secret-12345678901234567890",
+ );
+ });
+
+ it("rejects a secret shorter than 32 characters", () => {
+ expect(() => resolveAuthSecret("a".repeat(31))).toThrow(/less than 32/);
+ });
+
+ it("accepts a secret of exactly 32 characters", () => {
+ expect(resolveAuthSecret(valid)).toBe(valid);
+ });
+});