Skip to content

Commit 844a11a

Browse files
authored
fix: /base64 endpoint decodes both URL-safe and standard b64 encodings (#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
1 parent e3c4f8d commit 844a11a

File tree

3 files changed

+16
-11
lines changed

3 files changed

+16
-11
lines changed

httpbin/handlers_test.go

+7-6
Original file line numberDiff line numberDiff line change
@@ -2707,6 +2707,13 @@ func TestBase64(t *testing.T) {
27072707
"/base64/decode/YWJjMTIzIT8kKiYoKSctPUB-",
27082708
"abc123!?$*&()'-=@~",
27092709
},
2710+
{
2711+
// Std base64 is also supported for decoding (+ instead of - in
2712+
// encoded input string). See also:
2713+
// https://github.com/mccutchen/go-httpbin/issues/152
2714+
"/base64/decode/8J+Ziywg8J+MjSEK4oCm",
2715+
"🙋, 🌍!\n…",
2716+
},
27102717
{
27112718
// URL-safe base64 is used for encoding (note the - instead of + in
27122719
// encoded output string)
@@ -2764,12 +2771,6 @@ func TestBase64(t *testing.T) {
27642771
"/base64/unknown/dmFsaWRfYmFzZTY0X2VuY29kZWRfc3RyaW5n",
27652772
"invalid operation: unknown",
27662773
},
2767-
{
2768-
// we only support URL-safe base64 encoded strings (note the +
2769-
// instead of - in encoded input string)
2770-
"/base64/decode/YWJjMTIzIT8kKiYoKSctPUB+",
2771-
"illegal base64 data",
2772-
},
27732774
}
27742775

27752776
for _, test := range errorTests {

httpbin/helpers.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -429,16 +429,20 @@ func newBase64Helper(path string) (*base64Helper, error) {
429429
return &b, nil
430430
}
431431

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

439-
// Decode - decode data from base64
439+
// Decode - decode data from base64, attempting both URL-safe and standard
440+
// encodings.
440441
func (b *base64Helper) Decode() ([]byte, error) {
441-
return base64.URLEncoding.DecodeString(b.data)
442+
if result, err := base64.URLEncoding.DecodeString(b.data); err == nil {
443+
return result, nil
444+
}
445+
return base64.StdEncoding.DecodeString(b.data)
442446
}
443447

444448
func wildCardToRegexp(pattern string) string {

httpbin/static/index.html

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)