Skip to content

feat: check for external auth before running task #18339

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 2 commits into from
Jun 12, 2025
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
54 changes: 54 additions & 0 deletions site/src/hooks/useExternalAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { templateVersionExternalAuth } from "api/queries/templates";
import { useCallback, useEffect, useState } from "react";
import { useQuery } from "react-query";

export type ExternalAuthPollingState = "idle" | "polling" | "abandoned";

export const useExternalAuth = (versionId: string | undefined) => {
const [externalAuthPollingState, setExternalAuthPollingState] =
useState<ExternalAuthPollingState>("idle");

const startPollingExternalAuth = useCallback(() => {
setExternalAuthPollingState("polling");
}, []);

const {
data: externalAuth,
isPending: isLoadingExternalAuth,
error,
} = useQuery({
...templateVersionExternalAuth(versionId ?? ""),
enabled: !!versionId,
refetchInterval: externalAuthPollingState === "polling" ? 1000 : false,
});

const allSignedIn = externalAuth?.every((it) => it.authenticated);

useEffect(() => {
if (allSignedIn) {
setExternalAuthPollingState("idle");
return;
}

if (externalAuthPollingState !== "polling") {
return;
}

// Poll for a maximum of one minute
const quitPolling = setTimeout(
() => setExternalAuthPollingState("abandoned"),
60_000,
);
return () => {
clearTimeout(quitPolling);
};
}, [externalAuthPollingState, allSignedIn]);

return {
startPollingExternalAuth,
externalAuth,
externalAuthPollingState,
isLoadingExternalAuth,
externalAuthError: error,
};
};
48 changes: 1 addition & 47 deletions site/src/pages/CreateWorkspacePage/CreateWorkspacePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { checkAuthorization } from "api/queries/authCheck";
import {
richParameters,
templateByName,
templateVersionExternalAuth,
templateVersionPresets,
} from "api/queries/templates";
import { autoCreateWorkspace, createWorkspace } from "api/queries/workspaces";
Expand All @@ -17,6 +16,7 @@ import type {
import { Loader } from "components/Loader/Loader";
import { useAuthenticated } from "hooks";
import { useEffectEvent } from "hooks/hookPolyfills";
import { useExternalAuth } from "hooks/useExternalAuth";
import { useDashboard } from "modules/dashboard/useDashboard";
import { generateWorkspaceName } from "modules/workspaces/generateWorkspaceName";
import { type FC, useCallback, useEffect, useRef, useState } from "react";
Expand All @@ -35,8 +35,6 @@ import {
const createWorkspaceModes = ["form", "auto", "duplicate"] as const;
export type CreateWorkspaceMode = (typeof createWorkspaceModes)[number];

export type ExternalAuthPollingState = "idle" | "polling" | "abandoned";

const CreateWorkspacePage: FC = () => {
const { organization: organizationName = "default", template: templateName } =
useParams() as { organization?: string; template: string };
Expand Down Expand Up @@ -237,50 +235,6 @@ const CreateWorkspacePage: FC = () => {
);
};

const useExternalAuth = (versionId: string | undefined) => {
const [externalAuthPollingState, setExternalAuthPollingState] =
useState<ExternalAuthPollingState>("idle");

const startPollingExternalAuth = useCallback(() => {
setExternalAuthPollingState("polling");
}, []);

const { data: externalAuth, isPending: isLoadingExternalAuth } = useQuery({
...templateVersionExternalAuth(versionId ?? ""),
enabled: !!versionId,
refetchInterval: externalAuthPollingState === "polling" ? 1000 : false,
});

const allSignedIn = externalAuth?.every((it) => it.authenticated);

useEffect(() => {
if (allSignedIn) {
setExternalAuthPollingState("idle");
return;
}

if (externalAuthPollingState !== "polling") {
return;
}

// Poll for a maximum of one minute
const quitPolling = setTimeout(
() => setExternalAuthPollingState("abandoned"),
60_000,
);
return () => {
clearTimeout(quitPolling);
};
}, [externalAuthPollingState, allSignedIn]);

return {
startPollingExternalAuth,
externalAuth,
externalAuthPollingState,
isLoadingExternalAuth,
};
};

const getAutofillParameters = (
urlSearchParams: URLSearchParams,
userParameters: UserParameter[],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { Stack } from "components/Stack/Stack";
import { Switch } from "components/Switch/Switch";
import { UserAutocomplete } from "components/UserAutocomplete/UserAutocomplete";
import { type FormikContextType, useFormik } from "formik";
import type { ExternalAuthPollingState } from "hooks/useExternalAuth";
import { generateWorkspaceName } from "modules/workspaces/generateWorkspaceName";
import { type FC, useCallback, useEffect, useMemo, useState } from "react";
import {
Expand All @@ -40,10 +41,7 @@ import {
useValidationSchemaForRichParameters,
} from "utils/richParameters";
import * as Yup from "yup";
import type {
CreateWorkspaceMode,
ExternalAuthPollingState,
} from "./CreateWorkspacePage";
import type { CreateWorkspaceMode } from "./CreateWorkspacePage";
import { ExternalAuthButton } from "./ExternalAuthButton";
import type { CreateWorkspacePermissions } from "./permissions";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
} from "components/Tooltip/Tooltip";
import { UserAutocomplete } from "components/UserAutocomplete/UserAutocomplete";
import { type FormikContextType, useFormik } from "formik";
import type { ExternalAuthPollingState } from "hooks/useExternalAuth";
import { ArrowLeft, CircleHelp } from "lucide-react";
import { useSyncFormParameters } from "modules/hooks/useSyncFormParameters";
import { Diagnostics } from "modules/workspaces/DynamicParameter/DynamicParameter";
Expand All @@ -47,10 +48,7 @@ import { docs } from "utils/docs";
import { nameValidator } from "utils/formUtils";
import type { AutofillBuildParameter } from "utils/richParameters";
import * as Yup from "yup";
import type {
CreateWorkspaceMode,
ExternalAuthPollingState,
} from "./CreateWorkspacePage";
import type { CreateWorkspaceMode } from "./CreateWorkspacePage";
import { ExternalAuthButton } from "./ExternalAuthButton";
import type { CreateWorkspacePermissions } from "./permissions";

Expand Down
108 changes: 107 additions & 1 deletion site/src/pages/TasksPage/TasksPage.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { Meta, StoryObj } from "@storybook/react";
import { expect, spyOn, userEvent, within } from "@storybook/test";
import { expect, spyOn, userEvent, waitFor, within } from "@storybook/test";
import { API } from "api/api";
import { MockUsers } from "pages/UsersPage/storybookData/users";
import {
MockTemplate,
MockTemplateVersionExternalAuthGithub,
MockTemplateVersionExternalAuthGithubAuthenticated,
MockUserOwner,
MockWorkspace,
MockWorkspaceAppStatus,
Expand All @@ -27,10 +29,20 @@ const meta: Meta<typeof TasksPage> = {
},
},
beforeEach: () => {
spyOn(API, "getTemplateVersionExternalAuth").mockResolvedValue([]);
spyOn(API, "getUsers").mockResolvedValue({
users: MockUsers,
count: MockUsers.length,
});
spyOn(data, "fetchAITemplates").mockResolvedValue([
MockTemplate,
{
...MockTemplate,
id: "test-template-2",
name: "template 2",
display_name: "Template 2",
},
]);
},
};

Expand Down Expand Up @@ -134,6 +146,7 @@ export const CreateTaskSuccessfully: Story = {
const prompt = await canvas.findByLabelText(/prompt/i);
await userEvent.type(prompt, newTaskData.prompt);
const submitButton = canvas.getByRole("button", { name: /run task/i });
await waitFor(() => expect(submitButton).toBeEnabled());
await userEvent.click(submitButton);
});

Expand Down Expand Up @@ -164,6 +177,7 @@ export const CreateTaskError: Story = {
const prompt = await canvas.findByLabelText(/prompt/i);
await userEvent.type(prompt, "Create a new task");
const submitButton = canvas.getByRole("button", { name: /run task/i });
await waitFor(() => expect(submitButton).toBeEnabled());
await userEvent.click(submitButton);
});

