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
47 changes: 47 additions & 0 deletions apps/api/src/app/api/cli/create-code/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { randomBytes } from "node:crypto";
import { auth } from "@superset/auth/server";
import { db } from "@superset/db/client";
import { members } from "@superset/db/schema";
import { Redis } from "@upstash/redis";
import { and, eq } from "drizzle-orm";
import { env } from "@/env";

const redis = new Redis({
url: env.KV_REST_API_URL,
token: env.KV_REST_API_TOKEN,
});

export async function POST(request: Request) {
const session = await auth.api.getSession({ headers: request.headers });
if (!session) {
return Response.json({ error: "Not authenticated" }, { status: 401 });
}

const body = (await request.json()) as { organizationId?: string };
const { organizationId } = body;
if (!organizationId) {
return Response.json({ error: "organizationId required" }, { status: 400 });
}

const membership = await db.query.members.findFirst({
where: and(
eq(members.userId, session.user.id),
eq(members.organizationId, organizationId),
),
});
if (!membership) {
return Response.json(
{ error: "Not a member of this organization" },
{ status: 403 },
);
}

const code = randomBytes(24).toString("base64url");
await redis.set(
`cli:code:${code}`,
{ userId: session.user.id, organizationId },
{ ex: 300 },
);

return Response.json({ code });
}
51 changes: 51 additions & 0 deletions apps/api/src/app/api/cli/exchange/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { auth } from "@superset/auth/server";
import { Redis } from "@upstash/redis";
import { env } from "@/env";

const redis = new Redis({
url: env.KV_REST_API_URL,
token: env.KV_REST_API_TOKEN,
});

interface CodePayload {
userId: string;
organizationId: string;
}

export async function POST(request: Request) {
const body = (await request.json()) as { code?: string };
const { code } = body;
if (!code) {
return Response.json({ error: "code required" }, { status: 400 });
}

const key = `cli:code:${code}`;
const payload = await redis.get<CodePayload>(key);
if (!payload) {
return Response.json({ error: "Invalid or expired code" }, { status: 400 });
}

await redis.del(key);

if (!payload.userId || !payload.organizationId) {
return Response.json({ error: "Malformed code data" }, { status: 500 });
}

const context = await auth.$context;
const session = await context.internalAdapter.createSession(
payload.userId,
false,
{ activeOrganizationId: payload.organizationId },
);
if (!session) {
return Response.json(
{ error: "Failed to create session" },
{ status: 500 },
);
}

return Response.json({
token: session.token,
expiresAt: session.expiresAt.toISOString(),
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
"use client";

import { Button } from "@superset/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@superset/ui/select";
import { useState } from "react";
import { LuBuilding2 } from "react-icons/lu";

interface Organization {
id: string;
name: string;
}

interface CliAuthorizeFormProps {
state: string;
redirectUri: string;
userName: string;
organizations: Organization[];
apiUrl: string;
}

export function CliAuthorizeForm({
state,
redirectUri,
userName,
organizations,
apiUrl,
}: CliAuthorizeFormProps) {
const [selectedOrgId, setSelectedOrgId] = useState(
organizations[0]?.id ?? "",
);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);

const selectedOrg = organizations.find((o) => o.id === selectedOrgId);

const handleAuthorize = async () => {
if (!selectedOrgId) {
setError("Please select an organization");
return;
}

setIsLoading(true);
setError(null);

try {
const res = await fetch(`${apiUrl}/api/cli/create-code`, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ organizationId: selectedOrgId }),
});

if (!res.ok) {
const data = (await res.json()) as { error?: string };
throw new Error(data.error ?? `Failed: ${res.status}`);
}

const { code } = (await res.json()) as { code: string };

const url = new URL(redirectUri);
url.searchParams.set("code", code);
url.searchParams.set("state", state);
window.location.href = url.toString();
} catch (err) {
setError(err instanceof Error ? err.message : "An error occurred");
setIsLoading(false);
}
};

