⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(web): keep the session on GitLab token errors and avoid blank messages
Andrej1b8f06b03d07
diff --git a/apps/api/src/gitlab-integration/controllers/list-gitlab-projects.ts b/apps/api/src/gitlab-integration/controllers/list-gitlab-projects.tsindex 66f35964f..538616070 100644--- a/apps/api/src/gitlab-integration/controllers/list-gitlab-projects.ts+++ b/apps/api/src/gitlab-integration/controllers/list-gitlab-projects.ts@@ -1,4 +1,4 @@-import { HTTPException } from "hono/http-exception";+import { ApiError } from "../../errors/api-error";import type { GitlabTokenType } from "../../plugins/gitlab/config";import {createGitlabClient,@@ -32,8 +32,9 @@ async function listGitlabProjects({try {await verifyGitlabToken(normalized, accessToken, tokenType);} catch {- throw new HTTPException(401, {+ throw new ApiError(401, {message: "Invalid GitLab token or could not reach instance.",+ code: "INTEGRATION_AUTH_FAILED",});}diff --git a/apps/api/src/gitlab-integration/controllers/verify-gitlab-access.ts b/apps/api/src/gitlab-integration/controllers/verify-gitlab-access.tsindex c5eb919ec..72d62cdcc 100644--- a/apps/api/src/gitlab-integration/controllers/verify-gitlab-access.ts+++ b/apps/api/src/gitlab-integration/controllers/verify-gitlab-access.ts@@ -1,4 +1,5 @@import { HTTPException } from "hono/http-exception";+import { ApiError } from "../../errors/api-error";import type { GitlabTokenType } from "../../plugins/gitlab/config";import {createGitlabClient,@@ -113,8 +114,9 @@ async function verifyGitlabAccess({}if (error.status === 401 || error.status === 403) {- throw new HTTPException(401, {+ throw new ApiError(401, {message: "Invalid GitLab token or unauthorized.",+ code: "INTEGRATION_AUTH_FAILED",});}}diff --git a/apps/docs/api-reference/errors.mdx b/apps/docs/api-reference/errors.mdxindex 01a465fb0..30a5915b4 100644--- a/apps/docs/api-reference/errors.mdx+++ b/apps/docs/api-reference/errors.mdx@@ -54,9 +54,12 @@ An unknown path under `/api` returns `404` with `{"message": "Not found", "code"| `MISSING_PERMISSION` | 403 | Your workspace role does not grant the action. `missingPermissions` lists what is missing, such as `task:update`. || `API_KEY_SCOPE` | 403 | The API key was created with permissions that do not cover the action. `missingPermissions` lists what is missing. || `SESSION_REQUIRED` | 403 | The endpoint needs a signed-in user session and does not accept API keys. This covers account-level actions such as billing, instance administration, and some GitHub setup routes. |+| `INTEGRATION_AUTH_FAILED` | 401 | A connected service such as GitLab rejected the token in the request, or could not be reached to check it. Your Kaneo session or API key is still valid. |`missingPermissions` only names permissions for the route you called in the workspace it targets.+A `401` with `UNAUTHORIZED` means Kaneo did not accept your session or API key. Sign in again or replace the key only for that code, not for every `401`.+Sign-in, sign-up, and workspace membership endpoints under `/api/auth/*` return the same `message` and `code` fields. Their codes describe the specific failure, for example `INVALID_EMAIL_OR_PASSWORD`, `PASSWORD_REGISTRATION_DISABLED`, or `CAPTCHA_FAILED`.## Validation issuesdiff --git a/apps/web/src/fetchers/instance/get-instance-status.ts b/apps/web/src/fetchers/instance/get-instance-status.tsindex 58102964b..a6250c672 100644--- a/apps/web/src/fetchers/instance/get-instance-status.ts+++ b/apps/web/src/fetchers/instance/get-instance-status.ts@@ -15,12 +15,9 @@ export async function getInstanceStatus(): Promise<InstanceStatus> {// Surface the server's error body when available so the UI can// distinguish "instance unreachable" from other failures.const error = await HttpError.fromResponse(response);- const detail = error.message.trim();throw new HttpError(response.status,- detail- ? `Failed to fetch instance status: ${detail}`- : "Failed to fetch instance status",+ `Failed to fetch instance status: ${error.message}`,error,);}diff --git a/apps/web/src/lib/http-error.test.ts b/apps/web/src/lib/http-error.test.tsindex ae4d7adaa..9fa402a94 100644--- a/apps/web/src/lib/http-error.test.ts+++ b/apps/web/src/lib/http-error.test.ts@@ -1,6 +1,8 @@-import { describe, expect, it } from "vite-plus/test";+import { describe, expect, it, vi } from "vite-plus/test";import { HttpError, isUnauthorizedError } from "./http-error";+vi.mock("i18next", () => ({ default: { t: (key: string) => key } }));+describe("isUnauthorizedError", () => {it("recognizes a 401 HttpError with a different prototype", () => {const error = Object.assign(new Error("Session expired"), {@@ -12,6 +14,11 @@ describe("isUnauthorizedError", () => {expect(isUnauthorizedError(new HttpError(401, "Session expired"))).toBe(true,);+ expect(+ isUnauthorizedError(+ new HttpError(401, "Unauthorized", { code: "UNAUTHORIZED" }),+ ),+ ).toBe(true);});it.each([@@ -24,6 +31,10 @@ describe("isUnauthorizedError", () => {{ name: "HttpError", status: 500 },{ name: "TypeError", status: 401 },{ status: 401 },+ new HttpError(401, "Invalid GitLab token or unauthorized.", {+ code: "INTEGRATION_AUTH_FAILED",+ }),+ { name: "HttpError", status: 401, code: "INVALID_EMAIL_OR_PASSWORD" },])("rejects other errors: %j", (error) => {expect(isUnauthorizedError(error)).toBe(false);});@@ -79,13 +90,13 @@ describe("HttpError.fromResponse", () => {expect(error.code).toBeUndefined();});- it("keeps an empty message for an empty body", async () => {+ it("falls back to the server error message for an empty 5xx body", async () => {const error = await HttpError.fromResponse(new Response(null, { status: 502 }),);expect(error.status).toBe(502);- expect(error.message).toBe("");+ expect(error.message).toBe("common:error.messages.server");expect(error.code).toBeUndefined();});@@ -96,6 +107,23 @@ describe("HttpError.fromResponse", () => {});expect(error.status).toBe(500);- expect(error.message).toBe("");+ expect(error.message).toBe("common:error.messages.server");+ });++ it("falls back to the unknown error message for a blank 4xx body", async () => {+ const error = await HttpError.fromResponse(+ new Response(" \n", { status: 404 }),+ );++ expect(error.message).toBe("common:error.messages.unknown");+ });++ it("keeps the code when the JSON message is blank", async () => {+ const error = await HttpError.fromResponse(+ Response.json({ message: "", code: "CONFLICT" }, { status: 409 }),+ );++ expect(error.message).toBe("common:error.messages.unknown");+ expect(error.code).toBe("CONFLICT");});});diff --git a/apps/web/src/lib/http-error.ts b/apps/web/src/lib/http-error.tsindex 7064c698b..255a0a2d8 100644--- a/apps/web/src/lib/http-error.ts+++ b/apps/web/src/lib/http-error.ts@@ -1,9 +1,18 @@+import i18n from "i18next";import {type ApiErrorDetails,type ApiErrorIssue,parseApiErrorBody,} from "./parse-api-error-body";+function fallbackMessage(status: number): string {+ return i18n.t(+ status >= 500+ ? "common:error.messages.server"+ : "common:error.messages.unknown",+ );+}+export class HttpError extends Error {status: number;code?: string;@@ -24,23 +33,23 @@ export class HttpError extends Error {): Promise<HttpError> {const text = await response.text().catch(() => "");const body = parseApiErrorBody(text);- return body- ? new HttpError(response.status, body.message, body)- : new HttpError(response.status, text);+ const message =+ (body ? body.message : text).trim() || fallbackMessage(response.status);+ return new HttpError(response.status, message, body ?? {});}}export function isUnauthorizedError(error: unknown): boolean {- if (error instanceof HttpError) return error.status === 401;+ if (typeof error !== "object" || error === null) return false;// Recognize HttpError-shaped values even when their prototype differs.- return (- typeof error === "object" &&- error !== null &&- "name" in error &&- error.name === "HttpError" &&- "status" in error &&- error.status === 401- );+ const isHttpError =+ error instanceof HttpError ||+ ("name" in error && error.name === "HttpError");+ if (!isHttpError || !("status" in error) || error.status !== 401) {+ return false;+ }+ const code = "code" in error ? error.code : undefined;+ return code === undefined || code === "UNAUTHORIZED";}// Shared unauthorized redirect for both the React Query error cache and directdiff --git a/apps/web/src/query-client/index.test.ts b/apps/web/src/query-client/index.test.tsnew file mode 100644index 000000000..88fdb4097--- /dev/null+++ b/apps/web/src/query-client/index.test.ts@@ -0,0 +1,96 @@+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import listGitlabProjects from "@/fetchers/gitlab-integration/list-gitlab-projects";+import verifyGitlabAccess from "@/fetchers/gitlab-integration/verify-gitlab-access";+import queryClient from "./index";++const { handleUnauthorized, listProjects, verify } = vi.hoisted(() => ({+ handleUnauthorized: vi.fn(),+ listProjects: vi.fn(),+ verify: vi.fn(),+}));++vi.mock("@kaneo/libs", () => ({+ client: {+ "gitlab-integration": {+ projects: { $post: listProjects },+ verify: { $post: verify },+ },+ },+}));+vi.mock("@sentry/react", () => ({ captureException: vi.fn() }));+vi.mock("@/lib/http-error", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/http-error")>()),+ handleUnauthorized,+}));++const credentials = {+ projectId: "project-1",+ baseUrl: "https://gitlab.example.com",+ accessToken: "glpat-rejected",+};++const gitlabRejected = () =>+ Response.json(+ {+ message: "Invalid GitLab token or unauthorized.",+ code: "INTEGRATION_AUTH_FAILED",+ },+ { status: 401 },+ );++const sessionRejected = () =>+ Response.json(+ { message: "Unauthorized", code: "UNAUTHORIZED" },+ { status: 401 },+ );++beforeEach(() => {+ vi.clearAllMocks();+ queryClient.clear();+});++describe("global unauthorized handling", () => {+ it("keeps the Kaneo session when GitLab rejects a token while listing projects", async () => {+ listProjects.mockResolvedValue(gitlabRejected());++ await expect(+ queryClient.fetchQuery({+ queryKey: ["gitlab-projects"],+ queryFn: () => listGitlabProjects(credentials),+ retry: false,+ }),+ ).rejects.toMatchObject({+ status: 401,+ code: "INTEGRATION_AUTH_FAILED",+ message: "Invalid GitLab token or unauthorized.",+ });+ expect(handleUnauthorized).not.toHaveBeenCalled();+ });++ it("keeps the Kaneo session when GitLab rejects a token during verification", async () => {+ verify.mockResolvedValue(gitlabRejected());++ const mutation = queryClient.getMutationCache().build(queryClient, {+ mutationFn: () =>+ verifyGitlabAccess({ ...credentials, projectPath: "acme/web" }),+ });++ await expect(mutation.execute(undefined)).rejects.toMatchObject({+ status: 401,+ code: "INTEGRATION_AUTH_FAILED",+ });+ expect(handleUnauthorized).not.toHaveBeenCalled();+ });++ it("signs out when Kaneo rejects the session", async () => {+ listProjects.mockResolvedValue(sessionRejected());++ await expect(+ queryClient.fetchQuery({+ queryKey: ["gitlab-projects"],+ queryFn: () => listGitlabProjects(credentials),+ }),+ ).rejects.toMatchObject({ status: 401, code: "UNAUTHORIZED" });+ expect(handleUnauthorized).toHaveBeenCalledTimes(1);+ });+});diff --git a/tests/api/gitlab-integration/list-gitlab-projects.test.ts b/tests/api/gitlab-integration/list-gitlab-projects.test.tsnew file mode 100644index 000000000..fa83a1f74--- /dev/null+++ b/tests/api/gitlab-integration/list-gitlab-projects.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it, vi } from "vite-plus/test";++vi.mock("../../../apps/api/src/plugins/gitlab/utils/gitlab-api", () => ({+ verifyGitlabToken: () => Promise.reject(new Error("GitLab API error 401")),+ createGitlabClient: () => ({ listMemberProjects: () => Promise.resolve([]) }),+}));++const { default: listGitlabProjects } =+ await import("../../../apps/api/src/gitlab-integration/controllers/list-gitlab-projects");++describe("listGitlabProjects", () => {+ it("reports a rejected GitLab token as an integration auth failure", async () => {+ await expect(+ listGitlabProjects({+ baseUrl: "https://gitlab.com",+ accessToken: "token",+ tokenType: "private",+ }),+ ).rejects.toMatchObject({+ status: 401,+ code: "INTEGRATION_AUTH_FAILED",+ });+ });+});diff --git a/tests/api/gitlab-integration/verify-gitlab-access.test.ts b/tests/api/gitlab-integration/verify-gitlab-access.test.tsindex e9c371077..d4a799d04 100644--- a/tests/api/gitlab-integration/verify-gitlab-access.test.ts+++ b/tests/api/gitlab-integration/verify-gitlab-access.test.ts@@ -5,8 +5,20 @@ const { mockGitlabFetch } = vi.hoisted(() => ({mockGitlabFetch: vi.fn(),}));+const { MockGitlabApiError } = vi.hoisted(() => ({+ MockGitlabApiError: class GitlabApiError extends Error {+ constructor(+ message: string,+ public status: number,+ public kind: string,+ ) {+ super(message);+ }+ },+}));+vi.mock("../../../apps/api/src/plugins/gitlab/utils/gitlab-api", () => ({- GitlabApiError: class GitlabApiError extends Error {},+ GitlabApiError: MockGitlabApiError,verifyGitlabToken: (...args: unknown[]) => mockGitlabFetch(...args),createGitlabClient: () => ({getProject: (...args: unknown[]) => mockGitlabFetch(...args),@@ -74,3 +86,26 @@ describe("verifyGitlabAccess input", () => {expect(mockGitlabFetch).toHaveBeenLastCalledWith("acme/web");});});++describe("verifyGitlabAccess token rejection", () => {+ it.each([401, 403])(+ "reports GitLab HTTP %i as an integration auth failure",+ async (status) => {+ mockGitlabFetch.mockRejectedValueOnce(+ new MockGitlabApiError("GitLab API error", status, "HTTP_ERROR"),+ );++ await expect(+ verifyGitlabAccess({+ baseUrl: "https://gitlab.com",+ accessToken: "token",+ tokenType: "private",+ projectPath: "acme/web",+ }),+ ).rejects.toMatchObject({+ status: 401,+ code: "INTEGRATION_AUTH_FAILED",+ });+ },+ );+});