Skip to content

Commit

Permalink
fix: /base64 endpoint decodes both URL-safe and standard b64 encodings (
Browse files Browse the repository at this point in the history
#153)

As reported in #152, the `/base64` endpoint can only decode the
"URL-safe" base64 encoding, but the error it returns is not very useful
if you're not already familiar with different base64 encoding variants.

Here we follow [Postel's law][1] and accept either the URL-safe or
standard encodings, while continuing to use the URL-safe variant
when encoding ourselves.

Fixes #152.

[1]: https://en.wikipedia.org/wiki/Robustness_principle
  • Loading branch information
mccutchen authored Nov 5, 2023
1 parent e3c4f8d commit 844a11a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 11 deletions.
13 changes: 7 additions & 6 deletions httpbin/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2707,6 +2707,13 @@ func TestBase64(t *testing.T) {
"/base64/decode/YWJjMTIzIT8kKiYoKSctPUB-",
"abc123!?$*&()'-=@~",
},
{
// Std base64 is also supported for decoding (+ instead of - in
// encoded input string). See also:
// https://github.com/mccutchen/go-httpbin/issues/152
"/base64/decode/8J+Ziywg8J+MjSEK4oCm",
"🙋, 🌍!\n…",
},
{
// URL-safe base64 is used for encoding (note the - instead of + in
// encoded output string)
Expand Down Expand Up @@ -2764,12 +2771,6 @@ func TestBase64(t *testing.T) {
"/base64/unknown/dmFsaWRfYmFzZTY0X2VuY29kZWRfc3RyaW5n",
"invalid operation: unknown",
},
{
// we only support URL-safe base64 encoded strings (note the +
// instead of - in encoded input string)
"/base64/decode/YWJjMTIzIT8kKiYoKSctPUB+",
"illegal base64 data",
},
}

for _, test := range errorTests {
Expand Down
10 changes: 7 additions & 3 deletions httpbin/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,16 +429,20 @@ func newBase64Helper(path string) (*base64Helper, error) {
return &b, nil
}

// Encode - encode data as base64
// Encode - encode data as URL-safe base64
func (b *base64Helper) Encode() ([]byte, error) {
buff := make([]byte, base64.URLEncoding.EncodedLen(len(b.data)))
base64.URLEncoding.Encode(buff, []byte(b.data))
return buff, nil
}

// Decode - decode data from base64
// Decode - decode data from base64, attempting both URL-safe and standard
// encodings.
func (b *base64Helper) Decode() ([]byte, error) {
return base64.URLEncoding.DecodeString(b.data)
if result, err := base64.URLEncoding.DecodeString(b.data); err == nil {
return result, nil
}
return base64.StdEncoding.DecodeString(b.data)
}

func wildCardToRegexp(pattern string) string {
Expand Down
4 changes: 2 additions & 2 deletions httpbin/static/index.html

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 844a11a

Please sign in to comment.