Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
30 changes: 20 additions & 10 deletions web/services/vms/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -810,34 +810,44 @@ async function resolveStackTeamMembership(
};
}
const requestedTeamId = normalizedOptionalString(options.requestedTeamId);
// Full pagination is reserved for the explicit team-picker route. Other
// callers resolve one requested team with Stack's exact-ID search so shared
// VM authentication never inherits an unbounded multi-page dependency.
// Stack may return only the selected team's ID. Resolve its details before
// choosing billing, or paid members inherit the user's free plan instead.
const selectedTeamNeedsDetails = !!selectedTeam && selectedTeam.clientReadOnlyMetadata === undefined;
const teamIdsToLookup = uniqueStrings([
requestedTeamId && requestedTeamId !== selectedTeam?.id ? requestedTeamId : undefined,
selectedTeamNeedsDetails ? selectedTeam.id : undefined,
]);
// Snapshot-capable callers need a complete paginated list. Bounded
// subrouter callers resolve only the requested and selected IDs so shared VM
// authentication does not inherit an unbounded multi-page dependency.
const needsListedTeams = options.forceCompleteTeamList === true ||
!selectedTeam ||
(!!requestedTeamId && requestedTeamId !== selectedTeam.id);
teamIdsToLookup.length > 0;
// Whether the branch taken below enumerates every team the user belongs to.
// Only that case may be stored as an identity snapshot.
const completeTeamList = options.subrouterAuthorizationSignal === undefined
? needsListedTeams && typeof user.listTeams === "function"
: options.listAllTeams === true;
const listedTeamRaw = options.subrouterAuthorizationSignal === undefined
? completeTeamList
? await user.listTeams!()
? await listAllStackTeams(user, undefined)
Comment thread
teamleaderleo marked this conversation as resolved.
Resolved
: []
: options.listAllTeams === true
? await listAllStackTeams(user, options.subrouterAuthorizationSignal)
: requestedTeamId && requestedTeamId !== selectedTeam?.id
? await findStackTeam(
: teamIdsToLookup.length > 0
? (await Promise.all(teamIdsToLookup.map((teamId) => findStackTeam(
user,
requestedTeamId,
teamId,
options.subrouterAuthorizationSignal,
)
)))).flat()
: [];
const listedTeams = listedTeamRaw
.map(billingTeamFromUnknown)
.filter((team): team is BillingTeamLike => !!team);
return { selectedTeam, listedTeams, completeTeamList };
const resolvedSelectedTeam = selectedTeamNeedsDetails
? listedTeams.find((team) => team.id === selectedTeam.id) ?? selectedTeam
: selectedTeam;
return { selectedTeam: resolvedSelectedTeam, listedTeams, completeTeamList };
}

