Skip to content

Conversation

@dwrz
Copy link
Contributor

@dwrz dwrz commented Oct 8, 2025

Introduce HTTPS support with net/http Server.ListenAndServeTLS.

This should enable the option of serving via HTTPS without a reverse proxy.

Add two flags:

  • tls-cert-file (path to the TLS certificate file)
  • tls-key-file (path to the TLS private key file)

Both flags must be supplied together; otherwise exit with error.

If both flags are present, call srv.ListenAndServeTLS. If not, fall back to the existing srv.ListenAndServe (HTTP); no changes to existing non‑TLS behavior.

Summary by CodeRabbit

  • New Features

    • Optional TLS/HTTPS support via certificate and key flags; service chooses HTTPS port when enabled and logs the correct protocol and listening URL.
  • Bug Fixes

    • Validates certificate/key pair and exits with a clear error if only one is provided.
    • Server now fails fast on TLS misconfiguration and consistently logs the active listening URL and port.

@coderabbitai
Copy link

coderabbitai bot commented Oct 8, 2025

Walkthrough

Adds two CLI flags (--tls-cert-file, --tls-key-file), enforces both-or-none, chooses default listen port (:8443 when TLS, :8080 otherwise), and conditionally starts the server with ListenAndServeTLS when both TLS files are provided; exits on TLS misconfiguration.

Changes

