Skip to content

fix: only show editable orgs on deployment page #14193

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 14 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
151 changes: 106 additions & 45 deletions site/src/api/queries/organizations.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import type { QueryClient } from "react-query";
import { API } from "api/api";
import type {
AuthorizationCheck,
AuthorizationResponse,
CreateOrganizationRequest,
Organization,
UpdateOrganizationRequest,
} from "api/typesGenerated";
import { meKey } from "./users";
Expand Down Expand Up @@ -121,6 +124,60 @@ export const provisionerDaemons = (organization: string) => {
};
};

const orgChecks = (
organizationId: string,
): Record<string, AuthorizationCheck> => ({
viewMembers: {
object: {
resource_type: "organization_member",
organization_id: organizationId,
},
action: "read",
},
editMembers: {
object: {
resource_type: "organization_member",
organization_id: organizationId,
},
action: "update",
},
createGroup: {
object: {
resource_type: "group",
organization_id: organizationId,
},
action: "create",
},
viewGroups: {
object: {
resource_type: "group",
organization_id: organizationId,
},
action: "read",
},
editGroups: {
object: {
resource_type: "group",
organization_id: organizationId,
},
action: "update",
},
editOrganization: {
object: {
resource_type: "organization",
organization_id: organizationId,
},
action: "update",
},
auditOrganization: {
object: {
resource_type: "audit_log",
organization_id: organizationId,
},
action: "read",
},
});

/**
* Fetch permissions for a single organization.
*
Expand All @@ -133,51 +190,55 @@ export const organizationPermissions = (organizationId: string | undefined) => {
return {
queryKey: ["organization", organizationId, "permissions"],
queryFn: () =>
API.checkAuthorization({
checks: {
viewMembers: {
object: {
resource_type: "organization_member",
organization_id: organizationId,
},
action: "read",
},
editMembers: {
object: {
resource_type: "organization_member",
organization_id: organizationId,
},
action: "update",
},
createGroup: {
object: {
resource_type: "group",
organization_id: organizationId,
},
action: "create",
},
viewGroups: {
object: {
resource_type: "group",
organization_id: organizationId,
},
action: "read",
},
editOrganization: {
object: {
resource_type: "organization",
organization_id: organizationId,
},
action: "update",
},
auditOrganization: {
object: {
resource_type: "audit_log",
organization_id: organizationId,
},
action: "read",
},
API.checkAuthorization({ checks: orgChecks(organizationId) }),
};
};

/**
* Fetch permissions for all provided organizations.
*
* If organizations are undefined, return a disabled query.
*/
export const organizationsPermissions = (
organizations: Organization[] | undefined,
) => {
if (!organizations) {
return { enabled: false };
}

return {
queryKey: ["organizations", "permissions"],
queryFn: async () => {
// The endpoint takes a flat array, so to avoid collisions prepend each
// check with the org ID (the key can be anything we want).
const checks = organizations
.map((org) =>
Object.entries(orgChecks(org.id)).map(([key, val]) => [
`${org.id}.${key}`,
val,
]),
)
.flat();

const response = await API.checkAuthorization({
checks: Object.fromEntries(checks),
});

// Now we can unflatten by parsing out the org ID from each check.
return Object.entries(response).reduce(
(acc, [key, value]) => {
const index = key.indexOf(".");
const orgId = key.substring(0, index);
const perm = key.substring(index + 1);
if (!acc[orgId]) {
acc[orgId] = { [perm]: value };
} else {
acc[orgId][perm] = value;
}
return acc;
},
}),
{} as Record<string, AuthorizationResponse>,
);
},
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { type FC, Suspense } from "react";
import { useQuery } from "react-query";
import { Outlet } from "react-router-dom";
import { deploymentConfig } from "api/queries/deployment";
import type { Organization } from "api/typesGenerated";
import type { AuthorizationResponse, Organization } from "api/typesGenerated";
import { Loader } from "components/Loader/Loader";
import { Margins } from "components/Margins/Margins";
import { Stack } from "components/Stack/Stack";
Expand All @@ -21,6 +21,20 @@ export const useOrganizationSettings = (): OrganizationSettingsValue => {
return { organizations };
};