async function authedUserFromStackUser(
Expand Down
98 changes: 98 additions & 0 deletions web/tests/vm-route-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,104 @@ describe("VM REST auth", () => {
expect(runVmWorkflow).toHaveBeenCalled();
});

test.each(["cookie", "native"])("hydrates an ID-only selected team for paid VM list limits (%s)", async (auth) => {
const listTeams = mock(async () => [
{ id: "team-other", clientReadOnlyMetadata: { cmuxVmPlan: "free" } },
{ id: "team-1", displayName: "Paid team", clientReadOnlyMetadata: { cmuxPlan: "team", cmuxSeats: 4 } },
]);
getUser.mockResolvedValue({
...authedStackUser(),
clientReadOnlyMetadata: { cmuxPlan: "free" },
selectedTeam: { id: "team-1" },
listTeams,
});
runVmWorkflow.mockResolvedValue([{
providerVmId: "provider-vm-team-1", provider: "freestyle",
image: "snapshot-test", status: "running", createdAt: 1_777_000_000_000,
}]);

const response = await GET(new Request("https://cmux.test/api/vm", {
headers: auth === "native" ? {
authorization: "Bearer access-token", "x-stack-refresh-token": "refresh-token",
} : {},
}));

expect(response.status).toBe(200);
expect(await response.json()).toMatchObject({
limits: { planId: "team", maxActiveVms: 200, activeVmCount: 1, freeAccessWindowDays: 0, freeAccessExpiresAt: null },
vms: [{ freeAccessExpiresAt: null }],
});
expect(listUserVms).toHaveBeenCalledWith("user-1", "team-1");
expect(listTeams).toHaveBeenCalledTimes(1);
});

test.each([undefined, "team-1"])("hydrates an ID-only selected team with bounded auth (requested %s)", async (requestedTeamId) => {
const listTeams = mock(async () => [{
id: "team-1", displayName: "Paid team",
clientReadOnlyMetadata: { cmuxPlan: "team", cmuxSeats: 4 },
}]);
getUser.mockResolvedValue({ ...authedStackUser(), selectedTeam: { id: "team-1" }, listTeams });

const user = await verifyRequest(new Request("https://cmux.test/api/vm"), {
requestedTeamId, subrouterAuthorizationSignal: new AbortController().signal,
});

expect(user).toMatchObject({
billingTeamId: "team-1", billingPlanId: "team", billingSeats: 4,
selectedTeamId: "team-1",
teams: [{ id: "team-1", displayName: "Paid team", billingPlanId: "team", billingSeats: 4 }],
});
expect(listTeams).toHaveBeenCalledWith({ query: "team-1", limit: 100 });
expect(listTeams).toHaveBeenCalledTimes(1);
});

test("hydrates the ID-only selected team even when bounded auth requests another team", async () => {
const listTeams = mock(async (options?: { query?: string }) => options?.query === "team-other"
? [{ id: "team-other", clientReadOnlyMetadata: { cmuxVmPlan: "free" } }]
: [{ id: "team-1", displayName: "Paid team", clientReadOnlyMetadata: { cmuxPlan: "team", cmuxSeats: 4 } }]);
getUser.mockResolvedValue({
...authedStackUser(),
clientReadOnlyMetadata: { cmuxPlan: "free" },
selectedTeam: { id: "team-1" },
listTeams,
});

const user = await verifyRequest(new Request("https://cmux.test/api/vm"), {
requestedTeamId: "team-other",
subrouterAuthorizationSignal: new AbortController().signal,
});

expect(user).toMatchObject({ billingTeamId: "team-1", billingPlanId: "team", billingSeats: 4 });
expect(listTeams).toHaveBeenNthCalledWith(1, { query: "team-other", limit: 100 });
expect(listTeams).toHaveBeenNthCalledWith(2, { query: "team-1", limit: 100 });
});

test("paginates complete membership when hydrating an ID-only selected team", async () => {
const listTeams = mock(async (options?: { cursor?: string }) => options?.cursor === "page-2"
? [{ id: "team-second", clientReadOnlyMetadata: { cmuxVmPlan: "free" } }]
: Object.assign([{ id: "team-1", clientReadOnlyMetadata: { cmuxPlan: "team" } }], { nextCursor: "page-2" }));
getUser.mockResolvedValue({ ...authedStackUser(), selectedTeam: { id: "team-1" }, listTeams });

const user = await verifyRequest(new Request("https://cmux.test/api/vm"));

expect(user?.teamIds).toEqual(["team-1", "team-second"]);
expect(listTeams).toHaveBeenNthCalledWith(1, { cursor: undefined, limit: 100 });
expect(listTeams).toHaveBeenNthCalledWith(2, { cursor: "page-2", limit: 100 });
});

test("does not borrow another paid team's details when the selected team is absent from the lookup", async () => {
getUser.mockResolvedValue({
...authedStackUser(),
clientReadOnlyMetadata: { cmuxPlan: "free" },
selectedTeam: { id: "team-1" },
listTeams: async () => [{ id: "team-other", clientReadOnlyMetadata: { cmuxPlan: "team", cmuxSeats: 4 } }],
});

const user = await verifyRequest(new Request("https://cmux.test/api/vm"));

expect(user).toMatchObject({ billingTeamId: "team-1", billingPlanId: "free", billingSeats: null });
});

test("tunnel POST and GET forward the complete fresh membership, not only the selected team", async () => {
const user = authedStackUser();
getUser.mockResolvedValue({
Expand Down
Loading