Repository navigation
fix(cli): switch CLI auth to OAuth code + PKCE + loopback #3318
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b3d3207
fix(cli): switch CLI auth to OAuth code + PKCE + loopback
saddlepaddle ece9446
fix: remove oauth client seed, insert row directly into prod/dev
saddlepaddle b4b4ddb
fix(cli): replace JWT auth with session tokens
saddlepaddle 311067d
refactor(cli): framework-owned dev/build, fix native packaging
saddlepaddle f7b0bbf
fix(cli): PR review followups on framework refactor
saddlepaddle File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(), | ||
| }); | ||
| } |
138 changes: 138 additions & 0 deletions
138
apps/web/src/app/cli/authorize/components/CliAuthorizeForm/CliAuthorizeForm.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| ); | ||
| } |
1 change: 1 addition & 0 deletions
1
apps/web/src/app/cli/authorize/components/CliAuthorizeForm/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { CliAuthorizeForm } from "./CliAuthorizeForm"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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:") | ||
| ) { | ||
| 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> | ||
| ); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Parse
redirect_uriinstead of prefix-matching it.This check is bypassable with userinfo, e.g.
http://127.0.0.1:51789@attacker.example/callback. That still passesstartsWith(...)but sends the auth code to a non-loopback host. Parse the URL and requireprotocol === "http:",hostnameto be exactly127.0.0.1orlocalhost, and emptyusername/password.Suggested fix
🤖 Prompt for AI Agents