return (
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[400px]">
<div className="flex flex-col space-y-2 text-center">
<h1 className="text-2xl font-semibold tracking-tight">
Authorize Superset CLI
</h1>
<p className="text-muted-foreground text-sm">
Sign in to the CLI as{" "}
<span className="font-medium text-foreground">{userName}</span>
</p>
</div>

<div className="bg-muted/50 rounded-lg border p-4">
{organizations.length > 1 ? (
<div className="mb-4">
<label
htmlFor="org-select"
className="mb-2 block text-sm font-medium"
>
Select organization
</label>
<Select value={selectedOrgId} onValueChange={setSelectedOrgId}>
<SelectTrigger id="org-select" className="w-full">
<SelectValue placeholder="Select an organization" />
</SelectTrigger>
<SelectContent>
{organizations.map((org) => (
<SelectItem key={org.id} value={org.id}>
<div className="flex items-center gap-2">
<LuBuilding2 className="size-4 text-muted-foreground" />
{org.name}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
) : selectedOrg ? (
<p className="text-muted-foreground mb-3 text-sm">
Organization:{" "}
<span className="font-medium text-foreground">
{selectedOrg.name}
</span>
</p>
) : null}
</div>

{error && <p className="text-destructive text-center text-sm">{error}</p>}

<Button
className="w-full"
disabled={isLoading || !selectedOrgId}
onClick={handleAuthorize}
>
{isLoading ? "Authorizing..." : "Authorize"}
</Button>

<p className="text-muted-foreground px-8 text-center text-xs">
This will create a CLI session for the selected organization.
</p>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { CliAuthorizeForm } from "./CliAuthorizeForm";
83 changes: 83 additions & 0 deletions apps/web/src/app/cli/authorize/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { auth } from "@superset/auth/server";
import { headers } from "next/headers";
import Image from "next/image";
import { redirect } from "next/navigation";

import { env } from "@/env";
import { api } from "@/trpc/server";
import { CliAuthorizeForm } from "./components/CliAuthorizeForm";

interface CliAuthorizePageProps {
searchParams: Promise<Record<string, string>>;
}

export default async function CliAuthorizePage({
searchParams,
}: CliAuthorizePageProps) {
const session = await auth.api.getSession({
headers: await headers(),
});

const params = await searchParams;

if (!session) {
const returnUrl = `/cli/authorize?${new URLSearchParams(params).toString()}`;
redirect(`/sign-in?redirect=${encodeURIComponent(returnUrl)}`);
}

const { state, redirect_uri } = params;

if (!state || !redirect_uri) {
return (
<div className="flex min-h-screen items-center justify-center">
<p className="text-muted-foreground">
Missing required parameters. Use <code>superset auth login</code>.
</p>
</div>
);
}

if (
!redirect_uri.startsWith("http://127.0.0.1:") &&
!redirect_uri.startsWith("http://localhost:")
) {
Comment on lines +40 to +43

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Parse redirect_uri instead of prefix-matching it.

This check is bypassable with userinfo, e.g. http://127.0.0.1:51789@attacker.example/callback. That still passes startsWith(...) but sends the auth code to a non-loopback host. Parse the URL and require protocol === "http:", hostname to be exactly 127.0.0.1 or localhost, and empty username/password.

Suggested fix
-	if (
-		!redirect_uri.startsWith("http://127.0.0.1:") &&
-		!redirect_uri.startsWith("http://localhost:")
-	) {
+	let validatedRedirectUri: string;
+	try {
+		const parsed = new URL(redirect_uri);
+		const isLoopbackHost =
+			parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost";
+		if (
+			parsed.protocol !== "http:" ||
+			!isLoopbackHost ||
+			parsed.username ||
+			parsed.password
+		) {
+			throw new Error("invalid redirect");
+		}
+		validatedRedirectUri = parsed.toString();
+	} catch {
 		return (
 			<div className="flex min-h-screen items-center justify-center">
 				<p className="text-destructive">
 					Invalid redirect_uri — only loopback addresses are allowed.
 				</p>
 			</div>
 		);
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web/src/app/cli/authorize/page.tsx` around lines 40 - 43, The current
redirect_uri validation uses startsWith and is bypassable; replace it by parsing
redirect_uri with the URL parser (new URL(redirect_uri)) and enforce:
url.protocol === "http:", url.hostname is exactly "127.0.0.1" or "localhost",
and url.username and url.password are empty; update the conditional around
redirect_uri in page.tsx (the block that currently checks
redirect_uri.startsWith(...)) to perform these checks and reject any
redirect_uri that fails them.

return (
<div className="flex min-h-screen items-center justify-center">
<p className="text-destructive">
Invalid redirect_uri — only loopback addresses are allowed.
</p>
</div>
);
}

const trpc = await api();
const organizations = await trpc.user.myOrganizations.query();

return (
<div className="relative flex min-h-screen flex-col">
<header className="container mx-auto px-6 py-6">
<a href={env.NEXT_PUBLIC_MARKETING_URL}>
<Image
src="/title.svg"
alt="Superset"
width={140}
height={24}
priority
/>
</a>
</header>
<main className="flex flex-1 items-center justify-center">
<CliAuthorizeForm
state={state}
redirectUri={redirect_uri}
userName={session.user.name}
organizations={organizations.map((organization) => ({
id: organization.id,
name: organization.name,
}))}
apiUrl={env.NEXT_PUBLIC_API_URL}
/>
</main>
</div>
);
}
Loading
Loading