Filter out some basic errors in ParseHeader

Added VerifyHeader to reduce repeated code (that's everywhere)
Fixed ParsedHeader values not being exported.
This commit is contained in:
Caleb Gardner
2024-06-07 11:10:46 -05:00
parent 2040631737
commit 99c881b51e
3 changed files with 77 additions and 36 deletions
+12 -13
View File
@@ -3,6 +3,7 @@ package darkstorm
import (
"encoding/json"
"errors"
"log"
"net/http"
)
@@ -31,18 +32,14 @@ func (c CrashReport) GetID() string {
}
func (b *Backend) reportCrash(w http.ResponseWriter, r *http.Request) {
var ap App
hdr, err := b.ParseHeader(r)
if hdr.k != nil {
ap = b.GetApp(hdr.k)
hdr, err := b.VerifyHeader(w, r, "crash", false)
if hdr == nil {
if err == nil {
log.Println("request key parsing error:", err)
}
if ap == nil || hdr.k.Perm["crash"] || errors.Is(err, ErrApiKeyUnauthorized) {
ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application not authorized")
return
} else if err != nil {
ReturnError(w, http.StatusInternalServerError, "internal", "Server error")
return
}
ap := b.GetApp(hdr.Key)
defer r.Body.Close()
var crash IndividualCrash
err = json.NewDecoder(r.Body).Decode(&crash)
@@ -52,12 +49,14 @@ func (b *Backend) reportCrash(w http.ResponseWriter, r *http.Request) {
}
tab := ap.CrashTable()
if tab == nil {
log.Printf("key %v has crash permission, but app does not have a crash table", hdr.Key.AppID)
ReturnError(w, http.StatusInternalServerError, "misconfigured", "Server misconfigured")
return
}
if !tab.IsArchived(crash) {
err = tab.InsertCrash(crash)
if err != nil {
log.Println("crash insertion error:", err)
ReturnError(w, http.StatusInternalServerError, "internal", "Server error")
return
}
@@ -67,7 +66,7 @@ func (b *Backend) reportCrash(w http.ResponseWriter, r *http.Request) {
func (b *Backend) deleteCrash(w http.ResponseWriter, r *http.Request) {
hdr, err := b.ParseHeader(r)
if hdr.k == nil || hdr.k.Perm["management"] || errors.Is(err, ErrApiKeyUnauthorized) {
if hdr.Key == nil || hdr.Key.Perm["management"] || errors.Is(err, ErrApiKeyUnauthorized) {
ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application not authorized")
return
} else if err != nil {
@@ -79,7 +78,7 @@ func (b *Backend) deleteCrash(w http.ResponseWriter, r *http.Request) {
func (b *Backend) managementDeleteCrash(w http.ResponseWriter, r *http.Request) {
hdr, err := b.ParseHeader(r)
if hdr.k == nil || hdr.k.Perm["management"] || errors.Is(err, ErrApiKeyUnauthorized) {
if hdr.Key == nil || hdr.Key.Perm["management"] || errors.Is(err, ErrApiKeyUnauthorized) {
ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application not authorized")
return
} else if err != nil {
@@ -93,7 +92,7 @@ func (b *Backend) actualCrashDelete(w http.ResponseWriter, ap App, crashID strin
func (b *Backend) archiveCrash(w http.ResponseWriter, r *http.Request) {
hdr, err := b.ParseHeader(r)
if hdr.k == nil || hdr.k.Perm["management"] {
if hdr.Key == nil || hdr.Key.Perm["management"] {
w.WriteHeader(http.StatusUnauthorized)
return
}
@@ -106,7 +105,7 @@ func (b *Backend) archiveCrash(w http.ResponseWriter, r *http.Request) {
func (b *Backend) managementArchiveCrash(w http.ResponseWriter, r *http.Request) {
hdr, err := b.ParseHeader(r)
if hdr.k == nil || hdr.k.Perm["management"] {
if hdr.Key == nil || hdr.Key.Perm["management"] {
w.WriteHeader(http.StatusUnauthorized)
return
}
+57 -15
View File
@@ -15,31 +15,33 @@ var (
)
type ParsedHeader struct {
u *ReqUser
k *ApiKey
User *ReqUser
Key *ApiKey
}
// Parses the X-API-Key and Authorization headers. If the API Key provided but invalid (either due to expiring or isn't found),
// ErrApiKeyUnauthorized is part of the returned error (check with errors.Is).
// Parses the X-API-Key and Authorization headers. If the API Key provided but invalid (either due to expiring or isn't found), ErrApiKeyUnauthorized is returned.
// If the Authorization header is present but invalid, ErrTokenUnauthorized is part of the returned error (check with errors.Is).
func (b *Backend) ParseHeader(r *http.Request) (ParsedHeader, error) {
out := ParsedHeader{}
// NOTE: An invalid apiKey will cause a nil return, but a invalid token will not. Token parsing is only
func (b *Backend) ParseHeader(r *http.Request) (*ParsedHeader, error) {
out := &ParsedHeader{}
key := r.Header.Get("X-API-Key")
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if key != "" {
apiKey, err := b.keyTable.Get(key)
if err != nil {
return out, errors.Join(ErrApiKeyUnauthorized, err)
if err == ErrNotFound {
return nil, ErrApiKeyUnauthorized
} else if err != nil {
return nil, err
}
if apiKey.Death > 0 && time.Unix(apiKey.Death, 0).Before(time.Now()) {
return out, ErrApiKeyUnauthorized
return nil, ErrApiKeyUnauthorized
}
out.k = &apiKey
out.Key = &apiKey
}
if token != "" && b.userTable != nil {
t, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
return b.jwtPub, nil
}, jwt.WithIssuer("darkstorm.tech"), jwt.WithExpirationRequired())
}, jwt.WithIssuer("darkstorm.tech"), jwt.WithExpirationRequired(), jwt.WithValidMethods([]string{"EdDSA"}))
if err != nil {
return out, errors.Join(ErrTokenUnauthorized, err)
}
@@ -48,21 +50,61 @@ func (b *Backend) ParseHeader(r *http.Request) (ParsedHeader, error) {
return out, ErrTokenUnauthorized
}
sub, err := t.Claims.GetSubject()
if err != nil {
if err == jwt.ErrInvalidKey {
return out, ErrTokenUnauthorized
} else if err != nil {
return out, errors.Join(ErrTokenUnauthorized, err)
}
usr, err := b.userTable.Get(sub)
if err != nil {
if err == jwt.ErrInvalidKey {
return out, ErrTokenUnauthorized
} else if err != nil {
return out, errors.Join(ErrTokenUnauthorized, err)
}
iss, err := t.Claims.GetIssuedAt()
if err != nil {
if err == jwt.ErrInvalidKey {
return out, ErrTokenUnauthorized
} else if err != nil {
return out, errors.Join(ErrTokenUnauthorized, err)
}
if usr.PasswordChange > 0 && iss.Time.Before(time.Unix(usr.PasswordChange, 0)) {
return out, ErrTokenUnauthorized
}
out.u = usr.toReqUser()
out.User = usr.toReqUser()
}
return out, nil
}
// Similiar to ParseHeader, but with key checking and automatic error returns. Guarentess Backend.GetApp is non-nil
// Checks that the key is a management key (not management permission and if allowManagement is true) or that it has the necessary permission.
// If the check if failed, ReturnError will be called and the returned *ParsedHeader will be nil.
// If token is present but invalid, no error will be returned just ParsedHeader.User will be nil.
// The error return will only be populated on "internal" errors and should *probably* be logged.
func (b *Backend) VerifyHeader(w http.ResponseWriter, r *http.Request, keyPerm string, allowManagementKey bool) (*ParsedHeader, error) {
hdr, err := b.ParseHeader(r)
if hdr == nil || hdr.Key == nil {
if err != ErrApiKeyUnauthorized {
ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application not authorized")
return nil, nil
}
ReturnError(w, http.StatusInternalServerError, "internal", "Server error")
return nil, err
}
if err != nil && !errors.Is(err, ErrTokenUnauthorized) {
ReturnError(w, http.StatusInternalServerError, "internal", "Server error")
return nil, err
}
if hdr.Key.AppID == b.managementKeyID {
if allowManagementKey {
return hdr, nil
} else {
ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application not authorized")
return nil, nil
}
}
if _, ok := b.apps[hdr.Key.AppID]; !ok {
ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application not authorized")
return nil, errors.New("server misconfigured, appID present in DB, but App not added to backend")
}
return hdr, nil
}
+7 -7
View File
@@ -5,6 +5,7 @@ import (
"encoding/base64"
"encoding/json"
"errors"
"log"
"net/http"
"time"
@@ -114,12 +115,11 @@ type createUserReturn struct {
}
func (b *Backend) CreateUser(w http.ResponseWriter, r *http.Request) {
hdr, err := b.ParseHeader(r)
if hdr.k == nil || !hdr.k.Perm["user"] || errors.Is(err, ErrApiKeyUnauthorized) {
ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application not authorized")
return
} else if err != nil {
ReturnError(w, http.StatusInternalServerError, "internal", "Server error")
hdr, err := b.VerifyHeader(w, r, "user", false)
if hdr == nil {
if err == nil {
log.Println("request key parsing error:", err)
}
return
}
defer r.Body.Close()
@@ -186,7 +186,7 @@ type loginReturn struct {
func (b *Backend) Login(w http.ResponseWriter, r *http.Request) {
hdr, err := b.ParseHeader(r)
if hdr.k == nil || !hdr.k.Perm["user"] || errors.Is(err, ErrApiKeyUnauthorized) {
if hdr.Key == nil || !hdr.Key.Perm["user"] || errors.Is(err, ErrApiKeyUnauthorized) {
ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application not authorized")
return
} else if err != nil {