Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
import type {
DeleteInProgressCause,
TeardownFailureCause,
} from "@superset/host-service";
import { TRPCClientError } from "@trpc/client";
import type { TeardownFailureCause } from "@superset/host-service";
import { useCallback } from "react";
import { useCloudWorkspaces } from "renderer/hooks/useCloudWorkspaces";
import { apiTrpcClient } from "renderer/lib/api-trpc-client";
import { hasExpiredJwt } from "renderer/lib/auth-client";
import { cloudTrpc } from "renderer/lib/cloud-trpc";
import { usesRelayJwt } from "renderer/lib/host-service-auth";
import { getHostServiceClientByUrl } from "renderer/lib/host-service-client";
import { useLocalHostService } from "renderer/routes/_authenticated/providers/LocalHostServiceProvider";
import {
useWorkspaceHostTarget,
type WorkspaceHostTarget,
} from "../useWorkspaceHostUrl";
import { normalizeDestroyWorkspaceError } from "./utils/normalizeDestroyWorkspaceError";

interface DestroyWorkspaceInput {
deleteBranch?: boolean;
Expand Down Expand Up @@ -59,6 +58,8 @@ export type DestroyWorkspaceError =
| { kind: "in-progress"; message: string }
| { kind: "teardown-failed"; cause: TeardownFailureCause }
| { kind: "host-unavailable"; reason: WorkspaceHostTarget["status"] }
| { kind: "host-offline"; message: string }
| { kind: "sign-in-expired"; message: string }
| { kind: "unknown"; message: string };

interface UseDestroyWorkspace {
Expand Down Expand Up @@ -86,7 +87,7 @@ export async function destroyWorkspaceAtHost(
skipTeardown: input.skipTeardown ?? false,
});
} catch (error) {
throw normalizeDestroyWorkspaceError(error);
throw normalizeDestroyWorkspaceError(error, relayContext(hostUrl));
}
}

