Skip to content

refactor(cloud-native): avoid using f-string in logger message#13383

Open
iromli wants to merge 10 commits intomainfrom
cn-refactor-logger
Open

refactor(cloud-native): avoid using f-string in logger message#13383
iromli wants to merge 10 commits intomainfrom
cn-refactor-logger

Conversation

@iromli
Copy link
Contributor

@iromli iromli commented Feb 27, 2026

Prepare


Description

Target issue

closes #13369

Implementation Details


Test and Document the changes

  • Static code analysis has been run locally and issues have been fixed
  • Relevant unit and integration tests have been added/updated
  • Relevant documentation has been updated if any (i.e. user guides, installation and configuration guides, technical design docs etc)

Please check the below before submitting your PR. The PR will not be merged if there are no commits that start with docs: to indicate documentation changes or if the below checklist is not selected.

  • I confirm that there is no impact on the docs due to the code changes in this PR.

Summary by CodeRabbit

  • Chores
    • Standardized logging across many components to use parameterized messages for consistent, deferred formatting.
  • Removals
    • Removed several internal helper routines that downloaded/extracted common libraries and deleted the WebDAV-based Casa sync script.
  • Bug Fixes
    • Minor cleanups: removed unused imports, tightened exception handling, deleted an obsolete comment, and ensured a consistent return in one API path.

Signed-off-by: iromli <isman.firmansyah@gmail.com>
@iromli iromli self-assigned this Feb 27, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 27, 2026

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: ebe9ad6b-2545-46c5-8a96-8fd6370d3edd

📥 Commits

Reviewing files that changed from the base of the PR and between df6297a and 9c982a2.

📒 Files selected for processing (6)
  • docker-jans-auth-server/scripts/mod_context.py
  • docker-jans-casa/scripts/mod_context.py
  • docker-jans-config-api/scripts/mod_context.py
  • docker-jans-fido2/scripts/mod_context.py
  • docker-jans-link/scripts/mod_context.py
  • docker-jans-scim/scripts/mod_context.py
💤 Files with no reviewable changes (6)
  • docker-jans-auth-server/scripts/mod_context.py
  • docker-jans-scim/scripts/mod_context.py
  • docker-jans-fido2/scripts/mod_context.py
  • docker-jans-link/scripts/mod_context.py
  • docker-jans-casa/scripts/mod_context.py
  • docker-jans-config-api/scripts/mod_context.py

📝 Walkthrough

Walkthrough

Converts many f-string logger invocations to parameterized logging across numerous scripts and modules, removes unused imports and the internal extract_common_libs helpers from several mod_context.py files, and deletes the WebDAV sync script plus a commented reference in an entrypoint.

Changes

