Skip to content

Add credential extraction and normalization for gateway URLs - #23

Closed
minikolic wants to merge 5 commits into
openclaw:masterfrom
minikolic:feat/add-support-for-embedded-credentials
Closed

minikolic wants to merge 5 commits into
openclaw:masterfrom
minikolic:feat/add-support-for-embedded-credentials

Conversation

@minikolic

Copy link
Copy Markdown

Add HTTP Basic Auth support for gateway URLs with embedded credentials

Summary

This PR adds support for gateway URLs with embedded credentials in the format wss://username:password@host. This enables connecting to gateways behind reverse proxies (like nginx) that require HTTP Basic Authentication.

Motivation

When deploying OpenClaw gateway behind a reverse proxy with Basic Auth protection (common setup with nginx), in my case I'm hosting Gateway on Coolify, users need a way to pass both:

  1. HTTP Basic Auth credentials - to authenticate with the reverse proxy
  2. Token - for application-level authentication with the gateway itself

Previously, ClientWebSocket doesn't automatically extract credentials from URLs, causing connection failures when using URLs like wss://user:[email protected].

Changes

  • GatewayUrlHelper.cs:

    • Added ExtractCredentials(string gatewayUrl) method to extract user:password from URLs using Uri.UserInfo
  • WindowsNodeClient.cs & OpenClawGatewayClient.cs:

    • Added _credentials field to store extracted credentials
    • Extract credentials from gateway URL in constructor using GatewayUrlHelper.ExtractCredentials()
    • Set Authorization: Basic <base64> header on WebSocket connection when credentials are present
    • Token continues to be sent in the auth.token JSON field for gateway authentication
  • Tests: Added tests for credential extraction (ExtractCredentials_ExtractsCredentialsFromUrl, ExtractCredentials_ReturnsNullWhenNoCredentials) and URL normalization with credentials

Usage

Gateway URL: wss://user:[email protected]
Token: your-gateway-token

The credentials (user:pass) are extracted and sent as HTTP Basic Auth header to reach the gateway through the proxy, while the token authenticates with the gateway application.

Related

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR adds support for HTTP Basic Authentication when connecting to OpenClaw gateway instances behind reverse proxies (like nginx) by extracting embedded credentials from gateway URLs in the format wss://username:password@host. The credentials are sent as an Authorization header during WebSocket connection, while the existing token-based authentication continues to be used for gateway application-level authentication.

Changes:

  • Added ExtractCredentials() method to GatewayUrlHelper to extract credentials from URL UserInfo
  • Modified WindowsNodeClient and OpenClawGatewayClient to extract credentials and set HTTP Basic Auth header during connection
  • Added comprehensive tests for credential extraction and URL normalization with credentials

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 8 comments.

File Description
src/OpenClaw.Shared/GatewayUrlHelper.cs Added ExtractCredentials() method to extract username:password from URL UserInfo component
src/OpenClaw.Shared/WindowsNodeClient.cs Added credential extraction and Authorization header setting for node connections
src/OpenClaw.Shared/OpenClawGatewayClient.cs Added credential extraction and Authorization header setting for operator connections
tests/OpenClaw.Shared.Tests/GatewayUrlHelperTests.cs Added tests for credential extraction and URL normalization with embedded credentials

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 65 to +67
_gatewayUrl = GatewayUrlHelper.NormalizeForWebSocket(gatewayUrl);
_token = token;
_credentials = GatewayUrlHelper.ExtractCredentials(gatewayUrl);

Copilot AI Feb 23, 2026

Copy link

Choose a reason for hiding this comment

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

The normalized gateway URL stored in _gatewayUrl preserves embedded credentials (as confirmed by the test TryNormalizeWebSocketUrl_PreservesPathAndCredentials). This normalized URL is later logged at line 124 ("Connecting to gateway as node: {_gatewayUrl}"), which will expose credentials in log files. Additionally, _gatewayUrl is exposed via the public GatewayUrl property at line 46, which is used in UI displays (e.g., StatusDetailForm.cs line 127). Consider either: 1) Stripping credentials from the normalized URL and only storing them in _credentials, or 2) Adding a sanitized version of the URL for logging/display purposes that removes the UserInfo component.

Copilot uses AI. Check for mistakes.

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.

@copilot open a new pull request to apply changes based on this feedback

Comment on lines 60 to +62
_gatewayUrl = GatewayUrlHelper.NormalizeForWebSocket(gatewayUrl);
_token = token;
_credentials = GatewayUrlHelper.ExtractCredentials(gatewayUrl);

Copilot AI Feb 23, 2026

Copy link

Choose a reason for hiding this comment

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

The normalized gateway URL stored in _gatewayUrl preserves embedded credentials (as confirmed by the test TryNormalizeWebSocketUrl_PreservesPathAndCredentials). This normalized URL is later logged at line 72 ("Connecting to gateway: {_gatewayUrl}"), which will expose credentials in log files. Consider either: 1) Stripping credentials from the normalized URL and only storing them in _credentials, or 2) Adding a sanitized version of the URL for logging/display purposes that removes the UserInfo component.

Copilot uses AI. Check for mistakes.

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.

@copilot open a new pull request to apply changes based on this feedback

Comment on lines +65 to +74
[Theory]
[InlineData("wss://user:[email protected]/path/to/endpoint", "wss://user:[email protected]/path/to/endpoint")]
[InlineData("wss://user:[email protected]:8443/api", "wss://user:[email protected]:8443/api")]
public void TryNormalizeWebSocketUrl_PreservesPathAndCredentials(string inputUrl, string expectedUrl)
{
var result = GatewayUrlHelper.TryNormalizeWebSocketUrl(inputUrl, out var normalized);

Assert.True(result);
Assert.Equal(expectedUrl, normalized);
}

Copilot AI Feb 23, 2026

Copy link

Choose a reason for hiding this comment

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

The tests verify that TryNormalizeWebSocketUrl preserves credentials in the normalized URL. However, this design choice has security implications: the normalized URL (containing credentials) is stored in _gatewayUrl and later logged or exposed via public properties. An alternative design would be to strip credentials during normalization and rely solely on the separately extracted _credentials field. This would prevent accidental credential exposure in logs and UI. Consider whether the current behavior of preserving credentials in the normalized URL is intentional and necessary, or if it would be safer to remove them during normalization.

Copilot uses AI. Check for mistakes.

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.

@copilot open a new pull request to apply changes based on this feedback

Comment on lines +17 to +30
public static string? ExtractCredentials(string gatewayUrl)
{
if (string.IsNullOrWhiteSpace(gatewayUrl))
{
return null;
}

if (!Uri.TryCreate(gatewayUrl.Trim(), UriKind.Absolute, out var uri))
{
return null;
}

return string.IsNullOrEmpty(uri.UserInfo) ? null : uri.UserInfo;
}

Copilot AI Feb 23, 2026

Copy link

Choose a reason for hiding this comment

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

The ExtractCredentials method lacks XML documentation comments. Since this is a public API that handles security-sensitive data (credentials), it should include documentation explaining: 1) What format of credentials it extracts (username:password from UserInfo), 2) That the returned value may be URL-encoded and might need decoding before use, 3) Example usage. Consider adding XML documentation similar to other public methods in GatewayUrlHelper.

Copilot uses AI. Check for mistakes.

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.

@copilot open a new pull request to apply changes based on this feedback

Comment on lines +37 to +48
[Theory]
[InlineData("wss://user:[email protected]", "user:pass")]
[InlineData("wss://mytoken:[email protected]", "mytoken:secretkey")]
[InlineData("wss://apikey:[email protected]", "apikey:secrettoken")]
[InlineData("ws://user:pass@localhost:18789", "user:pass")]
[InlineData("https://user:[email protected]", "user:pass")]
[InlineData("http://user:pass@localhost:8080", "user:pass")]
public void ExtractCredentials_ExtractsCredentialsFromUrl(string inputUrl, string expectedToken)
{
var token = GatewayUrlHelper.ExtractCredentials(inputUrl);
Assert.Equal(expectedToken, token);
}

Copilot AI Feb 23, 2026

Copy link

Choose a reason for hiding this comment

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

The tests don't cover edge cases where credentials contain special characters that need to be URL-encoded in the URL (e.g., @, :, /, %). Consider adding test cases for URLs like wss://user%40domain:p%40ss@host to verify that URL-encoded credentials are handled correctly. This is particularly important given the potential bug in the Authorization header construction where URL-encoded values might not be properly decoded.

Copilot uses AI. Check for mistakes.

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.

@copilot open a new pull request to apply changes based on this feedback

@shanselman

Copy link
Copy Markdown
Collaborator

@copilot open a new pull request to apply changes based on the comments in this thread

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

var username = Uri.UnescapeDataString(parts[0]);
var password = Uri.UnescapeDataString(parts[1]);
credentialsToEncode = $"{username}:{password}";
}

Copilot AI Feb 24, 2026

Copy link