Expand All @@ -99,7 +100,7 @@ export async function inspectWorkspaceAtHost({
try {
return await client.workspaceCleanup.inspect.query({ workspaceId });
} catch (error) {
throw normalizeDestroyWorkspaceError(error);
throw normalizeDestroyWorkspaceError(error, relayContext(hostUrl));
}
}

Expand Down Expand Up @@ -191,6 +192,13 @@ export function useDestroyWorkspace(workspaceId: string): UseDestroyWorkspace {
return { hostTarget, destroy, inspect };
}

function relayContext(hostUrl: string | null) {
return {
viaRelay: hostUrl !== null && usesRelayJwt(hostUrl),
relayTokenExpired: hasExpiredJwt(),
};
}

function getReadyClient(
hostUrl: string | null,
hostStatus: WorkspaceHostTarget["status"],
Expand All @@ -203,40 +211,3 @@ function getReadyClient(
}
return getHostServiceClientByUrl(hostUrl);
}

function normalizeDestroyWorkspaceError(err: unknown): DestroyWorkspaceError {
if (isDestroyWorkspaceError(err)) return err;
if (err instanceof TRPCClientError) {
const data = err.data as
| {
code?: string;
teardownFailure?: TeardownFailureCause;
deleteInProgress?: DeleteInProgressCause;
}
| undefined;

if (data?.teardownFailure) {
return { kind: "teardown-failed", cause: data.teardownFailure };
}
if (data?.deleteInProgress) {
return { kind: "in-progress", message: err.message };
}
if (data?.code === "CONFLICT") {
return { kind: "conflict", message: err.message };
}
return { kind: "unknown", message: err.message };
}
return {
kind: "unknown",
message: err instanceof Error ? err.message : String(err),
};
}

function isDestroyWorkspaceError(err: unknown): err is DestroyWorkspaceError {
return (
!!err &&
typeof err === "object" &&
"kind" in err &&
typeof (err as { kind: unknown }).kind === "string"
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { normalizeDestroyWorkspaceError } from "./normalizeDestroyWorkspaceError";
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { describe, expect, test } from "bun:test";
import { TRPCClientError } from "@trpc/client";
import { normalizeDestroyWorkspaceError } from "./normalizeDestroyWorkspaceError";

function relayError(code: string, message: string) {
return TRPCClientError.from({
error: { message, code: -32603, data: { code } },
});
}

describe("normalizeDestroyWorkspaceError", () => {
test("an offline host is its own kind, not the relay's raw text", () => {
const error = normalizeDestroyWorkspaceError(
relayError("SERVICE_UNAVAILABLE", "Host is not online"),
{ viaRelay: true, relayTokenExpired: false },
);
expect(error.kind).toBe("host-offline");
});

test("a refusal of an expired relay token reads as a sign-in problem", () => {
const error = normalizeDestroyWorkspaceError(
relayError("UNAUTHORIZED", "Unauthorized"),
{ viaRelay: true, relayTokenExpired: true },
);
expect(error.kind).toBe("sign-in-expired");
});

test("a refusal of a valid token keeps the server's message", () => {
const error = normalizeDestroyWorkspaceError(
relayError("UNAUTHORIZED", "Unauthorized"),
{ viaRelay: true, relayTokenExpired: false },
);
expect(error).toEqual({ kind: "unknown", message: "Unauthorized" });
});

test("a directly reached host's own unavailable error is not an offline host", () => {
const error = normalizeDestroyWorkspaceError(
relayError("SERVICE_UNAVAILABLE", "Worker restarting"),
{ viaRelay: false, relayTokenExpired: true },
);
expect(error).toEqual({ kind: "unknown", message: "Worker restarting" });
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { msg } from "@lingui/core/macro";
import type {
DeleteInProgressCause,
TeardownFailureCause,
} from "@superset/host-service";
import { i18n } from "@superset/i18n";
import { TRPCClientError } from "@trpc/client";
import type { DestroyWorkspaceError } from "../../useDestroyWorkspace";

export function normalizeDestroyWorkspaceError(
err: unknown,
{
viaRelay,
relayTokenExpired,
}: { viaRelay: boolean; relayTokenExpired: boolean },
): DestroyWorkspaceError {
if (isDestroyWorkspaceError(err)) return err;
if (err instanceof TRPCClientError) {
const data = err.data as
| {
code?: string;
teardownFailure?: TeardownFailureCause;
deleteInProgress?: DeleteInProgressCause;
}
| undefined;

if (data?.teardownFailure) {
return { kind: "teardown-failed", cause: data.teardownFailure };
}
if (data?.deleteInProgress) {
return { kind: "in-progress", message: err.message };
}
if (data?.code === "CONFLICT") {
return { kind: "conflict", message: err.message };
}
// A host reached directly also uses this code, for its own failures.
if (data?.code === "SERVICE_UNAVAILABLE" && viaRelay) {
return {
kind: "host-offline",
message: i18n._(
msg({
message: "The host is offline. Try again when it's back online.",
}),
),
};
}
// The relay refuses an expired token, and the token is only still
// expired here when refreshing it failed.
if (data?.code === "UNAUTHORIZED" && viaRelay && relayTokenExpired) {
return {
kind: "sign-in-expired",
message: i18n._(
msg({
message:
"Your sign-in couldn't be refreshed. Check your connection, then try again.",
}),
),
};
}
return { kind: "unknown", message: err.message };
}
return {
kind: "unknown",
message: err instanceof Error ? err.message : String(err),
};
}

function isDestroyWorkspaceError(err: unknown): err is DestroyWorkspaceError {
return (
!!err &&
typeof err === "object" &&
"kind" in err &&
typeof (err as { kind: unknown }).kind === "string"
);
}
30 changes: 30 additions & 0 deletions apps/desktop/src/renderer/lib/auth-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ let jwtRefreshInFlight: Promise<string | null> | null = null;
// Refresh ahead of expiry so a token handed to a WS URL is still valid by the
// time the relay verifies it.
const JWT_REFRESH_LEEWAY_MS = 60_000;
// After a refresh fails, callers get the cached token at once for this long.
const JWT_REFRESH_COOLDOWN_MS = 10_000;
let jwtRefreshBlockedUntilMs = 0;
let jwtRefreshStartedAtMs = 0;

export function setJwt(token: string | null) {
jwt = token;
Expand All @@ -70,6 +74,13 @@ function jwtIsFresh(): boolean {
return Date.now() < jwtExpiresAtMs - JWT_REFRESH_LEEWAY_MS;
}

/** A token is cached and its expiry has passed, so the relay will refuse it. */
export function hasExpiredJwt(): boolean {
return (
jwt !== null && jwtExpiresAtMs !== null && Date.now() >= jwtExpiresAtMs
);
}

export function getJwt(): string | null {
// Relay JWTs rotate hourly, but this cache only updates when some API
// response happens to carry `set-auth-jwt`. Sync callers (WS URL builders,
Expand All @@ -86,8 +97,10 @@ export function getJwt(): string | null {
*/
export async function ensureFreshJwt(): Promise<string | null> {
if (jwtIsFresh()) return jwt;
if (!jwtRefreshInFlight && Date.now() < jwtRefreshBlockedUntilMs) return jwt;
if (!jwtRefreshInFlight) {
const generationAtStart = jwtGeneration;
jwtRefreshStartedAtMs = Date.now();
jwtRefreshInFlight = authClient
.$fetch<{ token?: string }>("/token")
.then((res) => {
Expand All @@ -108,12 +121,29 @@ export async function ensureFreshJwt(): Promise<string | null> {
return jwt;
})
.finally(() => {
if (!jwtIsFresh() && jwtGeneration === generationAtStart) {
jwtRefreshBlockedUntilMs = Date.now() + JWT_REFRESH_COOLDOWN_MS;
}
jwtRefreshInFlight = null;
});
}
return jwtRefreshInFlight;
}

/**
* Waits for a refresh, but only until `maxWaitMs` after that refresh began:
* a slow refresh keeps running, and callers arriving later do not wait again.
*/
export async function waitForFreshJwt(maxWaitMs: number): Promise<void> {
const refresh = ensureFreshJwt();
const remainingMs = jwtRefreshStartedAtMs + maxWaitMs - Date.now();
if (remainingMs <= 0) return;
await Promise.race([
refresh,
new Promise((resolve) => setTimeout(resolve, remainingMs)),
]);
}

/**
* Better Auth client for Electron desktop app.
*
Expand Down
57 changes: 57 additions & 0 deletions apps/desktop/src/renderer/lib/host-service-auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { afterEach, expect, test } from "bun:test";
import { setJwt } from "./auth-client";
import {
removeHostServiceSecret,
resolveHostServiceHeaders,
setHostServiceSecret,
} from "./host-service-auth";

const RELAY_HOST_URL = "https://relay.example/hosts/org:machine";
const LOCAL_HOST_URL = "http://127.0.0.1:4879";

afterEach(() => {
setJwt(null);
removeHostServiceSecret(LOCAL_HOST_URL);
});

test("a relay call sends the token the refresh produced", async () => {
setJwt("stale");

const headers = await resolveHostServiceHeaders(
RELAY_HOST_URL,
async () => {
setJwt("fresh");
},
() => true,
);

expect(headers.Authorization).toBe("Bearer fresh");
});

test("a host reached with its own secret does not wait on a refresh", async () => {
setHostServiceSecret(LOCAL_HOST_URL, "secret");
let refreshed = false;

const headers = await resolveHostServiceHeaders(LOCAL_HOST_URL, async () => {
refreshed = true;
});

expect(refreshed).toBe(false);
expect(headers.Authorization).toBe("Bearer secret");
});

test("a relay call with a usable token does not wait on a refresh", async () => {
setJwt("usable");
let refreshed = false;

const headers = await resolveHostServiceHeaders(
RELAY_HOST_URL,
async () => {
refreshed = true;
},
() => false,
);

expect(refreshed).toBe(false);
expect(headers.Authorization).toBe("Bearer usable");
});
23 changes: 22 additions & 1 deletion apps/desktop/src/renderer/lib/host-service-auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { SUPERSET_USER_ID_HEADER } from "@superset/shared/host-routing";
import { getJwt } from "./auth-client";
import { getJwt, hasExpiredJwt, waitForFreshJwt } from "./auth-client";

const RELAY_TOKEN_WAIT_MS = 5_000;

/**
* The bearer a host accepts, by URL. A local host-service takes its
Expand Down Expand Up @@ -52,6 +54,25 @@ export function getHostServiceHeaders(hostUrl: string): Record<string, string> {
return headers;
}

/** True when the host is reached through the relay, with the user's JWT. */
export function usesRelayJwt(hostUrl: string): boolean {
return !secrets.has(hostUrl);
}

/**
* For request paths that can wait: a relay call made with no JWT or an expired
* one is refused, so refresh the token before building the headers.
*/
export async function resolveHostServiceHeaders(
hostUrl: string,
refreshJwt: () => Promise<unknown> = () =>
waitForFreshJwt(RELAY_TOKEN_WAIT_MS),
jwtIsUnusable: () => boolean = () => getJwt() === null || hasExpiredJwt(),
): Promise<Record<string, string>> {
if (usesRelayJwt(hostUrl) && jwtIsUnusable()) await refreshJwt();
return getHostServiceHeaders(hostUrl);
}

/**
* A browser can't set headers on a WebSocket upgrade, so the socket routes
* read the same bearer from the `token` query param instead.
Expand Down
Loading
Loading