Skip to content

fix(cli): guard against accidental Spring Boot debug mode#4244

Merged
nixel2007 merged 5 commits into
developfrom
claude/spring-boot-debug-guard-ovygse
Jul 10, 2026
Merged

fix(cli): guard against accidental Spring Boot debug mode#4244
nixel2007 merged 5 commits into
developfrom
claude/spring-boot-debug-guard-ovygse

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jul 8, 2026

Copy link
Copy Markdown
Member

Описание

Защита от случайного включения отладочного режима Spring Boot.

Флаги --debug/--trace, а также переменные среды DEBUG/TRACE (Spring привязывает их к свойствам debug/trace по relaxed binding) включают объёмный лог core-логгеров и отчёт об автоконфигурации. Для LSP по stdio это особенно опасно: посторонний вывод способен замусорить канал протокола. При этом DEBUG — распространённое имя переменной среды, её легко выставить в окружении случайно.

Переименовать или отключить ключи debug/trace на уровне Spring Boot нельзя (они захардкожены в LoggingApplicationListener), поэтому добавлен внешний гвард в MainApplication.main(), срабатывающий до старта контекста:

  • Без явного согласия запрос на отладку нейтрализуется: флаги --debug/--trace убираются из аргументов, а свойства debug/trace принудительно ставятся в false через системные свойства (они приоритетнее переменных среды — так гасится случайный DEBUG/TRACE). На stderr печатается предупреждение с подсказкой, как включить осознанно.
  • С опцией --enable-debug-i-know-what-i-am-doing=true (учитывается только из командной строки) отладка пропускается как есть; сама опция удаляется из аргументов, чтобы её не увидели picocli/Spring.
  • В allowedAdditionalArgs добавлен --trace (и форма =value), чтобы при осознанном включении picocli не считал флаг неизвестной опцией.

Связанные задачи

Closes

Чеклист

Общие

  • Ветка PR обновлена из develop
  • Отладочные, закомментированные и прочие, не имеющие смысла участки кода удалены
  • Изменения покрыты тестами
  • Обязательные действия перед коммитом выполнены (запускал команду gradlew precommit)

Для диагностик

  • Описание диагностики заполнено для обоих языков (изменение не касается диагностик)

Дополнительно

Новые тесты в MainApplicationModeTest: снятие флагов без опции с форсом debug/trace=false, сохранение флагов при осознанном включении, =false не включает отладку, no-op без запроса на отладку.

Замечание по проверке: в окружении не удалось прогнать ./gradlew — дистрибутив Gradle 9.6.1 блокируется egress-политикой прокси (403 на services.gradle.org), а системный Gradle 8.14.3 не парсит текущий build.gradle.kts. Фактический прогон тестов остаётся за CI.

🤖 Generated with Claude Code

https://claude.ai/code/session_01JEuMeqWyv8FsPMfEX5pCR7


Generated by Claude Code

Summary by CodeRabbit

  • New Features
    • Added an explicit opt-in flag to enable Spring Boot debug/trace logging.
  • Bug Fixes
    • Prevents accidental debug/trace activation unless the opt-in flag is provided.
    • Cleans startup arguments by stripping --debug/--trace (including =... forms) when not allowed.
    • Forces debug/trace off when detected via system settings and warns if the request was ignored.
  • Tests
    • Expanded coverage for the debug/trace guarding behavior.
  • Chores
    • Tightened the architecture check to disallow standard-stream access from the main application class.

Passing --debug/--trace or setting the DEBUG/TRACE environment variables
(Spring binds them to the debug/trace properties via relaxed binding) turns
on verbose core-logger logging plus the auto-configuration report. Over LSP
stdio that stray output can corrupt the protocol channel, and DEBUG is a
common env var that is easy to set by accident.

Spring Boot does not let you rename or disable the debug/trace keys, so guard
them before the context boots: honor the request only when the explicit
--enable-debug-i-know-what-i-am-doing opt-in is given on the command line.
Otherwise strip the flags from the args and force debug/trace to false via
system properties (higher precedence than env vars), warning on stderr.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JEuMeqWyv8FsPMfEX5pCR7
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 370b01a8-1fd0-4b55-ae76-6607d5f56c24

📥 Commits

Reviewing files that changed from the base of the PR and between 3581471 and 3e03772.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/MainApplication.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/MainApplicationModeTest.java

📝 Walkthrough

Walkthrough

MainApplication now guards Spring Boot debug and trace handling behind an explicit opt-in flag. It filters related CLI args, forces debug and trace properties off when not opted in, and updates tests plus the standard-stream rule to cover the new behavior.

Changes

Spring Debug/Trace Guard

Layer / File(s) Summary
Opt-in flag and CLI allowance
src/main/java/com/github/_1c_syntax/bsl/languageserver/MainApplication.java
Adds ENABLE_DEBUG_OPTION, the supporting Predicate import, and the CLI patterns that accept --debug(=.*)? and --trace(=.*)?.
Guard logic and application entry
src/main/java/com/github/_1c_syntax/bsl/languageserver/MainApplication.java
Calls the debug guard from main and adds the guard helpers that detect opt-in, filter debug/trace arguments, force system properties off, and print the stderr notice.
Mode tests and stream access rule
src/test/java/com/github/_1c_syntax/bsl/languageserver/MainApplicationModeTest.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/architecture/ArchitectureTest.java
Adds coverage for the opted-out, opted-in, disabled, non-debug, and inherited-property cases, and updates the architecture rule to include MainApplication in the standard-stream restriction.

