Skip to content

Commit fc7bafa

Browse files
committed
Reject foreign-host URLs in api command to prevent token leak
parsePath now validates absolute URLs against the configured base URL host: a path is accepted only if it's relative or an absolute Basecamp URL on the same host (path extracted, account segment dropped — the SDK re-prefixes the configured account). Absolute URLs on any other host are rejected before any network call, so the SDK never attaches the Authorization: Bearer header to a foreign host. A stray leading slash ('/https://evil/…') and mixed-case schemes ('HTTPS://…') are normalized first so neither can smuggle an absolute URL past the host check. Error propagated through get/post/put/delete; api_test.go covers same-host extraction, query preservation, and foreign-host rejection.
1 parent f989b11 commit fc7bafa

2 files changed

Lines changed: 126 additions & 16 deletions

File tree

‎internal/commands/api.go‎

Lines changed: 78 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package commands
33
import (
44
"encoding/json"
55
"fmt"
6+
"net/url"
67
"regexp"
78
"strings"
89

@@ -47,7 +48,10 @@ func newAPIGetCmd() *cobra.Command {
4748
return err
4849
}
4950

50-
path := parsePath(args[0])
51+
path, err := parsePath(args[0], app.Config.BaseURL)
52+
if err != nil {
53+
return err
54+
}
5155
resp, err := app.Account().Get(cmd.Context(), path)
5256
if err != nil {
5357
return convertSDKError(err)
@@ -85,7 +89,10 @@ func newAPIPostCmd() *cobra.Command {
8589
return err
8690
}
8791

88-
path := parsePath(args[0])
92+
path, err := parsePath(args[0], app.Config.BaseURL)
93+
if err != nil {
94+
return err
95+
}
8996

9097
// Parse JSON data
9198
var body any
@@ -134,7 +141,10 @@ func newAPIPutCmd() *cobra.Command {
134141
return err
135142
}
136143

137-
path := parsePath(args[0])
144+
path, err := parsePath(args[0], app.Config.BaseURL)
145+
if err != nil {
146+
return err
147+
}
138148

139149
// Parse JSON data
140150
var body any
@@ -176,7 +186,10 @@ func newAPIDeleteCmd() *cobra.Command {
176186
return err
177187
}
178188

179-
path := parsePath(args[0])
189+
path, err := parsePath(args[0], app.Config.BaseURL)
190+
if err != nil {
191+
return err
192+
}
180193
resp, err := app.Account().Delete(cmd.Context(), path)
181194
if err != nil {
182195
return convertSDKError(err)
@@ -201,20 +214,70 @@ func apiPathArgs(cmd *cobra.Command, args []string) error {
201214
return nil
202215
}
203216

204-
// parsePath extracts and normalizes the API path.
205-
// Handles full URLs and relative paths. The leading slash is stripped because
206-
// the SDK's accountPath and buildURL both add one — keeping it here would
207-
// double-slash and, on Windows, MSYS/Git Bash converts /path to C:\...\path.
208-
func parsePath(input string) string {
209-
urlPattern := regexp.MustCompile(`^https?://[^/]+/[0-9]+(/.*)`)
210-
if matches := urlPattern.FindStringSubmatch(input); len(matches) > 1 {
211-
return matches[1]
217+
// accountSegmentPattern matches a leading /<account-id>/ segment in an API
218+
// path so it can be dropped — the SDK re-prefixes the configured account.
219+
var accountSegmentPattern = regexp.MustCompile(`^/[0-9]+(/.*)$`)
220+
221+
// parsePath normalizes the user-supplied API path against the configured base
222+
// URL. It accepts relative paths ("projects.json", "/projects.json") and
223+
// absolute Basecamp URLs whose host matches baseURL — from which the path is
224+
// extracted and a leading /<account-id> segment dropped (the SDK re-prefixes
225+
// the configured account). Absolute URLs on ANY other host are rejected so the
226+
// bearer token is never attached to a request bound for a foreign host.
227+
//
228+
// All leading slashes and a mixed-case scheme are normalized first so neither
229+
// "//https://evil/…" nor "HTTPS://evil/…" can smuggle an absolute URL past the
230+
// host check (URL schemes are case-insensitive per RFC 3986 §3.1).
231+
func parsePath(input, baseURL string) (string, error) {
232+
candidate := strings.TrimLeft(input, "/")
233+
lower := strings.ToLower(candidate)
234+
if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") {
235+
u, err := url.Parse(candidate)
236+
if err != nil || u.Host == "" {
237+
return "", output.ErrUsage("invalid API URL: " + input)
238+
}
239+
base, baseErr := url.Parse(baseURL)
240+
if baseErr != nil || base.Host == "" || !sameHostPort(u, base) {
241+
return "", output.ErrUsage("API path must be relative or a Basecamp URL on the configured host; refusing to send credentials to " + input)
242+
}
243+
// Same host: use the path (+ query), dropping a leading /<account-id>.
244+
path := u.EscapedPath()
245+
if m := accountSegmentPattern.FindStringSubmatch(path); m != nil {
246+
path = m[1]
247+
}
248+
if u.RawQuery != "" {
249+
path += "?" + u.RawQuery
250+
}
251+
return path, nil
212252
}
213253

214-
// Strip leading slash — the SDK prefixes the account path.
215-
input = strings.TrimPrefix(input, "/")
254+
// Relative path — return without leading slashes; the SDK prefixes the
255+
// account path (keeping one here would double-slash and, on Windows,
256+
// MSYS/Git Bash converts /path to C:\...\path).
257+
return candidate, nil
258+
}
216259

217-
return input
260+
// sameHostPort reports whether u and base address the same host: hostnames
261+
// compared case-insensitively, ports compared after normalizing an omitted
262+
// port to the scheme default. A matching hostname on a different port is
263+
// still a different origin and must not receive credentials.
264+
func sameHostPort(u, base *url.URL) bool {
265+
if !strings.EqualFold(u.Hostname(), base.Hostname()) {
266+
return false
267+
}
268+
return effectivePort(u) == effectivePort(base)
269+
}
270+
271+
// effectivePort returns the URL's explicit port, or the scheme's default
272+
// (80 for http, 443 for https) when omitted.
273+
func effectivePort(u *url.URL) string {
274+
if port := u.Port(); port != "" {
275+
return port
276+
}
277+
if strings.EqualFold(u.Scheme, "http") {
278+
return "80"
279+
}
280+
return "443"
218281
}
219282

220283
// apiSummary generates a summary from the API response.

‎internal/commands/api_test.go‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import (
1212
"github.com/basecamp/basecamp-cli/internal/output"
1313
)
1414

15+
const testBaseURL = "https://3.basecampapi.com"
16+
1517
func TestParsePath(t *testing.T) {
1618
tests := []struct {
1719
input string
@@ -21,13 +23,58 @@ func TestParsePath(t *testing.T) {
2123
{"/projects.json", "projects.json"},
2224
{"buckets/123/todos/456.json", "buckets/123/todos/456.json"},
2325
{"/buckets/123/todos/456.json", "buckets/123/todos/456.json"},
26+
// Same-host absolute URLs: extract the path, dropping the account segment.
2427
{"https://3.basecampapi.com/999/projects.json", "/projects.json"},
2528
{"https://3.basecampapi.com/12345/buckets/1/todos/2.json", "/buckets/1/todos/2.json"},
29+
// Same host but no account segment — accepted, path used as-is.
30+
{"https://3.basecampapi.com/projects.json", "/projects.json"},
31+
// Query strings are preserved.
32+
{"https://3.basecampapi.com/999/projects.json?page=2", "/projects.json?page=2"},
33+
// Schemes are case-insensitive (RFC 3986): a same-host uppercase scheme
34+
// still extracts the path.
35+
{"HTTPS://3.basecampapi.com/999/projects.json", "/projects.json"},
36+
// An explicit default port is still the configured host.
37+
{"https://3.basecampapi.com:443/999/projects.json", "/projects.json"},
2638
}
2739

2840
for _, tt := range tests {
2941
t.Run(tt.input, func(t *testing.T) {
30-
assert.Equal(t, tt.want, parsePath(tt.input))
42+
got, err := parsePath(tt.input, testBaseURL)
43+
require.NoError(t, err)
44+
assert.Equal(t, tt.want, got)
45+
})
46+
}
47+
}
48+
49+
// TestParsePathRejectsForeignHosts guards against bearer-token exfiltration: an
50+
// absolute URL whose host differs from the configured base URL must be rejected
51+
// before it reaches the SDK, which would otherwise attach the Authorization
52+
// header and send credentials to the foreign host. Covers mixed-case schemes,
53+
// leading-slash smuggling attempts, and a same-hostname non-default port.
54+
func TestParsePathRejectsForeignHosts(t *testing.T) {
55+
bad := []string{
56+
"https://evil.com/projects.json",
57+
"http://evil.com/projects.json",
58+
"https://evil.com/",
59+
"https://evil.com",
60+
"https://evil.example/999/projects.json", // foreign host, numeric form
61+
"http://127.0.0.1:9999/projects.json",
62+
"HTTPS://evil.example/projects.json", // uppercase scheme
63+
"HtTpS://evil.example/projects.json", // mixed-case scheme
64+
"/https://evil.example/projects.json", // leading-slash smuggling
65+
"/HTTPS://evil.example/projects.json", // leading slash + uppercase
66+
"//https://evil.example/projects.json", // double-slash smuggling
67+
"///https://evil.example/x", // triple-slash smuggling
68+
"https://3.basecampapi.com:8443/projects.json", // same hostname, non-default port
69+
"https://3.basecampapi.com:443.evil.com/projects.json", // port-lookalike host smuggling
70+
"https://3.basecampapi.com:abc/x", // non-numeric port
71+
}
72+
73+
for _, input := range bad {
74+
t.Run(input, func(t *testing.T) {
75+
got, err := parsePath(input, testBaseURL)
76+
require.Error(t, err)
77+
assert.Empty(t, got)
3178
})
3279
}
3380
}

0 commit comments

Comments
 (0)