378fdcdff8e8afe2bd7fb53d1e1d6a7f8923106e
[arvados.git] / sdk / go / keepclient / perms.go
1 // Generate and verify permission signatures for Keep locators.
2 //
3 // See https://dev.arvados.org/projects/arvados/wiki/Keep_locator_format
4
5 package keepclient
6
7 import (
8         "crypto/hmac"
9         "crypto/sha1"
10         "errors"
11         "fmt"
12         "regexp"
13         "strconv"
14         "strings"
15         "time"
16 )
17
18 var (
19         // ErrSignatureExpired - a signature was rejected because the
20         // expiry time has passed.
21         ErrSignatureExpired = errors.New("Signature expired")
22         // ErrSignatureInvalid - a signature was rejected because it
23         // was badly formatted or did not match the given secret key.
24         ErrSignatureInvalid = errors.New("Invalid signature")
25         // ErrSignatureMissing - the given locator does not have a
26         // signature hint.
27         ErrSignatureMissing = errors.New("Missing signature")
28 )
29
30 // makePermSignature generates a SHA-1 HMAC digest for the given blob,
31 // token, expiry, and site secret.
32 func makePermSignature(blobHash, apiToken, expiry string, blobSigningTTL time.Duration, permissionSecret []byte) string {
33         hmac := hmac.New(sha1.New, permissionSecret)
34         hmac.Write([]byte(blobHash))
35         hmac.Write([]byte("@"))
36         hmac.Write([]byte(apiToken))
37         hmac.Write([]byte("@"))
38         hmac.Write([]byte(expiry))
39         hmac.Write([]byte("@"))
40         hmac.Write([]byte(strconv.Itoa(int(blobSigningTTL.Seconds()))))
41         digest := hmac.Sum(nil)
42         return fmt.Sprintf("%x", digest)
43 }
44
45 // SignLocator returns blobLocator with a permission signature
46 // added. If either permissionSecret or apiToken is empty, blobLocator
47 // is returned untouched.
48 //
49 // This function is intended to be used by system components and admin
50 // utilities: userland programs do not know the permissionSecret.
51 func SignLocator(blobLocator, apiToken string, expiry time.Time, blobSigningTTL time.Duration, permissionSecret []byte) string {
52         if len(permissionSecret) == 0 || apiToken == "" {
53                 return blobLocator
54         }
55         // Strip off all hints: only the hash is used to sign.
56         blobHash := strings.Split(blobLocator, "+")[0]
57         timestampHex := fmt.Sprintf("%08x", expiry.Unix())
58         return blobLocator +
59                 "+A" + makePermSignature(blobHash, apiToken, timestampHex, blobSigningTTL, permissionSecret) +
60                 "@" + timestampHex
61 }
62
63 var signedLocatorRe = regexp.MustCompile(`^([[:xdigit:]]{32}).*\+A([[:xdigit:]]{40})@([[:xdigit:]]{8})`)
64
65 // VerifySignature returns nil if the signature on the signedLocator
66 // can be verified using the given apiToken. Otherwise it returns
67 // ErrSignatureExpired (if the signature's expiry time has passed,
68 // which is something the client could have figured out
69 // independently), ErrSignatureMissing (if there is no signature hint
70 // at all), or ErrSignatureInvalid (if the signature is present but
71 // badly formatted or incorrect).
72 //
73 // This function is intended to be used by system components and admin
74 // utilities: userland programs do not know the permissionSecret.
75 func VerifySignature(signedLocator, apiToken string, blobSigningTTL time.Duration, permissionSecret []byte) error {
76         matches := signedLocatorRe.FindStringSubmatch(signedLocator)
77         if matches == nil {
78                 return ErrSignatureMissing
79         }
80         blobHash := matches[1]
81         signatureHex := matches[2]
82         expiryHex := matches[3]
83         if expiryTime, err := parseHexTimestamp(expiryHex); err != nil {
84                 return ErrSignatureInvalid
85         } else if expiryTime.Before(time.Now()) {
86                 return ErrSignatureExpired
87         }
88         if signatureHex != makePermSignature(blobHash, apiToken, expiryHex, blobSigningTTL, permissionSecret) {
89                 return ErrSignatureInvalid
90         }
91         return nil
92 }
93
94 func parseHexTimestamp(timestampHex string) (ts time.Time, err error) {
95         if tsInt, e := strconv.ParseInt(timestampHex, 16, 0); e == nil {
96                 ts = time.Unix(tsInt, 0)
97         } else {
98                 err = e
99         }
100         return ts, err
101 }