Repository navigation
fix(cli): use the app's account in a Superset terminal, so pages publish stops failing with "Not a member of organization" #8274
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
651bd9b
1a70acb
9279cd7
9d39720
ec0f4d5
f64e216
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import type { AppRouter as HostServiceRouter } from "@superset/host-service/trpc"; | ||
| import { createTRPCClient, httpBatchLink } from "@trpc/client"; | ||
| import SuperJSON from "superjson"; | ||
| import { isProcessAlive, readManifest } from "./host/manifest"; | ||
|
|
||
| /** Long enough for the host to refresh its token over the network first. */ | ||
| const HOST_API_TOKEN_TIMEOUT_MS = 5_000; | ||
|
|
||
| /** | ||
| * In a Superset terminal, the API token of the account that runs the | ||
| * workspace's host, so the CLI acts as that account and not its own login. | ||
| * Null outside one, or when the host is down or too old to give one. | ||
| */ | ||
| export async function readHostApiToken( | ||
| timeoutMs = HOST_API_TOKEN_TIMEOUT_MS, | ||
| ): Promise<string | null> { | ||
| const organizationId = process.env.SUPERSET_ORGANIZATION_ID?.trim(); | ||
| if (!organizationId || !process.env.SUPERSET_WORKSPACE_ID) return null; | ||
| if (process.env.SUPERSET_SANDBOX_WORKSPACE_ID) return null; | ||
|
|
||
| const manifest = readManifest(organizationId); | ||
| if (!manifest || !isProcessAlive(manifest.pid)) return null; | ||
|
|
||
| const host = createTRPCClient<HostServiceRouter>({ | ||
| links: [ | ||
| httpBatchLink({ | ||
| url: `${manifest.endpoint}/trpc`, | ||
| transformer: SuperJSON, | ||
| headers: { Authorization: `Bearer ${manifest.authToken}` }, | ||
| }), | ||
| ], | ||
| }); | ||
| try { | ||
| const { token } = await host.host.apiToken.query(undefined, { | ||
| signal: AbortSignal.timeout(timeoutMs), | ||
| }); | ||
| return token; | ||
| } catch { | ||
| return null; | ||
| } | ||
|
Comment on lines
+38
to
+40
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: sed -n '1,140p' packages/cli/src/lib/host-api-token.ts
sed -n '1,155p' packages/cli/src/lib/resolve-auth.ts
sed -n '1,120p' packages/cli/src/commands/auth/whoami/command.ts
sed -n '155,235p' packages/cli/src/lib/resolve-auth.test.tsRepository: superset-sh/superset Length of output: 7432 Surface non-404 host-token failures. When Keep the fallback for the expected missing-procedure case, and emit a debug log for other failures. A comment alone would not surface the unexpected failure. 🤖 Prompt for AI Agents |
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| import { describe, expect, it } from "bun:test"; | ||
| import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; | ||
| import { tmpdir } from "node:os"; | ||
| import { join } from "node:path"; | ||
| import type { TRPCError } from "@trpc/server"; | ||
| import { | ||
| ConfigFileSessionTokenSource, | ||
| JwtApiAuthProvider, | ||
| } from "../../../providers/auth"; | ||
| import type { HostServiceContext } from "../../../types"; | ||
| import { hostRouter } from "./host"; | ||
|
|
||
| const apiAuth = { | ||
| getHeaders: async () => ({ Authorization: "Bearer owner-jwt" }), | ||
| invalidateCache: () => {}, | ||
| }; | ||
|
|
||
| const callerFor = (context: Partial<HostServiceContext>) => | ||
| hostRouter.createCaller({ | ||
| isAuthenticated: true, | ||
| apiAuth, | ||
| ...context, | ||
| } as HostServiceContext); | ||
|
|
||
| describe("host.apiToken", () => { | ||
| it("gives a caller on this machine the token the host uses", async () => { | ||
| const caller = callerFor({ isLocalCaller: true }); | ||
| expect(await caller.apiToken()).toEqual({ token: "owner-jwt" }); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ["through the relay", false], | ||
| ["of unknown origin", undefined], | ||
| ])("refuses a caller %s", async (_name, isLocalCaller) => { | ||
| const error = (await callerFor({ isLocalCaller }) | ||
| .apiToken() | ||
| .catch((thrown: unknown) => thrown)) as TRPCError; | ||
| expect(error.code).toBe("FORBIDDEN"); | ||
| }); | ||
| }); | ||
|
|
||
| describe("host.apiToken with a token near expiry", () => { | ||
| const jwtExpiringIn = (seconds: number) => | ||
| [ | ||
| "header", | ||
| Buffer.from( | ||
| JSON.stringify({ exp: Math.floor(Date.now() / 1000) + seconds }), | ||
| ).toString("base64url"), | ||
| "signature", | ||
| ].join("."); | ||
|
|
||
| const sourceOf = (tokens: string[]) => { | ||
| let invalidated = 0; | ||
| return { | ||
| apiAuth: { | ||
| getHeaders: async () => ({ | ||
| Authorization: `Bearer ${tokens[Math.min(invalidated, tokens.length - 1)]}`, | ||
| }), | ||
| invalidateCache: () => { | ||
| invalidated++; | ||
| }, | ||
| }, | ||
| }; | ||
| }; | ||
|
|
||
| it("refreshes the expired OAuth token of a host from `superset start`", async () => { | ||
| const fresh = jwtExpiringIn(3600); | ||
| const tokenEndpoint = Bun.serve({ | ||
| port: 0, | ||
| fetch: () => | ||
| Response.json({ | ||
| access_token: fresh, | ||
| refresh_token: "rt_next", | ||
| expires_in: 3600, | ||
| }), | ||
| }); | ||
| const dir = mkdtempSync(join(tmpdir(), "host-api-token-")); | ||
| try { | ||
| const configPath = join(dir, "config.json"); | ||
| writeFileSync( | ||
| configPath, | ||
| JSON.stringify({ | ||
| auth: { | ||
| accessToken: jwtExpiringIn(-60), | ||
| refreshToken: "rt_stored", | ||
| expiresAt: Date.now() - 60_000, | ||
| }, | ||
| }), | ||
| ); | ||
| const apiUrl = `http://127.0.0.1:${tokenEndpoint.port}`; | ||
| const source = new ConfigFileSessionTokenSource({ configPath, apiUrl }); | ||
| const apiAuth = new JwtApiAuthProvider({ | ||
| getSessionToken: () => source.getSessionToken(), | ||
| onInvalidateCache: () => source.invalidateCache(), | ||
| apiUrl, | ||
| }); | ||
|
|
||
| const caller = callerFor({ isLocalCaller: true, apiAuth }); | ||
|
|
||
| expect(await caller.apiToken()).toEqual({ token: fresh }); | ||
| } finally { | ||
| tokenEndpoint.stop(true); | ||
| rmSync(dir, { recursive: true, force: true }); | ||
| } | ||
| }); | ||
|
|
||
| it("refuses when the refreshed token still expires within minutes", async () => { | ||
| const source = sourceOf([jwtExpiringIn(-60), jwtExpiringIn(30)]); | ||
| const error = (await callerFor({ | ||
| isLocalCaller: true, | ||
| apiAuth: source.apiAuth, | ||
| }) | ||
| .apiToken() | ||
| .catch((thrown: unknown) => thrown)) as TRPCError; | ||
| expect(error.code).toBe("PRECONDITION_FAILED"); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Allow host-token refresh to complete before selecting stored credentials.
If the host refreshes an expiring token,
apiTokencan take longer than this 500 ms deadline. The timeout then makesreadHostApiTokenreturnnull, andresolveAuthselects the CLI’s stored credentials instead of the host account. Give token refresh a suitable deadline, and do not treat an ambiguous refresh timeout as proof that the host is unavailable.🤖 Prompt for AI Agents