-
Notifications
You must be signed in to change notification settings - Fork 415
[UX-902] fix: create user client-side validation #2233
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
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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([]), | ||
| }); | ||
|
|
||
| export type UserCreateFormValues = z.infer<ReturnType<typeof createUserFormSchema>>; | ||
|
|
||
| export const initialValues: UserCreateFormValues = { | ||
| username: '', | ||
| password: '', | ||
| mechanism: 'SCRAM-SHA-256', | ||
| roles: [], | ||
| }; | ||
| 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() {} | ||
| }; | ||
|
Comment on lines
+58
to
+63
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If this is required, I would put it in the setup utils because it probably should be reused across tests. |
||
| 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); | ||
|
Comment on lines
+84
to
+102
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's use an approach such as const getAIAgentMock = vi.fn().mockReturnValue(getAIAgentResponse);
const transport = createRouterTransport(({ rpc }) => {
rpc(getAIAgent, getAIAgentMock);
});
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think if there is a REST endpoint it makes sense to mock the function for now (if we can't use connectRPC, connect RPC migration can be a separate PR too). For connect native RPC calls, let's use |
||
| }); | ||
|
|
||
| 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(); | ||
| }); | ||
| }); | ||
| }); | ||
There was a problem hiding this comment.
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
zodandprotovaildateinternals.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 otherc) 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.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Discussed with @eblairmckee, we can do this in a separate PR.