-
Notifications
You must be signed in to change notification settings - Fork 413
[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
Draft
eblairmckee
wants to merge
2
commits into
master
Choose a base branch
from
fix/ux-902
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,162
−398
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
46 changes: 46 additions & 0 deletions
46
frontend/src/components/pages/acls/user-create-form-schema.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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: [], | ||
| }; | ||
233 changes: 233 additions & 0 deletions
233
frontend/src/components/pages/acls/user-create.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.