Skip to content
Draft
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
46 changes: 46 additions & 0 deletions frontend/src/components/pages/acls/user-create-form-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* Copyright 2026 Redpanda Data, Inc.
*
* Use of this software is governed by the Business Source License
* included in the file https://github.com/redpanda-data/redpanda/blob/dev/licenses/bsl.md
*
* As of the Change Date specified in that file, in accordance with
* the Business Source License, use of this software will be governed
* by the Apache License, Version 2.0
*/

import { CreateUserRequest_UserSchema } from 'protogen/redpanda/api/dataplane/v1/user_pb';
import { protoToZodSchema } from 'utils/proto-constraints';
import { SASL_MECHANISMS, USERNAME_ERROR_MESSAGE, USERNAME_REGEX } from 'utils/user';
import { z } from 'zod';

/**
* Base schema derived from proto CreateUserRequest.User constraints:
* - name: string, min_len=1, max_len=128
* - password: string, min_len=3, max_len=128
* - mechanism: enum (numeric)
*/
const protoSchema = protoToZodSchema(CreateUserRequest_UserSchema);

export const createUserFormSchema = (existingUsers: string[]) =>
z.object({
// Proto provides min(1) + max(128), we add regex and uniqueness check
username: (protoSchema.shape.name as z.ZodString)
.regex(USERNAME_REGEX, USERNAME_ERROR_MESSAGE)
.refine((val) => !existingUsers.includes(val), 'User already exists'),
// Proto provides min(3) + max(128)
password: protoSchema.shape.password as z.ZodString,
// Keep as string enum for form UX (proto uses numeric enum)
mechanism: z.enum(SASL_MECHANISMS),
// Not in proto — frontend-only field for role assignment
roles: z.array(z.string()).default([]),
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any way we can get it working without casting such as as z.ZodString?

Ideally I would like to rely as much as possible on zod and protovaildate internals.

That being said, we need to discuss whether we go with:
a) merging the zod and protovalidate validation step and present the user with errors accordingly
b) 1st rely on the z.infer() handler where we get all the zod powered schema validation on every form change and then do a 2nd pass on protovalidate on submission? Ideally the 2 schemas should not be very far away from each other
c) have a dedicated package which would have the power to convert all protovalidate schemas to zod, but then we would lose on the protovalidate descriptive errors, so perhaps we may want to consolidate them. Just talking out loud

Personally I would be leaning towards the approach in Gateway where you have protovalidateResolver, but with the additional zod resolver.


export type UserCreateFormValues = z.infer<ReturnType<typeof createUserFormSchema>>;

export const initialValues: UserCreateFormValues = {
username: '',
password: '',
mechanism: 'SCRAM-SHA-256',
roles: [],
};
233 changes: 233 additions & 0 deletions frontend/src/components/pages/acls/user-create.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
/**
* Copyright 2026 Redpanda Data, Inc.
*
* Use of this software is governed by the Business Source License
* included in the file https://github.com/redpanda-data/redpanda/blob/dev/licenses/bsl.md
*
* As of the Change Date specified in that file, in accordance with
* the Business Source License, use of this software will be governed
* by the Apache License, Version 2.0
*/

import userEvent from '@testing-library/user-event';
import { fireEvent, renderWithFileRoutes, screen, waitFor } from 'test-utils';
import { beforeEach, describe, expect, test, vi } from 'vitest';

// Mock hooks
vi.mock('react-query/api/user', () => ({
useLegacyListUsersQuery: vi.fn(),
useCreateUserMutation: vi.fn(),
getSASLMechanism: vi.fn(() => 1),
}));

vi.mock('react-query/api/security', () => ({
useListRolesQuery: vi.fn(),
useUpdateRoleMembershipMutation: vi.fn(),
}));

vi.mock('state/supported-features', async (importOriginal) => {
const actual = await importOriginal<typeof import('state/supported-features')>();
return {
...actual,
Features: { rolesApi: false },
};
});

vi.mock('state/ui-state', () => ({
uiState: { pageTitle: '', pageBreadcrumbs: [] },
}));

vi.mock('sonner', () => ({
toast: { success: vi.fn(), error: vi.fn() },
}));

// Mock Radix tooltip — avoids context mismatch between radix-ui and @radix-ui/react-tooltip
vi.mock('components/redpanda-ui/components/tooltip', () => ({
Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
TooltipContent: () => null,
TooltipProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));

import React from 'react';
import { useListRolesQuery, useUpdateRoleMembershipMutation } from 'react-query/api/security';
import { useCreateUserMutation, useLegacyListUsersQuery } from 'react-query/api/user';

import UserCreatePage from './user-create';

// jsdom polyfills
global.ResizeObserver = class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
};
Element.prototype.scrollIntoView = vi.fn();

