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

auth: using headers is optional #155

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
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
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ The method allows you to update the TXT answer contents of your unique subdomain

```POST /update```

#### Required headers
#### Optional (deprecated) headers
| Header name | Description | Example |
| ------------- |--------------------------------------------|-------------------------------------------------------|
| X-Api-User | UUIDv4 username received from registration | `X-Api-User: c36f50e8-4632-44f0-83fe-e070fef28a10` |
Expand All @@ -88,6 +88,7 @@ The method allows you to update the TXT answer contents of your unique subdomain
#### Example input
```json
{
"password": "htB9mR9DYgcu9bX_afHF62erXaH2TS7bg9KW3F7Z",
"subdomain": "8e5700ea-a4bf-41c7-8a77-e990661dcc6a",
"txt": "___validation_token_received_from_the_ca___"
}
Expand All @@ -98,6 +99,7 @@ The method allows you to update the TXT answer contents of your unique subdomain
```Status: 200 OK```
```json
{
"fulldomain": "8e5700ea-a4bf-41c7-8a77-e990661dcc6a.auth.acme-dns.io",
"txt": "___validation_token_received_from_the_ca___"
}
```
Expand Down Expand Up @@ -219,8 +221,7 @@ $ curl -X POST http://auth.example.org/register
```
$ curl -X POST \
-H "X-Api-User: eabcdb41-d89f-4580-826f-3e62e9755ef2" \
-H "X-Api-Key: pbAXVjlIOE01xbut7YnAbkhMQIkcwoHO0ek2j4Q0" \
-d '{"subdomain": "d420c923-bbd7-4056-ab64-c3ca54c9b3cf", "txt": "___validation_token_received_from_the_ca___"}' \
-d '{"password": "pbAXVjlIOE01xbut7YnAbkhMQIkcwoHO0ek2j4Q0", "subdomain": "d420c923-bbd7-4056-ab64-c3ca54c9b3cf", "txt": "___validation_token_received_from_the_ca___"}' \
http://auth.example.org/update
```

Expand Down
14 changes: 13 additions & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@ func webRegisterPost(w http.ResponseWriter, r *http.Request, _ httprouter.Params
w.Write(reg)
}

// UpdateResponse is a struct for update response JSON
type UpdateResponse struct {
TextValue string `json:"txt"`
Fulldomain string `json:"fulldomain"`
}

func webUpdatePost(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var updStatus int
var upd []byte
Expand Down Expand Up @@ -99,7 +105,13 @@ func webUpdatePost(w http.ResponseWriter, r *http.Request, _ httprouter.Params)
} else {
log.WithFields(log.Fields{"subdomain": a.Subdomain, "txt": a.Value}).Debug("TXT updated")
updStatus = http.StatusOK
upd = []byte("{\"txt\": \"" + a.Value + "\"}")
updStruct := UpdateResponse{a.Value, a.Subdomain + "." + Config.General.Domain}
upd, err = json.Marshal(updStruct)
if err != nil {
updStatus = http.StatusInternalServerError
upd = jsonError("json_error")
log.WithFields(log.Fields{"error": "json"}).Debug("Could not marshal JSON")
}
}
}
w.Header().Set("Content-Type", "application/json")
Expand Down
187 changes: 186 additions & 1 deletion api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ func TestApiManyUpdateWithCredentials(t *testing.T) {
{"a097455b-52cc-4569-90c8-7a4b97c6eba8", "LongEnoughPassButNoUserExists___________", "bb97455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 401},
{newUser.Username.String(), newUser.Password, "a097455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 401},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, "tooshortfortxt", 400},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, 1234567890, 400},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, 1234567890, 401},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, validTxtData, 200},
{newUserWithCIDR.Username.String(), newUserWithCIDR.Password, newUserWithCIDR.Subdomain, validTxtData, 401},
{newUserWithValidCIDR.Username.String(), newUserWithValidCIDR.Password, newUserWithValidCIDR.Subdomain, validTxtData, 200},
Expand All @@ -383,6 +383,130 @@ func TestApiManyUpdateWithCredentials(t *testing.T) {
}
}

func TestApiManyUpdateWithCredentialsInBody(t *testing.T) {
validTxtData := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

updateJSON := map[string]interface{}{
"username": "",
"password": "",
"subdomain": "",
"txt": ""}

router := setupRouter(true, false)
server := httptest.NewServer(router)
defer server.Close()
e := getExpect(t, server)
// User without defined CIDR masks
newUser, err := DB.Register(cidrslice{})
if err != nil {
t.Errorf("Could not create new user, got error [%v]", err)
}

// User with defined allow from - CIDR masks, all invalid
// (httpexpect doesn't provide a way to mock remote ip)
newUserWithCIDR, err := DB.Register(cidrslice{"192.168.1.1/32", "invalid"})
if err != nil {
t.Errorf("Could not create new user with CIDR, got error [%v]", err)
}

// Another user with valid CIDR mask to match the httpexpect default
newUserWithValidCIDR, err := DB.Register(cidrslice{"10.1.2.3/32", "invalid"})
if err != nil {
t.Errorf("Could not create new user with a valid CIDR, got error [%v]", err)
}

for _, test := range []struct {
user string
pass string
subdomain string
txt interface{}
status int
}{
{"non-uuid-user", "tooshortpass", "non-uuid-subdomain", validTxtData, 401},
{"a097455b-52cc-4569-90c8-7a4b97c6eba8", "tooshortpass", "bb97455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 401},
{"a097455b-52cc-4569-90c8-7a4b97c6eba8", "LongEnoughPassButNoUserExists___________", "bb97455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 401},
{newUser.Username.String(), newUser.Password, "a097455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 401},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, "tooshortfortxt", 400},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, 1234567890, 401},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, validTxtData, 200},
{newUserWithCIDR.Username.String(), newUserWithCIDR.Password, newUserWithCIDR.Subdomain, validTxtData, 401},
{newUserWithValidCIDR.Username.String(), newUserWithValidCIDR.Password, newUserWithValidCIDR.Subdomain, validTxtData, 200},
{newUser.Username.String(), "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", newUser.Subdomain, validTxtData, 401},
} {
updateJSON = map[string]interface{}{
"username": test.user,
"password": test.pass,
"subdomain": test.subdomain,
"txt": test.txt}
e.POST("/update").
WithJSON(updateJSON).
WithHeader("X-Forwarded-For", "10.1.2.3").
Expect().
Status(test.status)
}
}

func TestApiManyUpdateWithPasswordInBody(t *testing.T) {
validTxtData := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

updateJSON := map[string]interface{}{
"password": "",
"subdomain": "",
"txt": ""}

router := setupRouter(true, false)
server := httptest.NewServer(router)
defer server.Close()
e := getExpect(t, server)
// User without defined CIDR masks
newUser, err := DB.Register(cidrslice{})
if err != nil {
t.Errorf("Could not create new user, got error [%v]", err)
}

// User with defined allow from - CIDR masks, all invalid
// (httpexpect doesn't provide a way to mock remote ip)
newUserWithCIDR, err := DB.Register(cidrslice{"192.168.1.1/32", "invalid"})
if err != nil {
t.Errorf("Could not create new user with CIDR, got error [%v]", err)
}

// Another user with valid CIDR mask to match the httpexpect default
newUserWithValidCIDR, err := DB.Register(cidrslice{"10.1.2.3/32", "invalid"})
if err != nil {
t.Errorf("Could not create new user with a valid CIDR, got error [%v]", err)
}

for _, test := range []struct {
user string
pass string
subdomain string
txt interface{}
status int
}{
{"non-uuid-user", "tooshortpass", "non-uuid-subdomain", validTxtData, 401},
{"a097455b-52cc-4569-90c8-7a4b97c6eba8", "tooshortpass", "bb97455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 401},
{"a097455b-52cc-4569-90c8-7a4b97c6eba8", "LongEnoughPassButNoUserExists___________", "bb97455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 401},
{newUser.Username.String(), newUser.Password, "a097455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 401},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, "tooshortfortxt", 400},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, 1234567890, 401},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, validTxtData, 200},
{newUserWithCIDR.Username.String(), newUserWithCIDR.Password, newUserWithCIDR.Subdomain, validTxtData, 401},
{newUserWithValidCIDR.Username.String(), newUserWithValidCIDR.Password, newUserWithValidCIDR.Subdomain, validTxtData, 200},
{newUser.Username.String(), "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", newUser.Subdomain, validTxtData, 401},
} {
updateJSON = map[string]interface{}{
"password": test.pass,
"subdomain": test.subdomain,
"txt": test.txt}
e.POST("/update").
WithJSON(updateJSON).
WithHeader("X-Forwarded-For", "10.1.2.3").
Expect().
Status(test.status)
}
}

func TestApiManyUpdateWithIpCheckHeaders(t *testing.T) {

updateJSON := map[string]interface{}{
Expand Down Expand Up @@ -439,6 +563,67 @@ func TestApiManyUpdateWithIpCheckHeaders(t *testing.T) {
Config.API.UseHeader = false
}

func TestApiManyUpdateWithoutAuth(t *testing.T) {
validTxtData := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

updateJSON := map[string]interface{}{
"subdomain": "",
"txt": ""}

router := setupRouter(true, true)
server := httptest.NewServer(router)
defer server.Close()
e := getExpect(t, server)
// User without defined CIDR masks
newUser, err := DB.Register(cidrslice{})
if err != nil {
t.Errorf("Could not create new user, got error [%v]", err)
}

// User with defined allow from - CIDR masks, all invalid
// (httpexpect doesn't provide a way to mock remote ip)
newUserWithCIDR, err := DB.Register(cidrslice{"192.168.1.1/32", "invalid"})
if err != nil {
t.Errorf("Could not create new user with CIDR, got error [%v]", err)
}

// Another user with valid CIDR mask to match the httpexpect default
newUserWithValidCIDR, err := DB.Register(cidrslice{"10.1.2.3/32", "invalid"})
if err != nil {
t.Errorf("Could not create new user with a valid CIDR, got error [%v]", err)
}

for _, test := range []struct {
user string
pass string
subdomain string
txt interface{}
status int
}{
{"non-uuid-user", "tooshortpass", "non-uuid-subdomain", validTxtData, 400},
{"a097455b-52cc-4569-90c8-7a4b97c6eba8", "tooshortpass", "bb97455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 200},
{"a097455b-52cc-4569-90c8-7a4b97c6eba8", "LongEnoughPassButNoUserExists___________", "bb97455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 200},
{newUser.Username.String(), newUser.Password, "a097455b-52cc-4569-90c8-7a4b97c6eba8", validTxtData, 200},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, "tooshortfortxt", 400},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, 1234567890, 400},
{newUser.Username.String(), newUser.Password, newUser.Subdomain, validTxtData, 200},
{newUserWithCIDR.Username.String(), newUserWithCIDR.Password, newUserWithCIDR.Subdomain, validTxtData, 200},
{newUserWithValidCIDR.Username.String(), newUserWithValidCIDR.Password, newUserWithValidCIDR.Subdomain, validTxtData, 200},
{newUser.Username.String(), "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", newUser.Subdomain, validTxtData, 200},
} {
updateJSON = map[string]interface{}{
"subdomain": test.subdomain,
"txt": test.txt}
e.POST("/update").
WithJSON(updateJSON).
WithHeader("X-Api-User", test.user).
WithHeader("X-Api-Key", test.pass).
WithHeader("X-Forwarded-For", "10.1.2.3").
Expect().
Status(test.status)
}
}

func TestApiHealthCheck(t *testing.T) {
router := setupRouter(false, false)
server := httptest.NewServer(router)
Expand Down
81 changes: 47 additions & 34 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"

Expand All @@ -19,31 +18,42 @@ const ACMETxtKey key = 0
// Auth middleware for update request
func Auth(update httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
postData := ACMETxt{}
userOK := false
user, err := getUserFromRequest(r)
if err == nil {
if updateAllowedFromIP(r, user) {
dec := json.NewDecoder(r.Body)
err = dec.Decode(&postData)
if err != nil {
log.WithFields(log.Fields{"error": "json_error", "string": err.Error()}).Error("Decode error")
}
if user.Subdomain == postData.Subdomain {
userOK = true
userSupplied := false
user := ACMETxt{}
postData, err := decodePostData(r)
if err != nil {
log.WithFields(log.Fields{"error": "json_error", "string": err.Error()}).Error("Decode error")
} else {
userSupplied = getCredsFromRequest(r, &postData)
}
if !validSubdomain(postData.Subdomain) {
log.WithFields(log.Fields{"error": "invalid_subdomain"}).Error("Invalid subdomain UUID")
} else {
user, err = DB.GetBySubdomain(postData.Subdomain)
if err != nil {
log.WithFields(log.Fields{"error": "subdomain_not_found", "string": err.Error()}).Error("Subdomain is not registered")
} else {
if updateAllowedFromIP(r, user) {
if correctPassword(postData.Password, user.Password) {
if userSupplied {
userOK = postData.Username == user.Username
} else {
userOK = true
}
} else {
log.WithFields(log.Fields{"error": "invalid_password"}).Error("Password was not correct")
}
} else {
log.WithFields(log.Fields{"error": "subdomain_mismatch", "name": postData.Subdomain, "expected": user.Subdomain}).Error("Subdomain mismatch")
log.WithFields(log.Fields{"error": "ip_unauthorized"}).Error("Update not allowed from IP")
}
} else {
log.WithFields(log.Fields{"error": "ip_unauthorized"}).Error("Update not allowed from IP")
}
} else {
log.WithFields(log.Fields{"error": err.Error()}).Error("Error while trying to get user")
}
if userOK {
// Set user info to the decoded ACMETxt object
postData.Username = user.Username
postData.Password = user.Password
postData.Subdomain = user.Subdomain
// Set the ACMETxt struct to context to pull in from update function
ctx := context.WithValue(r.Context(), ACMETxtKey, postData)
update(w, r.WithContext(ctx), p)
Expand All @@ -55,28 +65,31 @@ func Auth(update httprouter.Handle) httprouter.Handle {
}
}

func getUserFromRequest(r *http.Request) (ACMETxt, error) {
uname := r.Header.Get("X-Api-User")
passwd := r.Header.Get("X-Api-Key")
username, err := getValidUsername(uname)
func decodePostData(r *http.Request) (ACMETxt, error) {
postData := ACMETxt{}
dec := json.NewDecoder(r.Body)
err := dec.Decode(&postData)
if err != nil {
return ACMETxt{}, fmt.Errorf("Invalid username: %s: %s", uname, err.Error())
return ACMETxt{}, err
}
if validKey(passwd) {
dbuser, err := DB.GetByUsername(username)
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Error("Error while trying to get user")
// To protect against timed side channel (never gonna give you up)
correctPassword(passwd, "$2a$10$8JEFVNYYhLoBysjAxe2yBuXrkDojBQBkVpXEQgyQyjn43SvJ4vL36")
return postData, nil
}

return ACMETxt{}, fmt.Errorf("Invalid username: %s", uname)
}
if correctPassword(passwd, dbuser.Password) {
return dbuser, nil
func getCredsFromRequest(r *http.Request, postData *ACMETxt) bool {
if !validKey(postData.Password) {
key := r.Header.Get("X-Api-Key")
if validKey(key) {
postData.Password = key
}
return ACMETxt{}, fmt.Errorf("Invalid password for user %s", uname)
}
return ACMETxt{}, fmt.Errorf("Invalid key for user %s", uname)

user := r.Header.Get("X-Api-User")
uname, err := getValidUsername(user)
if err != nil {
return false
}
postData.Username = uname
return true
}

func updateAllowedFromIP(r *http.Request, user ACMETxt) bool {
Expand Down
Loading