Estimated code review effort: 3 (Moderate) | ~25 minutes

🚥 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 clearly summarizes the main change: guarding the CLI against accidental Spring Boot debug mode.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ 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/spring-boot-debug-guard-ovygse

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.

The debug-mode guard in MainApplication runs in main() before Spring
configures logging and writes its warning to stderr (stdout is the LSP
protocol channel), so it must be exempted from no_classes_should_access_
standard_streams — same rationale as the ParentProcessWatcher fallback.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JEuMeqWyv8FsPMfEX5pCR7

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

🧹 Nitpick comments (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/MainApplicationModeTest.java (1)

116-130: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider covering the environment/property-driven debug path.

The four tests exercise the CLI-flag paths well, but the debugRequestedFromEnvironment() branch (no --debug/--trace flag, yet debug/trace requested via property) is untested. Since env vars are hard to set in-test, a property-based case would close the gap:

💚 Suggested additional test
`@Test`
void debugFromSystemPropertyForcedOff() {
  System.clearProperty("debug");
  System.clearProperty("trace");
  try {
    System.setProperty("debug", "true");
    var result = MainApplication.guardSpringDebugMode(new String[]{"analyze"});

    assertThat(result).containsExactly("analyze");
    assertThat(System.getProperty("debug")).isEqualTo("false");
  } finally {
    System.clearProperty("debug");
    System.clearProperty("trace");
  }
}
🤖 Prompt for 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.

In
`@src/test/java/com/github/_1c_syntax/bsl/languageserver/MainApplicationModeTest.java`
around lines 116 - 130, Add a test that covers the property-driven debug branch
in MainApplication.guardSpringDebugMode, since only CLI-flag paths are currently
exercised. Create a case where no --debug/--trace flag is passed but the debug
state is requested via system properties (for example by setting debug before
calling the method), then assert the returned args stay unchanged and that the
debug property is forced off as expected. Keep the existing cleanup around
System.clearProperty for debug and trace.
🤖 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.

Nitpick comments:
In
`@src/test/java/com/github/_1c_syntax/bsl/languageserver/MainApplicationModeTest.java`:
- Around line 116-130: Add a test that covers the property-driven debug branch
in MainApplication.guardSpringDebugMode, since only CLI-flag paths are currently
exercised. Create a case where no --debug/--trace flag is passed but the debug
state is requested via system properties (for example by setting debug before
calling the method), then assert the returned args stay unchanged and that the
debug property is forced off as expected. Keep the existing cleanup around
System.clearProperty for debug and trace.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6bb21a13-2609-4e76-99d6-e4a63eace247

📥 Commits

Reviewing files that changed from the base of the PR and between 0a1a89f and 9ce32da.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/MainApplication.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/MainApplicationModeTest.java

Add a case where debug is requested via the debug system property (no
--debug/--trace flag), exercising debugRequestedFromEnvironment(): args stay
unchanged and debug is forced off.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JEuMeqWyv8FsPMfEX5pCR7
@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Test Results

 3 588 files   3 588 suites   1h 48m 50s ⏱️
 3 562 tests  3 544 ✅  18 💤 0 ❌
21 372 runs  21 260 ✅ 112 💤 0 ❌

Results for commit 3e03772.

♻️ This comment has been updated with latest results.

Comment thread src/main/java/com/github/_1c_syntax/bsl/languageserver/MainApplication.java Outdated
Per review: the inline comment above the --debug/--trace patterns was
redundant.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JEuMeqWyv8FsPMfEX5pCR7
Comment thread src/main/java/com/github/_1c_syntax/bsl/languageserver/MainApplication.java Outdated
Comment thread src/main/java/com/github/_1c_syntax/bsl/languageserver/MainApplication.java Outdated
Comment thread src/main/java/com/github/_1c_syntax/bsl/languageserver/MainApplication.java Outdated
Comment thread src/main/java/com/github/_1c_syntax/bsl/languageserver/MainApplication.java Outdated
Per review:
- on explicit opt-in, return args unchanged instead of filtering them
  (the opt-in flag and --debug/--trace are whitelisted for picocli);
- match the opt-in option and --debug/--trace with single regexes,
  dropping the duplicated equalsIgnoreCase / regionMatches helpers;
- when not opted in, force debug/trace properties off unconditionally,
  which removes the separate environment-detection and isEnabled helpers.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JEuMeqWyv8FsPMfEX5pCR7
@sonarqubecloud

sonarqubecloud Bot commented Jul 8, 2026

Copy link
Copy Markdown

@nixel2007

Copy link
Copy Markdown
Member Author

/buildJar

@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

✅ Собраны JAR-файлы для этого PR по команде /buildJar.

Артефакт: 8172457277

Файлы внутри:

  • bsl-language-server-claude-spring-boot-debug-guard-ovygse-3e03772-exec.jar

@nixel2007
nixel2007 merged commit 61640a0 into develop Jul 10, 2026
37 checks passed
@nixel2007
nixel2007 deleted the claude/spring-boot-debug-guard-ovygse branch July 10, 2026 14:43
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.

2 participants