Choose a reason for hiding this comment

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

If Uri.UserInfo contains only a username (no ':'), Basic auth should encode username: (empty password). Currently this encodes just the username, which can cause authentication failures for proxies expecting the standard user:pass shape.

Suggested change
}
}
else if (parts.Length == 1)
{
// Handle the case where only a username is provided (no colon/password)
var username = Uri.UnescapeDataString(parts[0]);
credentialsToEncode = $"{username}:";
}

Copilot uses AI. Check for mistakes.
Comment on lines +37 to +48
[Theory]
[InlineData("wss://user:[email protected]", "user:pass")]
[InlineData("wss://mytoken:[email protected]", "mytoken:secretkey")]
[InlineData("wss://apikey:[email protected]", "apikey:secrettoken")]
[InlineData("ws://user:pass@localhost:18789", "user:pass")]
[InlineData("https://user:[email protected]", "user:pass")]
[InlineData("http://user:pass@localhost:8080", "user:pass")]
public void ExtractCredentials_ExtractsCredentialsFromUrl(string inputUrl, string expectedCredentials)
{
var credentials = GatewayUrlHelper.ExtractCredentials(inputUrl);
Assert.Equal(expectedCredentials, credentials);
}

Copilot AI Feb 24, 2026

Copy link

Choose a reason for hiding this comment

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

The new decoding/Basic-auth behavior isn’t covered for URL-encoded credentials (e.g., wss://user%40domain:p%40ss@host) or edge cases like username-only credentials. Add test cases to verify ExtractCredentials output and the Authorization header construction expectations.

Copilot uses AI. Check for mistakes.
Comment on lines 65 to 68
_gatewayUrl = GatewayUrlHelper.NormalizeForWebSocket(gatewayUrl);
_token = token;
_credentials = GatewayUrlHelper.ExtractCredentials(gatewayUrl);
_logger = logger ?? NullLogger.Instance;

Copilot AI Feb 24, 2026

Copy link

Choose a reason for hiding this comment

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

_gatewayUrl is derived from NormalizeForWebSocket(gatewayUrl) and can include embedded credentials (user:pass@...). That value is later logged (and exposed via the GatewayUrl property), which will leak Basic Auth credentials into logs/UI. Store a sanitized URL (strip UserInfo) for logging/display, or strip credentials during normalization and keep them only in _credentials.

See below for a potential fix:

    private static string SanitizeGatewayUrl(string gatewayUrl)
    {
        if (string.IsNullOrWhiteSpace(gatewayUrl))
        {
            return gatewayUrl;
        }

        if (Uri.TryCreate(gatewayUrl, UriKind.Absolute, out var uri))
        {
            if (!string.IsNullOrEmpty(uri.UserInfo))
            {
                var builder = new UriBuilder(uri)
                {
                    UserName = string.Empty,
                    Password = string.Empty
                };

                return builder.Uri.ToString();
            }
        }

        return gatewayUrl;
    }

    public WindowsNodeClient(string gatewayUrl, string token, string dataPath, IOpenClawLogger? logger = null)
    {
        var normalizedGatewayUrl = GatewayUrlHelper.NormalizeForWebSocket(gatewayUrl);
        _gatewayUrl = SanitizeGatewayUrl(normalizedGatewayUrl);

Copilot uses AI. Check for mistakes.
Comment on lines +135 to +144
if (!string.IsNullOrEmpty(_credentials))
{
var authCredentials = _credentials;
var separatorIndex = _credentials.IndexOf(':');
if (separatorIndex >= 0)
{
var userPart = _credentials.Substring(0, separatorIndex);
var passwordPart = _credentials.Substring(separatorIndex + 1);
try
{

Copilot AI Feb 24, 2026

Copy link

Choose a reason for hiding this comment

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

When _credentials contains only a username (no ':' in Uri.UserInfo), the Basic auth header should still encode the username: form (empty password) per RFC 7617. Currently if separatorIndex < 0 you encode just username, which some proxies will reject.

Copilot uses AI. Check for mistakes.

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.

@copilot open a new pull request to apply changes based on this feedback

@shanselman

Copy link
Copy Markdown
Collaborator

@copilot open a new pull request to apply changes based on the comments in this thread

shanselman added a commit that referenced this pull request Feb 24, 2026
…redentials

Harden gateway credential handling, sanitize display URLs, and expand credential edge-case tests.

Co-authored-by: Copilot <[email protected]>
@shanselman

Copy link
Copy Markdown
Collaborator

Squash-merged into master in 63b9268.

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.

3 participants