litellm/ui/litellm-dashboard/src/components/model_add/GithubCopilotConnectModal.integration.test.tsx
Yassin Kortam d36b66e19e
feat(github_copilot): per-user GitHub OAuth connections for Copilot credentials (#45241)
* feat(github_copilot): per-user GitHub OAuth connections for Copilot credentials

Related to LIT-9306

* fix(ui): make per-user GitHub Copilot OAuth credential-only in Add Model

* fix(proxy): render LiteLLM_UserProviderCredentials prisma spans

* style(ui): prettier-format add_model tests

* fix(lint): annotate connection endpoints and narrow per-user credential excepts

* fix(lint): satisfy type-discipline gate for per-user copilot code

* fix(types): clear basedpyright and strict-lint gate regressions

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(types): keep runtime guards on untyped responses input

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* style: ruff format per-user Copilot files

* fix(lint): keep type-discipline suppressions on flagged lines

* fix(github_copilot): resolve team and deployment-id per-user routes, share token cache invalidation

* test(github_copilot): scope response-cache mutation via monkeypatch, assert route allowlist

* fix(github_copilot): fall back to the database on Redis errors and skip worker-local token caching

* fix(lint): suppress mutable return annotation after base merge

* style: shorten rebind-ok reason so the dispatch line stays formatted

* fix(github_copilot): harden per-user token cache, overrides, fallbacks, headers and device flow

* fix(lint): suppress MutableMapping param on session auth pinning

* test(github_copilot): narrow pytest.raises to HTTPException for service-key override

* fix(github_copilot): fail closed on revoke errors, strip caller auth headers, widen fallback discovery

* fix(github_copilot): verify revoke tombstone, bound fallback discovery, cover aliased fallbacks

* fix(github_copilot): make fallback discovery a router superset and guard credential override at deployment

* style(router): drop explanatory comment on per-user credential guard

* fix(github_copilot): gate fallback discovery on per-user credentials and bound aggregate targets

* fix(github_copilot): count every fallback mapping toward the discovery limit

* fix(github_copilot): suppress banned typing cast imports with per-line reasons

* test(github_copilot): cover per-user 401 cooldown skip through the router failure callback

* test(github_copilot): cover per-user 401 cooldown skip through router and fallback paths

* fix(github_copilot): cover auto-router discovery, per-user fallback cooldown and connect cache race

* fix(github_copilot): cover every strategy router kind and verify the connect cache write

* fix merge conflict marker remnant in credential endpoint tests

* fix(github_copilot): do not purge user connections on label-only credential updates

* fix(github_copilot): read user provider credentials from the writer engine

* test(github_copilot): move per-user auth type form test to the integration tier

* test(github_copilot): annotate new credential regression test locals as Final

* fix(github_copilot): type per-user OAuth JSON and DB boundaries

* fix(github_copilot): validate per-user OAuth boundaries and restore truncated comments

* style(github_copilot): complete cut-off suppression reasons on new casts

* refactor(github_copilot): annotate new boundary-typing locals as Final

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-09 15:19:07 -07:00

126 lines
4.8 KiB
TypeScript

import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import GithubCopilotConnectModal from "./GithubCopilotConnectModal";
const networking = vi.hoisted(() => ({
userConnectionStartCall: vi.fn(),
userConnectionPollCall: vi.fn(),
}));
vi.mock("@/components/networking", () => networking);
vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({ default: () => ({ accessToken: "session-token" }) }));
const START_RESPONSE = {
user_code: "ABCD-1234",
verification_uri: "https://github.com/login/device",
expires_in: 900,
interval: 5,
flow_handle: "fh-1",
};
const renderModal = () => {
const props = { onClose: vi.fn(), onConnected: vi.fn(), onDisconnect: vi.fn() };
render(<GithubCopilotConnectModal credentialName="copilot-per-user" {...props} />);
return props;
};
const advance = async (seconds: number) => {
await act(async () => {
await vi.advanceTimersByTimeAsync(seconds * 1000);
});
};
describe("GithubCopilotConnectModal", () => {
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: false });
networking.userConnectionStartCall.mockReset().mockResolvedValue(START_RESPONSE);
networking.userConnectionPollCall.mockReset();
});
afterEach(() => {
vi.useRealTimers();
});
it("shows the device code and link, polls at the given interval, honours slow_down and ends connected", async () => {
networking.userConnectionPollCall
.mockResolvedValueOnce({ status: "pending" })
.mockResolvedValueOnce({ status: "slow_down", interval: 10 })
.mockResolvedValueOnce({ status: "connected", github_login: "octocat" });
const props = renderModal();
await advance(0);
expect(networking.userConnectionStartCall).toHaveBeenCalledWith("session-token", "copilot-per-user");
expect(screen.getByTestId("github-device-code")).toHaveTextContent("ABCD-1234");
expect(screen.getByRole("link", { name: "https://github.com/login/device" })).toHaveAttribute(
"href",
"https://github.com/login/device",
);
await advance(4.9);
expect(networking.userConnectionPollCall).not.toHaveBeenCalled();
await advance(0.1);
expect(networking.userConnectionPollCall).toHaveBeenCalledTimes(1);
expect(networking.userConnectionPollCall).toHaveBeenCalledWith("session-token", "copilot-per-user", "fh-1");
await advance(5);
expect(networking.userConnectionPollCall).toHaveBeenCalledTimes(2);
await advance(9.9);
expect(networking.userConnectionPollCall).toHaveBeenCalledTimes(2);
await advance(0.1);
expect(networking.userConnectionPollCall).toHaveBeenCalledTimes(3);
expect(screen.getByText("Connected as @octocat")).toBeInTheDocument();
expect(props.onConnected).toHaveBeenCalledTimes(1);
await advance(30);
expect(networking.userConnectionPollCall).toHaveBeenCalledTimes(3);
fireEvent.click(screen.getByRole("button", { name: "Disconnect" }));
expect(props.onDisconnect).toHaveBeenCalledTimes(1);
});
it("stops polling and offers a restart when the device code expires", async () => {
networking.userConnectionStartCall.mockResolvedValue({ ...START_RESPONSE, expires_in: 12 });
networking.userConnectionPollCall.mockResolvedValue({ status: "pending" });
renderModal();
await advance(0);
await advance(5);
await advance(5);
await advance(5);
expect(networking.userConnectionPollCall).toHaveBeenCalledTimes(2);
expect(screen.getByRole("alert")).toHaveTextContent("The device code expired");
await advance(30);
expect(networking.userConnectionPollCall).toHaveBeenCalledTimes(2);
fireEvent.click(screen.getByRole("button", { name: "Start again" }));
await advance(0);
expect(networking.userConnectionStartCall).toHaveBeenCalledTimes(2);
expect(screen.getByTestId("github-device-code")).toBeInTheDocument();
});
it.each([
["denied", "denied on GitHub"],
["no_copilot_seat", "does not have GitHub Copilot access"],
["expired", "The device code expired"],
])("shows the %s error and stops polling", async (status, message) => {
networking.userConnectionPollCall.mockResolvedValue({ status });
const props = renderModal();
await advance(0);
await advance(5);
expect(screen.getByRole("alert")).toHaveTextContent(message);
expect(props.onConnected).not.toHaveBeenCalled();
await advance(30);
expect(networking.userConnectionPollCall).toHaveBeenCalledTimes(1);
});
it("shows the proxy error when the start request fails", async () => {
networking.userConnectionStartCall.mockRejectedValue(new Error("Credential not found"));
renderModal();
await advance(0);
expect(screen.getByRole("alert")).toHaveTextContent("Credential not found");
expect(networking.userConnectionPollCall).not.toHaveBeenCalled();
});
});