Skip to content

Potential fixes for 5 code quality findings#1614

Open
riderx wants to merge 8 commits intomainfrom
ai-findings-autofix/tests-password-policy.test.ts
Open

Potential fixes for 5 code quality findings#1614
riderx wants to merge 8 commits intomainfrom
ai-findings-autofix/tests-password-policy.test.ts

Conversation

@riderx
Copy link
Member

@riderx riderx commented Feb 10, 2026

This PR applies 5/5 suggestions from code quality AI findings.

Summary by CodeRabbit

  • Tests
    • Improved password policy tests to use production hash computation consistently.
    • Added assertions ensuring password policy config is present and non-null when fetched.
    • Strengthened error-handling checks to fail immediately and surface combined test errors.
    • Tightened HTTP status assertion for invalid JSON to expect a 400 response.

riderx and others added 5 commits February 10, 2026 13:47
…ofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
…ofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
…ofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
…ofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
…ofix

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
@riderx riderx marked this pull request as ready for review February 10, 2026 13:47
Copilot AI review requested due to automatic review settings February 10, 2026 13:47
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 10, 2026

📝 Walkthrough

Walkthrough

Tests updated to use the production RPC get_password_policy_hash(policy_config) for policy hash computation, tighten an HTTP status assertion to exact 400, and simplify error handling by throwing errors directly in finally blocks; test expectations for password policy config presence were also added. (46 words)

Changes

Cohort / File(s) Summary
Password Policy Tests
tests/password-policy.test.ts
Replaced inline Base64 policy-hash generation with RPC get_password_policy_hash(policy_config) across tests; switched to throwing errors directly in finally blocks and removed local restoreError patterns; tightened invalid-JSON status assertion from >= 400 to exact 400; added assertions for password_policy_config presence and updated related test flows.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I hopped through tests with nimble paws,

RPCs now hum without a pause,
Hashes fetched from where they live,
Errors thrown — no tricks to give,
Tests celebrate the tidy laws 🥕

🚥 Pre-merge checks | ✅ 1 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is incomplete and missing most required sections from the template, including detailed summary, test plan, and checklist items. Complete the PR description by filling in the Summary section with details about the changes, providing a Test plan section with reproduction steps, and checking off relevant checklist items.
Merge Conflict Detection ⚠️ Warning ❌ Merge conflicts detected (54 files):

⚔️ .github/workflows/tests.yml (content)
⚔️ AGENTS.md (content)
⚔️ README.md (content)
⚔️ android/app/proguard-rules.pro (content)
⚔️ bun.lock (content)
⚔️ messages/de.json (content)
⚔️ messages/en.json (content)
⚔️ messages/es.json (content)
⚔️ messages/fr.json (content)
⚔️ messages/hi.json (content)
⚔️ messages/id.json (content)
⚔️ messages/it.json (content)
⚔️ messages/ja.json (content)
⚔️ messages/ko.json (content)
⚔️ messages/pl.json (content)
⚔️ messages/pt-br.json (content)
⚔️ messages/ru.json (content)
⚔️ messages/tr.json (content)
⚔️ messages/vi.json (content)
⚔️ messages/zh-cn.json (content)
⚔️ package.json (content)
⚔️ scripts/start-cloudflare-workers.sh (content)
⚔️ src/components/CreditsCta.vue (content)
⚔️ src/components/dashboard/DevicesStats.vue (content)
⚔️ src/components/dashboard/Usage.vue (content)
⚔️ src/pages/ApiKeys.vue (content)
⚔️ src/pages/admin/dashboard/plugins.vue (content)
⚔️ src/pages/admin/dashboard/users.vue (content)
⚔️ src/pages/app/[app].channel.[channel].statistics.vue (content)
⚔️ src/pages/settings/organization/Plans.vue (content)
⚔️ src/services/chartDataService.ts (content)
⚔️ src/services/chartTooltip.ts (content)
⚔️ src/stores/organization.ts (content)
⚔️ src/types/supabase.types.ts (content)
⚔️ supabase/functions/_backend/plugins/channel_self.ts (content)
⚔️ supabase/functions/_backend/plugins/stats.ts (content)
⚔️ supabase/functions/_backend/private/admin_credits.ts (content)
⚔️ supabase/functions/_backend/private/channel_stats.ts (content)
⚔️ supabase/functions/_backend/private/credits.ts (content)
⚔️ supabase/functions/_backend/public/build/status.ts (content)
⚔️ supabase/functions/_backend/public/replication.ts (content)
⚔️ supabase/functions/_backend/public/statistics/index.ts (content)
⚔️ supabase/functions/_backend/triggers/logsnag_insights.ts (content)
⚔️ supabase/functions/_backend/utils/appStatus.ts (content)
⚔️ supabase/functions/_backend/utils/cloudflare.ts (content)
⚔️ supabase/functions/_backend/utils/pg.ts (content)
⚔️ supabase/functions/_backend/utils/plugin_parser.ts (content)
⚔️ supabase/functions/_backend/utils/supabase.types.ts (content)
⚔️ supabase/functions/_backend/utils/update.ts (content)
⚔️ supabase/functions/_backend/utils/version.ts (content)
⚔️ supabase/functions/triggers/index.ts (content)
⚔️ tests/admin-credits.test.ts (content)
⚔️ tests/bundle-usage.unit.test.ts (content)
⚔️ tests/password-policy.test.ts (content)

