Repository navigation
Conversation
RStudio serves the chat UI HTML directly via rsession, bypassing the databot Express server's CSP middleware. Add CSP header support to the static file handler so the browser enforces Content-Security-Policy in RStudio mode. CSP directives are read from dist/csp.json (emitted by the databot build) so the policy stays in sync without hardcoding values in C++. The only RStudio-specific augmentation is adding the WebSocket origin to connect-src in desktop mode. Replace the inline <script> theme injection with a <meta> tag carrying theme colors as data attributes plus a class="dark" on the <html> tag. This avoids needing a CSP nonce for inline scripts.
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
Replace the local htmlEscapeAttr() with the existing string_utils::htmlEscape(str, isAttributeValue=true) from core/StringUtils, which handles the same characters plus carriage returns and newlines.
| R"(<meta name="rstudio-theme" )" | ||
| R"(data-background="{background}" )" | ||
| R"(data-foreground="{foreground}">)", |
There was a problem hiding this comment.
Nit: would be slightly more readable as a single multiline raw string instead of separate implicitly-joined strings.
| FilePath positAiPath = locatePositAiInstallation(); | ||
| if (positAiPath.isEmpty()) | ||
| return s_cached; | ||
|
|
||
| FilePath cspFile = positAiPath.completeChildPath(kCspConfigPath); | ||
| if (!cspFile.exists()) | ||
| return s_cached; | ||
|
|
||
| std::string content; | ||
| Error error = readStringFromFile(cspFile, &content); | ||
| if (error) | ||
| return s_cached; | ||
|
|
||
| json::Value jsonValue; | ||
| if (jsonValue.parse(content)) | ||
| return s_cached; | ||
|
|
||
| if (!jsonValue.isObject()) | ||
| return s_cached; | ||
|
|
||
| json::Object obj = jsonValue.getObject(); | ||
| for (auto it = obj.begin(); it != obj.end(); ++it) | ||
| { | ||
| json::Value val = (*it).getValue(); | ||
| if (val.isString()) | ||
| s_cached[(*it).getName()] = val.getString(); | ||
| } |
There was a problem hiding this comment.
Worth logging when any of these fail and we return the empty s_cached object?
There was a problem hiding this comment.
Maybe do that below with the "restrictive fallback" mode?
kevinushey
left a comment
There was a problem hiding this comment.
Summary
This PR adds Content-Security-Policy headers to the AI chat pane and replaces inline <script> theme injection with a <meta> tag + class="dark" approach. The motivation is solid -- eliminating unsafe-inline from CSP is the right move. The implementation is mostly competent: thread-safe port sharing via std::atomic, proper HTML escaping, and a clean fallback policy. However, there are thread-safety issues in the CSP cache, a missing frame-ancestors directive, and the CSP header is applied broadly to all HTML files rather than just index.html.
See inline comments for details. Issues are numbered and categorized by severity.
Verdict
Request Changes -- The thread-safety issue in loadCspDirectives() (#1) is a real data race that needs fixing before merge. The remaining items are legitimate improvements but not merge-blocking on their own.
| if (s_loaded) | ||
| return s_cached; | ||
|
|
||
| s_loaded = true; |
There was a problem hiding this comment.
#1 -- Blocking: Data race in loadCspDirectives()
This function is called from HTTP handler threads (the comment on s_chatBackendPort at line 56 acknowledges the threading model). Two threads can both see s_loaded == false, both proceed to populate s_cached, and one can read s_cached while the other writes to it. This is undefined behavior per the C++ standard.
The pattern is only "safe" on x86 by accident (strong memory model), and even then the std::map writes are not atomic -- concurrent insertions into the same map can corrupt it.
Options:
std::once_flag+std::call_once(cleanest, standard C++11)boost::mutex(consistent with patterns elsewhere in the codebase)- Load and cache at initialization time on the main thread, so the HTTP threads only ever read
| isServerMode = (options().programMode() == kSessionProgramModeServer); | ||
| #endif | ||
|
|
||
| if (!isServerMode && s_chatBackendPort > 0) |
There was a problem hiding this comment.
#5 -- Required: Port comparison doesn't match sentinel
The sentinel value is -1 (set in clearChatBackendPort and the initializer), but the check here is > 0. Port 0 is a valid OS-assigned ephemeral port. If the backend ever gets port 0, it would be silently excluded from connect-src.
Use >= 0 or != -1 to match the sentinel semantics. (In practice RStudio's port allocation probably never assigns 0, but the comparison should match the documented invariant.)
| std::string content; | ||
| Error error = readStringFromFile(cspFile, &content); | ||
| if (error) | ||
| return s_cached; |
There was a problem hiding this comment.
#8 -- Suggestion: All errors silently swallowed
Missing file, parse error, invalid JSON type -- all silently fall through to the default-src 'self' fallback. The restrictive fallback is the right behavior, but at least one LOG_WARNING on parse failure would help debugging. If someone ships a malformed csp.json, there's currently no indication why the CSP is wrong.
| /** | ||
| * Get the current chat backend port, or -1 if not set. | ||
| */ | ||
| int getChatBackendPort(); |
There was a problem hiding this comment.
#9 -- Noted: getChatBackendPort() has no callers
This accessor is declared and defined but has zero callers in this PR. If it's intended for testing or future use, a brief comment saying so would be helpful. Otherwise it's dead code.
- Fix TOCTOU race in buildCspHeader by loading atomic port into a local variable instead of reading it twice - Fix thread-unsafe caching in loadCspDirectives by using a C++11 static-initialized lambda instead of a manual bool guard - Add WLOG calls for file read, JSON parse, and schema errors in loadCspDirectives so failures are no longer silently swallowed - Add DLOG calls in injectThemeInfo when expected HTML tags are missing - Replace magic number with constexpr + strlen for class attribute offset - Fix inaccurate @return doc on handleAIChatRequest - Fix incomplete doc on setChatBackendPort (also called on stop) - Remove redundant inline comments covered by function-level docs Addresses #17100.
- Restrict theme injection to index.html only (not all HTML files) - Cache built CSP header string with mutex; rebuild only on port change - Fix port comparison to use >= 0 (port 0 is valid; sentinel is -1) - Add frame-ancestors 'self' to prevent clickjacking - Add kChatBackendPortNone sentinel constant, replace magic -1 - Remove unused getChatBackendPort() - Consolidate meta tag format to single raw string - Clarify HTML parsing comment about Vite output constraints
Summary
dist/csp.jsonfile emitted by the Posit AI (databot) build<script>to a<meta>tag +class="dark"on<html>, eliminating the need for CSP noncesconnect-srcis augmented with the WebSocket origin (ws://127.0.0.1:{port}) since it's cross-originSessionChat.cppandChatStaticFiles.cppis thread-safe (std::atomic<int>) and cleared at all 6 backend reset sitesIntent
Addresses #17100.
Companion PR: posit-dev/databot#687
Test plan
ai-chat/index.htmlin DevTools Network tabimg-src