Skip to content

Conversation

fm3
Copy link
Member

@fm3 fm3 commented Jan 21, 2025

We decided to no longer the about page to the same domain as wk, but use a redirect to a subdomain. This PR implements the wk side of this change.

Steps to test:

  • In application.conf, set isWkOrgInstance.true, set aboutPageRedirect.prefix to the target root address, and aboutPagePredirect.routes to a list of test url paths (e.g. ["/test.html"]
  • visiting localhost:9000/test.html should redirect to targetHost/test.html

@fm3 fm3 self-assigned this Jan 21, 2025
Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

📝 Walkthrough

Walkthrough

The pull request introduces significant changes to the WEBKNOSSOS application's configuration and routing mechanism. The primary focus is on transitioning from a proxy-based approach to a more direct about page redirection strategy. This involves renaming configuration options, updating the RequestHandler, modifying the AboutPageRedirectController (previously WkorgProxyController), and adjusting related configuration files to support the new routing behavior.

Changes

File Change Summary
MIGRATIONS.unreleased.md Updated migration guide with renamed configuration options from proxy to aboutPageRedirect
app/RequestHandler.scala Replaced WkorgProxyController with AboutPageRedirectController in routing logic
app/controllers/AboutPageRedirectController.scala Refactored controller with renamed methods and simplified redirection mechanism
app/utils/SitemapWriter.scala Updated proxyURLs source from wkConf.Proxy.routes to wkConf.AboutPageRedirect.routes
app/utils/WkConf.scala Removed Proxy object, added AboutPageRedirect object
conf/application.conf Changed section header from proxy to aboutPageRedirect

Poem

🐰 A Rabbit's Routing Tale 🌐

From proxy paths to redirect's grace,
Our code now dances with a nimble pace.
Configuration shifts, a subtle art,
Redirecting routes with a clever start.
WEBKNOSSOS evolves, hop by hop!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@fm3 fm3 requested a review from normanrz January 21, 2025 13:51
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: 1

🧹 Nitpick comments (2)
app/controllers/AboutPageRedirectController.scala (1)

53-55: Clarify Complex Conditional Logic

The condition in matchesRedirectRoute combines multiple checks, which may reduce readability and maintainability. The expression (request.identity.isEmpty || request.uri != "/") could lead to unintended behavior, especially when the user is authenticated, and the request URI is the root ("/").

Consider refactoring the condition into separate, well-named boolean variables:

private def matchesRedirectRoute(request: UserAwareRequest[WkEnv, AnyContent]): Boolean = {
  val isWkorg = conf.Features.isWkorgInstance
  val matchesRoute = conf.AboutPageRedirect.routes.exists(route => matchesRouteWithWildcard(route, request.path))
  val isUnauthenticatedOrNotRoot = request.identity.isEmpty || request.uri != "/"

  isWkorg && matchesRoute && isUnauthenticatedOrNotRoot
}

This enhances readability and makes the logic easier to understand and maintain.

MIGRATIONS.unreleased.md (1)

13-13: Consider enhancing the migration guide.

The migration note is clear and well-documented. Consider adding an example of the new configuration format to make it easier for users to migrate.

Add configuration example:

- config options `proxy.prefix` and `proxy.routes` were renamed to `aboutPageRedirect.prefix` and `aboutPageRedirect.routes` (as we no longer proxy, but redirect). [#8344](https://github.com/scalableminds/webknossos/pull/8344)
+ config options `proxy.prefix` and `proxy.routes` were renamed to `aboutPageRedirect.prefix` and `aboutPageRedirect.routes` (as we no longer proxy, but redirect). Example:
+ ```conf
+ aboutPageRedirect {
+   prefix = "https://about.example.com"
+   routes = ["/about", "/terms"]
+ }
+ ```
+ [#8344](https://github.com/scalableminds/webknossos/pull/8344)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eb1423c and 63beb4e.

📒 Files selected for processing (6)
  • MIGRATIONS.unreleased.md (1 hunks)
  • app/RequestHandler.scala (3 hunks)
  • app/controllers/AboutPageRedirectController.scala (2 hunks)
  • app/utils/SitemapWriter.scala (1 hunks)
  • app/utils/WkConf.scala (2 hunks)
  • conf/application.conf (1 hunks)
🔇 Additional comments (7)
app/controllers/AboutPageRedirectController.scala (1)

19-23: Class Renaming and Dependency Injection Confirmed

The AboutPageRedirectController has been correctly renamed from WkorgProxyController, and the dependencies are appropriately injected. This change aligns with the new redirection functionality.

app/utils/SitemapWriter.scala (1)

23-23: Verify Inclusion of Redirect Routes in Sitemap

The proxyURLs now source from wkConf.AboutPageRedirect.routes. Ensure that these routes are intended to be included in the sitemap and that they do not contain wildcard patterns, which could generate invalid URLs.

Consider adding validation to filter out any routes with wildcards and confirm that AboutPageRedirect.routes is correctly configured.

 private val proxyURLs = wkConf.AboutPageRedirect.routes
+  .filter(route => !route.contains("*") && route.startsWith("/"))
   .map(SitemapURL(_))
✅ Verification successful

Current Implementation is Correct

The current filtering of wildcard routes is intentional and correct. The AboutPageRedirect controller explicitly supports wildcard patterns for matching requests, but these shouldn't be included in the sitemap. The additional validation for paths starting with "/" is unnecessary as the paths are already normalized when used.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find AboutPageRedirect configuration and related files
rg -l "AboutPageRedirect" --type scala

# Look for sitemap-related files and configurations
fd -e scala -e conf sitemap

# Search for route validation patterns
rg -A 5 "route.*filter" --type scala

Length of output: 797


Script:

#!/bin/bash
# Check WkConf configuration for AboutPageRedirect
rg -A 10 "AboutPageRedirect" app/utils/WkConf.scala

# Examine the redirect controller implementation
cat app/controllers/AboutPageRedirectController.scala

Length of output: 3061

app/RequestHandler.scala (3)

3-3: Updated Imports Confirmed

The import statement correctly includes AboutPageRedirectController, replacing WkorgProxyController. This ensures that the new controller is available in RequestHandler.


21-21: Dependency Injection for AboutPageRedirectController

The aboutPageRedirectController is properly injected into RequestHandler. Verify that all references to wkorgProxyController have been removed and that the new controller functions as expected.


58-58: Review Routing Logic for Unhandled Requests

The default handler now redirects unhandled requests using aboutPageRedirectController.redirectToAboutPageOrSendMainView. Ensure this does not unintentionally redirect requests that should be served differently, such as static resources or valid routes not covered by earlier conditions.

Evaluate the ordering of conditions in routeRequest and consider adding specific checks for any additional routes that should bypass the redirect.

conf/application.conf (1)

226-229: LGTM! Verify the configuration documentation.

The configuration section is well-structured with sensible defaults. The comment accurately describes the conditional behavior.

Let's verify that the configuration is used correctly in the codebase:

✅ Verification successful

Documentation accurately reflects the implementation

The configuration comment correctly describes that:

  • Redirects only work when features.isWkorgInstance is true
  • The "/" route is only redirected for logged-out users
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of isWkorgInstance with aboutPageRedirect
rg -A 3 "isWkorgInstance.*aboutPageRedirect|aboutPageRedirect.*isWkorgInstance"

Length of output: 81


Script:

#!/bin/bash
# Search for aboutPageRedirect usage
rg -A 5 "aboutPageRedirect"

# Search for configuration loading patterns
ast-grep --pattern 'config.get("aboutPageRedirect")'

Length of output: 2063


Script:

#!/bin/bash
# Search for AboutPageRedirectController implementation
ast-grep --pattern 'class AboutPageRedirectController $$$'

# Search for isWkorgInstance usage in AboutPageRedirectController
rg -A 5 "class AboutPageRedirectController" 

Length of output: 808


Script:

#!/bin/bash
# Search for redirectToAboutPageOrSendMainView implementation
ast-grep --pattern 'def redirectToAboutPageOrSendMainView $$$'

# Search for the method content
rg -A 10 "redirectToAboutPageOrSendMainView"

Length of output: 1888


Script:

#!/bin/bash
# Search for matchesRedirectRoute implementation
rg -A 10 "matchesRedirectRoute"

# Search for isWkorgInstance usage in the controller
rg "isWkorgInstance" app/controllers/AboutPageRedirectController.scala

Length of output: 2228

app/utils/WkConf.scala (1)

139-141: LGTM! Clean implementation following established patterns.

The AboutPageRedirect object correctly maps to the new configuration section and follows the codebase's configuration management patterns.

Also applies to: 253-253

@fm3 fm3 enabled auto-merge (squash) January 22, 2025 09:13
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: 0

♻️ Duplicate comments (1)
app/controllers/AboutPageRedirectController.scala (1)

30-30: ⚠️ Potential issue

Fix potential open redirect vulnerability.

Direct concatenation of request.uri with the prefix could allow malicious redirects.

Apply this fix to validate the URI:

-      Fox.successful(Redirect(conf.AboutPageRedirect.prefix + request.uri, status = status))
+      val safeUri = UriEncoding.encodePathSegment(request.uri, "UTF-8")
+      Fox.successful(Redirect(conf.AboutPageRedirect.prefix + safeUri, status = status))
🧹 Nitpick comments (3)
app/controllers/AboutPageRedirectController.scala (3)

29-30: Document status code selection.

The different status codes (303 vs 301) for root vs non-root paths should be documented to explain the reasoning.

Add a comment explaining the status code selection:

+      // Use 303 for root path to prevent browser caching, 301 for other paths
       val status = if (request.uri == "/") SEE_OTHER else MOVED_PERMANENTLY

Line range hint 31-53: Consider extracting the main view rendering logic.

The else block contains nested logic for rendering the main view. Consider extracting it to improve readability.

Extract the main view rendering to a separate private method:

+  private def renderMainView(request: UserAwareRequest[WkEnv, AnyContent]) = {
+    for {
+      multiUserOpt <- Fox.runOptional(request.identity)(user =>
+        multiUserDAO.findOne(user._multiUser)(GlobalAccessContext))
+      openGraphTags <- openGraphService.getOpenGraphTags(
+        request.path,
+        request.getQueryString("sharingToken").orElse(request.getQueryString("token")))
+    } yield addCspHeader(
+      Ok(views.html.main(
+        conf,
+        multiUserOpt.map(_.selectedTheme).getOrElse(Theme.auto).toString,
+        openGraphTags.title,
+        openGraphTags.description,
+        openGraphTags.image
+      ))
+    )
+  }

54-56: Document the redirect route matching logic.

The complex condition combining multiple checks would benefit from documentation explaining the routing rules.

Add documentation explaining the conditions:

+  /**
+   * Determines if the request should be redirected based on:
+   * 1. If this is a wkorg instance
+   * 2. If the path matches configured routes
+   * 3. If the user is not authenticated or the path is not root
+   */
   private def matchesRedirectRoute(request: UserAwareRequest[WkEnv, AnyContent]): Boolean =
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 63beb4e and 20f7c3d.

📒 Files selected for processing (2)
  • MIGRATIONS.unreleased.md (1 hunks)
  • app/controllers/AboutPageRedirectController.scala (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • MIGRATIONS.unreleased.md
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: circleci_build
🔇 Additional comments (2)
app/controllers/AboutPageRedirectController.scala (2)

19-23: LGTM! Clean constructor refactoring.

The class renaming and dependency changes accurately reflect the transition from proxying to redirection.


58-61: Consider validating route patterns.

The wildcard matching logic assumes well-formed route patterns. Consider adding validation for the route patterns.

Run this script to check for potentially problematic route patterns:

@fm3 fm3 merged commit e9c31a9 into master Jan 22, 2025
3 checks passed
@fm3 fm3 deleted the about-page-redirect branch January 22, 2025 09:26
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.

2 participants