Cohort / File(s) Summary
Auth & bootstrap scripts
docker-jans-auth-server/scripts/bootstrap.py, docker-jans-auth-server/scripts/auth_conf.py, docker-jans-auth-server/scripts/jks_sync.py, docker-jans-auth-server/scripts/lock.py
Replaced f-string logger calls with parameterized logging for SSL/cert, config load, exceptions, and lock lifecycle messages.
Service bootstraps
docker-jans-casa/scripts/bootstrap.py, docker-jans-fido2/scripts/bootstrap.py, docker-jans-link/scripts/bootstrap.py, docker-jans-scim/scripts/bootstrap.py, docker-jans-config-api/scripts/bootstrap.py, docker-jans-configurator/scripts/bootstrap.py
Converted many logging messages from f-strings to placeholder-based logging (cert pulls, logging config warnings, invalid log-level/target, LDIF import messages).
mod_context removals
docker-jans-auth-server/scripts/mod_context.py, docker-jans-casa/scripts/mod_context.py, docker-jans-config-api/scripts/mod_context.py, docker-jans-fido2/scripts/mod_context.py, docker-jans-link/scripts/mod_context.py, docker-jans-scim/scripts/mod_context.py
Removed the internal extract_common_libs(...) function and its download/extract logic; dropped unused imports (glob, os, sys, exec_cmd) where applicable.
CASA sync removal
docker-jans-casa/scripts/jca_sync.py, docker-jans-casa/scripts/entrypoint.sh
Deleted jca_sync.py (WebDAV sync) and removed a related commented line in entrypoint.sh.
Cloudtools & cleaner
docker-jans-cloudtools/scripts/certmanager.py, docker-jans-cloudtools/scripts/cleaner.py
Switched many cert/key, merge, validation, status, and cleanup logs to parameterized format; added SQLAlchemyError import and narrowed exception handling in cleaner; added explicit cleanup invocation in __main__.
Persistence / SQL setup
docker-jans-persistence-loader/scripts/sql_setup.py
Replaced f-strings with parameterized logging for column/LDIF import and type-conversion messages.
pycloudlib — config & manager
jans-pycloudlib/jans/pycloudlib/config/file_config.py, jans-pycloudlib/jans/pycloudlib/config/google_config.py, jans-pycloudlib/jans/pycloudlib/manager.py, jans-pycloudlib/jans/pycloudlib/meta/kubernetes_meta.py
Converted config/secret-related and Kubernetes log messages to parameterized style; minor import cleanup.
pycloudlib — lock, persistence & wait
jans-pycloudlib/jans/pycloudlib/lock/__init__.py, jans-pycloudlib/jans/pycloudlib/persistence/sql.py, jans-pycloudlib/jans/pycloudlib/wait.py
Replaced many lock lifecycle, SQL, and retry/wait logs with placeholder-based logging; removed an unused import.
pycloudlib — secrets, utils & others
jans-pycloudlib/jans/pycloudlib/secret/aws_secret.py, .../file_secret.py, .../google_secret.py, .../vault_secret.py, jans-pycloudlib/jans/pycloudlib/utils.py
Updated multipart secret, secret loading, Google/Vault secret logs, and password-loading logs to use parameterized logging instead of f-strings.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • moabu
  • yuremm
  • yuriyz
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Two changes are out-of-scope: removal of extract_common_libs functions (5 files) and removal of jca_sync.py are not directly related to the logging refactoring objective stated in issue #13369. Clarify whether the function removals are necessary dependencies for the logging refactor or should be addressed in a separate PR to maintain focused scope.
Docstring Coverage ⚠️ Warning Docstring coverage is 31.96% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly summarizes the main refactoring effort: replacing f-strings in logger messages with parameterized logging for improved performance through lazy evaluation.
Description check ✅ Passed The PR description follows the template with all required sections completed: target issue linked (#13369), implementation notes provided, and documentation impact confirmed as none.
Linked Issues check ✅ Passed The PR successfully addresses issue #13369 by replacing f-strings in logger calls with parameterized logging (logger.info(format, args)) across 27 files, preventing eager string rendering when logging is disabled.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cn-refactor-logger
📝 Coding Plan
  • Generate coding plan for human review comments

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.

@mo-auto mo-auto added comp-jans-pycloudlib kind-enhancement Issue or PR is an enhancement to an existing functionality labels Feb 27, 2026
@mo-auto
Copy link
Member

mo-auto commented Feb 27, 2026

Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
Open Source Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 27, 2026
Signed-off-by: iromli <isman.firmansyah@gmail.com>
@iromli iromli marked this pull request as ready for review March 13, 2026 08:53
@iromli iromli requested a review from moabu as a code owner March 13, 2026 08:53
Signed-off-by: iromli <isman.firmansyah@gmail.com>
Copy link
Contributor

@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: 12

Caution

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

⚠️ Outside diff range comments (1)
jans-pycloudlib/jans/pycloudlib/config/google_config.py (1)

224-224: ⚠️ Potential issue | 🟡 Minor

Inconsistent logging format: still uses .format() instead of %-style.

This line was not updated to use parameterized logging like the rest of the file. For consistency with the PR's goal of enabling lazy evaluation, this should also be converted to %-style formatting.

🔧 Proposed fix
-        logger.info("Added secret version: {}".format(response.name))
+        logger.info("Added secret version: %s", response.name)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@jans-pycloudlib/jans/pycloudlib/config/google_config.py` at line 224, The
logging call uses str.format instead of parameterized %-style logging; update
the logger.info("Added secret version: {}".format(response.name)) to use
logger.info("Added secret version: %s", response.name) (locate the call in
google_config.py where response.name is logged, e.g., inside the function that
adds a secret version) so the log becomes lazily-evaluated and consistent with
the rest of the file.
♻️ Duplicate comments (1)
docker-jans-casa/scripts/mod_context.py (1)

34-34: ⚠️ Potential issue | 🔴 Critical

exec_cmd is called with an invalid signature (runtime failure).

Line 34 passes three positional arguments, but exec_cmd takes a single command string. This will fail before download runs.

Proposed fix
-        out, err, code = exec_cmd("wget -q %s -O %s", download_url, dist_file)
+        out, err, code = exec_cmd(f"wget -q {download_url} -O {dist_file}")
#!/bin/bash
# Verify exec_cmd signature and this call site.
rg -nP '^def exec_cmd\(cmd: str\)' jans-pycloudlib/jans/pycloudlib/utils.py -C3
rg -nP 'exec_cmd\(' docker-jans-casa/scripts/mod_context.py -C2
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docker-jans-casa/scripts/mod_context.py` at line 34, The call site in
mod_context.py uses exec_cmd("wget -q %s -O %s", download_url, dist_file) but
exec_cmd accepts a single command string; change the call to pass a single
formatted command string (e.g., build the command with f-strings or
%-formatting) so exec_cmd receives one argument; update the call referencing
exec_cmd in mod_context.py (the wget download call) to something like
exec_cmd(f"wget -q {download_url} -O {dist_file}") or the equivalent string
formatting.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docker-jans-casa/scripts/bootstrap.py`:
- Around line 169-173: Replace the overly broad Exception handler around
Path.unlink with a filesystem-specific one: catch OSError (and its subclasses)
instead of Exception in the try/except that calls
lock_path.unlink(missing_ok=True); update the except block that currently logs
via logger.warning("Unable to remove %s; reason=%s", lock_file, exc) to catch
OSError as exc so only filesystem errors are handled while allowing other
exceptions to surface.

In `@docker-jans-casa/scripts/mod_context.py`:
- Around line 45-46: The error fallback is inverted: change the fallback
assignment so the actual command output is preserved (set err = err or out) and
keep the logger.error call using err.decode(); update the assignment where out
and err are handled (the variables out, err) so logger.error("Unable to extract
%s; reason=%s", dist_file, err.decode()) logs the correct output for dist_file.

In `@docker-jans-cloudtools/scripts/certmanager.py`:
- Around line 444-445: The log calls are using the stale variable name because
`name` is set after logging; before calling logger.info and
self.meta_client.exec_cmd you must resolve the container's name for the current
`container` (e.g., call whatever resolver is used elsewhere in this module to
get the container name for that `container`) and then use that resolved `name`
in the log and command. Update both occurrences around the restore loop (the
logger.info that references `name` and the subsequent exec via
`self.meta_client.exec_cmd(container, ...)`) so `name` is assigned from the
current `container` first, then log and execute using that `name` and
`container`.
- Line 421: Replace the incorrect brace-style format in the logger call: change
the logger.info invocation that currently reads logger.info("creating backup of
{name}:{jks_fn}", name, jks_fn) to use the logging module's printf-style
formatting and positional args (i.e. "creating backup of %s:%s", name, jks_fn)
so the logger.info call with variables name and jks_fn matches the surrounding
lines and won't raise a formatting error.

In `@docker-jans-cloudtools/scripts/cleaner.py`:
- Around line 45-47: Replace the broad "except Exception as exc" in the table
cleanup loop with an explicit catch for database errors: import SQLAlchemyError
from sqlalchemy.exc and change the handler to "except SQLAlchemyError as exc" so
only DB-layer issues are logged with logger.warning("Unable to cleanup expired
entries in %s; reason=%s", table, exc); let other exceptions propagate (do not
swallow them) so programming errors surface. Ensure the import and the exception
symbol (SQLAlchemyError), the logger variable, and the table loop location
(where the current except sits) are updated accordingly.

In `@docker-jans-fido2/scripts/mod_context.py`:
- Around line 45-46: The error log uses a different variable than the fallback
assignment: after the line "out = out or err" ensure the logger.error call uses
that same fallback (out) instead of err (i.e., change the logger.error call that
currently uses err.decode() to use out.decode() or otherwise reference the "out"
variable), so the actual extracted output is logged consistently for dist_file.

In `@docker-jans-link/scripts/mod_context.py`:
- Around line 45-46: The log for extraction failures is using err.decode() even
though the code normalizes the process output into the variable out; update the
logger.error call that references dist_file to log the normalized buffer
(out.decode()) instead of err.decode() so any captured stderr/stdout merged into
out is preserved; locate the logger.error(...) near the out = out or err
assignment in mod_context.py and replace the error payload to use out (decoded)
and keep the existing message format.

In `@docker-jans-scim/scripts/mod_context.py`:
- Around line 44-47: The log currently prints err.decode() after assigning out =
out or err, which can report the wrong buffer; update the block around the
failing-extraction handling so the decoded value logged matches the variable
used—either change the assignment to err = out or err (to match the existing
logger.error(err.decode())) or keep out = out or err and log out.decode()
instead; ensure this fix is applied in the failing-extract branch that
references dist_file, out, err and logger.error.

In `@jans-pycloudlib/jans/pycloudlib/config/google_config.py`:
- Line 104: Remove the leftover commented debug line containing the logger call
in the GoogleConfig code (the commented "logger.info(...
self.google_secret_name, self.version_id)" line); delete that commented-out
statement from the class/method where it appears (references:
self.google_secret_name, self.version_id, logger.info) so the codebase is clean,
unless you intentionally need the log—in which case uncomment and ensure the
variables are available and formatted correctly.

In `@jans-pycloudlib/jans/pycloudlib/persistence/sql.py`:
- Around line 1239-1241: The warning handler that catches ProgrammingError is
indexing exc.args[1] which can raise IndexError if the exception lacks that
element; update the logger call in the except block that references
ProgrammingError (the block containing logger.warning("Unable to detect
JSON...")) to avoid direct indexing—log the full exception or a safe fallback
(e.g., use str(exc) or check len(exc.args) before accessing exc.args[1]) so the
warning always prints a reason without risking IndexError.

In `@jans-pycloudlib/jans/pycloudlib/secret/aws_secret.py`:
- Around line 217-220: Fix the typo in the logger.warning message in
aws_secret.py: change "splitted" to "split" in the parameterized log string used
in the logger.warning call (the one that logs data_length,
self.max_payload_size, parts) so the message reads "... It will be split into %s
parts."; keep the existing parameterized logging style for lazy evaluation.

In `@jans-pycloudlib/jans/pycloudlib/secret/google_secret.py`:
- Around line 271-273: Update the multipart warning message in google_secret.py
(the logger.warning call that logs data_length, self.max_payload_size, parts) to
use clearer wording: replace "is exceeding" with "exceeds" and "splitted" with
"split", and tighten phrasing (e.g., "The secret payload size %s bytes exceeds
the maximum of %s bytes; it will be split into %s parts."). Keep the same format
specifiers and variables (data_length, self.max_payload_size, parts) and call
site (logger.warning) unchanged.

---

Outside diff comments:
In `@jans-pycloudlib/jans/pycloudlib/config/google_config.py`:
- Line 224: The logging call uses str.format instead of parameterized %-style
logging; update the logger.info("Added secret version:
{}".format(response.name)) to use logger.info("Added secret version: %s",
response.name) (locate the call in google_config.py where response.name is
logged, e.g., inside the function that adds a secret version) so the log becomes
lazily-evaluated and consistent with the rest of the file.

---

Duplicate comments:
In `@docker-jans-casa/scripts/mod_context.py`:
- Line 34: The call site in mod_context.py uses exec_cmd("wget -q %s -O %s",
download_url, dist_file) but exec_cmd accepts a single command string; change
the call to pass a single formatted command string (e.g., build the command with
f-strings or %-formatting) so exec_cmd receives one argument; update the call
referencing exec_cmd in mod_context.py (the wget download call) to something
like exec_cmd(f"wget -q {download_url} -O {dist_file}") or the equivalent string
formatting.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: ef2edacf-dd14-49a9-9581-8af55f209e80

📥 Commits

Reviewing files that changed from the base of the PR and between 5aa4d67 and 7e3c5e1.

📒 Files selected for processing (36)
  • docker-jans-auth-server/scripts/auth_conf.py
  • docker-jans-auth-server/scripts/bootstrap.py
  • docker-jans-auth-server/scripts/jks_sync.py
  • docker-jans-auth-server/scripts/lock.py
  • docker-jans-auth-server/scripts/mod_context.py
  • docker-jans-casa/scripts/auth_conf.py
  • docker-jans-casa/scripts/bootstrap.py
  • docker-jans-casa/scripts/entrypoint.sh
  • docker-jans-casa/scripts/jca_sync.py
  • docker-jans-casa/scripts/mod_context.py
  • docker-jans-casa/scripts/upgrade.py
  • docker-jans-cloudtools/scripts/certmanager.py
  • docker-jans-cloudtools/scripts/cleaner.py
  • docker-jans-config-api/scripts/bootstrap.py
  • docker-jans-config-api/scripts/mod_context.py
  • docker-jans-config-api/scripts/plugins.py
  • docker-jans-configurator/scripts/bootstrap.py
  • docker-jans-fido2/scripts/bootstrap.py
  • docker-jans-fido2/scripts/mod_context.py
  • docker-jans-link/scripts/bootstrap.py
  • docker-jans-link/scripts/mod_context.py
  • docker-jans-persistence-loader/scripts/sql_setup.py
  • docker-jans-scim/scripts/bootstrap.py
  • docker-jans-scim/scripts/mod_context.py
  • jans-pycloudlib/jans/pycloudlib/config/file_config.py
  • jans-pycloudlib/jans/pycloudlib/config/google_config.py
  • jans-pycloudlib/jans/pycloudlib/lock/__init__.py
  • jans-pycloudlib/jans/pycloudlib/manager.py
  • jans-pycloudlib/jans/pycloudlib/meta/kubernetes_meta.py
  • jans-pycloudlib/jans/pycloudlib/persistence/sql.py
  • jans-pycloudlib/jans/pycloudlib/secret/aws_secret.py
  • jans-pycloudlib/jans/pycloudlib/secret/file_secret.py
  • jans-pycloudlib/jans/pycloudlib/secret/google_secret.py
  • jans-pycloudlib/jans/pycloudlib/secret/vault_secret.py
  • jans-pycloudlib/jans/pycloudlib/utils.py
  • jans-pycloudlib/jans/pycloudlib/wait.py
💤 Files with no reviewable changes (2)
  • docker-jans-casa/scripts/entrypoint.sh
  • docker-jans-casa/scripts/jca_sync.py

Copy link
Contributor

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

♻️ Duplicate comments (1)
docker-jans-casa/scripts/mod_context.py (1)

45-46: ⚠️ Potential issue | 🟡 Minor

Fix extract error fallback variable before logging.

Line 45 updates out, but Line 46 logs err, so fallback output can be lost. Update the fallback target to err in this block.

Proposed fix
-    if code != 0:
-        out = out or err
-        logger.error("Unable to extract %s; reason=%s", dist_file, err.decode())
+    if code != 0:
+        err = err or out
+        logger.error("Unable to extract %s; reason=%s", dist_file, err.decode())
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docker-jans-casa/scripts/mod_context.py` around lines 45 - 46, The code sets
the fallback with out = out or err but then logs err, losing the fallback;
update the logger call in the extract/error handling to log out (e.g. use
out.decode()) instead of err.decode() so the fallback output is preserved when
reporting the failure for dist_file via logger.error.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@docker-jans-casa/scripts/mod_context.py`:
- Around line 45-46: The code sets the fallback with out = out or err but then
logs err, losing the fallback; update the logger call in the extract/error
handling to log out (e.g. use out.decode()) instead of err.decode() so the
fallback output is preserved when reporting the failure for dist_file via
logger.error.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: c873dcae-9733-4cea-ba30-314b9c4c3b56

📥 Commits

Reviewing files that changed from the base of the PR and between 7e3c5e1 and 4ef850a.

📒 Files selected for processing (1)
  • docker-jans-casa/scripts/mod_context.py

Signed-off-by: iromli <isman.firmansyah@gmail.com>
Signed-off-by: iromli <isman.firmansyah@gmail.com>
Signed-off-by: iromli <isman.firmansyah@gmail.com>
Copy link
Contributor

@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: 3

♻️ Duplicate comments (1)
docker-jans-link/scripts/mod_context.py (1)

45-46: ⚠️ Potential issue | 🟡 Minor

Inconsistent error-buffer assignment breaks logging output.

Line 45 uses out = err or out, but line 46 logs err.decode(). If err is empty and out contains the failure message, the log will display an empty reason. This deviates from the canonical pattern used in line 37 and in docker-jans-auth-server/scripts/mod_context.py (see context snippet), where the assignment is err = err or out.

,

Proposed fix to align with canonical pattern
     if code != 0:
-        out = err or out
+        err = err or out
         logger.error("Unable to extract %s; reason=%s", dist_file, err.decode())
         sys.exit(1)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docker-jans-link/scripts/mod_context.py` around lines 45 - 46, The log call
uses err.decode() but the preceding assignment is incorrect (out = err or out),
so when err is empty the reason logged is blank; change the assignment to mirror
the canonical pattern by setting err = err or out before the logger.error call
so the logger.error("Unable to extract %s; reason=%s", dist_file, err.decode())
will always show the non-empty error buffer (refer to variables err, out and the
logger.error call in mod_context.py).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docker-jans-fido2/scripts/mod_context.py`:
- Around line 37-38: The error logging currently calls err.decode() directly
which can raise if err is None or contains undecodable bytes; update the logging
to safely handle None and decoding errors by using a safe buffer and decode with
errors='replace' (e.g. use (err or out or b'').decode('utf-8',
errors='replace')) before passing to logger.error, and apply the same change for
the second occurrence that references err and out; target the block where
variables err, out, basename and logger are used (the download/error reporting
code in mod_context.py).

In `@jans-pycloudlib/jans/pycloudlib/config/google_config.py`:
- Around line 151-153: Compute safe_value(all_) once into a local variable
(e.g., payload) inside the affected methods (set and set_all), use
sys.getsizeof(payload) for the size log, and pass that local variable to
add_secret_version; this avoids evaluating safe_value(all_) twice and prevents
eager payload serialization inside logger calls by logging payload size from the
precomputed variable and then calling self.add_secret_version(payload).

In `@jans-pycloudlib/jans/pycloudlib/secret/google_secret.py`:
- Line 84: The code currently assigns a hardcoded fallback passphrase ("secret")
to self.passphrase from CN_GOOGLE_SECRET_MANAGER_PASSPHRASE and suppresses the
security finding; remove the insecure default and NOSONAR by making the env var
required: retrieve CN_GOOGLE_SECRET_MANAGER_PASSPHRASE into self.passphrase and
if it's missing or empty, raise a clear exception (or abort initialization) so
callers must provide a secure passphrase (refer to self.passphrase and
CN_GOOGLE_SECRET_MANAGER_PASSPHRASE in the GoogleSecret/initializer code).

---

Duplicate comments:
In `@docker-jans-link/scripts/mod_context.py`:
- Around line 45-46: The log call uses err.decode() but the preceding assignment
is incorrect (out = err or out), so when err is empty the reason logged is
blank; change the assignment to mirror the canonical pattern by setting err =
err or out before the logger.error call so the logger.error("Unable to extract
%s; reason=%s", dist_file, err.decode()) will always show the non-empty error
buffer (refer to variables err, out and the logger.error call in
mod_context.py).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1b2f6b86-771b-4fd9-8088-1cb0277fb0fb

📥 Commits

Reviewing files that changed from the base of the PR and between 4ef850a and a165393.

📒 Files selected for processing (13)
  • docker-jans-auth-server/scripts/mod_context.py
  • docker-jans-casa/scripts/bootstrap.py
  • docker-jans-casa/scripts/mod_context.py
  • docker-jans-cloudtools/scripts/certmanager.py
  • docker-jans-cloudtools/scripts/cleaner.py
  • docker-jans-config-api/scripts/mod_context.py
  • docker-jans-fido2/scripts/mod_context.py
  • docker-jans-link/scripts/mod_context.py
  • docker-jans-scim/scripts/mod_context.py
  • jans-pycloudlib/jans/pycloudlib/config/google_config.py
  • jans-pycloudlib/jans/pycloudlib/persistence/sql.py
  • jans-pycloudlib/jans/pycloudlib/secret/aws_secret.py
  • jans-pycloudlib/jans/pycloudlib/secret/google_secret.py

Copy link
Contributor

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

♻️ Duplicate comments (2)
docker-jans-link/scripts/mod_context.py (1)

37-38: ⚠️ Potential issue | 🟡 Minor

Normalize failure text before logging to avoid losing diagnostics.

At Line 37 and Line 45, err = err or out prefers stderr and can drop useful stdout context; direct decode() is also brittle for malformed bytes. Build a normalized reason once and log that.

Proposed fix
-        err = err or out
-        logger.error("Unable to download %s; reason=%s", basename, err.decode())
+        reason = (out or err or b"").decode(errors="replace")
+        logger.error("Unable to download %s; reason=%s", basename, reason)
         sys.exit(1)
@@
-        err = err or out
-        logger.error("Unable to extract %s; reason=%s", dist_file, err.decode())
+        reason = (out or err or b"").decode(errors="replace")
+        logger.error("Unable to extract %s; reason=%s", dist_file, reason)
         sys.exit(1)

Also applies to: 45-46

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

In `@docker-jans-link/scripts/mod_context.py` around lines 37 - 38, The log
currently prefers stderr via "err = err or out" and decodes bytes directly,
which can lose stdout context or crash on malformed bytes; update the logging to
build a normalized reason string once (e.g., choose combined output like
reason_bytes = err or out or b""), decode with errors='replace' and strip, and
ensure it's a str before calling logger.error("Unable to download %s;
reason=%s", basename, reason); apply the same change to the second occurrence
around lines handling err/out so both logger.error sites use the normalized
reason variable.
jans-pycloudlib/jans/pycloudlib/config/google_config.py (1)

150-152: ⚠️ Potential issue | 🟠 Major

Avoid duplicate safe_value(all_) work and incorrect payload-size metric.

Line 151/152 and Line 177/178 still evaluate safe_value(all_) twice per call path, and sys.getsizeof(...) is not the serialized payload byte size. This reintroduces avoidable work and logs a misleading size.

♻️ Proposed fix
@@
-        logger.info('Adding/updating key %s to google secret manager', key)
-        logger.info('Size of secret payload : %s bytes', sys.getsizeof(safe_value(all_)))
-        return self.add_secret_version(safe_value(all_))
+        logger.info("Adding/updating key %s to google secret manager", key)
+        payload = safe_value(all_)
+        if logger.isEnabledFor(logging.INFO):
+            payload_size = len(payload.encode("UTF-8")) if isinstance(payload, str) else len(payload)
+            logger.info("Size of secret payload: %s bytes", payload_size)
+        return self.add_secret_version(payload)
@@
-        logger.info('Size of secret payload : %s bytes', sys.getsizeof(safe_value(all_)))
-        return self.add_secret_version(safe_value(all_))
+        payload = safe_value(all_)
+        if logger.isEnabledFor(logging.INFO):
+            payload_size = len(payload.encode("UTF-8")) if isinstance(payload, str) else len(payload)
+            logger.info("Size of secret payload: %s bytes", payload_size)
+        return self.add_secret_version(payload)
#!/bin/bash
set -euo pipefail
FILE="jans-pycloudlib/jans/pycloudlib/config/google_config.py"

echo "Inspecting set/set_all blocks..."
nl -ba "$FILE" | sed -n '145,182p'

echo
echo "Finding repeated safe_value(all_) and sys.getsizeof usage..."
rg -nP 'safe_value\(all_\)|sys\.getsizeof\(' "$FILE"

Expected result: current code shows duplicate safe_value(all_) evaluations in both methods and sys.getsizeof(...) usage for size logging.

Also applies to: 177-178

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

In `@jans-pycloudlib/jans/pycloudlib/config/google_config.py` around lines 150 -
152, Compute the serialized secret payload once into a local variable and reuse
it for both logging and the call to add_secret_version instead of calling
safe_value(all_) twice; additionally replace sys.getsizeof(...) with the actual
serialized byte length (e.g., len(payload_bytes)) when logging the "Size of
secret payload" so the logged size reflects the true payload size; update the
code paths that call safe_value(all_) (the set/set_all flow that then calls
add_secret_version) to use this single payload variable.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@docker-jans-link/scripts/mod_context.py`:
- Around line 37-38: The log currently prefers stderr via "err = err or out" and
decodes bytes directly, which can lose stdout context or crash on malformed
bytes; update the logging to build a normalized reason string once (e.g., choose
combined output like reason_bytes = err or out or b""), decode with
errors='replace' and strip, and ensure it's a str before calling
logger.error("Unable to download %s; reason=%s", basename, reason); apply the
same change to the second occurrence around lines handling err/out so both
logger.error sites use the normalized reason variable.

In `@jans-pycloudlib/jans/pycloudlib/config/google_config.py`:
- Around line 150-152: Compute the serialized secret payload once into a local
variable and reuse it for both logging and the call to add_secret_version
instead of calling safe_value(all_) twice; additionally replace
sys.getsizeof(...) with the actual serialized byte length (e.g.,
len(payload_bytes)) when logging the "Size of secret payload" so the logged size
reflects the true payload size; update the code paths that call safe_value(all_)
(the set/set_all flow that then calls add_secret_version) to use this single
payload variable.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: f0f6b47a-67fe-4c20-bd6f-c14464cc6bdf

📥 Commits

Reviewing files that changed from the base of the PR and between a165393 and df6297a.

📒 Files selected for processing (2)
  • docker-jans-link/scripts/mod_context.py
  • jans-pycloudlib/jans/pycloudlib/config/google_config.py

Signed-off-by: iromli <isman.firmansyah@gmail.com>
@iromli
Copy link
Contributor Author

iromli commented Mar 13, 2026

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 13, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@sonarqubecloud
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor(cloud-native): avoid using f-string in logger message

2 participants