Repository: ably/ably-go
Pull request #674 (2024-11-27 00:57:51)

auth: Add option to allow basic auth for non-TLS requests
We internally often want to use the Go SDK in private environments (e.g. local development, or within virtual private networks), where we do not use TLS, but find it convenient to be able to use API keys rather than tokens.

This commit adds an `InsecureAllowBasicAuthWithoutTLS` option which permits the use of an API key when the `NoTLS` option is also set.

We only require this in the Go SDK, so there is no intention of adding this option to the feature spec.

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
	- Introduced a new option allowing basic authentication without TLS for enhanced flexibility.
	- Added a method to easily configure the new authentication option.
- **Bug Fixes**
	- Improved security checks for basic authentication over non-TLS connections.
- **Tests**
	- Added tests to ensure correct behavior of basic authentication options with and without TLS.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

coderabbitai[bot]: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- This is an auto-generated comment: review in progress by coderabbit.ai -->

> [!NOTE]
> Currently processing new changes in this PR. This may take a few minutes, please wait...
> 
> <details>
> <summary>📥 Commits</summary>
> 
> Reviewing files that changed from the base of the PR and between a81632dfeb26bd545232674622463e5709d42e03 and 0e1c8e8988a94239b0bd96d676aa29a38b6fa09f.
> 
> </details>
> 
> <details>
> <summary>📒 Files selected for processing (2)</summary>
> 
> * `ably/auth.go` (1 hunks)
> * `ably/options.go` (2 hunks)
> 
> </details>
> 
> ```ascii
>  _____________________________________________________________________________________________________
> < Write code that writes code. Code generators increase your productivity and help avoid duplication. >
>  -----------------------------------------------------------------------------------------------------
>   \
>    \   \
>         \ /\
>         ( )
>       .( o ).
> ```

<!-- end of auto-generated comment: review in progress by coderabbit.ai -->

<!-- usage_tips_start -->

> [!TIP]
> <details>
> <summary>CodeRabbit can enforce grammar and style rules using `languagetool`.</summary>
> 
> Configure `languagetool` in your project's settings in CodeRabbit enable/disable rules and categories. Refer to the [LanguageTool Community](https://community.languagetool.org/rule/list) to learn more.
> 
> </details>

<!-- usage_tips_end -->
<!-- tips_start -->

---

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?

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai):

- 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 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->
sacOO7: Not sure why so many tests got flaky suddenly : ( . We always had green CI for every PR before.
One of the common test I can see failing is `TestRealtimeConn_RTN15i_OnErrorWhenConnected`
@lmars can you check what might be going wrong? 
lmars: @sacOO7 the failing test is `TestRealtimeConn_RTN16` which I have proposed a fix for in https://github.com/ably/ably-go/pull/675.
sacOO7: @lmars we are planning to create one more PR to fix present enter 250 test right?
lmars: @sacOO7 I've created a ticket for that here:

https://github.com/ably/ably-go/issues/676

It needs to be fixed, but I don't have an immediate plan to fix it.

Given this PR is unrelated to that failure, please can you review it so I can merge?
sacOO7: Simple test can be added to `options_test.go`, using `noTls=true` over `basic auth` returns error.

Patch:
diff --git a/ably/auth.go b/ably/auth.go
index 1b0dc1b..56d1a30 100644
--- a/ably/auth.go
+++ b/ably/auth.go
@@ -545,7 +545,7 @@ func detectAuthMethod(opts *clientOptions) (int, error) {
 	if !isKeyValid {
 		return 0, newError(ErrInvalidCredential, errInvalidKey)
 	}
-	if opts.NoTLS {
+	if opts.NoTLS && !opts.InsecureAllowBasicAuthWithoutTLS {
 		return 0, newError(ErrInvalidUseOfBasicAuthOverNonTLSTransport, errInsecureBasicAuth)
 	}
 	return authBasic, nil
diff --git a/ably/options.go b/ably/options.go
index 1bf2678..6c7c836 100644
--- a/ably/options.go
+++ b/ably/options.go
@@ -408,6 +408,10 @@ type clientOptions struct {
 	// LogHandler controls the log output of the library. This is a function to handle each line of log output.
 	// platform specific (TO3c)
 	LogHandler Logger
+
+	// InsecureAllowBasicAuthWithoutTLS permits an API key to be used even if the connection
+	// will not use TLS, something which would otherwise not be permitted for security reasons.
+	InsecureAllowBasicAuthWithoutTLS bool
 }
 
 func (opts *clientOptions) validate() error {
@@ -1316,6 +1320,14 @@ func WithDial(dial func(protocol string, u *url.URL, timeout time.Duration) (con
 	}
 }
 
+// WithInsecureAllowBasicAuthWithoutTLS permits an API key to be used even if the connection
+// will not use TLS, something which would otherwise not be permitted for security reasons.
+func WithInsecureAllowBasicAuthWithoutTLS() ClientOption {
+	return func(opts *clientOptions) {
+		opts.InsecureAllowBasicAuthWithoutTLS = true
+	}
+}
+
 func applyOptionsWithDefaults(opts ...ClientOption) *clientOptions {
 	to := defaultOptions
 	// No need to set hosts by default


Test patch:
diff --git a/ably/options_test.go b/ably/options_test.go
index 855076b..cc86e79 100644
--- a/ably/options_test.go
+++ b/ably/options_test.go
@@ -236,6 +236,28 @@ func TestScopeParams(t *testing.T) {
 	})
 }
 
+func TestOption_NoTLS(t *testing.T) {
+	t.Run("does not allow basic auth with no TLS", func(t *testing.T) {
+		_, err := ably.NewREST(
+			ably.WithKey("xxxxxx.yyyyyy:zzzzzz"),
+			ably.WithTLS(false),
+		)
+		assert.Error(t, err)
+		errInfo, ok := err.(*ably.ErrorInfo)
+		assert.True(t, ok)
+		assert.Equal(t, errInfo.Code, ably.ErrInvalidUseOfBasicAuthOverNonTLSTransport)
+	})
+
+	t.Run("allows basic auth with no TLS when InsecureAllowBasicAuthWithoutTLS is set", func(t *testing.T) {
+		_, err := ably.NewREST(
+			ably.WithKey("xxxxxx.yyyyyy:zzzzzz"),
+			ably.WithTLS(false),
+			ably.WithInsecureAllowBasicAuthWithoutTLS(),
+		)
+		assert.NoError(t, err)
+	})
+}
+
 func TestPaginateParams(t *testing.T) {
 	t.Run("returns nil with no values", func(t *testing.T) {