Cohort / File(s) Summary of changes
Server TLS startup and flags
llama-swap.go
Added --tls-cert-file and --tls-key-file flags and validation (require both or none). Default listen port set based on TLS presence (:8443 for TLS, :8080 for HTTP). Server startup branches to ListenAndServeTLS with cert/key when provided, otherwise ListenAndServe. Logs HTTPS/HTTP URL and exits on TLS misconfiguration.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    actor U as User
    participant M as llama-swap (main)
    participant S as HTTP(S) Server

    U->>M: Run binary with flags
    M->>M: Parse flags
    alt Exactly one TLS flag provided
        M->>U: Log error: both TLS flags required
        M-->>U: Exit (fatal)
    else Both TLS flags provided
        M->>S: Start ListenAndServeTLS(certFile, keyFile) on :8443
        M->>U: Log TLS URL (https://host:8443)
    else No TLS flags
        M->>S: Start ListenAndServe on :8080
        M->>U: Log HTTP URL (http://host:8080)
    end
    note over S,M: Server runs until error or shutdown
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly and concisely summarizes the main change by indicating that optional TLS support is being introduced, directly reflecting the addition of new TLS flags and server behavior modifications.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0472349 and afeb2ef.

📒 Files selected for processing (1)
  • llama-swap.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • llama-swap.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: run-tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@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

🧹 Nitpick comments (1)
llama-swap.go (1)

44-48: Consider validating file existence and readability.

The XOR logic correctly ensures both TLS flags are provided together. However, consider adding validation that the certificate and key files exist and are readable before proceeding. This would fail fast with a clear error message rather than deferring the error until ListenAndServeTLS is called.

Apply this diff to add early file validation:

 	if (*certFile != "" && *keyFile == "") ||
 		(*certFile == "" && *keyFile != "") {
 		fmt.Println("Error: Both --tls-cert-file and --tls-key-file must be provided for TLS.")
 		os.Exit(1)
 	}
+
+	// Validate TLS files exist and are readable
+	if *certFile != "" {
+		if _, err := os.Stat(*certFile); err != nil {
+			fmt.Printf("Error: TLS certificate file not accessible: %v\n", err)
+			os.Exit(1)
+		}
+		if _, err := os.Stat(*keyFile); err != nil {
+			fmt.Printf("Error: TLS key file not accessible: %v\n", err)
+			os.Exit(1)
+		}
+	}
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 00b738c and d93b47c.

📒 Files selected for processing (1)
  • llama-swap.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

Fix all staticcheck-reported issues in Go code

Files:

  • llama-swap.go
🔇 Additional comments (2)
llama-swap.go (2)

32-33: LGTM! Clean flag definitions.

The TLS flag definitions follow the existing pattern and use appropriate defaults.


179-190: LGTM! Clean conditional TLS startup.

The implementation correctly:

  • Uses separate code paths for TLS and non-TLS startup
  • Logs clear, protocol-appropriate URLs
  • Handles errors properly by treating all errors except http.ErrServerClosed as fatal

The redundant check at line 180 (given the earlier validation at lines 44-48) is harmless defensive programming.

@dwrz
Copy link
Contributor Author

dwrz commented Oct 8, 2025

I believe this works for the UI, but for llama-server, we will need to add this line if using TLS:

 srv.TLSConfig = &tls.Config{NextProtos: []string{"http/1.1"}} 

I will update the PR.

Copy link

@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

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d93b47c and dd94ffa.

📒 Files selected for processing (1)
  • llama-swap.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (CLAUDE.md)

Fix all staticcheck-reported issues in Go code

Files:

  • llama-swap.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: run-tests
🔇 Additional comments (2)
llama-swap.go (2)

31-33: LGTM!

The flag definitions follow Go conventions and appropriately use empty defaults since TLS usage is validated later.


190-198: Verify TLS configuration for llama-server component.

The server startup logic is correct, but according to your PR comment, the llama-server component requires setting srv.TLSConfig = &tls.Config{NextProtos: []string{"http/1.1"}} before calling ListenAndServeTLS. Please confirm this has been addressed or is planned for the update you mentioned.

If this configuration is still needed, apply this diff before line 194:

 	go func() {
 		var err error
 		if useTLS {
+			srv.TLSConfig = &tls.Config{NextProtos: []string{"http/1.1"}}
 			fmt.Printf("llama-swap listening with TLS on https://%s\n", *listenStr)
 			err = srv.ListenAndServeTLS(*certFile, *keyFile)

@dwrz
Copy link
Contributor Author

dwrz commented Oct 8, 2025

I am looking into using httputil.ReverseProxy. I'll continue this PR after I finish exploring that option.

@mostlygeek
Copy link
Owner

@dwrz anything that needs to be revisited in this PR?

dwrz added 3 commits October 14, 2025 12:20
Introduce HTTPS support with net/http Server.ListenAndServeTLS.

This should enable the option of serving via HTTPS without a reverse
proxy.

Add two flags:
- tls-cert-file (path to the TLS certificate file)
- tls-key-file (path to the TLS private key file)

Both flags must be supplied together; otherwise exit with error.

If both flags are present, call srv.ListenAndServeTLS.
If not, fall back to the existing srv.ListenAndServe (HTTP); no changes
to existing non‑TLS behavior.
If both tls-cert-file and tls-key-file are set, assume the intent to use
TLS.

If TLS is enabled, default to port 8443. Otherwise, 8080.
useTLS was set to true in the case that no certFile or keyFile was set.
@dwrz
Copy link
Contributor Author

dwrz commented Oct 14, 2025

@mostlygeek -- llama-swap works well on my end with these commits, both with and without TLS. I have not tested groups, though, as I don't have that in my configuration.

On the main branch, make test-all still results in some failures and data races for me, which persist on this branch. I'm not sure if anything needs to be initialized for the tests to succeed. We could merge and deal with those issues separately, or resolve those issues and then merge.

Either way -- thank you for your time and help with the issues. I hope other llama-swap users will benefit from these changes!

@mostlygeek mostlygeek merged commit 6516532 into mostlygeek:main Oct 16, 2025
3 checks passed
@mostlygeek
Copy link
Owner

hi @dwrz thanks for this PR and #342. Both changes are going out in v166.
Re: race conditions, looks like test action for linux/windows are both passing on main. I think we should be good for now. Appreciate you catching those too.

@dwrz dwrz deleted the tls branch October 16, 2025 11:18
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.

2 participants