codeant-ai-for-open-source[bot] commented on code in PR #39469: URL: https://github.com/apache/superset/pull/39469#discussion_r3427049907
########## superset-frontend/src/utils/generateAuthDbPassword.ts: ########## @@ -0,0 +1,259 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +import { t } from '@apache-superset/core/translation'; +/** + * Client-side generator aligned with default ``AUTH_DB_CONFIG`` / Python + * ``superset.utils.auth_db_password`` (minimum length, character classes, common list). + * Keep ``AUTH_DB_COMMON_PASSWORDS`` in sync with ``_COMMON_PASSWORDS`` in that module. + */ +export const AUTH_DB_PASSWORD_MIN_LENGTH = 12; +export interface AuthDbPasswordPolicy { + password_min_length: number; + password_require_uppercase: boolean; + password_require_lowercase: boolean; + password_require_digit: boolean; + password_require_special: boolean; + password_common_list_check: boolean; +} + +export const AUTH_DB_DEFAULT_PASSWORD_POLICY: AuthDbPasswordPolicy = { + password_min_length: AUTH_DB_PASSWORD_MIN_LENGTH, + password_require_uppercase: true, + password_require_lowercase: true, + password_require_digit: true, + password_require_special: true, + password_common_list_check: true, +}; + +/** Lowercased entries; keep in sync with ``_COMMON_PASSWORDS`` in auth_db_password.py */ +const AUTH_DB_COMMON_PASSWORDS = new Set( + [ + 'password', + 'password1', + 'password123', + '123456', + '12345678', + '123456789', + 'qwerty', + 'abc123', + 'monkey', + 'letmein', + 'trustno1', + 'dragon', + 'baseball', + 'iloveyou', + 'master', + 'sunshine', + 'ashley', + 'bailey', + 'shadow', + 'superman', + 'qazwsx', + 'michael', + 'football', + 'welcome', + 'jesus', + 'ninja', + 'mustang', + 'password1!', + 'admin', + 'admin123', + 'root', + 'toor', + 'guest', + 'p@ssw0rd', + 'Passw0rd', + 'Password1', + 'Password123', + 'Welcome1', + 'Qwerty123', + ].map(s => s.toLowerCase()), +); + +const UPPER = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; +const LOWER = 'abcdefghijkmnopqrstuvwxyz'; +const DIGIT = '23456789'; +const SPECIAL = '!@#$%^&*-_=+'; +const ALPHANUM = UPPER + LOWER + DIGIT; + +export interface AuthDbPasswordPolicyChecks { + minLength: boolean; + uppercase: boolean; + lowercase: boolean; + digit: boolean; + special: boolean; + commonPassword: boolean; +} + +function secureRandomInt(maxExclusive: number): number { + if (maxExclusive <= 0) { + throw new Error('secureRandomInt: maxExclusive must be positive'); + } + const maxUint32 = 0xffffffff; + const limit = maxUint32 - (maxUint32 % maxExclusive); + const buf = new Uint32Array(1); + let value: number; + do { + crypto.getRandomValues(buf); + value = buf[0]!; + } while (value >= limit); + return value % maxExclusive; +} + +function pick(pool: string): string { + return pool[secureRandomInt(pool.length)]!; +} + +function shuffleInPlace(chars: string[]): void { + for (let i = chars.length - 1; i > 0; i -= 1) { + const j = secureRandomInt(i + 1); + const t = chars[i]!; + chars[i] = chars[j]!; + chars[j] = t; + } +} + +function getRequiredCharacterPools( + policy: AuthDbPasswordPolicy, +): string[] { + const pools: string[] = []; + if (policy.password_require_uppercase) { + pools.push(UPPER); + } + if (policy.password_require_lowercase) { + pools.push(LOWER); + } + if (policy.password_require_digit) { + pools.push(DIGIT); + } + if (policy.password_require_special) { + pools.push(SPECIAL); + } + return pools; +} + +function getGenerationPool(policy: AuthDbPasswordPolicy): string { + let pool = ''; + if (policy.password_require_uppercase) { + pool += UPPER; + } + if (policy.password_require_lowercase) { + pool += LOWER; + } + if (policy.password_require_digit) { + pool += DIGIT; + } + if (policy.password_require_special) { + pool += SPECIAL; + } + return pool || ALPHANUM + SPECIAL; +} + +function satisfiesAuthDbPasswordPolicy( + password: string, + policy: AuthDbPasswordPolicy, +): boolean { + const checks = getAuthDbPasswordPolicyChecks(password, policy); + return Object.values(checks).every(Boolean); +} + +/** True when the string satisfies default AUTH_DB rules (mirrors backend checks). */ +export function satisfiesDefaultAuthDbPasswordPolicy(password: string): boolean { + return satisfiesAuthDbPasswordPolicy(password, AUTH_DB_DEFAULT_PASSWORD_POLICY); +} + +/** Returns rule-by-rule checks for default AUTH_DB password policy. */ +export function getAuthDbPasswordPolicyChecks( + password: string, + policy: AuthDbPasswordPolicy = AUTH_DB_DEFAULT_PASSWORD_POLICY, +): AuthDbPasswordPolicyChecks { + const minLength = Math.max(1, Number(policy.password_min_length) || 1); + return { + minLength: password.length >= minLength, Review Comment: **Suggestion:** Using JavaScript `password.length` for minimum-length validation is not backend-equivalent for non-BMP Unicode characters (e.g., emoji), because JS counts UTF-16 code units while Python counts Unicode code points. This can produce client-side "valid" passwords that are rejected by backend policy. Count Unicode code points instead to match server behavior. [api mismatch] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ Users see client "valid" but server rejects Unicode passwords. - ⚠️ Affects `/api/v1/me/password` self-service password changes. - ⚠️ Affects admin resets using UserListResetPasswordModal validation. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. In the self-service password change modal, `UserInfoModal` (superset-frontend/src/features/userInfo/UserInfoModal.tsx:82-145), the `new_password` `FormItem` uses `getPasswordPolicyError` to validate the candidate password before submission. 2. `getPasswordPolicyError` in `UserInfoModal` (lines 15-17) calls the shared helper `getAuthDbPasswordPolicyError(password, passwordPolicy)`, which in turn calls `getAuthDbPasswordPolicyChecks(password, policy)` from superset-frontend/src/utils/generateAuthDbPassword.ts:182-199. 3. `getAuthDbPasswordPolicyChecks` computes `minLength` as `password.length >= minLength` (generateAuthDbPassword.ts:186-188), where `password.length` is the JavaScript string length in UTF-16 code units; for a password consisting of 6 non-BMP emoji characters, `password.length` is 12 even though Python sees length 6. 4. On the backend, `validate_auth_db_password` (superset/superset/utils/auth_db_password.py:164-177) uses `len(password) < min_len` with Python's Unicode code point length, so the same 6-emoji password with `password_min_length` 12 passes the frontend check (length 12) but fails the backend check (length 6), causing the client to accept the password in the modal while the server responds with a 400 error when `PUT /api/v1/me/password` or the admin reset endpoint is called. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=9b8c0c394b84499dae64d51bc8202132&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=9b8c0c394b84499dae64d51bc8202132&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset-frontend/src/utils/generateAuthDbPassword.ts **Line:** 188:188 **Comment:** *Api Mismatch: Using JavaScript `password.length` for minimum-length validation is not backend-equivalent for non-BMP Unicode characters (e.g., emoji), because JS counts UTF-16 code units while Python counts Unicode code points. This can produce client-side "valid" passwords that are rejected by backend policy. Count Unicode code points instead to match server behavior. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39469&comment_hash=c61c3316bb3e400ac7b30870f7ddf6b55b3bbc337243f492caa2bb59eeca4b65&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39469&comment_hash=c61c3316bb3e400ac7b30870f7ddf6b55b3bbc337243f492caa2bb59eeca4b65&reaction=dislike'>👎</a> ########## superset-frontend/src/features/users/utils.ts: ########## @@ -19,8 +19,40 @@ import { t } from '@apache-superset/core/translation'; import { SupersetClient } from '@superset-ui/core'; import { SelectOption } from 'src/components/ListView'; +import type { UserObject } from 'src/pages/UsersList/types'; import { FormValues } from './types'; +/** Fields required for PUT `/api/v1/security/users/:id` when changing password only. */ +export function buildSecurityUserUpdatePayload(user: UserObject): FormValues { + return { + first_name: user.first_name, + last_name: user.last_name, + username: user.username, + email: user.email, + active: user.active, + roles: (user.roles ?? []).map(r => r.id), + groups: (user.groups ?? []).map(g => g.id), + }; +} + +export const fetchSecurityUser = async (userId: number): Promise<UserObject> => { + const { json } = await SupersetClient.get({ + endpoint: `/api/v1/security/users/${userId}`, + }); + return json.result as UserObject; +}; + +export const resetUserPassword = async ( + userId: number, + password: string, +): Promise<void> => { + const freshUser = await fetchSecurityUser(userId); + await updateUser(userId, { + ...buildSecurityUserUpdatePayload(freshUser), + password, + }); Review Comment: **Suggestion:** This reset flow does a read-then-write of the full user object, which creates a lost-update race: if another admin edits the same user between `fetchSecurityUser` and `updateUser`, the second call can overwrite those concurrent changes with stale values. Use a password-only API/update path (or optimistic concurrency/version checks) so password reset does not rewrite unrelated profile/role fields. [race condition] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Admin password reset can silently revert recent profile edits. - ❌ Concurrent role/group changes can be lost without warning. - ⚠️ Affects admin UI flows using UserListResetPasswordModal. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. An admin opens the reset-password modal for a user in the Users list; the modal component `UserListResetPasswordModal` (superset-frontend/src/features/users/UserListResetPasswordModal.tsx:49-54) is rendered and receives the target `user` prop. 2. When the admin submits the form, `handleFormSubmit` in `UserListResetPasswordModal` (superset-frontend/src/features/users/UserListResetPasswordModal.tsx:80-107) calls `resetUserPassword(user.id, rest.password)` from `./utils`. 3. `resetUserPassword` (superset-frontend/src/features/users/utils.ts:45-54) performs a read-then-write sequence: it first calls `fetchSecurityUser(userId)` (GET `/api/v1/security/users/:id`, utils.ts:38-43) to retrieve the current full user object, then calls `updateUser(userId, { ...buildSecurityUserUpdatePayload(freshUser), password })` which issues a PUT to `/api/v1/security/users/:id` with all profile/role fields plus the new password. 4. In parallel, a second admin edits the same user via the edit-user modal `UserListModal` (superset-frontend/src/features/users/UserListModal.tsx, `handleFormSubmit` uses `await updateUser(user.id, values)` at lines ~80-90). If the second admin saves their changes *after* `resetUserPassword` has fetched the user but *before* `resetUserPassword` issues its PUT, the subsequent PUT from `resetUserPassword` writes the stale snapshot from `freshUser` (via `buildSecurityUserUpdatePayload` at utils.ts:26-35), overwriting the other admin's recent changes to names, email, roles, or groups along with the new password. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e41967c6ac84474bb9d6a7151e3c8515&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=e41967c6ac84474bb9d6a7151e3c8515&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset-frontend/src/features/users/utils.ts **Line:** 49:53 **Comment:** *Race Condition: This reset flow does a read-then-write of the full user object, which creates a lost-update race: if another admin edits the same user between `fetchSecurityUser` and `updateUser`, the second call can overwrite those concurrent changes with stale values. Use a password-only API/update path (or optimistic concurrency/version checks) so password reset does not rewrite unrelated profile/role fields. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39469&comment_hash=94bf52972297191d49a12177e9d78d4f1dd5482a9951dbc3f5c21803b4e8d519&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39469&comment_hash=94bf52972297191d49a12177e9d78d4f1dd5482a9951dbc3f5c21803b4e8d519&reaction=dislike'>👎</a> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
