Skip to content
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

feat(subnets): Add support for reserved IPv6 addresses MAASENG-3162 #5453

Merged
merged 8 commits into from
Jun 7, 2024
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
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@
"history": "5.3.0",
"http-proxy-middleware": "2.0.6",
"human-interval": "2.0.1",
"ipaddr.js": "2.2.0",
"is-ip": "5.0.1",
"js-file-download": "0.4.12",
"path-parse": "1.0.7",
"pluralize": "8.0.0",
Expand Down
47 changes: 44 additions & 3 deletions src/app/base/components/PrefixedIpInput/PrefixedIpInput.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,19 @@ import PrefixedIpInput from "./PrefixedIpInput";

import { renderWithBrowserRouter } from "@/testing/utils";

it("displays the correct range help text for a subnet", () => {
it("displays the correct range help text for an IPv4 subnet", () => {
render(
<Formik initialValues={{}} onSubmit={vi.fn()}>
<PrefixedIpInput cidr="10.0.0.0/24" name="ip" />
</Formik>
);
expect(
screen.getByText(/The available range in this subnet is/i)
).toBeInTheDocument();
expect(screen.getByText("10.0.0.[1-254]")).toBeInTheDocument();
});

it("displays the correct placeholder for a subnet", () => {
it("displays the correct placeholder for an IPv4 subnet", () => {
render(
<Formik initialValues={{}} onSubmit={vi.fn()}>
<PrefixedIpInput cidr="10.0.0.0/24" name="ip" />
Expand All @@ -29,7 +32,32 @@ it("displays the correct placeholder for a subnet", () => {
expect(screen.getByRole("textbox")).toHaveAttribute("placeholder", "[1-254]");
});

it("trims the immutable octets from a pasted IP address", async () => {
it("hides the range help text for an IPv6 subnet", () => {
render(
<Formik initialValues={{}} onSubmit={vi.fn()}>
<PrefixedIpInput cidr="2001:db8::/32" name="ip" />
</Formik>
);

expect(
screen.queryByText(/The available range in this subnet is/i)
).not.toBeInTheDocument();
});

it("displays the correct placeholder for an IPv6 subnet", () => {
render(
<Formik initialValues={{}} onSubmit={vi.fn()}>
<PrefixedIpInput cidr="2001:db8::/32" name="ip" />
</Formik>
);

expect(screen.getByRole("textbox")).toHaveAttribute(
"placeholder",
"0000:0000:0000:0000:0000:0000"
);
});

it("trims the immutable octets from a pasted IPv4 address", async () => {
renderWithBrowserRouter(
<FormikForm initialValues={{ ip: "" }} onSubmit={vi.fn()}>
<FormikField cidr="10.0.0.0/24" component={PrefixedIpInput} name="ip" />
Expand All @@ -41,3 +69,16 @@ it("trims the immutable octets from a pasted IP address", async () => {

expect(screen.getByRole("textbox")).toHaveValue("1");
});

it("trims the network address and subnet ID from a pasted IPv6 address", async () => {
renderWithBrowserRouter(
<FormikForm initialValues={{ ip: "" }} onSubmit={vi.fn()}>
<FormikField cidr="2001:db8::/32" component={PrefixedIpInput} name="ip" />
</FormikForm>
);

await userEvent.click(screen.getByRole("textbox"));
await userEvent.paste("2001:db8::1");

expect(screen.getByRole("textbox")).toHaveValue(":1");
});
69 changes: 46 additions & 23 deletions src/app/base/components/PrefixedIpInput/PrefixedIpInput.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import type { ClipboardEvent } from "react";

import { useFormikContext } from "formik";
import { isIPv4 } from "is-ip";

import PrefixedInput from "../PrefixedInput";
import type { PrefixedInputProps } from "../PrefixedInput/PrefixedInput";
Expand All @@ -18,46 +21,66 @@ type Props = Omit<
};

const PrefixedIpInput = ({ cidr, name, ...props }: Props) => {
const [networkAddress] = cidr.split("/");
const ipv6Prefix = networkAddress.substring(
0,
networkAddress.lastIndexOf(":")
);
const subnetIsIpv4 = isIPv4(networkAddress);

const [startIp, endIp] = getIpRangeFromCidr(cidr);
const [immutable, editable] = getImmutableAndEditableOctets(startIp, endIp);

const formikProps = useFormikContext();

const getMaxLength = () => {
const getIPv6Placeholder = () => {
// 7 is the maximum number of colons in an IPv6 address
const placeholderColons = 7 - (ipv6Prefix.match(/:/g) || []).length;
return `${"0000:".repeat(placeholderColons)}0000`;
};

const getPlaceholderText = () =>
subnetIsIpv4 ? editable : getIPv6Placeholder();

const getIPv4MaxLength = () => {
const immutableOctetsLength = immutable.split(".").length;
const lengths = [15, 11, 7, 3]; // Corresponding to 0-3 immutable octets
return lengths[immutableOctetsLength];
};

const getMaxLength = () =>
subnetIsIpv4 ? getIPv4MaxLength() : getIPv6Placeholder().length;

if (immutableOctetsLength === 3) {
return 3; // 3 digits, no dots
} else if (immutableOctetsLength === 2) {
return 7; // 6 digits, 1 dot
} else if (immutableOctetsLength === 1) {
return 11; // 9 digits, 2 dots
const handlePaste = (e: ClipboardEvent<HTMLInputElement>) => {
e.preventDefault();
const pastedText = e.clipboardData.getData("text");
if (subnetIsIpv4) {
const octets = pastedText.split(".");
const trimmed = octets.slice(0 - editable.split(".").length);
formikProps.setFieldValue(name, trimmed.join("."));
} else {
return 15; // 12 digits, 3 dots
const interfaceId = pastedText.replace(ipv6Prefix, "");
formikProps.setFieldValue(name, interfaceId);
}
};

return (
<PrefixedInput
help={
<>
The available range in this subnet is{" "}
<code>
{immutable}.{editable}
</code>
</>
subnetIsIpv4 ? (
<>
The available range in this subnet is{" "}
<code>
{immutable}.{editable}
</code>
</>
) : null
}
immutableText={`${immutable}.`}
immutableText={subnetIsIpv4 ? `${immutable}.` : ipv6Prefix}
maxLength={getMaxLength()}
name={name}
onPaste={(e) => {
e.preventDefault();
const pastedText = e.clipboardData.getData("text");
const octets = pastedText.split(".");
const trimmed = octets.slice(0 - editable.split(".").length);
formikProps.setFieldValue(name, trimmed.join("."));
}}
placeholder={editable}
onPaste={handlePaste}
placeholder={getPlaceholderText()}
{...props}
/>
);
Expand Down
3 changes: 2 additions & 1 deletion src/app/store/reservedip/action.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ it("can create an action for creating a reserved IP", () => {
});

it("can create an action for deleting a reserved IP", () => {
expect(actions.delete(1)).toEqual({
expect(actions.delete({ id: 1, ip: "10.0.0.2" })).toEqual({
type: "reservedip/delete",
meta: {
model: "reservedip",
Expand All @@ -41,6 +41,7 @@ it("can create an action for deleting a reserved IP", () => {
payload: {
params: {
id: 1,
ip: "10.0.0.2",
},
},
});
Expand Down
4 changes: 3 additions & 1 deletion src/app/store/reservedip/reducers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,9 @@ describe("delete reducers", () => {
saving: true,
saved: false,
});
expect(reducers(initialState, actions.deleteSuccess({ id: 1 }))).toEqual(
expect(
reducers(initialState, actions.deleteSuccess({ id: 1, ip: "10.0.0.2" }))
).toEqual(
factory.reservedIpState({
saving: false,
saved: true,
Expand Down
12 changes: 12 additions & 0 deletions src/app/store/reservedip/slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ const reservedIpSlice = createSlice({
(state.items as ReservedIp[]).push(item);
}
},
delete: {
prepare: (params: DeleteParams) => ({
meta: {
model: ReservedIpMeta.MODEL,
method: "delete",
},
payload: {
params,
},
}),
reducer: () => {},
},
deleteSuccess: {
prepare: (params: DeleteParams) => ({
meta: {
Expand Down
1 change: 1 addition & 0 deletions src/app/store/reservedip/types/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ export type UpdateParams = Partial<CreateParams> & {

export type DeleteParams = {
[ReservedIpMeta.PK]: ReservedIp[ReservedIpMeta.PK];
ip: ReservedIp["ip"];
};
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ it("dispatches an action to delete a reserved IP", async () => {
payload: {
params: {
id: 1,
ip: state.reservedip.items[0].ip,
},
},
type: "reservedip/delete",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,20 @@ const DeleteDHCPLease = ({ setSidePanelContent, reservedIpId }: Props) => {

const handleClose = () => setSidePanelContent(null);

if (!reservedIpId) return null;

return (
<ModelActionForm
aria-label="Delete static IP"
cleanup={reservedIpActions.cleanup}
errors={errors}
initialValues={{}}
message={`Are you sure you want to delete ${reservedIp?.ip}? This action is permanent and cannot be undone.`}
modelType="static IP"
onCancel={handleClose}
onSubmit={() => {
dispatch(reservedIpActions.delete(reservedIpId));
reservedIp &&
dispatch(
reservedIpActions.delete({ id: reservedIp.id, ip: reservedIp.ip })
);
}}
onSuccess={handleClose}
saved={saved}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,38 @@ it("pre-fills the form if a reserved IP's ID is present", async () => {
);
});

it("pre-fills the form if a reserved IPv6 address's ID is present", async () => {
ndv99 marked this conversation as resolved.
Show resolved Hide resolved
const reservedIp = factory.reservedIp({
id: 1,
ip: "2001:db8::2",
mac_address: "FF:FF:FF:FF:FF:FF",
comment: "bla bla bla",
});
state.reservedip = factory.reservedIpState({
loading: false,
loaded: true,
items: [reservedIp],
});
state.subnet.items = [factory.subnet({ id: 1, cidr: "2001:db8::/64" })];

renderWithBrowserRouter(
<ReserveDHCPLease
reservedIpId={reservedIp.id}
setSidePanelContent={vi.fn()}
subnetId={state.subnet.items[0].id}
/>,
{ state }
);

expect(screen.getByRole("textbox", { name: "IP address" })).toHaveValue(":2");
expect(screen.getByRole("textbox", { name: "MAC address" })).toHaveValue(
reservedIp.mac_address
);
expect(screen.getByRole("textbox", { name: "Comment" })).toHaveValue(
reservedIp.comment
);
});

it("dispatches an action to update a reserved IP", async () => {
const reservedIp = factory.reservedIp({
id: 1,
Expand Down Expand Up @@ -223,3 +255,73 @@ it("dispatches an action to update a reserved IP", async () => {
type: "reservedip/update",
});
});

it("displays an error if an invalid IPv6 address is entered", async () => {
state.subnet.items = [factory.subnet({ id: 1, cidr: "2001:db8::/64" })];
renderWithBrowserRouter(
<ReserveDHCPLease
setSidePanelContent={vi.fn()}
subnetId={state.subnet.items[0].id}
/>,
{ state }
);

await userEvent.type(
screen.getByRole("textbox", { name: "IP address" }),
"420"
);
await userEvent.tab();

expect(
screen.getByText("This is not a valid IP address")
).toBeInTheDocument();
});

it("dispatches an action to create a reserved IPv6 address", async () => {
state.subnet.items = [factory.subnet({ id: 1, cidr: "2001:db8::/64" })];
const store = mockStore(state);
renderWithBrowserRouter(
<ReserveDHCPLease
setSidePanelContent={vi.fn()}
subnetId={state.subnet.items[0].id}
/>,
{ store }
);

await userEvent.type(
screen.getByRole("textbox", { name: "IP address" }),
":69"
);

await userEvent.type(
screen.getByRole("textbox", { name: "MAC address" }),
"FF:FF:FF:FF:FF:FF"
);

await userEvent.type(
screen.getByRole("textbox", { name: "Comment" }),
"bla bla bla"
);

await userEvent.click(
screen.getByRole("button", { name: "Reserve static DHCP lease" })
);

expect(
store.getActions().find((action) => action.type === "reservedip/create")
).toEqual({
meta: {
method: "create",
model: "reservedip",
},
payload: {
params: {
subnet: 1,
ip: "2001:db8::69",
mac_address: "FF:FF:FF:FF:FF:FF",
comment: "bla bla bla",
},
},
type: "reservedip/create",
});
});
Loading
Loading