segregated api machinery

This commit is contained in:
2021-03-07 16:43:51 -09:00
parent 5571401103
commit 86f304e1b8
2 changed files with 22 additions and 21 deletions

View File

@ -1,72 +0,0 @@
package server
import (
"crypto/hmac"
"crypto/sha256"
"encoding/json"
"fmt"
"time"
)
type APICommand struct {
Expires time.Time `json:"exp"`
Command string `json:"cmd"`
Scheme string `json:"sch"`
Signature []byte `json:"sig,omitempty"`
}
func ParseAPICommand(jsn []byte) (*APICommand, error) {
api := &APICommand{}
err := json.Unmarshal(jsn, api)
if err != nil {
return nil, err
}
return api, nil
}
func (ac *APICommand) JSON() ([]byte, error) {
return json.Marshal(ac)
}
func (ac *APICommand) Sign(key []byte) error {
switch ac.Scheme {
case "hmac-sha256":
j, err := ac.JSON()
if err != nil {
return fmt.Errorf("json encoding error")
}
mac := hmac.New(sha256.New, key)
mac.Write(j)
ac.Signature = mac.Sum(nil)
case "":
return fmt.Errorf("scheme may not be empty")
default:
return fmt.Errorf("unsupported scheme: %s", ac.Scheme)
}
return nil
}
func (ac *APICommand) Validate(key []byte) error {
cpy := &APICommand{
Expires: ac.Expires,
Command: ac.Command,
Scheme: ac.Scheme,
}
err := cpy.Sign(key)
if err != nil {
return err
}
if !hmac.Equal(cpy.Signature, ac.Signature) {
return fmt.Errorf("invalid signature")
}
if time.Now().After(ac.Expires) {
return fmt.Errorf("command expired")
}
return nil
}

View File

@ -3,6 +3,7 @@ package server
import (
"fmt"
"net/http"
"git.binarythought.com/cdramey/alrm/api"
)
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@ -14,7 +15,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, "no command given", http.StatusBadRequest)
return
}
cmd, err := ParseAPICommand([]byte(c))
cmd, err := api.ParseCommand([]byte(c))
if err != nil {
http.Error(w, fmt.Sprintf("error parsing command: %s", err.Error()),
http.StatusBadRequest)