These conflicts must be resolved before merging into main.
Resolve conflicts locally and push changes to this branch.
Title check ❓ Inconclusive The title is vague and generic, referring to 'code quality findings' without specifying what changes were made or which findings were addressed. Provide a more specific title that describes the actual changes, such as 'Fix password policy tests with RPC-based hash computation' or similar.
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ai-findings-autofix/tests-password-policy.test.ts
⚔️ Resolve merge conflicts (beta)
  • Auto-commit resolved conflicts to branch ai-findings-autofix/tests-password-policy.test.ts
  • Create stacked PR with resolved conflicts
  • Post resolved changes as copyable diffs in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/password-policy.test.ts (2)

1-1: ⚠️ Potential issue | 🔴 Critical

Remove unused PostgrestError import — pipeline failure.

The CI pipeline reports TS6133: 'PostgrestError' is declared but its value is never read. This will block the build.

Proposed fix
-import type { PostgrestError } from '@supabase/supabase-js'

296-303: ⚠️ Potential issue | 🟠 Major

throw inside finally overwrites any exception from the try block.

If the test assertion in the try block fails and the restore also fails, the original test failure is silently swallowed. Both ESLint (no-unsafe-finally) and Biome flag this.

Consider logging or combining errors instead of a bare throw:

Proposed fix
    finally {
      const { error } = await getSupabaseClient()
        .from('orgs')
        .update({ password_policy_config: policyConfig })
        .eq('id', ORG_ID)
-     if (error)
-       throw error
+     if (error)
+       console.error('Failed to restore password policy after test:', error)
    }
🤖 Fix all issues with AI agents
In `@tests/password-policy.test.ts`:
- Around line 555-560: The type error comes from passing
org?.password_policy_config (which can be undefined) to
getSupabaseClient().rpc('get_password_policy_hash', { policy_config }) where
policy_config expects Json; fix by ensuring a Json is passed — e.g. replace
policy_config: org?.password_policy_config with policy_config:
(org?.password_policy_config ?? null) as unknown as Json (or import and use the
Json type and cast appropriately) so the rpc call receives a Json value.
- Line 54: The describe block titles start with an uppercase letter and violate
the test/prefer-lowercase-title rule; update the string arguments passed to the
describe calls (the one currently "Password Policy Configuration via SDK" and
the other at the later describe) so they start with a lowercase letter (e.g.,
"password policy configuration via SDK" and the similar lowercase variant for
the second describe) to satisfy the linter.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR addresses code-quality findings by tightening and simplifying the password-policy test suite to better match production behavior and improve assertion strictness.

Changes:

  • Normalizes describe(...) titles capitalization for consistency.
  • Simplifies the “temporarily disable policy / restore policy” logic during /private/validate_password_compliance testing.
  • Makes tests use the production RPC (get_password_policy_hash) for computing the password policy hash and tightens an invalid-JSON status assertion.

