-
-func (e *KeepError) Error() string {
- return e.ErrMsg
-}
-
-// makePermSignature returns a string representing the signed permission
-// hint for the blob identified by blobHash, apiToken, expiration timestamp, and permission secret.
-//
-// The permissionSecret is the secret key used to generate SHA1 digests
-// for permission hints. apiserver and Keep must use the same key.
-func makePermSignature(blobHash string, apiToken string, expiry string, permissionSecret []byte) string {
- hmac := hmac.New(sha1.New, permissionSecret)
- hmac.Write([]byte(blobHash))
- hmac.Write([]byte("@"))
- hmac.Write([]byte(apiToken))
- hmac.Write([]byte("@"))
- hmac.Write([]byte(expiry))
- digest := hmac.Sum(nil)
- return fmt.Sprintf("%x", digest)
-}
-
-// SignLocator takes a blobLocator, an apiToken, an expiry time, and a permission secret
-// and returns a signed locator string.
-func SignLocator(blobLocator string, apiToken string, expiry time.Time, permissionSecret []byte) string {
- // If no permission secret or API token is available,
- // return an unsigned locator.
- if permissionSecret == nil || apiToken == "" {
- return blobLocator
- }
- // Extract the hash from the blob locator, omitting any size hint that may be present.
- blobHash := strings.Split(blobLocator, "+")[0]
- // Return the signed locator string.
- timestampHex := fmt.Sprintf("%08x", expiry.Unix())
- return blobLocator +
- "+A" + makePermSignature(blobHash, apiToken, timestampHex, permissionSecret) +
- "@" + timestampHex
-}
-
-var signedLocatorRe = regexp.MustCompile(`^([[:xdigit:]]{32}).*\+A([[:xdigit:]]{40})@([[:xdigit:]]{8})`)
-
-// VerifySignature returns nil if the signature on the signedLocator
-// can be verified using the given apiToken. Otherwise it returns
-// either ExpiredError (if the timestamp has expired, which is
-// something the client could have figured out independently) or
-// PermissionError.
-func VerifySignature(signedLocator string, apiToken string, permissionSecret []byte) error {
- matches := signedLocatorRe.FindStringSubmatch(signedLocator)
- if matches == nil {
- // Could not find a permission signature at all
- return PermissionError
- }
- blobHash := matches[1]
- sigHex := matches[2]
- expHex := matches[3]
- if expTime, err := parseHexTimestamp(expHex); err != nil {
- return PermissionError
- } else if expTime.Before(time.Now()) {
- return ExpiredError
- }
- if sigHex != makePermSignature(blobHash, apiToken, expHex, permissionSecret) {
- return PermissionError
- }
- return nil
-}
-
-// parseHexTimestamp parses timestamp
-func parseHexTimestamp(timestampHex string) (ts time.Time, err error) {
- if tsInt, e := strconv.ParseInt(timestampHex, 16, 0); e == nil {
- ts = time.Unix(tsInt, 0)
- } else {
- err = e
- }
- return ts, err
-}