Merge branch '21642-io-panel-collection-tab-bug' into main. Closes #21642
[arvados.git] / sdk / go / arvados / blob_signature.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 arvados
10
11 import (
12         "bytes"
13         "crypto/hmac"
14         "crypto/sha1"
15         "errors"
16         "fmt"
17         "regexp"
18         "strconv"
19         "strings"
20         "time"
21 )
22
23 var (
24         // ErrSignatureExpired - a signature was rejected because the
25         // expiry time has passed.
26         ErrSignatureExpired = errors.New("Signature expired")
27         // ErrSignatureInvalid - a signature was rejected because it
28         // was badly formatted or did not match the given secret key.
29         ErrSignatureInvalid = errors.New("Invalid signature")
30         // ErrSignatureMissing - the given locator does not have a
31         // signature hint.
32         ErrSignatureMissing = errors.New("Missing signature")
33 )
34
35 // makePermSignature generates a SHA-1 HMAC digest for the given blob,
36 // token, expiry, and site secret.
37 func makePermSignature(blobHash []byte, apiToken, expiry, blobSignatureTTL string, permissionSecret []byte) string {
38         hmac := hmac.New(sha1.New, permissionSecret)
39         hmac.Write(blobHash)
40         hmac.Write([]byte("@"))
41         hmac.Write([]byte(apiToken))
42         hmac.Write([]byte("@"))
43         hmac.Write([]byte(expiry))
44         hmac.Write([]byte("@"))
45         hmac.Write([]byte(blobSignatureTTL))
46         digest := hmac.Sum(nil)
47         return fmt.Sprintf("%x", digest)
48 }
49
50 var (
51         mBlkRe      = regexp.MustCompile(`^[0-9a-f]{32}.*`)
52         mPermHintRe = regexp.MustCompile(`\+A[^+]*`)
53 )
54
55 // SignManifest signs all locators in the given manifest, discarding
56 // any existing signatures.
57 func SignManifest(manifest string, apiToken string, expiry time.Time, ttl time.Duration, permissionSecret []byte) string {
58         return regexp.MustCompile(`\S+`).ReplaceAllStringFunc(manifest, func(tok string) string {
59                 if mBlkRe.MatchString(tok) {
60                         return SignLocator(mPermHintRe.ReplaceAllString(tok, ""), apiToken, expiry, ttl, permissionSecret)
61                 }
62                 return tok
63         })
64 }
65
66 // SignLocator returns blobLocator with a permission signature
67 // added. If either permissionSecret or apiToken is empty, blobLocator
68 // is returned untouched.
69 //
70 // This function is intended to be used by system components and admin
71 // utilities: userland programs do not know the permissionSecret.
72 func SignLocator(blobLocator, apiToken string, expiry time.Time, blobSignatureTTL time.Duration, permissionSecret []byte) string {
73         if len(permissionSecret) == 0 || apiToken == "" {
74                 return blobLocator
75         }
76         // Strip off all hints: only the hash is used to sign.
77         blobHash := []byte(blobLocator)
78         if hints := bytes.IndexRune(blobHash, '+'); hints > 0 {
79                 blobHash = blobHash[:hints]
80         }
81         timestampHex := fmt.Sprintf("%08x", expiry.Unix())
82         blobSignatureTTLHex := strconv.FormatInt(int64(blobSignatureTTL.Seconds()), 16)
83         return blobLocator +
84                 "+A" + makePermSignature(blobHash, apiToken, timestampHex, blobSignatureTTLHex, permissionSecret) +
85                 "@" + timestampHex
86 }
87
88 var SignedLocatorRe = regexp.MustCompile(
89         //1                 2          34                         5   6                  7                 89
90         `^([[:xdigit:]]{32})(\+[0-9]+)?((\+[B-Z][A-Za-z0-9@_-]*)*)(\+A([[:xdigit:]]{40})@([[:xdigit:]]{8}))((\+[B-Z][A-Za-z0-9@_-]*)*)$`)
91
92 // VerifySignature returns nil if the signature on the signedLocator
93 // can be verified using the given apiToken. Otherwise it returns
94 // ErrSignatureExpired (if the signature's expiry time has passed,
95 // which is something the client could have figured out
96 // independently), ErrSignatureMissing (if there is no signature hint
97 // at all), or ErrSignatureInvalid (if the signature is present but
98 // badly formatted or incorrect).
99 //
100 // This function is intended to be used by system components and admin
101 // utilities: userland programs do not know the permissionSecret.
102 func VerifySignature(signedLocator, apiToken string, blobSignatureTTL time.Duration, permissionSecret []byte) error {
103         matches := SignedLocatorRe.FindStringSubmatch(signedLocator)
104         if matches == nil {
105                 return ErrSignatureMissing
106         }
107         blobHash := []byte(matches[1])
108         signatureHex := matches[6]
109         expiryHex := matches[7]
110         if expiryTime, err := parseHexTimestamp(expiryHex); err != nil {
111                 return ErrSignatureInvalid
112         } else if expiryTime.Before(time.Now()) {
113                 return ErrSignatureExpired
114         }
115         blobSignatureTTLHex := strconv.FormatInt(int64(blobSignatureTTL.Seconds()), 16)
116         if signatureHex != makePermSignature(blobHash, apiToken, expiryHex, blobSignatureTTLHex, permissionSecret) {
117                 return ErrSignatureInvalid
118         }
119         return nil
120 }
121
122 func parseHexTimestamp(timestampHex string) (ts time.Time, err error) {
123         if tsInt, e := strconv.ParseInt(timestampHex, 16, 0); e == nil {
124                 ts = time.Unix(tsInt, 0)
125         } else {
126                 err = e
127         }
128         return ts, err
129 }
130
131 var errNoSignature = errors.New("locator has no signature")
132
133 func signatureExpiryTime(signedLocator string) (time.Time, error) {
134         matches := SignedLocatorRe.FindStringSubmatch(signedLocator)
135         if matches == nil {
136                 return time.Time{}, errNoSignature
137         }
138         expiryHex := matches[7]
139         return parseHexTimestamp(expiryHex)
140 }
141
142 func stripAllHints(locator string) string {
143         if i := strings.IndexRune(locator, '+'); i > 0 {
144                 return locator[:i]
145         }
146         return locator
147 }