Comment on lines 281 to 282
try {
const response = await fetch(`${BASE_URL}/private/validate_password_compliance`, {
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

PostgrestError is no longer referenced in this test after removing restoreError, so the type import at the top of the file is now unused and may fail lint/TS checks. Remove the unused import (or reintroduce a typed variable if still needed).

Copilot uses AI. Check for mistakes.
Comment on lines 296 to 303
finally {
const { error } = await getSupabaseClient()
.from('orgs')
.update({ password_policy_config: policyConfig })
.eq('id', ORG_ID)
restoreError = error ?? null
if (error)
throw error
}
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

Throwing inside this finally will override any failure thrown in the try block (e.g., assertion failures), which can mask the real test failure and make debugging harder. Consider capturing/propagating the original error and only failing the test due to restore failure when the main body succeeded (or log restore failure without replacing the original exception).

Copilot uses AI. Check for mistakes.
Comment on lines 555 to 560
// Use the same RPC that production uses to compute the password policy hash
const { data: rpcResult } = await getSupabaseClient().rpc('get_password_policy_hash', {
policy_config: org?.password_policy_config,
})

const policyHash = (rpcResult as string | null) ?? 'test_hash'
Copy link

Copilot AI Feb 10, 2026

Choose a reason for hiding this comment

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

This RPC call ignores the returned error and falls back to 'test_hash' when rpcResult is null, which can make the test pass even if get_password_policy_hash is broken/permissioned incorrectly or org.password_policy_config is unexpectedly null. To ensure the test is actually validating the production hash path, assert error is null and that the RPC returns a non-null string (and consider failing if the org has no policy config rather than using a dummy hash).

Copilot uses AI. Check for mistakes.
@riderx
Copy link
Member Author

riderx commented Feb 10, 2026

@copilot test are filing fix them

Copy link
Contributor

Copilot AI commented Feb 10, 2026

@riderx I've opened a new pull request, #1616, to work on those changes. Once the pull request is ready, I'll request review from you.

riderx and others added 2 commits February 11, 2026 04:46
* Initial plan

* fix: address code review feedback on password policy tests

- Remove unused PostgrestError import
- Fix finally block to preserve test errors
- Add proper error validation for RPC call

Co-authored-by: riderx <4084527+riderx@users.noreply.github.com>

* fix: lint

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: riderx <4084527+riderx@users.noreply.github.com>
Co-authored-by: Martin DONADIEU <martindonadieu@gmail.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/password-policy.test.ts (1)

614-634: ⚠️ Potential issue | 🟡 Minor

Silently falling back to empty string masks RPC failures.

Line 630 uses hashResult || '' — if the RPC fails or returns null, the test will upsert an empty policy_hash and potentially pass for the wrong reason. Add an assertion (as done in the first test at lines 578–580) to fail fast.

🛡️ Proposed fix
     const { data: hashResult } = await getSupabaseClient().rpc('get_password_policy_hash', {
       policy_config: {
         enabled: true,
         min_length: 10,
         require_uppercase: true,
         require_number: true,
         require_special: true,
       },
     })
 
+    expect(hashResult).not.toBeNull()
+
     // Insert compliance record with correct hash
     await getSupabaseClient()
       .from('user_password_compliance')
       .upsert({
         user_id: USER_ID,
         org_id: ORG_ID,
-        policy_hash: hashResult || '',
+        policy_hash: hashResult as string,
         validated_at: new Date().toISOString(),
       }, {
         onConflict: 'user_id,org_id',
       })
🧹 Nitpick comments (2)
tests/password-policy.test.ts (2)

296-315: Linter violations: throw inside finally block.

Both ESLint (no-unsafe-finally) and Biome (noUnsafeFinally) flag lines 308, 309, and 314. While the intent is sound (preserve the test error while also surfacing restore failures), you can restructure to avoid throw in finally entirely by moving the re-throw logic after the finally block completes.

♻️ Proposed restructure to eliminate throw-in-finally
-    catch (error) {
-      testError = error as Error
-    }
-    finally {
-      const { error: restoreError } = await getSupabaseClient()
-        .from('orgs')
-        .update({ password_policy_config: policyConfig })
-        .eq('id', ORG_ID)
-
-      // If restore failed, throw it (but preserve test failure if there was one)
-      if (restoreError) {
-        if (testError)
-          throw new Error(`Test failed AND restore failed: ${testError.message} | Restore error: ${restoreError.message}`)
-        throw restoreError
-      }
-
-      // Re-throw original test error if any
-      if (testError)
-        throw testError
+    catch (error) {
+      testError = error as Error
+    }
+    finally {
+      const { error: restoreError } = await getSupabaseClient()
+        .from('orgs')
+        .update({ password_policy_config: policyConfig })
+        .eq('id', ORG_ID)
+
+      if (restoreError) {
+        testError = testError
+          ? new Error(`Test failed AND restore failed: ${testError.message} | Restore error: ${restoreError.message}`)
+          : restoreError
+      }
+    }
+
+    if (testError)
+      throw testError

54-54: Tests use it() instead of it.concurrent().

Per the coding guidelines for tests/**/*.test.ts, tests should use it.concurrent() to run in parallel within the same file. All it(...) calls in this file use the synchronous variant. This is a pre-existing issue but worth noting since several it blocks were touched in this PR.

As per coding guidelines: "Use it.concurrent() instead of it() to run tests in parallel within the same test file".

Also applies to: 82-82, 109-109, 151-151, 166-166, 181-181, 196-196, 212-212, 228-228, 245-245, 263-263, 318-318, 334-334, 351-351, 416-416, 427-427, 454-454, 522-522, 538-538, 559-559, 598-598, 646-646, 671-671

@sonarqubecloud
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants