Skip to content

feat: configure logger and MongoDB TLS from environment variables and remove gRPC residuals#2043

Merged
ClaraTersi merged 5 commits intodevelopfrom
feature/MDZ-2023
Apr 13, 2026
Merged

feat: configure logger and MongoDB TLS from environment variables and remove gRPC residuals#2043
ClaraTersi merged 5 commits intodevelopfrom
feature/MDZ-2023

Conversation

@ClaraTersi
Copy link
Copy Markdown
Member

Summary

  • Standardize logger initialization in both ledger and CRM to read LOG_LEVEL, ENV_NAME, and OTEL_RESOURCE_SERVICE_NAME from environment variables with sensible defaults.
  • Add MongoDB TLS CA certificate support via MONGO_ONBOARDING_TLS_CA_CERT, MONGO_TRANSACTION_TLS_CA_CERT, and MONGO_TLS_CA_CERT env vars, following the same pattern as Redis (REDIS_CA_CERT → libRedis.TLSConfig).
  • Remove residual gRPC references left over from the component unification.

Logger configuration

Both entry points now read all logger config from env vars instead of hardcoding values:

  • LOG_LEVEL (default: "info")
  • ENV_NAME (default: "development")
  • OTEL_RESOURCE_SERVICE_NAME (default: "ledger" or "crm")

MongoDB TLS

MongoDB connections relied on tlsInsecure=true in the URI to skip certificate validation. Operators can now provide a base64-encoded PEM CA certificate via environment variable, enabling proper TLS validation against DocumentDB, Atlas, or self-signed CAs. The lib-commons mongo package already supported TLS (libMongo.Config.TLS field) — this change wires it through the bootstrap layer.

gRPC cleanup

After unifying ledger components, several gRPC references remained in the codebase despite the gRPC server/client code being removed. This PR cleans up:

  • ErrGRPCServiceUnavailable error constant and its mapping
  • ProtoAddress config field in CRM (unused, no gRPC server)
  • PROTO_ADDRESS in ledger integration test env setup
  • Comments and test names still referencing gRPC
  • Docs (CLAUDE.md, STRUCTURE.md, llms-full.txt) referencing PROTO_ADDRESS and mgrpc/

Left untouched: go.mod indirect deps (transitive via OpenTelemetry), OTEL gRPC collector ports (infra, not app), CHANGELOG.md (historical), PROJECT_RULES.md.

@ClaraTersi ClaraTersi requested review from a team as code owners April 13, 2026 12:48
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 13, 2026

Walkthrough

Removed CRM gRPC configuration and related error constant; added optional MongoDB TLS CA certificate configuration and wiring; made logger initialization read environment variables with defaults; bumped CRM VERSION to v3.6.0; small comment and test renames. (50 words)

Changes

Cohort / File(s) Summary
gRPC / docs removal
CLAUDE.md, STRUCTURE.md, llms-full.txt, components/ledger/internal/bootstrap/config_integration_test.go
Removed PROTO_ADDRESS doc/config entry and mgrpc directory reference; updated integration-test env setup and related documentation strings to drop gRPC-specific references.
Removed exported error
pkg/constant/errors.go, pkg/errors.go
Deleted exported error ErrGRPCServiceUnavailable and removed its mapping in ValidateBusinessError (input errors of that type now fall through).
Logger initialization changes
components/crm/cmd/app/main.go, components/ledger/cmd/app/main.go
Logger config now reads LOG_LEVEL, ENV_NAME, and OTEL_RESOURCE_SERVICE_NAME (trimmed/lowercased with defaults) instead of using hardcoded defaults / resolve helper.
MongoDB TLS config (CRM)
components/crm/.env.example, components/crm/internal/bootstrap/config.go
Added MONGO_TLS_CA_CERT env var and MongoTLSCACert config field; Mongo client initialization now conditionally builds/passes a TLS config when CA cert is provided.
MongoDB TLS config (Ledger)
components/ledger/.env.example, components/ledger/internal/bootstrap/config.go, components/ledger/internal/bootstrap/config.mongo.onboarding.go, components/ledger/internal/bootstrap/config.mongo.transaction.go
Added MONGO_ONBOARDING_TLS_CA_CERT and MONGO_TRANSACTION_TLS_CA_CERT env vars and config fields; onboarding and transaction Mongo client initializers now optionally construct and pass TLS configs when CA certs are set.
Version bump & wording/test edits
components/crm/.env.example, components/ledger/internal/services/command/create_account.go, components/ledger/internal/services/command/create_account_test.go, components/ledger/internal/services/command/create_asset.go, components/ledger/internal/services/command/create_asset_test.go, components/ledger/internal/services/command/delete_account.go
Bumped CRM VERSION v3.5.1 → v3.6.0; removed gRPC-specific wording from several service comments and test case names; adjusted some mocked error messages.

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

@lerian-studio
Copy link
Copy Markdown
Contributor

lerian-studio commented Apr 13, 2026

🔒 Security Scan Results — crm

Trivy

Filesystem Scan

✅ No vulnerabilities or secrets found.

Docker Image Scan

✅ No vulnerabilities found.


Docker Hub Health Score Compliance

✅ Policies — 4/4 met

Policy Status
Default non-root user ✅ Passed
No fixable critical/high CVEs ✅ Passed
No high-profile vulnerabilities ✅ Passed
No AGPL v3 licenses ✅ Passed

🔍 View full scan logs

@lerian-studio
Copy link
Copy Markdown
Contributor

lerian-studio commented Apr 13, 2026

🔒 Security Scan Results — ledger

Trivy

Filesystem Scan

✅ No vulnerabilities or secrets found.

Docker Image Scan

✅ No vulnerabilities found.


Docker Hub Health Score Compliance

✅ Policies — 4/4 met

Policy Status
Default non-root user ✅ Passed
No fixable critical/high CVEs ✅ Passed
No high-profile vulnerabilities ✅ Passed
No AGPL v3 licenses ✅ Passed

🔍 View full scan logs

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: 4

Caution

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

⚠️ Outside diff range comments (1)
components/ledger/.env.example (1)

57-67: ⚠️ Potential issue | 🟡 Minor

Reorder new Mongo TLS keys to satisfy dotenv-linter key ordering.

The newly added keys trigger UnorderedKey warnings; move them before each corresponding MONGO_*_URI block key.

Suggested fix
 # MONGO DB - Onboarding
+MONGO_ONBOARDING_TLS_CA_CERT=
 MONGO_ONBOARDING_URI=mongodb
 MONGO_ONBOARDING_HOST=midaz-mongodb
@@
 MONGO_ONBOARDING_MAX_POOL_SIZE=1000
 MONGO_ONBOARDING_PARAMETERS=
-MONGO_ONBOARDING_TLS_CA_CERT=
@@
 # MONGO DB - Transaction
+MONGO_TRANSACTION_TLS_CA_CERT=
 MONGO_TRANSACTION_URI=mongodb
 MONGO_TRANSACTION_HOST=midaz-mongodb
@@
 MONGO_TRANSACTION_MAX_POOL_SIZE=1000
 MONGO_TRANSACTION_PARAMETERS=
-MONGO_TRANSACTION_TLS_CA_CERT=

Also applies to: 100-110

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@components/ledger/.env.example` around lines 57 - 67, The dotenv keys are out
of order causing UnorderedKey linter warnings; reorder the TLS-related and
parameter keys (MONGO_ONBOARDING_PARAMETERS, MONGO_ONBOARDING_TLS_CA_CERT) so
they appear immediately before or grouped with their corresponding
MONGO_ONBOARDING_*_URI block (i.e., move MONGO_ONBOARDING_PARAMETERS and
MONGO_ONBOARDING_TLS_CA_CERT into the logical position before or adjacent to
MONGO_ONBOARDING_URI), and apply the same reorder for the other Mongo blocks
mentioned (also fix the same ordering in the later block around the 100-110
region) to satisfy dotenv-linter key ordering.
🤖 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/crm/.env.example`:
- Line 18: The environment key order is incorrect: move the MONGO_TLS_CA_CERT
entry so it appears before MONGO_URI to satisfy dotenv-linter’s UnorderedKey
rule; update the .env.example so MONGO_TLS_CA_CERT is placed immediately above
MONGO_URI (preserving its value/comment style) to match the file’s key-order
convention.

In `@components/crm/cmd/app/main.go`:
- Around line 37-50: Normalize envName the same way logLevel is normalized
before passing to libZap.Environment: trim whitespace and lower-case the value
(apply strings.TrimSpace and strings.ToLower) and default to "development" when
empty, mirroring the pattern used in resolveLoggerEnvironment() from
components/ledger/internal/bootstrap/config.go; update the envName assignment
and any related variable usage so libZap.New receives
libZap.Environment(normalizedEnvName).

In `@components/crm/internal/bootstrap/config.go`:
- Around line 212-215: Trim whitespace from cfg.MongoTLSCACert before
checking/using it so an env value with only whitespace doesn't enable TLS with
an invalid base64 payload; update the block that sets tlsCfg (the tlsCfg
variable and the libMongo.TLSConfig{CACertBase64: cfg.MongoTLSCACert}
assignment) to use strings.TrimSpace(cfg.MongoTLSCACert) and only assign tlsCfg
when the trimmed value is non-empty.

In `@components/ledger/cmd/app/main.go`:
- Around line 37-50: Replace the direct use of raw ENV_NAME when building the
zap config with the normalized value returned by resolveLoggerEnvironment;
specifically, call bootstrap.resolveLoggerEnvironment(os.Getenv("ENV_NAME")) (or
the appropriate import path) and pass its result into libZap.Environment in the
libZap.New call so the environment is trimmed/case-normalized and falls back to
EnvironmentDevelopment for invalid values instead of passing the unnormalized
envName.

---

Outside diff comments:
In `@components/ledger/.env.example`:
- Around line 57-67: The dotenv keys are out of order causing UnorderedKey
linter warnings; reorder the TLS-related and parameter keys
(MONGO_ONBOARDING_PARAMETERS, MONGO_ONBOARDING_TLS_CA_CERT) so they appear
immediately before or grouped with their corresponding MONGO_ONBOARDING_*_URI
block (i.e., move MONGO_ONBOARDING_PARAMETERS and MONGO_ONBOARDING_TLS_CA_CERT
into the logical position before or adjacent to MONGO_ONBOARDING_URI), and apply
the same reorder for the other Mongo blocks mentioned (also fix the same
ordering in the later block around the 100-110 region) to satisfy dotenv-linter
key ordering.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: a9e12cac-ee02-45a1-8c1c-173863193ea0

📥 Commits

Reviewing files that changed from the base of the PR and between 803b17e and b27bc39.

📒 Files selected for processing (19)
  • CLAUDE.md
  • STRUCTURE.md
  • components/crm/.env.example
  • components/crm/cmd/app/main.go
  • components/crm/internal/bootstrap/config.go
  • components/ledger/.env.example
  • components/ledger/cmd/app/main.go
  • components/ledger/internal/bootstrap/config.go
  • components/ledger/internal/bootstrap/config.mongo.onboarding.go
  • components/ledger/internal/bootstrap/config.mongo.transaction.go
  • components/ledger/internal/bootstrap/config_integration_test.go
  • components/ledger/internal/services/command/create_account.go
  • components/ledger/internal/services/command/create_account_test.go
  • components/ledger/internal/services/command/create_asset.go
  • components/ledger/internal/services/command/create_asset_test.go
  • components/ledger/internal/services/command/delete_account.go
  • llms-full.txt
  • pkg/constant/errors.go
  • pkg/errors.go
💤 Files with no reviewable changes (5)
  • STRUCTURE.md
  • CLAUDE.md
  • pkg/constant/errors.go
  • llms-full.txt
  • pkg/errors.go

Comment thread components/crm/.env.example
Comment thread components/crm/cmd/app/main.go Outdated
Comment thread components/crm/internal/bootstrap/config.go
Comment thread components/ledger/cmd/app/main.go Outdated
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

♻️ Duplicate comments (2)
components/ledger/cmd/app/main.go (1)

37-50: ⚠️ Potential issue | 🟡 Minor

Missing validation for ENV_NAME environment value.

While envName is properly trimmed and lowercased, it's cast directly to libZap.Environment without validation. Invalid values (e.g., "prod", "test", or typos) would create an unrecognized environment type, whereas bootstrap/config.go uses resolveLoggerEnvironment() to handle this with a safe fallback to EnvironmentDevelopment.

Consider either:

  1. Exporting and reusing resolveLoggerEnvironment() from the bootstrap package, or
  2. Adding inline validation with a switch statement
Option 2: Inline validation
 	envName := strings.ToLower(strings.TrimSpace(os.Getenv("ENV_NAME")))
 	if envName == "" {
 		envName = "development"
 	}

+	loggerEnv := libZap.EnvironmentDevelopment
+	switch envName {
+	case "production":
+		loggerEnv = libZap.EnvironmentProduction
+	case "staging":
+		loggerEnv = libZap.EnvironmentStaging
+	case "uat":
+		loggerEnv = libZap.EnvironmentUAT
+	case "local":
+		loggerEnv = libZap.EnvironmentLocal
+	}
+
 	logger, err := libZap.New(libZap.Config{
-		Environment:     libZap.Environment(envName),
+		Environment:     loggerEnv,
 		Level:           logLevel,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@components/ledger/cmd/app/main.go` around lines 37 - 50, The envName string
is lowercased and used directly as libZap.Environment which can produce invalid
environment values; update main.go to validate/normalize envName before passing
it into libZap.New by either calling the existing resolveLoggerEnvironment()
from the bootstrap package (export and use resolveLoggerEnvironment) or
implement an inline switch that maps permitted inputs (e.g.,
"development","staging","production") to libZap.Environment constants and falls
back to libZap.EnvironmentDevelopment; ensure you reference and replace the
current envName -> libZap.Environment conversion where logger is constructed so
the logger receives a validated libZap.Environment value.
components/crm/cmd/app/main.go (1)

37-50: ⚠️ Potential issue | 🟡 Minor

Missing validation for ENV_NAME environment value.

Same issue as in ledger/cmd/app/main.go: the direct cast to libZap.Environment(envName) doesn't validate against known environment types. Invalid values pass through without falling back to a safe default.

Additionally, OTEL_RESOURCE_SERVICE_NAME (line 42) isn't trimmed, unlike LOG_LEVEL and ENV_NAME, creating a minor inconsistency.

Suggested fix with validation and consistent trimming
 	envName := strings.ToLower(strings.TrimSpace(os.Getenv("ENV_NAME")))
 	if envName == "" {
 		envName = "development"
 	}

-	otelServiceName := os.Getenv("OTEL_RESOURCE_SERVICE_NAME")
+	otelServiceName := strings.TrimSpace(os.Getenv("OTEL_RESOURCE_SERVICE_NAME"))
 	if otelServiceName == "" {
 		otelServiceName = "crm"
 	}

+	loggerEnv := libZap.EnvironmentDevelopment
+	switch envName {
+	case "production":
+		loggerEnv = libZap.EnvironmentProduction
+	case "staging":
+		loggerEnv = libZap.EnvironmentStaging
+	case "uat":
+		loggerEnv = libZap.EnvironmentUAT
+	case "local":
+		loggerEnv = libZap.EnvironmentLocal
+	}
+
 	logger, err := libZap.New(libZap.Config{
-		Environment:     libZap.Environment(envName),
+		Environment:     loggerEnv,
 		Level:           logLevel,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@components/crm/cmd/app/main.go` around lines 37 - 50, ENV_NAME is not
validated before casting to libZap.Environment and OTEL_RESOURCE_SERVICE_NAME
isn't trimmed; update main.go to trim and validate ENV_NAME against allowed
values (e.g., "development","staging","production") before converting with
libZap.Environment and fall back to "development" for unknown values, and also
trim OTEL_RESOURCE_SERVICE_NAME like LOG_LEVEL and ENV_NAME; modify the code
around envName, otelServiceName, and the libZap.New call (references: envName
variable, OTEL_RESOURCE_SERVICE_NAME env var, and libZap.Environment cast) to
perform trimming and explicit validation with a safe default.
🤖 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/crm/.env.example`:
- Around line 4-5: The .env.example file triggers a dotenv-linter UnorderedKey
warning because the keys are not alphabetically ordered; swap the two entries so
SERVER_PORT appears before VERSION (i.e., ensure the keys SERVER_PORT and
VERSION are sorted) to satisfy the linter, or alternatively keep the original
order but add a linter-ignore comment if you intentionally want version first.

---

Duplicate comments:
In `@components/crm/cmd/app/main.go`:
- Around line 37-50: ENV_NAME is not validated before casting to
libZap.Environment and OTEL_RESOURCE_SERVICE_NAME isn't trimmed; update main.go
to trim and validate ENV_NAME against allowed values (e.g.,
"development","staging","production") before converting with libZap.Environment
and fall back to "development" for unknown values, and also trim
OTEL_RESOURCE_SERVICE_NAME like LOG_LEVEL and ENV_NAME; modify the code around
envName, otelServiceName, and the libZap.New call (references: envName variable,
OTEL_RESOURCE_SERVICE_NAME env var, and libZap.Environment cast) to perform
trimming and explicit validation with a safe default.

In `@components/ledger/cmd/app/main.go`:
- Around line 37-50: The envName string is lowercased and used directly as
libZap.Environment which can produce invalid environment values; update main.go
to validate/normalize envName before passing it into libZap.New by either
calling the existing resolveLoggerEnvironment() from the bootstrap package
(export and use resolveLoggerEnvironment) or implement an inline switch that
maps permitted inputs (e.g., "development","staging","production") to
libZap.Environment constants and falls back to libZap.EnvironmentDevelopment;
ensure you reference and replace the current envName -> libZap.Environment
conversion where logger is constructed so the logger receives a validated
libZap.Environment value.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 361a4461-e14b-4091-ae51-ff9c4b515b0d

📥 Commits

Reviewing files that changed from the base of the PR and between b27bc39 and 74180a1.

📒 Files selected for processing (7)
  • components/crm/.env.example
  • components/crm/cmd/app/main.go
  • components/crm/internal/bootstrap/config.go
  • components/ledger/.env.example
  • components/ledger/cmd/app/main.go
  • components/ledger/internal/bootstrap/config.mongo.onboarding.go
  • components/ledger/internal/bootstrap/config.mongo.transaction.go

Comment thread components/crm/.env.example
Copy link
Copy Markdown
Contributor

@gandalf-at-lerian gandalf-at-lerian left a comment

Choose a reason for hiding this comment

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

Clean PR — well-scoped, consistent patterns across all three concerns.

Logger config: Both entry points now read from env with sensible defaults. One minor observation: CRM previously had resolveLoggerEnvironment with an explicit switch that defaulted invalid values to EnvironmentDevelopment. The new code does a direct cast libZap.Environment(envName) — if someone sets ENV_NAME=typo, the old code would silently default, while the new code passes the raw string through. Not a blocker since lib-commons likely handles this, but worth a quick check that the zap wrapper doesn't panic on unknown environment values.

MongoDB TLS: Follows the same pattern as Redis (REDIS_CA_CERT → TLSConfig). Base64 PEM via env is the right approach for container/K8s deployments. TrimSpace guard is a nice touch.

gRPC cleanup: Thorough — error constants, config fields, comments, test names, docs. Good that CHANGELOG and go.mod indirect deps were left alone (historical / transitive).

CI green. LGTM. 🧙

@ClaraTersi ClaraTersi merged commit 7c3431e into develop Apr 13, 2026
10 checks passed
@ClaraTersi ClaraTersi deleted the feature/MDZ-2023 branch April 13, 2026 13:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants