Commit e6f0c1f3 authored by Jacob Vosmaer's avatar Jacob Vosmaer

Add api.Secret type

parent cfb90242
......@@ -15,18 +15,14 @@ import (
"github.com/dgrijalva/jwt-go"
)
const (
// Custom content type for API responses, to catch routing / programming mistakes
ResponseContentType = "application/vnd.gitlab-workhorse+json"
// Block size for HMAC SHA256
numSecretBytes = 64
)
// Custom content type for API responses, to catch routing / programming mistakes
const ResponseContentType = "application/vnd.gitlab-workhorse+json"
type API struct {
Client *http.Client
URL *url.URL
Version string
SecretFile string
Secret *Secret
}
func NewAPI(myURL *url.URL, version, secretFile string, roundTripper *badgateway.RoundTripper) *API {
......@@ -34,7 +30,7 @@ func NewAPI(myURL *url.URL, version, secretFile string, roundTripper *badgateway
Client: &http.Client{Transport: roundTripper},
URL: myURL,
Version: version,
SecretFile: secretFile,
Secret: &Secret{File: secretFile},
}
}
......@@ -130,18 +126,15 @@ func (api *API) newRequest(r *http.Request, body io.Reader, suffix string) (*htt
// configurations (Passenger) to solve auth request routing problems.
authReq.Header.Set("Gitlab-Workhorse", api.Version)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{Issuer: "gitlab-workhorse"})
secretBytes, err := ioutil.ReadFile(api.SecretFile)
secretBytes, err := api.Secret.Bytes()
if err != nil {
return nil, fmt.Errorf("read secretFile: %v", err)
}
if n := len(secretBytes); n != numSecretBytes {
return nil, fmt.Errorf("expected %d bytes in %s, found %d", numSecretBytes, api.SecretFile, n)
return nil, fmt.Errorf("newRequest: %v", err)
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{Issuer: "gitlab-workhorse"})
tokenString, err := token.SignedString(secretBytes)
if err != nil {
return nil, fmt.Errorf("sign JWT: %v", err)
return nil, fmt.Errorf("newRequest: sign JWT: %v", err)
}
authReq.Header.Set("Gitlab-Workhorse-Api-Request", tokenString)
......
package api
import (
"fmt"
"io/ioutil"
"sync"
)
const numSecretBytes = 64
type Secret struct {
File string
bytes []byte
sync.RWMutex
}
func (s *Secret) Bytes() ([]byte, error) {
if bytes := s.getBytes(); bytes != nil {
return bytes, nil
}
return s.setBytes()
}
func (s *Secret) getBytes() []byte {
s.RLock()
defer s.RUnlock()
return s.bytes
}
func (s *Secret) setBytes() ([]byte, error) {
bytes, err := ioutil.ReadFile(s.File)
if err != nil {
return nil, fmt.Errorf("read Secret.File: %v", err)
}
if n := len(bytes); n != numSecretBytes {
return nil, fmt.Errorf("expected %d bytes in %s, found %d", bytes, s.File, n)
}
s.Lock()
defer s.Unlock()
s.bytes = bytes
return bytes, nil
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment