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