Skip to content

feat(searchengine): support Basic Auth for ES connections#165

Merged
Joey0538 merged 1 commit intomainfrom
claude/searchengine-basic-auth
May 8, 2026
Merged

feat(searchengine): support Basic Auth for ES connections#165
Joey0538 merged 1 commit intomainfrom
claude/searchengine-basic-auth

Conversation

@Joey0538
Copy link
Copy Markdown
Collaborator

@Joey0538 Joey0538 commented May 8, 2026

Summary

ECK and most managed Elasticsearch clusters require credentials. This PR adds Basic Auth support to pkg/searchengine and plumbs SEARCH_USERNAME / SEARCH_PASSWORD env vars through both consuming services.

Service Env vars added Default
search-service SEARCH_USERNAME, SEARCH_PASSWORD empty (no auth)
search-sync-worker SEARCH_USERNAME, SEARCH_PASSWORD empty (no auth)

Empty defaults preserve current dev-stack behavior (make up against an unauthenticated elasticsearch:9200); operators set them per-environment for ECK / SaaS clusters.

Notable change: searchengine.New signature

New(ctx, backend, url, tlsSkipVerify) was already four positional args after the recent TLS toggle. Adding two more (username, password) would push call sites to six, all unlabeled. Refactored to a Config struct so each call site is labeled and the API can absorb future knobs without churning every caller:

engine, err := searchengine.New(ctx, searchengine.Config{
    Backend:       cfg.SearchBackend,
    URL:           cfg.SearchURL,
    Username:      cfg.SearchUsername,
    Password:      cfg.SearchPassword,
    TLSSkipVerify: cfg.SearchTLSSkipVerify,
})

All 9 integration-test call sites updated to the struct form. The two main.go call sites use the struct verbatim.

Drive-by fix

make lint was failing on main (typecheck error in history-service/internal/mongorepo/room.go and internal/service/service.go) — PR #157 moved Collection / NewCollection / WithProjection helpers out of the local mongorepo package into pkg/mongoutil, but room.go and the service.go compile-time check were left referencing the old package-local names. Fixed by adding the mongoutil import + qualifier and the missing mongorepo import on the service-side. Without this fix, the pre-commit hook would block any PR from this point forward.

Test plan

  • make lint clean
  • make test clean
  • go vet -tags integration ./pkg/searchengine/... ./search-service/... ./search-sync-worker/... clean
  • Confirm against an ECK cluster that SEARCH_USERNAME=elastic SEARCH_PASSWORD=<from k8s secret> authenticates successfully (CI doesn't cover this path; integration tests still hit unauthenticated containers via the empty-defaults code path)

Notes for ops

  • Recommend a dedicated least-privilege role per service (read-only on user-room-* / messages-* for search-service; write on the same indexes for search-sync-worker) rather than the ECK-generated elastic superuser.
  • Pair with SEARCH_TLS_SKIP_VERIFY=true only on internal/self-signed clusters; default-off remains correct for prod with a properly signed cert.

https://claude.ai/code/session_01UkLD7hpaypxjeh5zbEWTjp


Generated by Claude Code

Summary by CodeRabbit

  • New Features

    • Added support for authenticated connections to search backends via username and password configuration.
  • Refactor

    • Updated search engine initialization to use a configuration-based approach for improved flexibility.
    • Refactored internal repository components for enhanced code reusability.
  • Tests

    • Updated integration tests to reflect configuration changes.

ECK and most managed ES clusters require credentials. Add SEARCH_USERNAME
and SEARCH_PASSWORD env vars on search-service and search-sync-worker
(both default to empty so dev clusters without auth still work).

Also refactor searchengine.New to take a Config struct rather than
growing positional args (now five connection knobs: Backend, URL,
Username, Password, TLSSkipVerify) — labeled fields at every call site
and easy to extend. Test call sites (9) updated to the struct form.

Drive-by: fix history-service/internal/mongorepo/room.go and
service.go to import the Collection / NewCollection / WithProjection
helpers from pkg/mongoutil (they were moved out of the local package
in #157 but room.go and the compile-time check were left referencing
the old package-local names, breaking make lint on main).

https://claude.ai/code/session_01UkLD7hpaypxjeh5zbEWTjp
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 8, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces a configuration-based API for the search engine factory, consolidating backend selection, connection details, and credentials into a single Config struct. Concurrently, it migrates history-service's RoomRepo to use shared mongoutil helpers and reformats test struct definitions.

Changes

Search Engine Configuration Refactoring

Layer / File(s) Summary
Config Struct and Factory Refactoring
pkg/searchengine/factory.go
Defines new exported Config struct with Backend, URL, Username, Password, and TLSSkipVerify fields; refactors New(ctx, cfg Config) factory function to read credentials and TLS settings from config instead of positional arguments.
Service Configuration and Factory Calls
search-service/main.go, search-sync-worker/main.go
Extends service config structs with Username and Password environment variables; updates all searchengine.New calls to construct and pass Config struct with credentials and connection parameters.
Integration Test Updates
search-service/integration_test.go, search-sync-worker/inbox_integration_test.go, search-sync-worker/integration_test.go
Updates all test calls to searchengine.New across multiple test functions to use the new Config struct syntax instead of positional arguments.

Mongo Repository Utility Migration

Layer / File(s) Summary
RoomRepo Collection Utility Update
history-service/internal/mongorepo/room.go
Migrates RoomRepo from local Collection[model.Room] to mongoutil.Collection[model.Room]; updates NewRoomRepo constructor to use mongoutil.NewCollection; adjusts GetMinUserLastSeenAt to call mongoutil.WithProjection for the FindOne option.
Service Import Addition
history-service/internal/service/service.go
Adds import of internal/mongorepo package to support the existing RoomRepository type assertion against mongorepo.RoomRepo.

Test Struct Formatting

Layer / File(s) Summary
Minio Test Struct Formatting
pkg/minioutil/minio_integration_test.go
Reformats all local doc struct type definitions in test functions from compact single-line to multi-line syntax across eleven test cases; fields and JSON tags remain unchanged.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • hmchangw/chat#161: Updates history-service RoomRepo initialization and type wiring, which aligns with this PR's mongo utility migration to mongoutil.Collection.

Suggested reviewers

  • mliu33
  • yenta

Poem

🐰 Hops with joy through config refactoring
Credentials now bundled, clean and tight,
Mongoutil helpers shared, reducing duplication—
Test structs formatted just right! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding Basic Auth support to the searchengine factory and exposing it through new configuration options.
Docstring Coverage ✅ Passed Docstring coverage is 82.61% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 claude/searchengine-basic-auth

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

❤️ Share

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

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/searchengine/factory.go`:
- Around line 24-26: The New function's switch currently only accepts
"elasticsearch" and returns the "unsupported search backend" error despite the
docstring claiming "opensearch" is supported; update the switch in New to accept
"opensearch" as a valid case (mapping it to the same backend initialization as
"elasticsearch") or normalize the backend string to treat "opensearch"
equivalently, ensure the returned SearchEngine is still Ping()-verified, and
remove or adjust any hardcoded error message "unsupported search backend" to
only trigger for truly unknown values.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d2aee8e4-9e0a-4638-8db6-a61391ac68ae

📥 Commits

Reviewing files that changed from the base of the PR and between c779ede and 4b70c2f.

📒 Files selected for processing (9)
  • history-service/internal/mongorepo/room.go
  • history-service/internal/service/service.go
  • pkg/minioutil/minio_integration_test.go
  • pkg/searchengine/factory.go
  • search-service/integration_test.go
  • search-service/main.go
  • search-sync-worker/inbox_integration_test.go
  • search-sync-worker/integration_test.go
  • search-sync-worker/main.go

Comment thread pkg/searchengine/factory.go
Copy link
Copy Markdown
Collaborator

@GITMateuszCharczuk GITMateuszCharczuk left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Copy Markdown
Collaborator

@mliu33 mliu33 left a comment

Choose a reason for hiding this comment

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

Nice

@Joey0538 Joey0538 merged commit a2c2826 into main May 8, 2026
8 checks passed
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.

4 participants