Skip to content

Commit 3999bae

Browse files
authored
Validate CODER_URL scheme at startup (#160)
Add validation to ensure CODER_URL includes http:// or https:// scheme. Go's url.Parse() accepts URLs without schemes, which causes silent runtime failures when the HTTP client attempts requests. This change makes the application fail fast with a clear error message instead of starting successfully and failing silently at runtime.
1 parent 89272db commit 3999bae

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

main.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ func root() *cobra.Command {
4242
if err != nil {
4343
return fmt.Errorf("parse coder URL: %w", err)
4444
}
45+
if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
46+
return fmt.Errorf("CODER_URL must include http:// or https:// scheme, got: %q", coderURL)
47+
}
4548

4649
if len(kubeConfig) > 0 && kubeConfig[0] == '~' {
4750
home, err := os.UserHomeDir()

main_test.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package main
2+
3+
import (
4+
"strings"
5+
"testing"
6+
)
7+
8+
func TestRootCommand_URLValidation(t *testing.T) {
9+
tests := []struct {
10+
name string
11+
coderURL string
12+
wantError string
13+
}{
14+
{
15+
name: "missing scheme",
16+
coderURL: "coder.example.com",
17+
wantError: "CODER_URL must include http:// or https:// scheme",
18+
},
19+
{
20+
name: "empty scheme with path",
21+
coderURL: "//coder.example.com",
22+
wantError: "CODER_URL must include http:// or https:// scheme",
23+
},
24+
{
25+
name: "ftp scheme",
26+
coderURL: "ftp://coder.example.com",
27+
wantError: "CODER_URL must include http:// or https:// scheme",
28+
},
29+
{
30+
name: "empty URL",
31+
coderURL: "",
32+
wantError: "--coder-url is required",
33+
},
34+
}
35+
36+
for _, tt := range tests {
37+
t.Run(tt.name, func(t *testing.T) {
38+
cmd := root()
39+
cmd.SetArgs([]string{"--coder-url", tt.coderURL})
40+
41+
err := cmd.Execute()
42+
43+
if err == nil {
44+
t.Errorf("expected error containing %q, got nil", tt.wantError)
45+
} else if !strings.Contains(err.Error(), tt.wantError) {
46+
t.Errorf("expected error containing %q, got %q", tt.wantError, err.Error())
47+
}
48+
})
49+
}
50+
}

0 commit comments

Comments
 (0)