Skip to content

Add CSP headers and meta-tag theme injection for AI chat pane - #17132

Merged
jcheng5 merged 5 commits into
mainfrom
chat-csp
Feb 28, 2026
Merged

jcheng5 merged 5 commits into
mainfrom
chat-csp

Conversation

@gtritchie

Copy link
Copy Markdown
Member

Summary

  • rsession's static file handler now applies Content-Security-Policy headers when serving the AI chat HTML, reading directives from a dist/csp.json file emitted by the Posit AI (databot) build
  • Theme injection replaced from inline <script> to a <meta> tag + class="dark" on <html>, eliminating the need for CSP nonces
  • In desktop mode, connect-src is augmented with the WebSocket origin (ws://127.0.0.1:{port}) since it's cross-origin
  • Port sharing between SessionChat.cpp and ChatStaticFiles.cpp is thread-safe (std::atomic<int>) and cleared at all 6 backend reset sites

Intent

Addresses #17100.

Companion PR: posit-dev/databot#687

Test plan

  • Build rsession and verify no compile errors
  • Open chat pane in RStudio Desktop — verify CSP header present on ai-chat/index.html in DevTools Network tab
  • Verify chat UI loads with correct theme colors (light and dark)
  • Verify no CSP violation banner appears
  • Verify chat WebSocket connects and chat functions normally
  • Open chat pane in RStudio Server — verify same behavior (no WS origin in CSP)
  • Test prompt injection with external image URL — verify blocked by img-src

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.
@posit-snyk-bot

posit-snyk-bot commented Feb 27, 2026 •

Copy link
Copy Markdown
Contributor

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

Status Scanner Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

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

@gtritchie
gtritchie marked this pull request as ready for review February 27, 2026 23:24
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.
@gtritchie
gtritchie requested a review from jcheng5 February 27, 2026 23:31
@gtritchie gtritchie added this to the Globemaster Allium milestone Feb 27, 2026
@gtritchie
gtritchie requested a review from kevinushey February 27, 2026 23:39
Comment on lines +113 to +115
R"(<meta name="rstudio-theme" )"
R"(data-background="{background}" )"
R"(data-foreground="{foreground}">)",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit: would be slightly more readable as a single multiline raw string instead of separate implicitly-joined strings.

Comment on lines +147 to +173
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();
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Worth logging when any of these fail and we return the empty s_cached object?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Maybe do that below with the "restrictive fallback" mode?

@kevinushey kevinushey left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

#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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

#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.)

Comment thread src/cpp/session/modules/SessionChat.cpp Resolved
std::string content;
Error error = readStringFromFile(cspFile, &content);
if (error)
return s_cached;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

#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();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

#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
@jcheng5
jcheng5 merged commit 18a2228 into main Feb 28, 2026
8 checks passed
@jcheng5
jcheng5 deleted the chat-csp branch February 28, 2026 07:35
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