chore: add tests for validation#112
Conversation
📝 WalkthroughWalkthroughThe pull request extends validation schema and controller functionality by adding new fields ( Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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 (3)
app/http/requests/validation_create.go (1)
52-66:⚠️ Potential issue | 🟡 MinorUnsafe type assertion in
PrepareForValidation.At line 60,
c.(string)andctx.Value("ctx").(string)are direct type assertions that could panic if the values are nil or not strings.🛡️ Proposed defensive fix
func (r *ValidationCreate) PrepareForValidation(ctx http.Context, data validation.Data) error { if scores, exist := data.Get("scores"); exist { if err := data.Set("scores", cast.ToIntSlice(scores)); err != nil { return err } } if c, exist := data.Get("context"); exist { - // Test getting value from context: ValidationController.Request - if err := data.Set("context", c.(string)+"_"+ctx.Value("ctx").(string)); err != nil { - return err + cStr, ok := c.(string) + if !ok { + return nil + } + ctxVal := ctx.Value("ctx") + ctxStr, ok := ctxVal.(string) + if !ok { + return nil + } + if err := data.Set("context", cStr+"_"+ctxStr); err != nil { + return err } } return nil }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@app/http/requests/validation_create.go` around lines 52 - 66, In PrepareForValidation (type ValidationCreate) avoid unsafe type assertions for c.(string) and ctx.Value("ctx").(string) which can panic; instead, check types using the comma-ok idiom (e.g. v, ok := c.(string) and ctxVal, ok := ctx.Value("ctx").(string)), handle missing or wrong-type cases by returning an error (or a safe fallback) before calling data.Set("context", ...), and keep the existing scores cast logic unchanged; update the code paths in PrepareForValidation to validate types and return a clear error when either value is absent or not a string.app/rules/exists.go (2)
29-33:⚠️ Potential issue | 🟠 MajorUnsafe type assertions and missing bounds checks may cause runtime panics.
The code directly accesses
options[0],options[1], and type-assertsvalwithout any safety checks. If the rule is invoked with fewer than 2 options or with non-string values, this will panic at runtime.🛡️ Proposed fix to add safety checks
func (receiver *Exists) Passes(ctx context.Context, _ validation.Data, val any, options ...any) bool { + if len(options) < 2 { + return false + } + tableName, ok := options[0].(string) + if !ok { + return false + } + fieldName, ok := options[1].(string) + if !ok { + return false + } + requestValue, ok := val.(string) + if !ok { + return false + } - tableName := options[0].(string) - fieldName := options[1].(string) - requestValue := val.(string) if len(requestValue) == 0 { return false }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@app/rules/exists.go` around lines 29 - 33, In Exists.Passes ensure you guard against panics by validating inputs before type assertions: check len(options) >= 2, use safe type assertions for options[0] and options[1] into strings (e.g., ok idiom) to populate tableName and fieldName, and safely assert val is a string into requestValue (or handle non-string values); if any check fails, return false (or an appropriate error/false result) instead of letting the function panic. This targets the Exists.Pass(es) function where options, tableName, fieldName and requestValue are accessed.
41-45:⚠️ Potential issue | 🟡 MinorUnsafe type assertion in loop for additional field options.
The loop at lines 42-44 also performs an unsafe type assertion
options[i].(string)which could panic if a non-string value is passed.🛡️ Proposed fix
if len(options) > 2 { for i := 2; i < len(options); i++ { - query = query.OrWhere(options[i].(string), requestValue) + fieldOpt, ok := options[i].(string) + if !ok { + continue + } + query = query.OrWhere(fieldOpt, requestValue) } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@app/rules/exists.go` around lines 41 - 45, The loop in app/rules/exists.go uses an unsafe type assertion options[i].(string) which can panic; update the loop that builds query.OrWhere to validate each options[i] before using it (e.g., perform a type assertion with the two-value form or a type switch), and handle non-string values safely by skipping them or returning an error instead of panicking; reference the existing query.OrWhere call, the options slice and requestValue when implementing this check so only valid strings are passed into OrWhere.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@app/http/controllers/validation_controller.go`:
- Around line 93-102: The code builds a response using
user.Date.ToDateTimeString() without guarding against a nil pointer; update the
response construction in validation controller (where response, user and
ctx.Response().Success().Json are used) to nil-check user.Date before calling
ToDateTimeString() — e.g. determine a safe date value (empty string or nil) by
checking if user.Date != nil and only calling ToDateTimeString() when non-nil,
then include that safe value in the "date" field of the response.
In `@go.mod`:
- Line 34: Update the vulnerable module versions in go.mod: bump
google.golang.org/grpc to v1.79.3 or later to address the :path pseudo-header
auth bypass, and ensure the indirect dependency github.com/gofiber/utils is
upgraded to v2.0.0-rc.3 or later to eliminate the predictable-UUID fallback;
after editing the module versions run dependency resolution (go mod tidy / go
get equivalent) to update go.sum and vendor, then run the test suite and your
dependency vulnerability scanner to verify the fixes.
---
Outside diff comments:
In `@app/http/requests/validation_create.go`:
- Around line 52-66: In PrepareForValidation (type ValidationCreate) avoid
unsafe type assertions for c.(string) and ctx.Value("ctx").(string) which can
panic; instead, check types using the comma-ok idiom (e.g. v, ok := c.(string)
and ctxVal, ok := ctx.Value("ctx").(string)), handle missing or wrong-type cases
by returning an error (or a safe fallback) before calling data.Set("context",
...), and keep the existing scores cast logic unchanged; update the code paths
in PrepareForValidation to validate types and return a clear error when either
value is absent or not a string.
In `@app/rules/exists.go`:
- Around line 29-33: In Exists.Passes ensure you guard against panics by
validating inputs before type assertions: check len(options) >= 2, use safe type
assertions for options[0] and options[1] into strings (e.g., ok idiom) to
populate tableName and fieldName, and safely assert val is a string into
requestValue (or handle non-string values); if any check fails, return false (or
an appropriate error/false result) instead of letting the function panic. This
targets the Exists.Pass(es) function where options, tableName, fieldName and
requestValue are accessed.
- Around line 41-45: The loop in app/rules/exists.go uses an unsafe type
assertion options[i].(string) which can panic; update the loop that builds
query.OrWhere to validate each options[i] before using it (e.g., perform a type
assertion with the two-value form or a type switch), and handle non-string
values safely by skipping them or returning an error instead of panicking;
reference the existing query.OrWhere call, the options slice and requestValue
when implementing this check so only valid strings are passed into OrWhere.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 794c50d2-3ea3-4a6e-a070-6cb6e4d5665c
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (10)
app/http/controllers/validation_controller.goapp/http/controllers/validation_controller_test.goapp/http/requests/user_create.goapp/http/requests/validation_create.goapp/rules/exists.goapp/rules/not_exists.gobootstrap/rules.gogo.modtests/feature/http_test.gotests/feature/validation_test.go
💤 Files with no reviewable changes (3)
- bootstrap/rules.go
- tests/feature/http_test.go
- app/rules/not_exists.go
| response := http.Json{ | ||
| "context": user.Context, | ||
| "name": user.Name, | ||
| "date": user.Date.ToDateTimeString(), | ||
| }) | ||
| "age": user.Age, | ||
| "items": user.Items, | ||
| "meta": user.Meta, | ||
| } | ||
|
|
||
| return ctx.Response().Success().Json(response) |
There was a problem hiding this comment.
Potential nil pointer dereference on user.Date.
At line 96, user.Date.ToDateTimeString() is called without checking if Date is nil. Since Date is a pointer type (*carbon.DateTime), this could cause a panic if the validation passes but the date field is somehow not populated during binding.
🛡️ Proposed defensive check
response := http.Json{
"context": user.Context,
"name": user.Name,
- "date": user.Date.ToDateTimeString(),
+ "date": "",
"age": user.Age,
"items": user.Items,
"meta": user.Meta,
}
+ if user.Date != nil {
+ response["date"] = user.Date.ToDateTimeString()
+ }
return ctx.Response().Success().Json(response)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| response := http.Json{ | |
| "context": user.Context, | |
| "name": user.Name, | |
| "date": user.Date.ToDateTimeString(), | |
| }) | |
| "age": user.Age, | |
| "items": user.Items, | |
| "meta": user.Meta, | |
| } | |
| return ctx.Response().Success().Json(response) | |
| response := http.Json{ | |
| "context": user.Context, | |
| "name": user.Name, | |
| "date": "", | |
| "age": user.Age, | |
| "items": user.Items, | |
| "meta": user.Meta, | |
| } | |
| if user.Date != nil { | |
| response["date"] = user.Date.ToDateTimeString() | |
| } | |
| return ctx.Response().Success().Json(response) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@app/http/controllers/validation_controller.go` around lines 93 - 102, The
code builds a response using user.Date.ToDateTimeString() without guarding
against a nil pointer; update the response construction in validation controller
(where response, user and ctx.Response().Success().Json are used) to nil-check
user.Date before calling ToDateTimeString() — e.g. determine a safe date value
(empty string or nil) by checking if user.Date != nil and only calling
ToDateTimeString() when non-nil, then include that safe value in the "date"
field of the response.
| google.golang.org/grpc v1.78.0 | ||
| go.opentelemetry.io/otel v1.42.0 | ||
| go.opentelemetry.io/otel/metric v1.42.0 | ||
| google.golang.org/grpc v1.79.2 |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check for latest versions and security advisories
echo "=== Checking grpc security advisories ==="
gh api graphql -f query='
{
securityVulnerabilities(first: 5, ecosystem: GO, package: "google.golang.org/grpc") {
nodes {
advisory {
summary
severity
publishedAt
}
vulnerableVersionRange
firstPatchedVersion {
identifier
}
}
}
}'
echo ""
echo "=== Checking gofiber/utils security advisories ==="
gh api graphql -f query='
{
securityVulnerabilities(first: 5, ecosystem: GO, package: "github.com/gofiber/utils") {
nodes {
advisory {
summary
severity
publishedAt
}
vulnerableVersionRange
firstPatchedVersion {
identifier
}
}
}
}'Repository: goravel/example
Length of output: 456
🏁 Script executed:
cat go.mod | head -150Repository: goravel/example
Length of output: 7429
🌐 Web query:
GHSA-p77j-4mvh-x3m3 google.golang.org/grpc vulnerability
💡 Result:
GHSA-p77j-4mvh-x3m3 is a critical authorization bypass vulnerability (CVSS 9.1) in google.golang.org/grpc, also known as CVE-2026-33186. It affects versions before 1.79.3. The gRPC-Go server accepts HTTP/2 requests with malformed :path pseudo-headers missing the leading slash (e.g., "Service/Method" instead of "/Service/Method"). The server routes these to the correct handler, but authorization interceptors like grpc/authz evaluate the raw path. Deny rules for canonical paths (with "/") fail to match, allowing bypass if a fallback allow rule exists. Exploitation requires sending raw HTTP/2 frames, network access, path-based auth interceptors with deny rules + fallback allow. No known public exploits. Fix: Upgrade to v1.79.3 or later, where non-canonical paths are rejected with Unimplemented error. Published March 17, 2026.
Citations:
- 1: https://www.resolvedsecurity.com/vulnerability-catalog/GHSA-p77j-4mvh-x3m3
- 2: https://test.osv.dev/vulnerability/GHSA-p77j-4mvh-x3m3
- 3: https://advisories.gitlab.com/pkg/golang/google.golang.org/grpc/CVE-2026-33186/
- 4: https://github.com/grpc/grpc-go/security
- 5: https://github.com/grpc/grpc-go/security/advisories
- 6: https://github.com/grpc/grpc-go/releases
- 7: https://github.com/grpc/grpc-go/releases/tag/v1.79.3
🌐 Web query:
GHSA-m98w-cqp3-qcqr github.com/gofiber/utils vulnerability
💡 Result:
GHSA-m98w-cqp3-qcqr is a critical vulnerability (CVSS 9.2) in github.com/gofiber/utils affecting the UUIDv4 and UUID functions. When crypto/rand fails (on Go <1.24), they silently return predictable values like the zero UUID "00000000-0000-0000-0000-000000000000", compromising security in Fiber apps using these for session IDs, CSRF tokens, etc. CVE-2025-66565. Published Dec 2025. Affected: github.com/gofiber/utils <=1.1.0; github.com/gofiber/utils/v2 <=2.0.0-rc.3 (last known vulnerable: <2.0.0-rc.3.0.20251205210924-6c6cf047032b). Patched in: gofiber/utils@6c6cf04 (Dec 2025, post-advisory). Update to >=2.0.0-rc.3.0.20251205210924-6c6cf047032b (v2 branch). Go >=1.24 is unaffected as crypto/rand panics on failure. Workaround: Replace with github.com/google/uuid.New. CWE-252,331,338.
Citations:
- 1: GHSA-m98w-cqp3-qcqr
- 2: https://test.osv.dev/vulnerability/GHSA-m98w-cqp3-qcqr
- 3: https://nvd.nist.gov/vuln/detail/CVE-2025-66565
- 4: GHSA-m98w-cqp3-qcqr
🌐 Web query:
GO-2025-4208 golang vulnerability
💡 Result:
GO-2025-4208 is a vulnerability in the github.com/gofiber/utils and github.com/gofiber/utils/v2 Go packages. It affects UUID and UUIDv4 functions, which silently fall back to predictable values (including the zero UUID "00000000-0000-0000-0000-000000000000") when crypto/rand.Read fails. This compromises security for applications using these for critical operations. Affected versions: - github.com/gofiber/utils >=1.2.0 (no fixed version listed explicitly, but related to pre-fix commits) - github.com/gofiber/utils/v2 from 2.0.0-rc.4 (earlier rc versions and below) Aliases: CVE-2025-66565, GHSA-m98w-cqp3-qcqr Published: 2025-12-15 Fixed: In github.com/gofiber/utils commit 6c6cf047032b9c8dff43d29f990b4b10e9b02d47 (v2.0.0-rc.4 for v2). Note: Go 1.24+ panics on crypto/rand failures, mitigating the silent fallback. The report is unreviewed (auto-generated). Official Go security page: https://pkg.go.dev/vuln/GO-2025-4208 CVSS v3.1: 9.8 (Critical), allows high impact if rand fails (e.g., resource exhaustion or misconfiguration). Mitigation: Update to fixed versions, avoid using these UUID functions for security-sensitive purposes, ensure crypto/rand availability.
Citations:
- 1: https://pkg.go.dev/vuln/GO-2025-4208
- 2: https://test.osv.dev/vulnerability/GO-2025-4208
- 3: https://osv.dev/vulnerability/GO-2025-4208
- 4: https://www.tenable.com/cve/CVE-2025-66565
- 5: https://nvd.nist.gov/vuln/detail/CVE-2025-66565
- 6: https://advisories.gitlab.com/pkg/golang/github.com/gofiber/utils/v2/CVE-2025-66565/
Critical security vulnerabilities require immediate updates.
Two critical vulnerabilities affect the current dependencies:
-
google.golang.org/grpc v1.79.2: Authorization bypass via missing leading slash in
:pathpseudo-headers (GHSA-p77j-4mvh-x3m3, CVSS 9.1). Upgrade to v1.79.3 or later. -
github.com/gofiber/utils v1.1.0 (indirect): UUIDv4 and UUID functions silently fall back to predictable values when crypto/rand fails (GHSA-m98w-cqp3-qcqr / GO-2025-4208, CVSS 9.2). Upgrade to v2.0.0-rc.3 or later.
🧰 Tools
🪛 OSV Scanner (2.3.3)
[CRITICAL] 34-34: google.golang.org/grpc 1.79.2: gRPC-Go has an authorization bypass via missing leading slash in :path
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@go.mod` at line 34, Update the vulnerable module versions in go.mod: bump
google.golang.org/grpc to v1.79.3 or later to address the :path pseudo-header
auth bypass, and ensure the indirect dependency github.com/gofiber/utils is
upgraded to v2.0.0-rc.3 or later to eliminate the predictable-UUID fallback;
after editing the module versions run dependency resolution (go mod tidy / go
get equivalent) to update go.sum and vendor, then run the test suite and your
dependency vulnerability scanner to verify the fixes.
📑 Description
Relate goravel/framework#1417
Main Features
This PR updates the validation test suite and controller logic to support enhanced validation rules and more complex data structures. The key changes include:
map[string]stringtomap[string]anythroughout the validation frameworkExistsrule signature from"exists"to"custom_exists"and removed theNotExistsrule entirelyTechnical Changes
Controller Updates (
validation_controller.go):Userstruct withAge int,Items []ValidationItem, andMeta map[string]anyfieldsmap[string]anyand added validation for nesteditems.*.nameand optionalmeta.nameRequest Schema Changes (
validation_create.go):ValidationItemtype withNamefieldItems,Meta, andAgefields toValidationCreatestructRules()andFilters()return types frommap[string]stringtomap[string]anyValidation Rule Changes:
Existsrule signature to"custom_exists"for custom validation logicNotExistsrule implementation and its bootstrap registrationTest Suite Refactoring (
validation_test.go):TestValidationForm,TestValidationJson,TestValidationRequest) with granular unit testsTestValidateJson,TestValidateForm,TestValidateRequest, andTestValidateMakemap[string]stringtomap[string]any✅ Checks