-
Notifications
You must be signed in to change notification settings - Fork 58
fix: validate host URL in GitHub integration OAuth callback #806
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nimish-ks
wants to merge
1
commit into
main
Choose a base branch
from
fix/github-callback-url-validation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| import pytest | ||
| import json | ||
| import base64 | ||
| from unittest.mock import patch, MagicMock | ||
| from django.test import RequestFactory | ||
| from api.views.auth import github_integration_callback | ||
|
|
||
|
|
||
| class TestGitHubIntegrationCallbackURLValidation: | ||
| """Tests that the GitHub OAuth callback validates host URLs.""" | ||
|
|
||
| def _make_state(self, host_url="https://github.com", **kwargs): | ||
| """Create a base64-encoded state parameter.""" | ||
| state = { | ||
| "returnUrl": "/", | ||
| "isEnterprise": True, | ||
| "hostUrl": host_url, | ||
| "apiUrl": host_url, | ||
| "orgId": "test-org", | ||
| "name": "test", | ||
| **kwargs, | ||
| } | ||
| return base64.b64encode(json.dumps(state).encode()).decode() | ||
|
|
||
| def test_rejects_private_ip_host_url(self): | ||
| """host_url pointing to a private IP should be rejected.""" | ||
| factory = RequestFactory() | ||
| state = self._make_state(host_url="http://169.254.169.254/latest/meta-data") | ||
| request = factory.get( | ||
| "/oauth/github/callback", | ||
| {"code": "test-code", "state": state}, | ||
| ) | ||
|
|
||
| with patch.dict("os.environ", {"ALLOWED_ORIGINS": "https://example.com"}): | ||
| response = github_integration_callback(request) | ||
|
|
||
| assert response.status_code == 302 | ||
| assert "invalid_host_url" in response.url | ||
|
|
||
| def test_rejects_localhost_host_url(self): | ||
| """host_url pointing to localhost should be rejected.""" | ||
| factory = RequestFactory() | ||
| state = self._make_state(host_url="http://127.0.0.1:8080") | ||
| request = factory.get( | ||
| "/oauth/github/callback", | ||
| {"code": "test-code", "state": state}, | ||
| ) | ||
|
|
||
| with patch.dict("os.environ", {"ALLOWED_ORIGINS": "https://example.com"}): | ||
| response = github_integration_callback(request) | ||
|
|
||
| assert response.status_code == 302 | ||
| assert "invalid_host_url" in response.url | ||
|
|
||
| def test_rejects_internal_network_host_url(self): | ||
| """host_url pointing to internal network should be rejected.""" | ||
| factory = RequestFactory() | ||
| state = self._make_state(host_url="http://10.0.0.1") | ||
| request = factory.get( | ||
| "/oauth/github/callback", | ||
| {"code": "test-code", "state": state}, | ||
| ) | ||
|
|
||
| with patch.dict("os.environ", {"ALLOWED_ORIGINS": "https://example.com"}): | ||
| response = github_integration_callback(request) | ||
|
|
||
| assert response.status_code == 302 | ||
| assert "invalid_host_url" in response.url | ||
|
|
||
| def test_rejects_non_http_scheme(self): | ||
| """host_url with non-http scheme should be rejected.""" | ||
| factory = RequestFactory() | ||
| state = self._make_state(host_url="file:///etc/passwd") | ||
| request = factory.get( | ||
| "/oauth/github/callback", | ||
| {"code": "test-code", "state": state}, | ||
| ) | ||
|
|
||
| with patch.dict("os.environ", {"ALLOWED_ORIGINS": "https://example.com"}): | ||
| response = github_integration_callback(request) | ||
|
|
||
| assert response.status_code == 302 | ||
| assert "invalid_host_url" in response.url | ||
|
|
||
| @patch("api.views.auth.requests.post") | ||
| @patch("api.views.auth.store_oauth_token") | ||
| @patch("api.views.auth.get_secret", return_value="fake-secret") | ||
| def test_allows_valid_github_host_url(self, mock_secret, mock_store, mock_post): | ||
| """A valid public GitHub URL should be allowed through.""" | ||
| factory = RequestFactory() | ||
| state = self._make_state(host_url="https://github.com") | ||
| request = factory.get( | ||
| "/oauth/github/callback", | ||
| {"code": "test-code", "state": state}, | ||
| ) | ||
|
|
||
| mock_post.return_value = MagicMock( | ||
| json=MagicMock(return_value={"access_token": "gho_test123"}) | ||
| ) | ||
|
|
||
| with patch.dict( | ||
| "os.environ", | ||
| { | ||
| "ALLOWED_ORIGINS": "https://example.com", | ||
| "GITHUB_ENTERPRISE_INTEGRATION_CLIENT_ID": "test-id", | ||
| }, | ||
| ): | ||
| with patch("api.views.auth.validate_url_is_safe"): | ||
| response = github_integration_callback(request) | ||
|
|
||
| # Should redirect back to app (not error) | ||
| assert response.status_code == 302 | ||
| assert "invalid_host_url" not in response.url |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check warning
Code scanning / CodeQL
URL redirection from remote source Medium
Copilot Autofix
AI about 2 months ago
In general, to fix untrusted URL redirection you must not pass user-controlled data directly to
redirectas part of the URL path or query without constraining it. Instead, either (a) maintain a server-side allowlist of known valid redirect paths and map user input to that, or (b) enforce that the user-provided part is a safe relative URL (no scheme, no host, no leading//, etc.), rejecting or normalizing anything else.For this function, the safest change without altering existing behavior too much is to sanitize
original_urlbefore any use inredirect. We can: (1) ensure it is treated as a relative path, not a full URL; (2) reject absolute URLs, protocol-relative URLs, or URLs with a non-emptynetlocor scheme; and (3) fall back to/if it fails validation. We can implement a small helper inline in this function that usesurllib.parse.urlparseto parseoriginal_url, strips backslashes (as in the background example), and checks thatscheme,netloc, and dangerous prefixes are absent. Then we replace all uses oforiginal_urlin redirect targets with a sanitized version, e.g.safe_original_url. This requires adding an import forurlparseat the top of the file (or reusing an existing one if present in this file) and adding a few lines right afteroriginal_urlis extracted.Concretely in
backend/api/views/auth.py, withingithub_integration_callback, right afteroriginal_url = state.get("returnUrl", "/")we should: (a) importurlparseif not already imported globally; (b) normalize and validateoriginal_urlintosafe_original_url, defaulting to/on failure; and (c) usesafe_original_urlin all subsequent redirect constructions (lines 211, 218, 234, 241, and 276). This keeps the existing behavior for normal relative paths while blocking malicious or malformed redirect targets.