Expand All @@ -173,6 +187,98 @@ export const CreateTaskError: Story = {
},
};

export const WithExternalAuth: Story = {
decorators: [withProxyProvider()],
beforeEach: () => {
spyOn(data, "fetchTasks")
.mockResolvedValueOnce(MockTasks)
.mockResolvedValue([newTaskData, ...MockTasks]);
spyOn(data, "createTask").mockResolvedValue(newTaskData);
spyOn(API, "getTemplateVersionExternalAuth").mockResolvedValue([
MockTemplateVersionExternalAuthGithubAuthenticated,
]);
},
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);

await step("Run task", async () => {
const prompt = await canvas.findByLabelText(/prompt/i);
await userEvent.type(prompt, newTaskData.prompt);
const submitButton = canvas.getByRole("button", { name: /run task/i });
await waitFor(() => expect(submitButton).toBeEnabled());
await userEvent.click(submitButton);
});

await step("Verify task in the table", async () => {
await canvas.findByRole("row", {
name: new RegExp(newTaskData.prompt, "i"),
});
});

await step("Does not render external auth", async () => {
expect(
canvas.queryByText(/external authentication/),
).not.toBeInTheDocument();
});
},
};

export const MissingExternalAuth: Story = {
decorators: [withProxyProvider()],
beforeEach: () => {
spyOn(data, "fetchTasks")
.mockResolvedValueOnce(MockTasks)
.mockResolvedValue([newTaskData, ...MockTasks]);
spyOn(data, "createTask").mockResolvedValue(newTaskData);
spyOn(API, "getTemplateVersionExternalAuth").mockResolvedValue([
MockTemplateVersionExternalAuthGithub,
]);
},
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);

await step("Submit is disabled", async () => {
const prompt = await canvas.findByLabelText(/prompt/i);
await userEvent.type(prompt, newTaskData.prompt);
const submitButton = canvas.getByRole("button", { name: /run task/i });
expect(submitButton).toBeDisabled();
});

await step("Renders external authentication", async () => {
await canvas.findByRole("button", { name: /login with github/i });
});
},
};

export const ExternalAuthError: Story = {
decorators: [withProxyProvider()],
beforeEach: () => {
spyOn(data, "fetchTasks")
.mockResolvedValueOnce(MockTasks)
.mockResolvedValue([newTaskData, ...MockTasks]);
spyOn(data, "createTask").mockResolvedValue(newTaskData);
spyOn(API, "getTemplateVersionExternalAuth").mockRejectedValue(
mockApiError({
message: "Failed to load external auth",
}),
);
},
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);

await step("Submit is disabled", async () => {
const prompt = await canvas.findByLabelText(/prompt/i);
await userEvent.type(prompt, newTaskData.prompt);
const submitButton = canvas.getByRole("button", { name: /run task/i });
expect(submitButton).toBeDisabled();
});

await step("Renders error", async () => {
await canvas.findByText(/failed to load external auth/i);
});
},
};

export const NonAdmin: Story = {
decorators: [withProxyProvider()],
parameters: {
Expand Down
Loading
Loading