const renderPage = () => renderWithFileRoutes(<UserCreatePage />);

/** Find the password <input> inside the password Field wrapper. */
const getPasswordInput = () => {
const field = screen.getByTestId('create-user-password');
const input = field.querySelector('input');
if (!input) {
throw new Error('Password input not found');
}
return input;
};

describe('UserCreatePage', () => {
const mockCreateUserAsync = vi.fn().mockResolvedValue({});

beforeEach(() => {
vi.clearAllMocks();

vi.mocked(useLegacyListUsersQuery).mockReturnValue({
data: { users: [{ name: 'existing-user' }] },
isFetching: false,
error: null,
} as any);

vi.mocked(useCreateUserMutation).mockReturnValue({
mutateAsync: mockCreateUserAsync,
isPending: false,
} as any);

vi.mocked(useUpdateRoleMembershipMutation).mockReturnValue({
mutateAsync: vi.fn().mockResolvedValue({}),
isPending: false,
} as any);

vi.mocked(useListRolesQuery).mockReturnValue({
data: { roles: [] },
} as any);
});

describe('Username validation', () => {
test('shows error when username exceeds 128 characters', async () => {
renderPage();
const input = await screen.findByTestId('create-user-name');

fireEvent.change(input, { target: { value: 'a'.repeat(129) } });

await waitFor(() => {
expect(screen.getByText('Must not exceed 128 characters')).toBeInTheDocument();
});
});

test('accepts username at exactly 128 characters without max-length error', async () => {
renderPage();
const input = await screen.findByTestId('create-user-name');

fireEvent.change(input, { target: { value: 'a'.repeat(128) } });

await waitFor(() => {
expect(screen.queryByText('Must not exceed 128 characters')).not.toBeInTheDocument();
});
});

test('shows error for invalid characters (spaces)', async () => {
const user = userEvent.setup();
renderPage();
const input = await screen.findByTestId('create-user-name');

await user.type(input, 'user name');

await waitFor(() => {
expect(screen.getByRole('alert')).toHaveTextContent(/Must not contain any whitespace/);
});
});

test('shows error for duplicate username', async () => {
const user = userEvent.setup();
renderPage();
const input = await screen.findByTestId('create-user-name');

await user.type(input, 'existing-user');

await waitFor(() => {
expect(screen.getByText('User already exists')).toBeInTheDocument();
});
});
});

describe('Password validation', () => {
test('shows error when password is shorter than 3 characters', async () => {
const user = userEvent.setup();
renderPage();

await screen.findByTestId('create-user-name');
const passwordInput = getPasswordInput();

// Clear the auto-generated password and type a short one
await user.clear(passwordInput);
await user.type(passwordInput, 'ab');

await waitFor(() => {
expect(screen.getByText('Must be at least 3 characters')).toBeInTheDocument();
});
});

test('shows error when password exceeds 128 characters', async () => {
renderPage();

await screen.findByTestId('create-user-name');
const passwordInput = getPasswordInput();

fireEvent.change(passwordInput, { target: { value: 'a'.repeat(129) } });

await waitFor(() => {
expect(screen.getByText('Must not exceed 128 characters')).toBeInTheDocument();
});
});
});

describe('Form submission', () => {
test('submit button is disabled when username is empty', async () => {
renderPage();

await screen.findByTestId('create-user-name');

expect(screen.getByTestId('create-user-submit')).toBeDisabled();
});

test('creates user with valid form data', async () => {
const user = userEvent.setup();
renderPage();

const usernameInput = await screen.findByTestId('create-user-name');
await user.type(usernameInput, 'testuser');

const submitButton = screen.getByTestId('create-user-submit');
await waitFor(() => {
expect(submitButton).toBeEnabled();
});

await user.click(submitButton);

await waitFor(() => {
expect(mockCreateUserAsync).toHaveBeenCalledTimes(1);
});
});

test('shows confirmation page after successful creation', async () => {
const user = userEvent.setup();
renderPage();

const usernameInput = await screen.findByTestId('create-user-name');
await user.type(usernameInput, 'newuser');

const submitButton = screen.getByTestId('create-user-submit');
await waitFor(() => {
expect(submitButton).toBeEnabled();
});

await user.click(submitButton);

await waitFor(() => {
expect(screen.getByText('User created successfully')).toBeInTheDocument();
});

expect(screen.getByText('newuser')).toBeInTheDocument();
});
});
});
Loading
Loading