7167: Tidy up errors. Remove extra comment copy.
[arvados.git] / sdk / go / keepclient / perms.go
1 /*
2 Permissions management on Arvados locator hashes.
3
4 The permissions structure for Arvados is as follows (from
5 https://arvados.org/issues/2328)
6
7 A Keep locator string has the following format:
8
9     [hash]+[size]+A[signature]@[timestamp]
10
11 The "signature" string here is a cryptographic hash, expressed as a
12 string of hexadecimal digits, and timestamp is a 32-bit Unix timestamp
13 expressed as a hexadecimal number.  e.g.:
14
15     acbd18db4cc2f85cedef654fccc4a4d8+3+A257f3f5f5f0a4e4626a18fc74bd42ec34dcb228a@7fffffff
16
17 The signature represents a guarantee that this locator was generated
18 by either Keep or the API server for use with the supplied API token.
19 If a request to Keep includes a locator with a valid signature and is
20 accompanied by the proper API token, the user has permission to GET
21 that object.
22
23 The signature may be generated either by Keep (after the user writes a
24 block) or by the API server (if the user has can_read permission on
25 the specified object). Keep and API server share a secret that is used
26 to generate signatures.
27
28 To verify a permission hint, Keep generates a new hint for the
29 requested object (using the locator string, the timestamp, the
30 permission secret and the user's API token, which must appear in the
31 request headers) and compares it against the hint included in the
32 request. If the permissions do not match, or if the API token is not
33 present, Keep returns a 401 error.
34 */
35
36 package keepclient
37
38 import (
39         "crypto/hmac"
40         "crypto/sha1"
41         "errors"
42         "fmt"
43         "regexp"
44         "strconv"
45         "strings"
46         "time"
47 )
48
49 var (
50         ErrSignatureExpired   = errors.New("Signature expired")
51         ErrSignatureInvalid   = errors.New("Invalid signature")
52         ErrSignatureMalformed = errors.New("Malformed signature")
53         ErrSignatureMissing   = errors.New("Missing signature")
54 )
55
56 // makePermSignature returns a string representing the signed permission
57 // hint for the blob identified by blobHash, apiToken, expiration timestamp, and permission secret.
58 //
59 // The permissionSecret is the secret key used to generate SHA1 digests
60 // for permission hints. apiserver and Keep must use the same key.
61 func makePermSignature(blobHash string, apiToken string, expiry string, permissionSecret []byte) string {
62         hmac := hmac.New(sha1.New, permissionSecret)
63         hmac.Write([]byte(blobHash))
64         hmac.Write([]byte("@"))
65         hmac.Write([]byte(apiToken))
66         hmac.Write([]byte("@"))
67         hmac.Write([]byte(expiry))
68         digest := hmac.Sum(nil)
69         return fmt.Sprintf("%x", digest)
70 }
71
72 // SignLocator takes a blobLocator, an apiToken, an expiry time, and a permission secret
73 // and returns a signed locator string.
74 func SignLocator(blobLocator string, apiToken string, expiry time.Time, permissionSecret []byte) string {
75         // If no permission secret or API token is available,
76         // return an unsigned locator.
77         if permissionSecret == nil || apiToken == "" {
78                 return blobLocator
79         }
80         // Extract the hash from the blob locator, omitting any size hint that may be present.
81         blobHash := strings.Split(blobLocator, "+")[0]
82         // Return the signed locator string.
83         timestampHex := fmt.Sprintf("%08x", expiry.Unix())
84         return blobLocator +
85                 "+A" + makePermSignature(blobHash, apiToken, timestampHex, permissionSecret) +
86                 "@" + timestampHex
87 }
88
89 var signedLocatorRe = regexp.MustCompile(`^([[:xdigit:]]{32}).*\+A([[:xdigit:]]{40})@([[:xdigit:]]{8})`)
90
91 // VerifySignature returns nil if the signature on the signedLocator
92 // can be verified using the given apiToken. Otherwise it returns
93 // either ExpiredError (if the timestamp has expired, which is
94 // something the client could have figured out independently) or
95 // PermissionError.
96 func VerifySignature(signedLocator string, apiToken string, permissionSecret []byte) error {
97         matches := signedLocatorRe.FindStringSubmatch(signedLocator)
98         if matches == nil {
99                 // Could not find a permission signature at all
100                 return ErrSignatureMissing
101         }
102         blobHash := matches[1]
103         sigHex := matches[2]
104         expHex := matches[3]
105         if expTime, err := parseHexTimestamp(expHex); err != nil {
106                 return ErrSignatureMalformed
107         } else if expTime.Before(time.Now()) {
108                 return ErrSignatureExpired
109         }
110         if sigHex != makePermSignature(blobHash, apiToken, expHex, permissionSecret) {
111                 return ErrSignatureInvalid
112         }
113         return nil
114 }
115
116 // parseHexTimestamp parses timestamp
117 func parseHexTimestamp(timestampHex string) (ts time.Time, err error) {
118         if tsInt, e := strconv.ParseInt(timestampHex, 16, 0); e == nil {
119                 ts = time.Unix(tsInt, 0)
120         } else {
121                 err = e
122         }
123         return ts, err
124 }