Repository navigation
feat(RHOAIENG-50753): add LDAP user and group autocomplete for workspace sharing - #805
Conversation
This comment has been minimized.
This comment has been minimized.
a316335 to
18b453a
Compare
Ambient Code PlatformKubernetes-native AI automation platform that orchestrates agentic sessions through containerized microservices. Built with Go (backend, operator), NextJS + Shadcn (frontend), Python (runner), and Kubernetes CRDs.
Structure
Key Files
Session FlowCommandsmake build-all # Build all container images
make deploy # Deploy to cluster
make test # Run tests
make lint # Lint code
make kind-up # Start local Kind cluster
make test-e2e-local # Run E2E tests against KindPer-Component# Backend / Operator (Go)
cd components/backend && gofmt -l . && go vet ./... && golangci-lint run
cd components/operator && gofmt -l . && go vet ./... && golangci-lint run
# Frontend
cd components/frontend && npm run build # Must pass with 0 errors, 0 warnings
# Runner (Python)
cd components/runners/ambient-runner && uv venv && uv pip install -e .
# Docs
cd docs && npm run dev # http://localhost:4321Critical Context
Pre-commit HooksThe project uses the pre-commit framework to run linters locally before every commit. Configuration lives in Installmake setup-hooksWhat RunsOn every
On every
Run Manuallymake lint # All hooks, all files
pre-commit run gofmt-check --all-files # Single hook
pre-commit run --files path/to/file.go # Single fileSkip Hooksgit commit --no-verify # Skip pre-commit hooks
git push --no-verify # Skip pre-push hooksNotes
More InfoSee BOOKMARKS.md for architecture decisions, development context, code patterns, and component-specific guides. |
|
Claude Code Review SummaryThis PR adds LDAP-backed user and group autocomplete to the workspace sharing flow. The feature is well-scoped, optional-by-default (graceful degradation when unconfigured), and includes solid test coverage. The LDAP client uses proper filter escaping and input sanitization. A few issues need attention before merge: all three new handlers use the wrong variable for the auth nil check (deviating from the mandatory project pattern), and the frontend builds a custom combobox from scratch when a Shadcn equivalent exists. Issues by SeverityBlocker IssuesNone. Critical Issues1. Auth nil check uses wrong client variable in all 3 handlers Files: All three handlers discard _, k8sDyn := GetK8sClientsForRequest(c)
if k8sDyn == nil {The documented mandatory pattern across the entire codebase ( reqK8s, _ := GetK8sClientsForRequest(c)
if reqK8s == nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or missing token"})
c.Abort()
return
}While functionally equivalent today (both return nil together), this breaks the established convention, hides the unused Violates: Major Issues2. Custom combobox dropdown built from scratch instead of Shadcn Command File: The component renders a bare Per The Shadcn 3. New LDAP connection opened per search, no pooling File: Each search dials a fresh TCP+TLS connection and closes it immediately via 4. LDAP_GROUP_BASE_DN env var not mapped in deployment manifest File:
Minor Issues5. k8sDyn obtained but never used for K8s operations File: The dynamic client is obtained and only checked for nil, never used for actual K8s operations. Once Critical issue 1 is fixed, simplify to 6. Component exceeds 200-line guideline File:
7. Trivial JSDoc comments on self-evident functions Files: Comments like Positive Highlights
Recommendations
|
18b453a to
134aa71
Compare
This comment has been minimized.
This comment has been minimized.
134aa71 to
5c38d48
Compare
|
Disabling TLS verification in production is intentional for now until we switch to an authenticated LDAP server. The risk of doing this is minimal since the cluster is for authenticated users only and the risk of MITM is low. |
This comment has been minimized.
This comment has been minimized.
5c38d48 to
2aad455
Compare
This comment has been minimized.
This comment has been minimized.
2aad455 to
ebc132a
Compare
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThis pull request integrates LDAP directory support into the platform, enabling user and group search/autocomplete functionality. Changes span backend LDAP client implementation, API handlers and routes, frontend proxy routes and React components, Kubernetes configuration, and Go module dependencies. Changes
Sequence Diagram(s)sequenceDiagram
participant User as User
participant Frontend as Frontend UI
participant FrontendAPI as Frontend API Route
participant BackendAPI as Backend Handler
participant LDAPClient as LDAP Client
participant LDAPServer as LDAP Server
User->>Frontend: Type search query in autocomplete
Frontend->>Frontend: Debounce query (300ms)
Frontend->>FrontendAPI: GET /api/ldap/users?q=query
FrontendAPI->>FrontendAPI: Build forwarded headers
FrontendAPI->>BackendAPI: GET /ldap/users?q=query
BackendAPI->>BackendAPI: Validate token, check query length
BackendAPI->>LDAPClient: SearchUsers(query)
LDAPClient->>LDAPClient: Check cache for query
alt Cache Hit
LDAPClient-->>BackendAPI: Return cached users
else Cache Miss
LDAPClient->>LDAPClient: Sanitize and build LDAP filter
LDAPClient->>LDAPServer: LDAP search request
LDAPServer-->>LDAPClient: LDAP entries
LDAPClient->>LDAPClient: Map entries to LDAPUser objects
LDAPClient->>LDAPClient: Cache result (5 min TTL)
LDAPClient-->>BackendAPI: Return users
end
BackendAPI-->>FrontendAPI: 200 + users JSON
FrontendAPI-->>Frontend: 200 + users JSON
Frontend->>Frontend: Update dropdown list
User->>Frontend: Select user from dropdown
Frontend->>Frontend: Call onChange with selected UID
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes 🚥 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)
📝 Coding Plan
Comment |
|
test connection |
Ambient Code PlatformKubernetes-native AI automation platform that orchestrates agentic sessions through containerized microservices. Built with Go (backend, operator), NextJS + Shadcn (frontend), Python (runner), and Kubernetes CRDs.
Structure
Key Files
Session FlowCommandsmake build-all # Build all container images
make deploy # Deploy to cluster
make test # Run tests
make lint # Lint code
make kind-up # Start local Kind cluster
make test-e2e-local # Run E2E tests against KindPer-Component# Backend / Operator (Go)
cd components/backend && gofmt -l . && go vet ./... && golangci-lint run
cd components/operator && gofmt -l . && go vet ./... && golangci-lint run
# Frontend
cd components/frontend && npm run build # Must pass with 0 errors, 0 warnings
# Runner (Python)
cd components/runners/ambient-runner && uv venv && uv pip install -e .
# Docs
cd docs && npm run dev # http://localhost:4321Critical Context
Pre-commit HooksThe project uses the pre-commit framework to run linters locally before every commit. Configuration lives in Installmake setup-hooksWhat RunsOn every
On every
Run Manuallymake lint # All hooks, all files
pre-commit run gofmt-check --all-files # Single hook
pre-commit run --files path/to/file.go # Single fileSkip Hooksgit commit --no-verify # Skip pre-commit hooks
git push --no-verify # Skip pre-push hooksNotes
Testing
More InfoSee BOOKMARKS.md for architecture decisions, development context, code patterns, and component-specific guides. |
There was a problem hiding this comment.
Actionable comments posted: 9
♻️ Duplicate comments (1)
components/manifests/overlays/production/ldap-config.yaml (1)
8-10:⚠️ Potential issue | 🟠 MajorDo not ship the production overlay with LDAPS verification disabled.
Line 10 sets
LDAP_SKIP_TLS_VERIFY: "true", which makes the backend trust spoofed LDAPS endpoints. Please wire in the corporate CA/trusted bundle and keep verification enabled before rolling this out in production.Minimal manifest change once the CA bundle is wired in
- LDAP_SKIP_TLS_VERIFY: "true" + LDAP_SKIP_TLS_VERIFY: "false"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/manifests/overlays/production/ldap-config.yaml` around lines 8 - 10, Replace the insecure LDAP_SKIP_TLS_VERIFY=true with TLS verification enabled and wire in the corporate CA bundle: add an env var like LDAP_CA_BUNDLE (or LDAP_TRUSTED_CA) and populate it from the corporate CA secret/configMap, ensure the deployment mounts the CA bundle into the pod and the LDAP client (code that reads LDAP_BASE_DN/LDAP_URL) is configured to use LDAP_CA_BUNDLE for TLS verification, and set LDAP_SKIP_TLS_VERIFY to "false" (or remove it) so LDAPS verification remains enabled before shipping production.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@components/backend/go.mod`:
- Line 39: Run the verification commands shown to check whether any Go source in
the backend imports github.com/go-ldap/ldap/v3; if it does, remove the //
indirect marker and promote github.com/go-ldap/ldap/v3 to a direct require in
go.mod by adding a require entry for that module (same version currently listed)
and then run go mod tidy to update the module graph; if no direct imports exist,
leave the dependency as indirect. Ensure you reference the module name
"github.com/go-ldap/ldap/v3" and update the go.mod require block accordingly,
then run Go tooling (go mod tidy) to validate and commit the change.
In `@components/backend/handlers/ldap.go`:
- Around line 37-44: Change all LDAP error responses to use HTTP 503 Service
Unavailable for consistency with external dependency failures: update the
handlers that call LDAPClient.SearchUsers and LDAPClient.SearchGroups to return
c.JSON(http.StatusServiceUnavailable, ...) on err (instead of 500), and modify
the GetLDAPUser handler to return http.StatusServiceUnavailable when LDAP lookup
fails; ensure the error log messages remain unchanged and only the HTTP status
code is adjusted.
- Around line 18-24: The error returned from GetK8sClientsForRequest is being
discarded in SearchLDAPUsers (and likewise in SearchLDAPGroups and GetLDAPUser);
modify each function to capture the returned error and log it before returning
the 401 response — e.g., call your existing logger (or c.Error()/log.Printf)
with a clear message like "GetK8sClientsForRequest failed" plus the error value
when reqK8s is nil; ensure you do this in the SearchLDAPUsers, SearchLDAPGroups,
and GetLDAPUser functions where GetK8sClientsForRequest is called.
In `@components/backend/ldap/client_test.go`:
- Around line 233-257: The TestCacheTTL test uses a very small 10ms margin
(client.cacheTTL = 50ms, Sleep 60ms) which can flake under CI; either increase
the margin in TestCacheTTL (e.g., set cacheTTL to 200ms and Sleep to 300ms) or
refactor Client to accept a clock/time provider (inject a timeNow/Clock used by
cacheGet/cacheSet expiration logic) so tests can use a fake clock—update the
Client struct (and its cacheGet/cacheSet expiration checks) to read from the
injected clock and adjust TestCacheTTL to use the fake clock or a larger sleep
margin to eliminate flakiness.
In `@components/backend/ldap/client.go`:
- Around line 96-120: The cache currently only evicts expired entries on access
(cacheGet) so c.cache (sync.Map) can grow unbounded; add a background janitor
goroutine that periodically ranges over c.cache, type-asserts values to
cacheEntry, and deletes entries whose expiresAt is before time.Now(), using
c.cache.Delete, and start this janitor when the Client is created (e.g. in the
constructor or an init method) and stop it when the Client is closed; reference
cacheGet, cacheSet, cacheEntry, c.cache and c.cacheTTL when implementing the
interval and eviction logic.
- Around line 318-326: sanitizeQuery currently truncates by bytes using
q[:maxQueryLength], which can split multi-byte UTF-8 characters; change
truncation to be rune-aware by converting q to a rune slice and trimming like:
runes := []rune(q); if len(runes) > maxQueryLength { q =
string(runes[:maxQueryLength]) }; keep the existing TrimSpace and Replace steps
and reference the sanitizeQuery function and maxQueryLength constant when making
this change.
In `@components/backend/main.go`:
- Around line 141-144: The code currently falls back to using LDAP_BASE_DN for
LDAP_GROUP_BASE_DN which causes group searches to run under the users OU; change
the logic around handlers.LDAPClient creation so that LDAP_GROUP_BASE_DN is not
defaulted to LDAP_BASE_DN — read LDAP_GROUP_BASE_DN via os.Getenv and if empty
pass an empty string (or a sentinel) to ldap.NewClient and ensure
group-autocomplete is disabled when LDAP_GROUP_BASE_DN is empty instead of
searching under LDAP_BASE_DN; update ldap.NewClient (and any code using its
groupBaseDN parameter) or the caller to treat an empty groupBaseDN as “groups
disabled” rather than falling back to getEnvOrDefault("LDAP_BASE_DN", ...) or
reusing ldapBaseDN.
In `@components/frontend/src/app/api/ldap/users/route.ts`:
- Around line 9-12: The fetch call that proxies to
`${BACKEND_URL}/ldap/users${queryString}` can hang indefinitely; wrap it with an
AbortController and a short timeout (e.g., 2–5s) so the request is aborted when
the timer elapses, pass controller.signal to fetch (alongside existing headers
and method), and clear the timeout on success; apply the same pattern to the
sibling LDAP proxy routes that use BACKEND_URL, queryString, headers, and the
route handler(s) to ensure graceful degradation.
In `@components/manifests/overlays/kind/ldap-config.yaml`:
- Around line 8-10: The manifest currently disables server TLS verification via
LDAP_SKIP_TLS_VERIFY: "true"; change LDAP_SKIP_TLS_VERIFY to "false" in the YAML
and instead provision the LDAP CA into the runtime trust store for the container
image (for example by adding the CA to the image or mounting a ConfigMap/Secret
into the container's system trust directory and running the appropriate
trust-update step) so that the LDAPS endpoint at LDAP_URL and base LDAP_BASE_DN
are validated; ensure any container startup hooks or Dockerfile layers invoke
the platform's CA import command (e.g., update-ca-trust/update-ca-certificates)
so verification succeeds without skipping TLS.
---
Duplicate comments:
In `@components/manifests/overlays/production/ldap-config.yaml`:
- Around line 8-10: Replace the insecure LDAP_SKIP_TLS_VERIFY=true with TLS
verification enabled and wire in the corporate CA bundle: add an env var like
LDAP_CA_BUNDLE (or LDAP_TRUSTED_CA) and populate it from the corporate CA
secret/configMap, ensure the deployment mounts the CA bundle into the pod and
the LDAP client (code that reads LDAP_BASE_DN/LDAP_URL) is configured to use
LDAP_CA_BUNDLE for TLS verification, and set LDAP_SKIP_TLS_VERIFY to "false" (or
remove it) so LDAPS verification remains enabled before shipping production.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: bdfceffd-15bd-4f4d-b7a3-09443dc23b7b
⛔ Files ignored due to path filters (1)
components/backend/go.sumis excluded by!**/*.sum
📒 Files selected for processing (24)
Makefilecomponents/backend/go.modcomponents/backend/handlers/ldap.gocomponents/backend/ldap/client.gocomponents/backend/ldap/client_test.gocomponents/backend/main.gocomponents/backend/routes.gocomponents/frontend/src/app/api/ldap/groups/route.tscomponents/frontend/src/app/api/ldap/users/[uid]/route.tscomponents/frontend/src/app/api/ldap/users/route.tscomponents/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsxcomponents/frontend/src/components/workspace-sections/sharing-section.tsxcomponents/frontend/src/services/api/index.tscomponents/frontend/src/services/api/ldap.tscomponents/frontend/src/services/queries/index.tscomponents/frontend/src/services/queries/use-ldap.tscomponents/manifests/base/backend-deployment.yamlcomponents/manifests/base/flags.jsoncomponents/manifests/overlays/kind/kustomization.yamlcomponents/manifests/overlays/kind/ldap-config.yamlcomponents/manifests/overlays/local-dev/kustomization.yamlcomponents/manifests/overlays/local-dev/ldap-config.yamlcomponents/manifests/overlays/production/kustomization.yamlcomponents/manifests/overlays/production/ldap-config.yaml
|
Review posted - see full analysis below in a follow-up comment. |
|
CRITICAL: TLS verification disabled in production LDAP config (components/manifests/overlays/production/ldap-config.yaml:9 sets LDAP_SKIP_TLS_VERIFY to true). This exposes the ldaps:// connection to MITM attacks. Fix: set to false or remove the key in production overlay. The dev overlays can keep it. Standard: security-standards.md. |
|
MAJOR: Custom autocomplete dropdown instead of Shadcn Combobox pattern. File: ldap-autocomplete.tsx. The dropdown uses raw ul/li elements with hand-rolled focus, keyboard navigation, and click-outside logic. Shadcn ships Command + Popover Combobox for exactly this use case. Standard violated: frontend-development.md Shadcn UI Components Only rule (FORBIDDEN: Creating custom UI components from scratch). Fix: replace with Popover, PopoverContent, PopoverTrigger, Command, CommandInput, CommandList, CommandItem, CommandEmpty. Bonus: the component is also 252 lines (limit is 200); switching to Shadcn Combobox will bring it under the limit. Standard: frontend-development.md. |
|
MINOR issues (4): (1) Inconsistent HTTP status codes: SearchLDAPUsers/Groups return 503 but GetLDAPUser returns 500 for the same failure class — standardise on 503 (handlers/ldap.go:104 vs :164). (2) Hardcoded org domain fallback in NewClient: the fallback ou=managedGroups,dc=redhat,dc=com bakes a Red Hat-specific domain into a generic library — log a warning instead (ldap/client.go:249). (3) useLDAPUser hook and ldapApi.getUser are exported but not used anywhere in this PR — remove or document intent. (4) autocomplete component has no error state: the useEffect checks isLoading/hasResults but not error, so LDAP query failures silently close the dropdown — render a brief message when error is set. |
|
POSITIVE HIGHLIGHTS: (1) Excellent LDAP injection prevention — goldap.EscapeFilter() used in all filter builders, sanitizeQuery() strips newlines, %q format verb throughout error logs. (2) Auth pattern correct throughout — every handler uses GetK8sClientsForRequest(c) with 401 on nil, per k8s-client-usage.md. (3) Graceful degradation — LDAP optional (LDAP_URL env gated), Unleash-flag gated in frontend, sharing form falls back to plain Input. (4) Cache TTL consistent end-to-end — backend 5 min, frontend staleTime 5 min. (5) Solid test coverage — filters, TTL expiry, sanitizeQuery, ParseGitHubUsername, short-query cases all tested. (6) LDAPResultSizeLimitExceeded treated as non-fatal partial result — correct for autocomplete. (7) Makefile Unleash password fix replaces hardcoded default with kubectl secret lookup. |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx`:
- Around line 29-31: The test currently forces useWorkspaceFlag() to always
return disabled which prevents rendering the LDAP-autocomplete branch in
SharingSection; change the mock so tests can control the flag per-case by
exporting/using a mutable mock function (e.g., vi.fn()) for useWorkspaceFlag and
set its return value inside individual tests or beforeEach/within specific test
cases; locate the vi.mock for use-feature-flags-admin and replace the fixed
return with a configurable mock (referencing useWorkspaceFlag and
SharingSection) so tests can call mockReturnValue or mockImplementation to
enable/disable the feature as needed.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 2c6fddcf-913d-433a-9c5c-1bf1db00e25f
📒 Files selected for processing (1)
components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx
Claude Code ReviewSummaryThis PR adds LDAP-backed autocomplete for user and group selection in the workspace sharing dialog. The implementation is well-scoped: a new Go LDAP package with in-memory caching, three authenticated API endpoints, Next.js proxy routes, and a React Query-powered frontend. Graceful degradation (LDAP optional, feature-flagged) is handled correctly throughout. However, a production manifest with TLS verification disabled and a frontend component that bypasses Shadcn UI conventions need to be addressed. Issues by SeverityBlocker IssuesNone Critical Issues1. Production manifest ships with TLS verification disabled
InsecureSkipVerify: c.skipTLSVerify, //nolint:gosec // controlled by LDAP_SKIP_TLS_VERIFY env var for devSetting it Violates: 2.
The correct approach is Violates: Major Issues3. In-memory cache has no active eviction
go func() {
ticker := time.NewTicker(c.cacheTTL)
defer ticker.Stop()
for range ticker.C {
c.cache.Range(func(key, val any) bool {
if e, ok := val.(cacheEntry); ok && time.Now().After(e.expiresAt) {
c.cache.Delete(key)
}
return true
})
}
}()Violates: Minor Issues4.
Violates: 5. LDAP startup log reveals deployment configuration at INFO level
Positive Highlights
Recommendations
Review generated by Claude Code using repository standards from |
Review Queue Status
Action needed: Rebase to resolve conflicts. Discuss LDAP cert injection approach with @ktdreyer (runtime cert mounting vs baking into image).
|
caf55f0 to
732a07b
Compare
There was a problem hiding this comment.
Actionable comments posted: 8
♻️ Duplicate comments (5)
components/manifests/overlays/kind/ldap-config.yaml (1)
10-10:⚠️ Potential issue | 🟠 MajorDo not ship LDAPS with certificate verification disabled.
LDAP_SKIP_TLS_VERIFY: "true"on Line 10 disables server authentication and permits MITM/forged directory responses in sharing autocomplete flows. Keep verification enabled and trust the LDAP CA via runtime cert injection.Proposed fix
- LDAP_SKIP_TLS_VERIFY: "true" + LDAP_SKIP_TLS_VERIFY: "false"As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/manifests/overlays/kind/ldap-config.yaml` at line 10, Remove the insecure setting LDAP_SKIP_TLS_VERIFY: "true" (do not disable certificate verification); change it to "false" or remove the variable and ensure TLS verification remains enabled, and instead rely on runtime injection of the LDAP CA certificate into the trust store used by the service; update any startup/env handling that reads LDAP_SKIP_TLS_VERIFY (search for LDAP_SKIP_TLS_VERIFY) to treat absence or "false" as the default secure behavior and document how to supply the LDAP CA via runtime cert injection.components/manifests/overlays/production/ldap-config.yaml (1)
10-10:⚠️ Potential issue | 🟠 MajorDo not disable LDAP TLS verification in production.
Line 10 disables certificate validation, which weakens transport security and enables MITM risk on LDAPS traffic. Keep verification on and supply trusted CA material at runtime.
As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security."🔧 Minimal config fix
- LDAP_SKIP_TLS_VERIFY: "true" + LDAP_SKIP_TLS_VERIFY: "false"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/manifests/overlays/production/ldap-config.yaml` at line 10, The manifest currently sets LDAP_SKIP_TLS_VERIFY to "true", which disables LDAPS certificate validation; change this so TLS verification remains enabled (set LDAP_SKIP_TLS_VERIFY to "false" or remove the setting) and instead supply trusted CA material at runtime (e.g., provide a LDAP_CA_CERT / mounted CA bundle or configure the truststore used by the LDAP client). Update the environment/configuration that defines LDAP_SKIP_TLS_VERIFY and add the CA provisioning step so certificate validation is enforced in production.components/frontend/src/app/api/ldap/users/route.ts (1)
9-12:⚠️ Potential issue | 🟠 MajorBound the backend LDAP proxy call with a timeout.
The fetch is currently unbounded; if backend/LDAP stalls, this route can hang and tie up request handling.
As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security."⏱️ Suggested fix
- const response = await fetch(`${BACKEND_URL}/ldap/users${queryString}`, { - method: 'GET', - headers, - }); + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 5000); + let response: Response; + try { + response = await fetch(`${BACKEND_URL}/ldap/users${queryString}`, { + method: 'GET', + headers, + signal: controller.signal, + }); + } finally { + clearTimeout(timeoutId); + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/frontend/src/app/api/ldap/users/route.ts` around lines 9 - 12, The fetch to `${BACKEND_URL}/ldap/users${queryString}` in route.ts is unbounded; wrap it with an AbortController and a short configurable timeout to avoid hanging requests: create an AbortController, start a timer (e.g., via setTimeout) that calls controller.abort() after the desired timeout, pass controller.signal into the fetch call that constructs `response`, and clear the timer after fetch completes or errors; ensure you handle AbortError separately to return an appropriate timeout response from the route.components/backend/ldap/client.go (2)
96-120:⚠️ Potential issue | 🟠 MajorExpired cache entries still accumulate forever.
cacheGetonly evicts on read. With autocomplete's high-cardinality queries, entries that are never hit again stay insync.Mapindefinitely, so this pod's memory usage will keep growing over time. Add periodic cleanup or switch to a bounded TTL cache.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/backend/ldap/client.go` around lines 96 - 120, The cache currently only evicts expired items on read (cacheGet) so unused high-cardinality entries accumulate; to fix, add a periodic cleanup that scans c.cache (the sync.Map) and deletes entries whose cacheEntry.expiresAt < time.Now(), or alternatively replace this ad-hoc sync.Map with a bounded TTL cache implementation; implement the periodic purge as a background goroutine started when the Client is created (e.g., in NewClient or Client.init) that runs every configurable interval (based on c.cacheTTL or a separate cleanup interval) and removes expired entries, ensuring to stop the goroutine on Client shutdown.
319-324:⚠️ Potential issue | 🟠 MajorMake
sanitizeQueryrune-aware before truncating.
q[:maxQueryLength]slices bytes, not characters. A long non-ASCII name can be cut in the middle of a UTF-8 rune here, producing an invalid query before it reachesEscapeFilter.💡 Minimal fix
func sanitizeQuery(q string) string { q = strings.TrimSpace(q) q = strings.NewReplacer("\n", "", "\r", "").Replace(q) - if len(q) > maxQueryLength { - q = q[:maxQueryLength] + runes := []rune(q) + if len(runes) > maxQueryLength { + q = string(runes[:maxQueryLength]) } return q }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/backend/ldap/client.go` around lines 319 - 324, The truncate in sanitizeQuery currently slices bytes (q[:maxQueryLength]) which can split UTF-8 runes; change it to operate on runes instead: after trimming and replacing newlines, convert q to a rune slice (or use []rune(q)), check len(runes) against maxQueryLength, and if too long set q = string(runes[:maxQueryLength]) so truncation is rune-aware; keep the rest of sanitizeQuery unchanged and ensure the resulting string is what gets passed to EscapeFilter elsewhere.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@components/backend/handlers/ldap.go`:
- Around line 37-40: The LDAP error logs currently include raw user-supplied
query and UIDs (in handlers using LDAPClient.SearchUsers and related calls),
which leaks PII; change the handlers to stop logging the query/UIDs directly and
instead log a non-sensitive identifier (e.g., request ID from the Gin context or
the endpoint name) and the error, or log a hashed/redacted version of the query;
update the three locations around LDAPClient.SearchUsers (and analogous blocks
at lines ~67 and ~97) to use c.GetString("requestID") or similar and only emit
that ID plus err in log.Printf / processLogger, or compute a deterministic hash
of the query before logging.
In `@components/backend/ldap/client.go`:
- Around line 28-29: SearchUsers is returning unnecessary PII/group fields
because userAttributes includes "mail", "rhatSocialURL", and "memberOf"; trim
the LDAP fetch and response DTO used by the autocomplete to only the fields the
UI renders (fullName/cn, uid, and title) by updating the userAttributes slice
and the SearchUsers response serialization to a lean autocomplete DTO, and keep
the richer attributes and existing detailed user lookup code separate (do not
remove mail/rhatSocialURL/memberOf from the detailed lookup function—leave them
for the explicit detail endpoint).
- Around line 53-60: Add a trusted CA bundle field to the Client struct (e.g.,
caBundlePath or trustedCAPath) and stop relying solely on skipTLSVerify; when
the LDAP connection code creates a tls.Config (the place currently honoring
skipTLSVerify around lines 85-89), load the CA file into an x509.CertPool and
set tls.Config.RootCAs to that pool so verification can remain enabled, falling
back to system roots if no bundle is provided, and preserve skipTLSVerify as an
explicit override.
In `@components/frontend/src/app/api/ldap/groups/route.ts`:
- Around line 9-12: The fetch call that constructs "response = await
fetch(`${BACKEND_URL}/ldap/groups${queryString}`, { method: 'GET', headers })"
lacks an AbortController and timeout; wrap the request with an AbortController,
pass controller.signal into the fetch options, start a timer (e.g., setTimeout)
that calls controller.abort() after a sensible timeout, and clear that timer in
a finally block to ensure cleanup; apply the same pattern to the analogous
fetches in users/route.ts and users/[uid]/route.ts so all LDAP proxy calls use
an AbortController with timeout and clear the timer in finally.
In `@components/frontend/src/app/api/ldap/users/`[uid]/route.ts:
- Around line 12-15: The fetch call that proxies LDAP user requests (using
BACKEND_URL and encodeURIComponent(uid)) can hang; wrap it with an
AbortController and a timeout: create an AbortController, start a setTimeout
that calls controller.abort() after a short configurable ms, pass
controller.signal to fetch, and clear the timeout after fetch completes to avoid
leaks; ensure you handle AbortError (reject/return appropriate 504/timeout
response) in the same route handler so the route remains responsive.
In
`@components/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsx`:
- Around line 54-61: The effect that opens the dropdown (useEffect watching
debouncedQuery, hasResults, isLoading) reopens immediately after a user selects
an entry because the selection writes the chosen uid/group back into the same
`value`/search state; update the component so the committed selection is stored
separately from the search input (e.g., keep `selectedValue` vs `searchText`) or
add a short suppression flag/timestamp (e.g., `suppressOpenAfterSelect` or
`lastSelectAt`) that the useEffect checks before calling `setIsOpen(true)` to
ignore the immediate post-selection debouncedQuery change; modify the selection
handler that currently sets `value` to instead set the separate `selected` state
or set the suppression flag so the next open cycle is skipped.
- Around line 96-104: The Enter key handler currently always calls
e.preventDefault(), which blocks submitting manually typed values when no
suggestion is highlighted; change the logic in the 'Enter' case so that
e.preventDefault() is only invoked when highlightedIndex >= 0 (i.e., when you
are selecting a suggestion). Keep the existing behavior of selecting via
selectItem(users[highlightedIndex].uid) or
selectItem(groups[highlightedIndex].name) when mode is 'user' or 'group'
respectively, and allow the event to proceed (no preventDefault) when
highlightedIndex === -1 so manual-entry submission works.
In `@components/frontend/src/services/queries/use-ldap.ts`:
- Around line 22-28: The LDAP autocomplete hooks currently inherit the
QueryClient default retry behavior causing redundant retries; update
useLDAPUserSearch and useLDAPGroupSearch to pass retry: false in their useQuery
options so failed searches do not retry (i.e., add retry: false alongside
queryKey, queryFn, enabled, staleTime in each hook).
---
Duplicate comments:
In `@components/backend/ldap/client.go`:
- Around line 96-120: The cache currently only evicts expired items on read
(cacheGet) so unused high-cardinality entries accumulate; to fix, add a periodic
cleanup that scans c.cache (the sync.Map) and deletes entries whose
cacheEntry.expiresAt < time.Now(), or alternatively replace this ad-hoc sync.Map
with a bounded TTL cache implementation; implement the periodic purge as a
background goroutine started when the Client is created (e.g., in NewClient or
Client.init) that runs every configurable interval (based on c.cacheTTL or a
separate cleanup interval) and removes expired entries, ensuring to stop the
goroutine on Client shutdown.
- Around line 319-324: The truncate in sanitizeQuery currently slices bytes
(q[:maxQueryLength]) which can split UTF-8 runes; change it to operate on runes
instead: after trimming and replacing newlines, convert q to a rune slice (or
use []rune(q)), check len(runes) against maxQueryLength, and if too long set q =
string(runes[:maxQueryLength]) so truncation is rune-aware; keep the rest of
sanitizeQuery unchanged and ensure the resulting string is what gets passed to
EscapeFilter elsewhere.
In `@components/frontend/src/app/api/ldap/users/route.ts`:
- Around line 9-12: The fetch to `${BACKEND_URL}/ldap/users${queryString}` in
route.ts is unbounded; wrap it with an AbortController and a short configurable
timeout to avoid hanging requests: create an AbortController, start a timer
(e.g., via setTimeout) that calls controller.abort() after the desired timeout,
pass controller.signal into the fetch call that constructs `response`, and clear
the timer after fetch completes or errors; ensure you handle AbortError
separately to return an appropriate timeout response from the route.
In `@components/manifests/overlays/kind/ldap-config.yaml`:
- Line 10: Remove the insecure setting LDAP_SKIP_TLS_VERIFY: "true" (do not
disable certificate verification); change it to "false" or remove the variable
and ensure TLS verification remains enabled, and instead rely on runtime
injection of the LDAP CA certificate into the trust store used by the service;
update any startup/env handling that reads LDAP_SKIP_TLS_VERIFY (search for
LDAP_SKIP_TLS_VERIFY) to treat absence or "false" as the default secure behavior
and document how to supply the LDAP CA via runtime cert injection.
In `@components/manifests/overlays/production/ldap-config.yaml`:
- Line 10: The manifest currently sets LDAP_SKIP_TLS_VERIFY to "true", which
disables LDAPS certificate validation; change this so TLS verification remains
enabled (set LDAP_SKIP_TLS_VERIFY to "false" or remove the setting) and instead
supply trusted CA material at runtime (e.g., provide a LDAP_CA_CERT / mounted CA
bundle or configure the truststore used by the LDAP client). Update the
environment/configuration that defines LDAP_SKIP_TLS_VERIFY and add the CA
provisioning step so certificate validation is enforced in production.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 0a242b37-3da8-4d6f-b73e-3b3c44092573
⛔ Files ignored due to path filters (1)
components/backend/go.sumis excluded by!**/*.sum
📒 Files selected for processing (24)
Makefilecomponents/backend/go.modcomponents/backend/handlers/ldap.gocomponents/backend/ldap/client.gocomponents/backend/ldap/client_test.gocomponents/backend/main.gocomponents/backend/routes.gocomponents/frontend/src/app/api/ldap/groups/route.tscomponents/frontend/src/app/api/ldap/users/[uid]/route.tscomponents/frontend/src/app/api/ldap/users/route.tscomponents/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsxcomponents/frontend/src/components/workspace-sections/sharing-section.tsxcomponents/frontend/src/services/api/index.tscomponents/frontend/src/services/api/ldap.tscomponents/frontend/src/services/queries/index.tscomponents/frontend/src/services/queries/use-ldap.tscomponents/manifests/base/backend-deployment.yamlcomponents/manifests/base/flags.jsoncomponents/manifests/overlays/kind/kustomization.yamlcomponents/manifests/overlays/kind/ldap-config.yamlcomponents/manifests/overlays/local-dev/kustomization.yamlcomponents/manifests/overlays/local-dev/ldap-config.yamlcomponents/manifests/overlays/production/kustomization.yamlcomponents/manifests/overlays/production/ldap-config.yaml
There was a problem hiding this comment.
♻️ Duplicate comments (1)
components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx (1)
29-31:⚠️ Potential issue | 🟠 MajorFeature-flag mock is hardcoded, leaving the LDAP autocomplete path untested.
The mock always returns
{ enabled: false }, so no test exercises the new autocomplete UI that this PR introduces. Regressions in the main feature path won't be caught. Additionally,isLoadingis missing from the return value.Make the mock configurable per-test as suggested in the prior review, and add at least one test with
enabled: trueto cover the autocomplete branch.,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx` around lines 29 - 31, The current mock of useWorkspaceFlag in sharing-section.test.tsx is hardcoded to { enabled: false } and omits isLoading, so the LDAP autocomplete branch isn't exercised; update the vi.mock setup for '@/services/queries/use-feature-flags-admin' to return a configurable mock (e.g., a jest/vi.fn that tests can override) that includes both enabled and isLoading properties, then add at least one test that sets useWorkspaceFlag to return { enabled: true, isLoading: false } to cover the autocomplete UI path (reference the useWorkspaceFlag symbol and the existing tests in sharing-section.test.tsx to wire the per-test override).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In
`@components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx`:
- Around line 29-31: The current mock of useWorkspaceFlag in
sharing-section.test.tsx is hardcoded to { enabled: false } and omits isLoading,
so the LDAP autocomplete branch isn't exercised; update the vi.mock setup for
'@/services/queries/use-feature-flags-admin' to return a configurable mock
(e.g., a jest/vi.fn that tests can override) that includes both enabled and
isLoading properties, then add at least one test that sets useWorkspaceFlag to
return { enabled: true, isLoading: false } to cover the autocomplete UI path
(reference the useWorkspaceFlag symbol and the existing tests in
sharing-section.test.tsx to wire the per-test override).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 692b976b-3fde-43fb-b421-fc21f4b40903
📒 Files selected for processing (1)
components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx
Merge Queue Status
This pull request spent 3 seconds in the queue, with no time running CI. ReasonThe pull request conflicts with the base branch HintYou should update or rebase your pull request. If you want to requeue this pull request, you can post a |
…ace sharing Integrate LDAP to provide autocomplete when sharing workspaces. The backend queries LDAP with substring matching on uid, givenName, and sn for users, and prefix matching on cn for groups. Results are cached in-memory with a 5-minute TTL. The frontend replaces the plain text input with an autocomplete dropdown that debounces queries and supports keyboard navigation. LDAP is optional and gracefully degrades to manual input when unconfigured or unreachable. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> Signed-off-by: Martin Prpič <mprpic@redhat.com>
Register ldap.autocomplete.enabled in flags.json with the scope:workspace tag so it appears in the workspace Feature Flags UI. The backend LDAP endpoints check the flag via FeatureEnabled() (fail-closed), and the frontend uses useFlag() from the Unleash SDK. Workspace admins can toggle LDAP autocomplete per-workspace. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> Signed-off-by: Martin Prpič <mprpic@redhat.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> Signed-off-by: Martin Prpič <mprpic@redhat.com>
The feature flag hook requires a QueryClientProvider, causing all 8 sharing-section tests to fail after the LDAP feature flag gating commit. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> Signed-off-by: Martin Prpič <mprpic@redhat.com>
f66f5a7 to
018f10e
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (12)
components/backend/go.mod (1)
38-39: 🧹 Nitpick | 🔵 TrivialRe-check whether
github.com/go-ldap/ldap/v3should be a direct requirement.This looks like the same unresolved dependency-hygiene point from earlier review feedback: if the LDAP client imports this module directly, Line 39 should not remain
// indirect.
As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security."#!/bin/bash set -euo pipefail # Verify direct imports in backend code rg -nP --type=go '^\s*"github\.com/go-ldap/ldap/v3"' components/backend # Verify current go.mod entry rg -n 'github\.com/go-ldap/ldap/v3' components/backend/go.modExpected result:
- If the first command returns matches, promote
github.com/go-ldap/ldap/v3to a direct requirement and rungo mod tidy.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/backend/go.mod` around lines 38 - 39, The go.mod currently marks github.com/go-ldap/ldap/v3 as indirect; verify whether any backend packages import "github.com/go-ldap/ldap/v3" (search for that import string), and if so, add it as a direct requirement in go.mod (remove the // indirect annotation or run `go get github.com/go-ldap/ldap/v3@latest`) and then run `go mod tidy` to update dependencies; update any module comments so the module remains a direct dependency whenever backend code (the LDAP client) imports ldap/v3.components/frontend/src/app/api/ldap/users/route.ts (1)
9-12:⚠️ Potential issue | 🟠 MajorAdd a timeout/abort to the backend LDAP proxy fetch.
The proxy call can hang indefinitely, which blocks this route and delays fallback behavior.
As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security."⏱️ Bounded fetch pattern
- const response = await fetch(`${BACKEND_URL}/ldap/users${queryString}`, { - method: 'GET', - headers, - }); + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 5000); + let response: Response; + try { + response = await fetch(`${BACKEND_URL}/ldap/users${queryString}`, { + method: 'GET', + headers, + signal: controller.signal, + }); + } finally { + clearTimeout(timeoutId); + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/frontend/src/app/api/ldap/users/route.ts` around lines 9 - 12, The fetch to `${BACKEND_URL}/ldap/users${queryString}` must be bounded: create an AbortController, pass controller.signal into the existing fetch call (which currently stores the result in `response`), start a timeout (e.g., 5s) that calls controller.abort(), and clear the timeout after fetch resolves; also handle the abort case (catch the abort error and return/throw an appropriate timeout response) so the route can't hang indefinitely. Ensure you reference the existing `headers`, `queryString`, and `response` variables when applying the change and properly clean up the timer to avoid leaks.components/manifests/overlays/production/ldap-config.yaml (1)
10-10:⚠️ Potential issue | 🟠 MajorDo not disable LDAPS certificate verification in production.
Line 10 sets
LDAP_SKIP_TLS_VERIFYto"true", which permits MITM impersonation of the directory and weakens trust of autocomplete identity data.Suggested immediate fix in this file
- LDAP_SKIP_TLS_VERIFY: "true" + LDAP_SKIP_TLS_VERIFY: "false"Then mount trusted corporate CA material at runtime (ConfigMap/Secret + trust-store update in container startup) so LDAPS validation succeeds without bypassing verification.
As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/manifests/overlays/production/ldap-config.yaml` at line 10, LDAP_SKIP_TLS_VERIFY is set to "true" which disables LDAPS certificate verification; change this to "false" (or remove the env var) and implement runtime provisioning of trusted CA material instead: mount corporate CA certs via a Secret/ConfigMap and update the container trust store during startup (e.g., append certs and run update-ca-certificates or equivalent) so LDAPS validation succeeds without bypassing verification; ensure the change is applied where LDAP_SKIP_TLS_VERIFY is consumed and make the env var configurable per environment rather than defaulting to skip TLS verification.components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx (1)
29-31:⚠️ Potential issue | 🟠 MajorMake the feature-flag mock test-controllable and cover the enabled LDAP path.
Line 30 hard-codes
useWorkspaceFlagto disabled, so this suite never exercises the autocomplete branch and can miss regressions in the primary new flow.Suggested patch
const mockAddMutate = vi.fn(); const mockRemoveMutate = vi.fn(); const mockRefetch = vi.fn(); +const mockUseWorkspaceFlag = vi.fn(); vi.mock('@/services/queries/use-feature-flags-admin', () => ({ - useWorkspaceFlag: vi.fn(() => ({ enabled: false })), + useWorkspaceFlag: mockUseWorkspaceFlag, })); describe('SharingSection', () => { beforeEach(() => { vi.clearAllMocks(); + mockUseWorkspaceFlag.mockReturnValue({ enabled: false, isLoading: false }); }); + + it('renders LDAP autocomplete when workspace flag is enabled', () => { + mockUseWorkspaceFlag.mockReturnValue({ enabled: true, isLoading: false }); + render(<SharingSection projectName="test-project" />); + fireEvent.click(screen.getByText('Grant Permission')); + expect(screen.getByRole('combobox')).toBeDefined(); + });As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx` around lines 29 - 31, The test currently hard-codes useWorkspaceFlag to always return {enabled: false}, preventing the suite from exercising the LDAP/autocomplete branch; change the mock for useWorkspaceFlag (from '@/services/queries/use-feature-flags-admin') to be a vi.fn() you can control per-test (e.g. export the mocked function and call mockImplementation or mockImplementationOnce to return {enabled: true} in the specific test), then add a test case that sets useWorkspaceFlag to enabled and asserts the autocomplete/LDAP behavior in SharingSection to cover that code path; reference the mocked function useWorkspaceFlag and the test file sharing-section.test.tsx when making the change.components/frontend/src/app/api/ldap/users/[uid]/route.ts (1)
12-15:⚠️ Potential issue | 🟠 MajorAdd timeout/abort handling for the LDAP upstream proxy call.
Line 12 performs an unbounded fetch. If upstream hangs, this route can hang too and consume server capacity.
Suggested patch
try { const { uid } = await params; const headers = await buildForwardHeadersAsync(request); - const response = await fetch(`${BACKEND_URL}/ldap/users/${encodeURIComponent(uid)}`, { - method: 'GET', - headers, - }); + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 5000); + let response: Response; + try { + response = await fetch(`${BACKEND_URL}/ldap/users/${encodeURIComponent(uid)}`, { + method: 'GET', + headers, + signal: controller.signal, + }); + } finally { + clearTimeout(timeoutId); + } const data = await response.text(); return new NextResponse(data, { @@ } catch (error) { + if (error instanceof DOMException && error.name === 'AbortError') { + return NextResponse.json({ error: "LDAP upstream timed out" }, { status: 504 }); + } console.error("Failed to get LDAP user:", error); return NextResponse.json( { error: "Failed to get user" }, { status: 500 } ); }As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity."
Also applies to: 25-30
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/frontend/src/app/api/ldap/users/`[uid]/route.ts around lines 12 - 15, The fetch to the LDAP upstream in route.ts (the call that builds response = await fetch(`${BACKEND_URL}/ldap/users/${encodeURIComponent(uid)}`, { ... })) has no timeout/abort and can hang; update this code and the similar fetch block around lines 25-30 to use an AbortController with a reasonable timeout (create AbortController, pass controller.signal to fetch, set a timer to controller.abort() after the timeout, and clear the timer on success) and handle the resulting AbortError to return a proper 504/timeout response; ensure the same pattern is applied to both fetch calls and that timers are cleared to avoid leaks.components/frontend/src/services/queries/use-ldap.ts (1)
22-42:⚠️ Potential issue | 🟡 MinorAdd
retry: falseto LDAP search hooks.These hooks inherit the default retry behavior from QueryClient. For autocomplete, automatic retries with exponential backoff during LDAP outages degrade UX and create unnecessary backend load.
Proposed fix
export function useLDAPUserSearch(query: string) { return useQuery({ queryKey: ldapKeys.userSearch(query), queryFn: () => ldapApi.searchUsers(query), enabled: query.length >= 2, staleTime: 5 * 60 * 1000, + retry: false, }); } export function useLDAPGroupSearch(query: string) { return useQuery({ queryKey: ldapKeys.groupSearch(query), queryFn: () => ldapApi.searchGroups(query), enabled: query.length >= 2, staleTime: 5 * 60 * 1000, + retry: false, }); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/frontend/src/services/queries/use-ldap.ts` around lines 22 - 42, Both LDAP autocomplete hooks (useLDAPUserSearch and useLDAPGroupSearch) currently inherit QueryClient's default retry behavior; update each useQuery call to disable retries by adding retry: false to the options object so autocomplete queries won't be retried during LDAP outages and won't trigger backoff traffic.components/backend/handlers/ldap.go (2)
97-102: 🧹 Nitpick | 🔵 TrivialInconsistent HTTP status: use 503 for LDAP errors.
SearchUsers/SearchGroupsreturn 503 on LDAP errors, butGetLDAPUserreturns 500. Use 503 consistently since LDAP is an external dependency.Proposed fix
user, err := LDAPClient.GetUser(uid) if err != nil { - log.Printf("LDAP user get error for uid %q: %v", uid, err) - c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to look up user"}) + log.Printf("LDAP user get error: %v", err) + c.JSON(http.StatusServiceUnavailable, gin.H{"error": "LDAP lookup unavailable"}) return }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/backend/handlers/ldap.go` around lines 97 - 102, GetLDAPUser currently returns HTTP 500 when LDAPClient.GetUser fails while SearchUsers/SearchGroups return 503; update the error handling in GetLDAPUser (the block that calls LDAPClient.GetUser) to return http.StatusServiceUnavailable (503) and ensure the log and JSON error message remain, so LDAP errors are consistently reported as 503 across SearchUsers/SearchGroups and GetLDAPUser.
37-40:⚠️ Potential issue | 🟠 MajorRedact user-supplied queries and UIDs from error logs.
These log lines emit user-entered search terms and UIDs on LDAP failures. With autocomplete triggered on keystrokes, an outage will spray PII into backend logs rapidly. Log only the error and a request identifier, not the query content.
Proposed fix
users, err := LDAPClient.SearchUsers(query) if err != nil { - log.Printf("LDAP user search error for query %q: %v", query, err) + log.Printf("LDAP user search error: %v", err) c.JSON(http.StatusServiceUnavailable, gin.H{"error": "LDAP search unavailable"}) return }Apply similar changes to
SearchLDAPGroupsandGetLDAPUser.Also applies to: 67-70, 97-100
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/backend/handlers/ldap.go` around lines 37 - 40, The LDAP error logs currently include user-supplied values (query/uid) in handlers calling LDAPClient.SearchUsers, SearchLDAPGroups and GetLDAPUser; change those log.Printf calls to redact PII by logging only a short message, the error, and a request identifier from the Gin context (e.g., retrieve "request_id" via c.GetString("request_id") or equivalent) instead of printing query or uid, and keep the HTTP responses unchanged (c.JSON(...)). Update all three places (the SearchUsers error handling around LDAPClient.SearchUsers, the SearchLDAPGroups error path, and the GetLDAPUser error path) to follow this pattern.components/backend/ldap/client_test.go (1)
233-257: 🧹 Nitpick | 🔵 TrivialCache TTL test may be flaky under CI load.
The 10ms margin between TTL (50ms) and sleep (60ms) could cause intermittent failures on slow/loaded CI runners.
Consider increasing margin
func TestCacheTTL(t *testing.T) { client := &Client{ - cacheTTL: 50 * time.Millisecond, + cacheTTL: 20 * time.Millisecond, } // ... - time.Sleep(60 * time.Millisecond) + time.Sleep(50 * time.Millisecond)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/backend/ldap/client_test.go` around lines 233 - 257, The TestCacheTTL is flaky because the sleep (60ms) only gives a 10ms margin over client.cacheTTL (50ms); update TestCacheTTL to make the expiry margin larger and more robust by either increasing client.cacheTTL to a larger baseline (e.g., 100ms) or increasing the sleep after cacheSet (e.g., sleep at least 2x the TTL), or implement a short polling loop that repeatedly calls client.cacheGet until it misses with a reasonable overall timeout; update references in the test to the Client struct's cacheTTL and the cacheSet/cacheGet calls accordingly so the test reliably asserts expiration on CI.components/frontend/src/app/api/ldap/groups/route.ts (1)
9-12:⚠️ Potential issue | 🟠 MajorAdd timeout handling to prevent indefinite blocking.
The
fetchcall lacks anAbortControllerwith timeout. If the backend or LDAP stalls, this can block request threads indefinitely, risking thread saturation.Proposed fix
export async function GET(request: NextRequest) { try { const headers = await buildForwardHeadersAsync(request); const queryString = request.nextUrl.search; + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 5000); - const response = await fetch(`${BACKEND_URL}/ldap/groups${queryString}`, { - method: 'GET', - headers, - }); + let response: Response; + try { + response = await fetch(`${BACKEND_URL}/ldap/groups${queryString}`, { + method: 'GET', + headers, + signal: controller.signal, + }); + } finally { + clearTimeout(timeoutId); + }Apply the same pattern to
users/route.tsandusers/[uid]/route.ts.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/frontend/src/app/api/ldap/groups/route.ts` around lines 9 - 12, The fetch in groups route uses no AbortController/timeout and can hang; wrap the request in an AbortController with a configurable timeout (e.g., create controller = new AbortController(), set a setTimeout to controller.abort() after N ms) and pass signal: controller.signal into fetch, catch AbortError to return a sensible timeout response; update the fetch call in components/frontend/src/app/api/ldap/groups/route.ts (the call using BACKEND_URL, queryString, headers) and apply the identical pattern to the analogous fetches in users/route.ts and users/[uid]/route.ts so all LDAP/backend fetches use the same timeout/abort logic.components/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsx (2)
54-61:⚠️ Potential issue | 🟠 MajorSelecting an entry reopens the popup.
After selection,
selectItemwrites the chosen uid/group back tovalue(line 70), which triggers the effect on lines 55-57 to reopen the dropdown since the debounced value has 2+ characters. Suppress the next open cycle after selection or separate committed value from search text.Proposed fix
+ const justSelectedRef = useRef(false); + // Show dropdown when we have a query and results useEffect(() => { + if (justSelectedRef.current) { + justSelectedRef.current = false; + return; + } if (debouncedQuery.length >= 2 && (hasResults || isLoading)) { setIsOpen(true); } else if (debouncedQuery.length < 2) { setIsOpen(false); } }, [debouncedQuery, hasResults, isLoading]); const selectItem = useCallback( (identifier: string) => { + justSelectedRef.current = true; onChange(identifier); setIsOpen(false); }, [onChange] );Also applies to: 68-72
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsx` around lines 54 - 61, The dropdown reopens after selecting an entry because selectItem updates value which keeps debouncedQuery >=2 and retriggers the useEffect that calls setIsOpen(true); fix this by preventing one reopen cycle: either split the controlled value into committed "value" and editable "searchText"/"query" used by debouncedQuery (update only searchText during typing and update value on select), or add a transient ref/flag (e.g., selectionJustMadeRef) that selectItem sets before updating value and the useEffect for debouncedQuery checks this flag and clears it to suppress a single reopen; update references in selectItem, debouncedQuery, useEffect, and setIsOpen accordingly.
96-104:⚠️ Potential issue | 🟠 MajorDon't swallow Enter unless an option is highlighted.
Line 97 always calls
preventDefault()when the popup is open. WithhighlightedIndex === -1, this blocks submitting a manually typed value, breaking the manual-entry fallback.Proposed fix
case 'Enter': - e.preventDefault(); if (highlightedIndex >= 0) { + e.preventDefault(); if (mode === 'user' && users?.[highlightedIndex]) { selectItem(users[highlightedIndex].uid); } else if (mode === 'group' && groups?.[highlightedIndex]) { selectItem(groups[highlightedIndex].name); } } break;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@components/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsx` around lines 96 - 104, The Enter key handler in ldap-autocomplete.tsx currently calls e.preventDefault() unconditionally which blocks submitting a manually typed value when highlightedIndex === -1; update the Enter case so e.preventDefault() and the selection logic (using highlightedIndex, mode, users, groups and selectItem) only run when highlightedIndex >= 0 and a matching item exists, otherwise allow the event to proceed so manual-entry fallback can submit the input.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@components/backend/ldap/client.go`:
- Around line 289-303: ParseGitHubUsername currently uses a case-sensitive
prefix "Github->https://github.com/" so entries like "GITHUB->" or "github->"
are missed; update ParseGitHubUsername to perform a case-insensitive prefix
check (for example, compare strings.ToLower(socialURL) against a lowercased
prefix) and still strip trailing slashes and path segments the same way, also
consider trimming surrounding whitespace before matching so variants like "
Github->..." are handled.
In `@components/manifests/overlays/production/kustomization.yaml`:
- Line 21: The kustomization currently includes ldap-config.yaml which enables
production LDAP wiring while LDAP_SKIP_TLS_VERIFY is set to "true" and ldaps://
is used; remove ldap-config.yaml from the production overlay or gate its
inclusion behind a feature flag until a cert-injection mechanism or fail-closed
behavior is implemented and validated; update the ldap-config manifest (or the
deployment env handling) to ensure LDAP_SKIP_TLS_VERIFY is not true in
production and that a documented cert mount path or secret injection is required
before enabling ldaps:// connections.
In `@Makefile`:
- Line 687: The Makefile currently echoes the decoded Unleash admin password
directly (the echo using kubectl get secret unleash-credentials ... | base64
-d), which leaks a live secret; change the output to avoid printing the secret
by either showing a masked placeholder (e.g., "(hidden)") or printing an
explicit retrieval instruction instead of the value (for example show the
kubectl command to run to view the secret or instruct the user to run kubectl
get secret unleash-credentials -n ${NAMESPACE:-ambient-code} -o
jsonpath='{.data.default-admin-password}' | base64 -d), and ensure the secret
name ("unleash-credentials"), variable ("NAMESPACE"), and the kubectl/base64
pipeline are referenced so maintainers can locate and replace the echo
invocation safely.
---
Duplicate comments:
In `@components/backend/go.mod`:
- Around line 38-39: The go.mod currently marks github.com/go-ldap/ldap/v3 as
indirect; verify whether any backend packages import
"github.com/go-ldap/ldap/v3" (search for that import string), and if so, add it
as a direct requirement in go.mod (remove the // indirect annotation or run `go
get github.com/go-ldap/ldap/v3@latest`) and then run `go mod tidy` to update
dependencies; update any module comments so the module remains a direct
dependency whenever backend code (the LDAP client) imports ldap/v3.
In `@components/backend/handlers/ldap.go`:
- Around line 97-102: GetLDAPUser currently returns HTTP 500 when
LDAPClient.GetUser fails while SearchUsers/SearchGroups return 503; update the
error handling in GetLDAPUser (the block that calls LDAPClient.GetUser) to
return http.StatusServiceUnavailable (503) and ensure the log and JSON error
message remain, so LDAP errors are consistently reported as 503 across
SearchUsers/SearchGroups and GetLDAPUser.
- Around line 37-40: The LDAP error logs currently include user-supplied values
(query/uid) in handlers calling LDAPClient.SearchUsers, SearchLDAPGroups and
GetLDAPUser; change those log.Printf calls to redact PII by logging only a short
message, the error, and a request identifier from the Gin context (e.g.,
retrieve "request_id" via c.GetString("request_id") or equivalent) instead of
printing query or uid, and keep the HTTP responses unchanged (c.JSON(...)).
Update all three places (the SearchUsers error handling around
LDAPClient.SearchUsers, the SearchLDAPGroups error path, and the GetLDAPUser
error path) to follow this pattern.
In `@components/backend/ldap/client_test.go`:
- Around line 233-257: The TestCacheTTL is flaky because the sleep (60ms) only
gives a 10ms margin over client.cacheTTL (50ms); update TestCacheTTL to make the
expiry margin larger and more robust by either increasing client.cacheTTL to a
larger baseline (e.g., 100ms) or increasing the sleep after cacheSet (e.g.,
sleep at least 2x the TTL), or implement a short polling loop that repeatedly
calls client.cacheGet until it misses with a reasonable overall timeout; update
references in the test to the Client struct's cacheTTL and the cacheSet/cacheGet
calls accordingly so the test reliably asserts expiration on CI.
In `@components/frontend/src/app/api/ldap/groups/route.ts`:
- Around line 9-12: The fetch in groups route uses no AbortController/timeout
and can hang; wrap the request in an AbortController with a configurable timeout
(e.g., create controller = new AbortController(), set a setTimeout to
controller.abort() after N ms) and pass signal: controller.signal into fetch,
catch AbortError to return a sensible timeout response; update the fetch call in
components/frontend/src/app/api/ldap/groups/route.ts (the call using
BACKEND_URL, queryString, headers) and apply the identical pattern to the
analogous fetches in users/route.ts and users/[uid]/route.ts so all LDAP/backend
fetches use the same timeout/abort logic.
In `@components/frontend/src/app/api/ldap/users/`[uid]/route.ts:
- Around line 12-15: The fetch to the LDAP upstream in route.ts (the call that
builds response = await
fetch(`${BACKEND_URL}/ldap/users/${encodeURIComponent(uid)}`, { ... })) has no
timeout/abort and can hang; update this code and the similar fetch block around
lines 25-30 to use an AbortController with a reasonable timeout (create
AbortController, pass controller.signal to fetch, set a timer to
controller.abort() after the timeout, and clear the timer on success) and handle
the resulting AbortError to return a proper 504/timeout response; ensure the
same pattern is applied to both fetch calls and that timers are cleared to avoid
leaks.
In `@components/frontend/src/app/api/ldap/users/route.ts`:
- Around line 9-12: The fetch to `${BACKEND_URL}/ldap/users${queryString}` must
be bounded: create an AbortController, pass controller.signal into the existing
fetch call (which currently stores the result in `response`), start a timeout
(e.g., 5s) that calls controller.abort(), and clear the timeout after fetch
resolves; also handle the abort case (catch the abort error and return/throw an
appropriate timeout response) so the route can't hang indefinitely. Ensure you
reference the existing `headers`, `queryString`, and `response` variables when
applying the change and properly clean up the timer to avoid leaks.
In
`@components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx`:
- Around line 29-31: The test currently hard-codes useWorkspaceFlag to always
return {enabled: false}, preventing the suite from exercising the
LDAP/autocomplete branch; change the mock for useWorkspaceFlag (from
'@/services/queries/use-feature-flags-admin') to be a vi.fn() you can control
per-test (e.g. export the mocked function and call mockImplementation or
mockImplementationOnce to return {enabled: true} in the specific test), then add
a test case that sets useWorkspaceFlag to enabled and asserts the
autocomplete/LDAP behavior in SharingSection to cover that code path; reference
the mocked function useWorkspaceFlag and the test file sharing-section.test.tsx
when making the change.
In
`@components/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsx`:
- Around line 54-61: The dropdown reopens after selecting an entry because
selectItem updates value which keeps debouncedQuery >=2 and retriggers the
useEffect that calls setIsOpen(true); fix this by preventing one reopen cycle:
either split the controlled value into committed "value" and editable
"searchText"/"query" used by debouncedQuery (update only searchText during
typing and update value on select), or add a transient ref/flag (e.g.,
selectionJustMadeRef) that selectItem sets before updating value and the
useEffect for debouncedQuery checks this flag and clears it to suppress a single
reopen; update references in selectItem, debouncedQuery, useEffect, and
setIsOpen accordingly.
- Around line 96-104: The Enter key handler in ldap-autocomplete.tsx currently
calls e.preventDefault() unconditionally which blocks submitting a manually
typed value when highlightedIndex === -1; update the Enter case so
e.preventDefault() and the selection logic (using highlightedIndex, mode, users,
groups and selectItem) only run when highlightedIndex >= 0 and a matching item
exists, otherwise allow the event to proceed so manual-entry fallback can submit
the input.
In `@components/frontend/src/services/queries/use-ldap.ts`:
- Around line 22-42: Both LDAP autocomplete hooks (useLDAPUserSearch and
useLDAPGroupSearch) currently inherit QueryClient's default retry behavior;
update each useQuery call to disable retries by adding retry: false to the
options object so autocomplete queries won't be retried during LDAP outages and
won't trigger backoff traffic.
In `@components/manifests/overlays/production/ldap-config.yaml`:
- Line 10: LDAP_SKIP_TLS_VERIFY is set to "true" which disables LDAPS
certificate verification; change this to "false" (or remove the env var) and
implement runtime provisioning of trusted CA material instead: mount corporate
CA certs via a Secret/ConfigMap and update the container trust store during
startup (e.g., append certs and run update-ca-certificates or equivalent) so
LDAPS validation succeeds without bypassing verification; ensure the change is
applied where LDAP_SKIP_TLS_VERIFY is consumed and make the env var configurable
per environment rather than defaulting to skip TLS verification.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 3a3437ba-9c2b-4a66-a579-245469c7daa5
⛔ Files ignored due to path filters (1)
components/backend/go.sumis excluded by!**/*.sum
📒 Files selected for processing (25)
Makefilecomponents/backend/go.modcomponents/backend/handlers/ldap.gocomponents/backend/ldap/client.gocomponents/backend/ldap/client_test.gocomponents/backend/main.gocomponents/backend/routes.gocomponents/frontend/src/app/api/ldap/groups/route.tscomponents/frontend/src/app/api/ldap/users/[uid]/route.tscomponents/frontend/src/app/api/ldap/users/route.tscomponents/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsxcomponents/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsxcomponents/frontend/src/components/workspace-sections/sharing-section.tsxcomponents/frontend/src/services/api/index.tscomponents/frontend/src/services/api/ldap.tscomponents/frontend/src/services/queries/index.tscomponents/frontend/src/services/queries/use-ldap.tscomponents/manifests/base/core/backend-deployment.yamlcomponents/manifests/base/core/flags.jsoncomponents/manifests/overlays/kind/kustomization.yamlcomponents/manifests/overlays/kind/ldap-config.yamlcomponents/manifests/overlays/local-dev/kustomization.yamlcomponents/manifests/overlays/local-dev/ldap-config.yamlcomponents/manifests/overlays/production/kustomization.yamlcomponents/manifests/overlays/production/ldap-config.yaml
|
@Mergifyio queue |
Merge Queue Status
Required conditions to enter a queue
|
Merge Queue Status
This pull request spent 16 seconds in the queue, including 1 second running CI. Required conditions to merge
|
Integrate LDAP to provide autocomplete when sharing workspaces. The backend queries LDAP with substring matching on uid, givenName, and sn for users, and prefix matching on cn for groups. Results are cached in-memory with a 5-minute TTL. The frontend replaces the plain text input with an autocomplete dropdown that debounces queries and supports keyboard navigation. LDAP is optional and gracefully degrades to manual input when unconfigured or unreachable.
Jira: RHOAIENG-50753