Skip to content

feat(RHOAIENG-50753): add LDAP user and group autocomplete for workspace sharing - #805

Merged
mergify[bot] merged 4 commits into
mainfrom
ldap-autocomplete
Mar 18, 2026
Merged

mergify[bot] merged 4 commits into
mainfrom
ldap-autocomplete

Conversation

@mprpic

@mprpic mprpic commented Mar 4, 2026 •

Copy link
Copy Markdown
Contributor

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

@github-actions

This comment has been minimized.

@mprpic
mprpic force-pushed the ldap-autocomplete branch from a316335 to 18b453a Compare March 5, 2026 02:00
@github-actions

github-actions Bot commented Mar 5, 2026

Copy link
Copy Markdown
Contributor

Ambient Code Platform

Kubernetes-native AI automation platform that orchestrates agentic sessions through containerized microservices. Built with Go (backend, operator), NextJS + Shadcn (frontend), Python (runner), and Kubernetes CRDs.

Technical artifacts still use "vteam" for backward compatibility.

Structure

  • components/backend/ - Go REST API (Gin), manages K8s Custom Resources with multi-tenant project isolation
  • components/frontend/ - NextJS web UI for session management and monitoring
  • components/operator/ - Go Kubernetes controller, watches CRDs and creates Jobs
  • components/runners/ambient-runner/ - Python runner executing Claude Code CLI in Job pods
  • components/ambient-cli/ - Go CLI (acpctl), manages agentic sessions from the command line
  • components/public-api/ - Stateless HTTP gateway, proxies to backend (no direct K8s access)
  • components/manifests/ - Kustomize-based deployment manifests and overlays
  • e2e/ - Cypress end-to-end tests
  • docs/ - Astro Starlight documentation site

Key Files

  • CRD definitions: components/manifests/base/crds/agenticsessions-crd.yaml, projectsettings-crd.yaml
  • Session lifecycle: components/backend/handlers/sessions.go, components/operator/internal/handlers/sessions.go
  • Auth & RBAC middleware: components/backend/handlers/middleware.go
  • K8s client init: components/operator/internal/config/config.go
  • Runner entry point: components/runners/ambient-runner/main.py
  • Route registration: components/backend/routes.go
  • Frontend API layer: components/frontend/src/services/api/, src/services/queries/

Session Flow

User Creates Session → Backend Creates CR → Operator Spawns Job →
Pod Runs Claude CLI → Results Stored in CR → UI Displays Progress

Commands

make 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 Kind

Per-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:4321

Critical Context

  • User token auth required: All user-facing API ops use GetK8sClientsForRequest(c), never the backend service account
  • OwnerReferences on all child resources: Jobs, Secrets, PVCs must have controller owner refs
  • No panic() in production: Return explicit fmt.Errorf with context
  • No any types in frontend: Use proper types, unknown, or generic constraints
  • Conventional commits: Squashed on merge to main

Pre-commit Hooks

The project uses the pre-commit framework to run linters locally before every commit. Configuration lives in .pre-commit-config.yaml.

Install

make setup-hooks

What Runs

On every git commit:

Hook Scope
trailing-whitespace, end-of-file-fixer, check-yaml, check-added-large-files, check-merge-conflict, detect-private-key All files
ruff-format, ruff (check + fix) Python (runners, scripts)
gofmt, go vet, golangci-lint Go (backend, operator, public-api — per-module)
eslint Frontend TypeScript/JavaScript
branch-protection Blocks commits to main/master/production

On every git push:

Hook Scope
push-protection Blocks pushes to main/master/production

Run Manually

make lint                                    # All hooks, all files
pre-commit run gofmt-check --all-files       # Single hook
pre-commit run --files path/to/file.go       # Single file

Skip Hooks

git commit --no-verify    # Skip pre-commit hooks
git push --no-verify      # Skip pre-push hooks

Notes

  • Go and ESLint wrappers (scripts/pre-commit/) skip gracefully if the toolchain is not installed
  • tsc --noEmit and npm run build are not included (slow; CI gates on them)
  • Branch/push protection scripts remain in scripts/git-hooks/ and are invoked by pre-commit

More Info

See BOOKMARKS.md for architecture decisions, development context, code patterns, and component-specific guides.

@github-actions

github-actions Bot commented Mar 5, 2026

Copy link
Copy Markdown
Contributor

Claude Code Review

Summary

This 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 Severity

Blocker Issues

None.


Critical Issues

1. Auth nil check uses wrong client variable in all 3 handlers

Files: components/backend/handlers/ldap.go lines 69-70, 99-100, 129-130

All three handlers discard reqK8s with _ and check k8sDyn (the dynamic client) for nil:

_, k8sDyn := GetK8sClientsForRequest(c)
if k8sDyn == nil {

The documented mandatory pattern across the entire codebase (backend-development.md, k8s-client-usage.md, security-standards.md) is to check the typed K8s client (reqK8s):

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 reqK8s, and creates a maintenance hazard if GetK8sClientsForRequest behavior ever diverges. All three handlers (SearchLDAPUsers, SearchLDAPGroups, GetLDAPUser) need this fix.

Violates: backend-development.md Critical Rules - Authentication and Authorization; k8s-client-usage.md Pattern 1.


Major Issues

2. Custom combobox dropdown built from scratch instead of Shadcn Command

File: components/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsx

The component renders a bare <ul> styled with Shadcn design tokens to simulate a dropdown. Shadcn ships a Command component (built on CMDK) designed exactly for async-populated autocomplete patterns, already available in the project's UI kit.

Per frontend-development.md Shadcn UI Components Only rule: FORBIDDEN: Creating custom UI components from scratch for buttons, inputs, dialogs, etc.

The Shadcn Popover + Command + CommandInput + CommandList pattern is the correct implementation path. It also provides accessibility (ARIA roles, keyboard navigation) for free rather than re-implementing manually.

3. New LDAP connection opened per search, no pooling

File: components/backend/ldap/client.go - SearchUsers, SearchGroups, GetUser

Each search dials a fresh TCP+TLS connection and closes it immediately via defer conn.Close(). Every cache miss creates a new LDAP connection. A user typing 5 characters generates up to 4 cold-connection searches (after the first 2-char trigger). At scale this adds meaningful latency and load on the LDAP server. Recommend persisting a connection with reconnect-on-error, or at minimum documenting this as a known limitation.

4. LDAP_GROUP_BASE_DN env var not mapped in deployment manifest

File: components/manifests/base/backend-deployment.yaml

main.go reads os.Getenv("LDAP_GROUP_BASE_DN") but the deployment manifest only maps LDAP_URL, LDAP_BASE_DN, and LDAP_SKIP_TLS_VERIFY from the ldap-config ConfigMap. Operators who need a non-default group base DN cannot configure it without manually patching the manifest.


Minor Issues

5. k8sDyn obtained but never used for K8s operations

File: components/backend/handlers/ldap.go lines 69, 99, 129

The dynamic client is obtained and only checked for nil, never used for actual K8s operations. Once Critical issue 1 is fixed, simplify to reqK8s, _ := GetK8sClientsForRequest(c).

6. Component exceeds 200-line guideline

File: components/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsx (252 lines)

frontend-development.md sets a 200-line limit. Much of the excess comes from duplicated render blocks for user vs group modes. Extracting a shared ResultItem sub-component would reduce size and eliminate the duplication.

7. Trivial JSDoc comments on self-evident functions

Files: components/frontend/src/services/api/ldap.ts, components/frontend/src/services/queries/use-ldap.ts

Comments like /** Search LDAP users by query (min 2 chars) */ add no information beyond the function name. Per CLAUDE.md: only add comments where logic is not self-evident.


Positive Highlights

  • Injection prevention is solid: sanitizeQuery strips newlines and carriage returns to block log injection, and goldap.EscapeFilter() is applied to every query before it enters an LDAP filter. The %q format verb in log lines ensures special chars are Go-quoted, not literal.
  • TLS hardened correctly: MinVersion: tls.VersionTLS12 is set, and InsecureSkipVerify has a proper nolint:gosec annotation noting it is dev-only and env-var-controlled.
  • Cache is thread-safe: sync.Map is the right primitive for concurrent read-heavy access, and TTL expiry is correctly lazy-evaluated on read.
  • Comprehensive unit tests: 9 test cases cover filter generation (special chars, multi-word, asterisk), DN parsing, query sanitization (newline stripping, truncation), cache TTL expiry, and short-query early-exit. Exactly the coverage this new LDAP package warrants.
  • React Query hooks follow the pattern precisely: enabled: query.length >= 2, staleTime set, hierarchical key factory (ldapKeys.userSearch(query)) correctly includes the query in the cache key with no collision risk.
  • Graceful degradation is well-implemented: optional: true on all ConfigMap refs, LDAPClient == nil guards in every handler, frontend falls back silently to no suggestions.
  • UX improvement in sharing-section.tsx: Clearing subjectName on subject-type switch prevents stale values carrying over between user/group modes.

Recommendations

  1. (Critical) Fix all three handlers: reqK8s, _ := GetK8sClientsForRequest(c) and check reqK8s == nil.
  2. (Major) Replace the custom <ul> dropdown with Shadcn Popover + Command + CommandList.
  3. (Major) Add LDAP_GROUP_BASE_DN to backend-deployment.yaml env mappings and ConfigMap specs.
  4. (Major) Document the per-request connection model as a known limitation, or add connection pooling.
  5. (Minor) Remove trivial JSDoc comments from ldap.ts and use-ldap.ts.
  6. (Minor) Extract a shared ResultItem component to bring ldap-autocomplete.tsx under 200 lines.

@mprpic
mprpic force-pushed the ldap-autocomplete branch from 18b453a to 134aa71 Compare March 5, 2026 02:33
@github-actions

This comment has been minimized.

@mprpic
mprpic force-pushed the ldap-autocomplete branch from 134aa71 to 5c38d48 Compare March 6, 2026 19:30
@mprpic

mprpic commented Mar 6, 2026

Copy link
Copy Markdown
Contributor Author

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.

@github-actions

This comment has been minimized.

@mprpic
mprpic force-pushed the ldap-autocomplete branch from 5c38d48 to 2aad455 Compare March 6, 2026 20:45
@github-actions

This comment has been minimized.

@mprpic
mprpic force-pushed the ldap-autocomplete branch from 2aad455 to ebc132a Compare March 10, 2026 15:13
@coderabbitai

coderabbitai Bot commented Mar 10, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

This 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

Cohort / File(s) Summary
Backend LDAP Client
components/backend/ldap/client.go, components/backend/ldap/client_test.go
Introduces LDAP client with search capabilities for users and groups, caching with TTL, input sanitization, GitHub username extraction, and filter building. Comprehensive unit tests validate parsing, filtering, caching, and query behavior.
Backend LDAP Handlers & Routes
components/backend/handlers/ldap.go, components/backend/routes.go, components/backend/main.go
Adds three public HTTP endpoints for LDAP search and retrieval (SearchLDAPUsers, SearchLDAPGroups, GetLDAPUser) with token validation and error handling. Initializes shared LDAP client in main startup and registers routes in the API group.
Go Dependencies
components/backend/go.mod
Adds three indirect LDAP-related dependencies: go-ntlmssp, asn1-ber, and ldap/v3.
Frontend LDAP API & Queries
components/frontend/src/services/api/ldap.ts, components/frontend/src/services/api/index.ts, components/frontend/src/services/queries/use-ldap.ts, components/frontend/src/services/queries/index.ts
Exports LDAP API service with functions to search users, search groups, and fetch individual users; re-exports as ldapApi. Provides React Query hooks (useLDAPUserSearch, useLDAPGroupSearch, useLDAPUser) with debouncing, caching, and conditional enabling.
Frontend LDAP Proxy Routes
components/frontend/src/app/api/ldap/users/route.ts, components/frontend/src/app/api/ldap/users/[uid]/route.ts, components/frontend/src/app/api/ldap/groups/route.ts
Implements Next.js API route handlers that proxy LDAP requests to the backend, forwarding headers and query parameters with error handling.
Frontend LDAP Components
components/frontend/src/components/workspace-sections/ldap-autocomplete.tsx, components/frontend/src/components/workspace-sections/sharing-section.tsx, components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx
Adds LDAPAutocomplete component with debounced search, keyboard navigation, and accessibility support. Integrates autocomplete into sharing-section behind feature flag ldap.autocomplete.enabled; updates test setup with feature-flag mock.
Kubernetes Configuration
components/manifests/overlays/kind/..., components/manifests/overlays/local-dev/..., components/manifests/overlays/production/..., components/manifests/base/core/backend-deployment.yaml, components/manifests/base/core/flags.json
Adds ldap-config.yaml ConfigMaps across all overlays with LDAP_URL, LDAP_BASE_DN, and LDAP_SKIP_TLS_VERIFY. Updates backend deployment to inject LDAP environment variables. Registers ldap.autocomplete.enabled feature flag.
Makefile
Makefile
Updates port-forward login line to dynamically fetch Unleash admin password from Kubernetes unleash-credentials secret with base64 decoding; falls back to descriptive message if secret unavailable.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding LDAP user and group autocomplete for workspace sharing, with reference to the Jira ticket.
Description check ✅ Passed The description is directly related to the changeset, explaining the integration approach (backend LDAP queries, caching, frontend autocomplete) and graceful degradation when LDAP is unavailable.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ldap-autocomplete
📝 Coding Plan
  • Generate coding plan for human review comments

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

ktdreyer
ktdreyer previously approved these changes Mar 10, 2026
@github-actions

Copy link
Copy Markdown
Contributor

test connection

@github-actions

Copy link
Copy Markdown
Contributor

Ambient Code Platform

Kubernetes-native AI automation platform that orchestrates agentic sessions through containerized microservices. Built with Go (backend, operator), NextJS + Shadcn (frontend), Python (runner), and Kubernetes CRDs.

Technical artifacts still use "vteam" for backward compatibility.

Structure

  • components/backend/ - Go REST API (Gin), manages K8s Custom Resources with multi-tenant project isolation
  • components/frontend/ - NextJS web UI for session management and monitoring
  • components/operator/ - Go Kubernetes controller, watches CRDs and creates Jobs
  • components/runners/ambient-runner/ - Python runner executing Claude Code CLI in Job pods
  • components/ambient-cli/ - Go CLI (acpctl), manages agentic sessions from the command line
  • components/public-api/ - Stateless HTTP gateway, proxies to backend (no direct K8s access)
  • components/manifests/ - Kustomize-based deployment manifests and overlays
  • e2e/ - Cypress end-to-end tests
  • docs/ - Astro Starlight documentation site

Key Files

  • CRD definitions: components/manifests/base/crds/agenticsessions-crd.yaml, projectsettings-crd.yaml
  • Session lifecycle: components/backend/handlers/sessions.go, components/operator/internal/handlers/sessions.go
  • Auth & RBAC middleware: components/backend/handlers/middleware.go
  • K8s client init: components/operator/internal/config/config.go
  • Runner entry point: components/runners/ambient-runner/main.py
  • Route registration: components/backend/routes.go
  • Frontend API layer: components/frontend/src/services/api/, src/services/queries/

Session Flow

User Creates Session → Backend Creates CR → Operator Spawns Job →
Pod Runs Claude CLI → Results Stored in CR → UI Displays Progress

Commands

make 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 Kind

Per-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:4321

Critical Context

  • User token auth required: All user-facing API ops use GetK8sClientsForRequest(c), never the backend service account
  • OwnerReferences on all child resources: Jobs, Secrets, PVCs must have controller owner refs
  • No panic() in production: Return explicit fmt.Errorf with context
  • No any types in frontend: Use proper types, unknown, or generic constraints
  • Conventional commits: Squashed on merge to main

Pre-commit Hooks

The project uses the pre-commit framework to run linters locally before every commit. Configuration lives in .pre-commit-config.yaml.

Install

make setup-hooks

What Runs

On every git commit:

Hook Scope
trailing-whitespace, end-of-file-fixer, check-yaml, check-added-large-files, check-merge-conflict, detect-private-key All files
ruff-format, ruff (check + fix) Python (runners, scripts)
gofmt, go vet, golangci-lint Go (backend, operator, public-api — per-module)
eslint Frontend TypeScript/JavaScript
branch-protection Blocks commits to main/master/production

On every git push:

Hook Scope
push-protection Blocks pushes to main/master/production

Run Manually

make lint                                    # All hooks, all files
pre-commit run gofmt-check --all-files       # Single hook
pre-commit run --files path/to/file.go       # Single file

Skip Hooks

git commit --no-verify    # Skip pre-commit hooks
git push --no-verify      # Skip pre-push hooks

Notes

  • Go and ESLint wrappers (scripts/pre-commit/) skip gracefully if the toolchain is not installed
  • tsc --noEmit and npm run build are not included (slow; CI gates on them)
  • Branch/push protection scripts remain in scripts/git-hooks/ and are invoked by pre-commit

Testing

  • Frontend unit tests: cd components/frontend && npx vitest run --coverage (466 tests, ~74% coverage). See components/frontend/README.md.
  • E2E tests: cd e2e && npx cypress run --browser chrome (58 tests, mock SDK). See e2e/README.md.
  • Runner tests: cd components/runners/ambient-runner && python -m pytest tests/
  • Backend tests: cd components/backend && make test. See components/backend/TEST_GUIDE.md.

More Info

See BOOKMARKS.md for architecture decisions, development context, code patterns, and component-specific guides.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 9

♻️ Duplicate comments (1)
components/manifests/overlays/production/ldap-config.yaml (1)

8-10: ⚠️ Potential issue | 🟠 Major

Do 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

📥 Commits

Reviewing files that changed from the base of the PR and between 07d50e5 and ebc132a.

⛔ Files ignored due to path filters (1)
  • components/backend/go.sum is excluded by !**/*.sum
📒 Files selected for processing (24)
  • Makefile
  • components/backend/go.mod
  • components/backend/handlers/ldap.go
  • components/backend/ldap/client.go
  • components/backend/ldap/client_test.go
  • components/backend/main.go
  • components/backend/routes.go
  • components/frontend/src/app/api/ldap/groups/route.ts
  • components/frontend/src/app/api/ldap/users/[uid]/route.ts
  • components/frontend/src/app/api/ldap/users/route.ts
  • components/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsx
  • components/frontend/src/components/workspace-sections/sharing-section.tsx
  • components/frontend/src/services/api/index.ts
  • components/frontend/src/services/api/ldap.ts
  • components/frontend/src/services/queries/index.ts
  • components/frontend/src/services/queries/use-ldap.ts
  • components/manifests/base/backend-deployment.yaml
  • components/manifests/base/flags.json
  • components/manifests/overlays/kind/kustomization.yaml
  • components/manifests/overlays/kind/ldap-config.yaml
  • components/manifests/overlays/local-dev/kustomization.yaml
  • components/manifests/overlays/local-dev/ldap-config.yaml
  • components/manifests/overlays/production/kustomization.yaml
  • components/manifests/overlays/production/ldap-config.yaml

Comment thread components/backend/go.mod Resolved
Comment thread components/backend/handlers/ldap.go Resolved
Comment thread components/backend/handlers/ldap.go Resolved
Comment thread components/backend/ldap/client_test.go Resolved
Comment thread components/backend/ldap/client.go Resolved
Comment thread components/backend/ldap/client.go Resolved
Comment thread components/backend/main.go Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Review posted - see full analysis below in a follow-up comment.

@github-actions

Copy link
Copy Markdown
Contributor

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.

@github-actions

Copy link
Copy Markdown
Contributor

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.

@github-actions

Copy link
Copy Markdown
Contributor

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.

@github-actions

Copy link
Copy Markdown
Contributor

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between ebc132a and caf55f0.

📒 Files selected for processing (1)
  • components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx

@github-actions

Copy link
Copy Markdown
Contributor

Claude Code Review

Summary

This 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 Severity

Blocker Issues

None

Critical Issues

1. Production manifest ships with TLS verification disabled

components/manifests/overlays/production/ldap-config.yaml sets LDAP_SKIP_TLS_VERIFY: "true". This disables X.509 certificate verification on the LDAPS connection, making production traffic vulnerable to MITM attacks. The nolint comment in ldap/client.go already calls this out as dev-only:

InsecureSkipVerify: c.skipTLSVerify, //nolint:gosec // controlled by LDAP_SKIP_TLS_VERIFY env var for dev

Setting it "true" in kind and local-dev is fine. In production it must be "false" or the key omitted entirely (Go zero value for bool is false).

Violates: security-standards.md — no credential/transport bypass in production.


2. LDAPAutocomplete builds a custom dropdown instead of Shadcn Command/Combobox

ldap-autocomplete.tsx renders a hand-rolled <ul> dropdown with manual keyboard navigation and highlight tracking. Shadcn ships a Command component (built on cmdk) that provides exactly this pattern. Frontend standards are zero-tolerance here:

FORBIDDEN: Creating custom UI components from scratch for buttons, inputs, dialogs, etc.
REQUIRED: Use @/components/ui/* components

The correct approach is Popover + Command + CommandInput + CommandList + CommandItem, which also provides built-in keyboard navigation, ARIA semantics, and theming. The component is also 252 lines, exceeding the 200-line pre-commit limit.

Violates: frontend-development.md — Shadcn UI components only (zero tolerance).


Major Issues

3. In-memory cache has no active eviction

ldap/client.go — the sync.Map-based cache uses lazy expiry: stale entries are only removed when cacheGet is called for that exact key again. Entries for queries never repeated stay in memory indefinitely. In a long-running backend serving many distinct autocomplete queries, the cache will grow without bound. Recommend a periodic sweeper in NewClient:

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: backend-development.md — performance — unbounded list operations.


Minor Issues

4. useWorkspaceFlag isLoading not handled — brief UI flash

sharing-section.tsx:37 only destructures enabled from useWorkspaceFlag. While the flag is loading, ldapEnabled is false, so the plain <Input> renders first and then switches to <LDAPAutocomplete> once resolved. Destructure and use isLoading to disable the input while loading.

Violates: frontend-development.md — loading states must be handled.

5. LDAP startup log reveals deployment configuration at INFO level

main.go:144 logs the full LDAP URL, base DNs, and TLS skip setting at INFO on startup. These are not secrets, but verbose operational detail. A simple log.Println("LDAP client initialized") is preferable.


Positive Highlights

  • Excellent input sanitization: sanitizeQuery strips newlines (preventing log injection) and truncates to maxQueryLength. goldap.EscapeFilter() is used correctly throughout all filter builders — no LDAP injection risk.
  • Graceful degradation is well-implemented: LDAPClient == nil returns empty arrays (not errors) for search, and the feature flag gates the UI correctly. No panics if LDAP is unreachable.
  • User token auth correctly enforced on all three LDAP endpoints: GetK8sClientsForRequest is called in every handler with a 401 return on failure — no service account fallback.
  • React Query hooks follow project patterns exactly: ldapKeys factory, enabled guard on minimum query length, staleTime matching the backend 5-minute cache TTL, clean api/ vs queries/ separation.
  • Strong test coverage for filter logic: client_test.go covers filter building, GitHub username parsing, cache TTL behaviour, and sanitization edge cases.
  • Kubernetes configuration is clean: all LDAP env vars use optional: true, so existing deployments without the ConfigMap are unaffected.

Recommendations

  1. [Critical] Set LDAP_SKIP_TLS_VERIFY: "false" or remove the key from production/ldap-config.yaml.
  2. [Critical] Replace the hand-rolled dropdown in ldap-autocomplete.tsx with Shadcn Popover + Command + CommandList + CommandItem.
  3. [Major] Add a periodic cache sweeper in ldap/client.go NewClient to evict expired entries.
  4. [Minor] Destructure and use isLoading from useWorkspaceFlag in sharing-section.tsx.
  5. [Minor] Reduce the LDAP startup log verbosity in main.go.

Review generated by Claude Code using repository standards from .claude/context/ and .claude/patterns/.

@ambient-code ambient-code Bot modified the milestone: Merge Queue Mar 11, 2026
@ambient-code ambient-code deleted a comment from ambient-code Bot Mar 16, 2026
@Gkrumbach07

Copy link
Copy Markdown
Contributor

Review Queue Status

Check Status Detail
CI pass ---
Conflicts FAIL Has merge conflicts with main
Reviews FAIL CHANGES_REQUESTED from @ktdreyer — LDAP cert injection approach needs resolution
Jira pass RHOAIENG-50753

Action needed: Rebase to resolve conflicts. Discuss LDAP cert injection approach with @ktdreyer (runtime cert mounting vs baking into image).

Auto-generated by Review Queue workflow. Updated when PR changes.

@mprpic
mprpic force-pushed the ldap-autocomplete branch from caf55f0 to 732a07b Compare March 17, 2026 12:24

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 8

♻️ Duplicate comments (5)
components/manifests/overlays/kind/ldap-config.yaml (1)

10-10: ⚠️ Potential issue | 🟠 Major

Do 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 | 🟠 Major

Do 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.

🔧 Minimal config 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."
🤖 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 | 🟠 Major

Bound 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.

⏱️ 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);
+    }
As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security."
🤖 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 | 🟠 Major

Expired cache entries still accumulate forever.

cacheGet only evicts on read. With autocomplete's high-cardinality queries, entries that are never hit again stay in sync.Map indefinitely, 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 | 🟠 Major

Make sanitizeQuery rune-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 reaches EscapeFilter.

💡 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

📥 Commits

Reviewing files that changed from the base of the PR and between caf55f0 and 732a07b.

⛔ Files ignored due to path filters (1)
  • components/backend/go.sum is excluded by !**/*.sum
📒 Files selected for processing (24)
  • Makefile
  • components/backend/go.mod
  • components/backend/handlers/ldap.go
  • components/backend/ldap/client.go
  • components/backend/ldap/client_test.go
  • components/backend/main.go
  • components/backend/routes.go
  • components/frontend/src/app/api/ldap/groups/route.ts
  • components/frontend/src/app/api/ldap/users/[uid]/route.ts
  • components/frontend/src/app/api/ldap/users/route.ts
  • components/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsx
  • components/frontend/src/components/workspace-sections/sharing-section.tsx
  • components/frontend/src/services/api/index.ts
  • components/frontend/src/services/api/ldap.ts
  • components/frontend/src/services/queries/index.ts
  • components/frontend/src/services/queries/use-ldap.ts
  • components/manifests/base/backend-deployment.yaml
  • components/manifests/base/flags.json
  • components/manifests/overlays/kind/kustomization.yaml
  • components/manifests/overlays/kind/ldap-config.yaml
  • components/manifests/overlays/local-dev/kustomization.yaml
  • components/manifests/overlays/local-dev/ldap-config.yaml
  • components/manifests/overlays/production/kustomization.yaml
  • components/manifests/overlays/production/ldap-config.yaml

Comment thread components/backend/handlers/ldap.go Resolved
Comment thread components/backend/ldap/client.go Resolved
Comment thread components/backend/ldap/client.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx (1)

29-31: ⚠️ Potential issue | 🟠 Major

Feature-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, isLoading is 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: true to 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

📥 Commits

Reviewing files that changed from the base of the PR and between 732a07b and f66f5a7.

📒 Files selected for processing (1)
  • components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx

@ambient-code ambient-code Bot modified the milestone: Review Queue Mar 17, 2026
ktdreyer
ktdreyer previously approved these changes Mar 18, 2026
@mergify

mergify Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-03-18 17:29 UTC · Rule: default
  • 🚫 Left the queue — 2026-03-18 17:29 UTC · at f66f5a7e3d17b05677aec23896f41bde868dc0bf

This pull request spent 3 seconds in the queue, with no time running CI.

Reason

The pull request conflicts with the base branch

Hint

You should update or rebase your pull request.

If you want to requeue this pull request, you can post a @mergifyio queue comment.

@mergify mergify Bot added the dequeued label Mar 18, 2026
mprpic and others added 4 commits March 18, 2026 13:31
…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>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (12)
components/backend/go.mod (1)

38-39: 🧹 Nitpick | 🔵 Trivial

Re-check whether github.com/go-ldap/ldap/v3 should 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.mod

Expected result:

  • If the first command returns matches, promote github.com/go-ldap/ldap/v3 to a direct requirement and run go 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 | 🟠 Major

Add 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 | 🟠 Major

Do not disable LDAPS certificate verification in production.

Line 10 sets LDAP_SKIP_TLS_VERIFY to "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 | 🟠 Major

Make the feature-flag mock test-controllable and cover the enabled LDAP path.

Line 30 hard-codes useWorkspaceFlag to 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 | 🟠 Major

Add 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 | 🟡 Minor

Add retry: false to 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 | 🔵 Trivial

Inconsistent HTTP status: use 503 for LDAP errors.

SearchUsers/SearchGroups return 503 on LDAP errors, but GetLDAPUser returns 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 | 🟠 Major

Redact 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 SearchLDAPGroups and GetLDAPUser.

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 | 🔵 Trivial

Cache 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 | 🟠 Major

Add timeout handling to prevent indefinite blocking.

The fetch call lacks an AbortController with 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.ts and users/[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 | 🟠 Major

Selecting an entry reopens the popup.

After selection, selectItem writes the chosen uid/group back to value (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 | 🟠 Major

Don't swallow Enter unless an option is highlighted.

Line 97 always calls preventDefault() when the popup is open. With highlightedIndex === -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

📥 Commits

Reviewing files that changed from the base of the PR and between f66f5a7 and 018f10e.

⛔ Files ignored due to path filters (1)
  • components/backend/go.sum is excluded by !**/*.sum
📒 Files selected for processing (25)
  • Makefile
  • components/backend/go.mod
  • components/backend/handlers/ldap.go
  • components/backend/ldap/client.go
  • components/backend/ldap/client_test.go
  • components/backend/main.go
  • components/backend/routes.go
  • components/frontend/src/app/api/ldap/groups/route.ts
  • components/frontend/src/app/api/ldap/users/[uid]/route.ts
  • components/frontend/src/app/api/ldap/users/route.ts
  • components/frontend/src/components/workspace-sections/__tests__/sharing-section.test.tsx
  • components/frontend/src/components/workspace-sections/_components/ldap-autocomplete.tsx
  • components/frontend/src/components/workspace-sections/sharing-section.tsx
  • components/frontend/src/services/api/index.ts
  • components/frontend/src/services/api/ldap.ts
  • components/frontend/src/services/queries/index.ts
  • components/frontend/src/services/queries/use-ldap.ts
  • components/manifests/base/core/backend-deployment.yaml
  • components/manifests/base/core/flags.json
  • components/manifests/overlays/kind/kustomization.yaml
  • components/manifests/overlays/kind/ldap-config.yaml
  • components/manifests/overlays/local-dev/kustomization.yaml
  • components/manifests/overlays/local-dev/ldap-config.yaml
  • components/manifests/overlays/production/kustomization.yaml
  • components/manifests/overlays/production/ldap-config.yaml

Comment thread components/backend/ldap/client.go Resolved
Comment thread Makefile Resolved
@mprpic

mprpic commented Mar 18, 2026

Copy link
Copy Markdown
Contributor Author

@Mergifyio queue

@mergify

mergify Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • 🟠 Waiting for queue conditions
  • ⏳ Enter queue
  • ⏳ Run checks
  • ⏳ Merge
Required conditions to enter a queue
  • -closed [📌 queue requirement]
  • -conflict [📌 queue requirement]
  • -draft [📌 queue requirement]
  • any of [📌 queue -> configuration change requirements]:
    • -mergify-configuration-changed
    • check-success = Configuration changed
  • any of [🔀 queue conditions]:
    • all of [📌 queue conditions of queue default]:
      • #approved-reviews-by >= 1 [🛡 GitHub repository ruleset rule protect-main]
      • #approved-reviews-by>=1
      • #changes-requested-reviews-by = 0 [🛡 GitHub repository ruleset rule protect-main]
      • #changes-requested-reviews-by=0
      • check-success=End-to-End Tests
      • check-success=test-local-dev-simulation
      • check-success=validate-manifests
      • commented-reviews-by=coderabbitai[bot]
    • all of [📌 queue conditions of queue large-pr]:
      • #approved-reviews-by>=2
      • #approved-reviews-by >= 1 [🛡 GitHub repository ruleset rule protect-main]
      • #changes-requested-reviews-by = 0 [🛡 GitHub repository ruleset rule protect-main]
      • #changes-requested-reviews-by=0
      • check-success=End-to-End Tests
      • check-success=test-local-dev-simulation
      • check-success=validate-manifests
      • commented-reviews-by=coderabbitai[bot]

@mergify mergify Bot added the queued label Mar 18, 2026
mergify Bot added a commit that referenced this pull request Mar 18, 2026
@mergify
mergify Bot merged commit 44d7e11 into main Mar 18, 2026
37 checks passed
@mergify
mergify Bot deleted the ldap-autocomplete branch March 18, 2026 20:01
@mergify

mergify Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor

Merge Queue Status

This pull request spent 16 seconds in the queue, including 1 second running CI.

Required conditions to merge

@mergify mergify Bot removed the queued label Mar 18, 2026
@ambient-code ambient-code Bot removed this from the Review Queue milestone Mar 19, 2026
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.

3 participants