/**
* Return true if the user can edit the organization settings or its members.
*/
export const canEditOrganization = (
permissions: AuthorizationResponse | undefined,
) => {
return (
permissions &&
(permissions.editOrganization ||
permissions.editMembers ||
permissions.editGroups)
);
};

/**
* A multi-org capable settings page layout.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { screen, within } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import {
MockDefaultOrganization,
MockOrganization2,
} from "testHelpers/entities";
import {
renderWithManagementSettingsLayout,
waitForLoaderToBeRemoved,
} from "testHelpers/renderHelpers";
import { server } from "testHelpers/server";
import OrganizationSettingsPage from "./OrganizationSettingsPage";

jest.spyOn(console, "error").mockImplementation(() => {});

const renderRootPage = async () => {
renderWithManagementSettingsLayout(<OrganizationSettingsPage />, {
route: "/organizations",
path: "/organizations",
extraRoutes: [
{
path: "/organizations/:organization",
element: <OrganizationSettingsPage />,
},
],
});
await waitForLoaderToBeRemoved();
};

const renderPage = async (orgName: string) => {
renderWithManagementSettingsLayout(<OrganizationSettingsPage />, {
route: `/organizations/${orgName}`,
path: "/organizations/:organization",
});
await waitForLoaderToBeRemoved();
};

describe("OrganizationSettingsPage", () => {
it("has no organizations", async () => {
server.use(
http.get("/api/v2/organizations", () => {
return HttpResponse.json([]);
}),
http.post("/api/v2/authcheck", async () => {
return HttpResponse.json({
[`${MockDefaultOrganization.id}.editOrganization`]: true,
viewDeploymentValues: true,
});
}),
);
await renderRootPage();
await screen.findByText("No organizations found");
});

it("has no editable organizations", async () => {
server.use(
http.get("/api/v2/organizations", () => {
return HttpResponse.json([MockDefaultOrganization, MockOrganization2]);
}),
http.post("/api/v2/authcheck", async () => {
return HttpResponse.json({
viewDeploymentValues: true,
});
}),
);
await renderRootPage();
await screen.findByText("No organizations found");
});

it("redirects to default organization", async () => {
server.use(
http.get("/api/v2/organizations", () => {
// Default always preferred regardless of order.
return HttpResponse.json([MockOrganization2, MockDefaultOrganization]);
}),
http.post("/api/v2/authcheck", async () => {
return HttpResponse.json({
[`${MockDefaultOrganization.id}.editOrganization`]: true,
[`${MockOrganization2.id}.editOrganization`]: true,
viewDeploymentValues: true,
});
}),
);
await renderRootPage();
const form = screen.getByTestId("org-settings-form");
expect(within(form).getByRole("textbox", { name: "Name" })).toHaveValue(
MockDefaultOrganization.name,
);
});

it("redirects to non-default organization", async () => {
server.use(
http.get("/api/v2/organizations", () => {
return HttpResponse.json([MockDefaultOrganization, MockOrganization2]);
}),
http.post("/api/v2/authcheck", async () => {
return HttpResponse.json({
[`${MockOrganization2.id}.editOrganization`]: true,
viewDeploymentValues: true,
});
}),
);
await renderRootPage();
const form = screen.getByTestId("org-settings-form");
expect(within(form).getByRole("textbox", { name: "Name" })).toHaveValue(
MockOrganization2.name,
);
});

it("cannot find organization", async () => {
server.use(
http.get("/api/v2/organizations", () => {
return HttpResponse.json([MockDefaultOrganization, MockOrganization2]);
}),
http.post("/api/v2/authcheck", async () => {
return HttpResponse.json({
[`${MockOrganization2.id}.editOrganization`]: true,
viewDeploymentValues: true,
});
}),
);
await renderPage("the-endless-void");
await screen.findByText("Organization not found");
});
});
Loading
Loading