Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow HTTP basic authentication in addition to bearer #8

Merged
merged 1 commit into from
Jul 27, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
Expand Down Expand Up @@ -336,16 +337,28 @@ func validateAuth(auth string) bool {

parts := strings.Split(auth, " ")

// Expect ["Bearer", "sk_test_123"]
if len(parts) != 2 {
// Expect ["Bearer", "sk_test_123"] or ["Basic", "aaaaa"]
if len(parts) != 2 || parts[1] == "" {
return false
}

if parts[0] != "Bearer" {
var key string
switch parts[0] {
case "Basic":
keyBytes, err := base64.StdEncoding.DecodeString(parts[1])
if err != nil {
return false
}
key = string(keyBytes)

case "Bearer":
key = parts[1]

default:
return false
}

keyParts := strings.Split(parts[1], "_")
keyParts := strings.Split(key, "_")

// Expect ["sk", "test", "123"]
if len(keyParts) != 3 {
Expand Down
11 changes: 11 additions & 0 deletions server_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"encoding/base64"
"io/ioutil"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -152,9 +153,15 @@ func TestValidateAuth(t *testing.T) {
auth string
want bool
}{
{"Basic " + encode64("sk_test_123"), true},
{"Bearer sk_test_123", true},
{"", false},
{"Bearer", false},
{"Basic", false},
{"Bearer ", false},
{"Basic ", false},
{"Basic 123", false}, // "123" is not a valid key when decoded
{"Basic " + encode64("sk_test"), false},
{"Bearer sk_test_123 extra", false},
{"Bearer sk_test", false},
{"Bearer sk_test_123_extra", false},
Expand All @@ -172,6 +179,10 @@ func TestValidateAuth(t *testing.T) {
// ---
//

func encode64(s string) string {
return base64.StdEncoding.EncodeToString([]byte(s))
}

func getStubServer(t *testing.T) *StubServer {
server := &StubServer{spec: testSpec}
err := server.initializeRouter()
Expand Down