Fix 2.4.2 upgrade notes formatting refs #19330
[arvados.git] / lib / controller / localdb / collection.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package localdb
6
7 import (
8         "context"
9         "fmt"
10         "net/http"
11         "os"
12         "sort"
13         "strings"
14         "time"
15
16         "git.arvados.org/arvados.git/sdk/go/arvados"
17         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
18         "git.arvados.org/arvados.git/sdk/go/auth"
19         "git.arvados.org/arvados.git/sdk/go/httpserver"
20 )
21
22 // CollectionGet defers to railsProxy for everything except blob
23 // signatures.
24 func (conn *Conn) CollectionGet(ctx context.Context, opts arvados.GetOptions) (arvados.Collection, error) {
25         if len(opts.Select) > 0 {
26                 // We need to know IsTrashed and TrashAt to implement
27                 // signing properly, even if the caller doesn't want
28                 // them.
29                 opts.Select = append([]string{"is_trashed", "trash_at"}, opts.Select...)
30         }
31         resp, err := conn.railsProxy.CollectionGet(ctx, opts)
32         if err != nil {
33                 return resp, err
34         }
35         conn.signCollection(ctx, &resp)
36         return resp, nil
37 }
38
39 // CollectionList defers to railsProxy for everything except blob
40 // signatures.
41 func (conn *Conn) CollectionList(ctx context.Context, opts arvados.ListOptions) (arvados.CollectionList, error) {
42         if len(opts.Select) > 0 {
43                 // We need to know IsTrashed and TrashAt to implement
44                 // signing properly, even if the caller doesn't want
45                 // them.
46                 opts.Select = append([]string{"is_trashed", "trash_at"}, opts.Select...)
47         }
48         resp, err := conn.railsProxy.CollectionList(ctx, opts)
49         if err != nil {
50                 return resp, err
51         }
52         for i := range resp.Items {
53                 conn.signCollection(ctx, &resp.Items[i])
54         }
55         return resp, nil
56 }
57
58 // CollectionCreate defers to railsProxy for everything except blob
59 // signatures and vocabulary checking.
60 func (conn *Conn) CollectionCreate(ctx context.Context, opts arvados.CreateOptions) (arvados.Collection, error) {
61         err := conn.checkProperties(ctx, opts.Attrs["properties"])
62         if err != nil {
63                 return arvados.Collection{}, err
64         }
65         if len(opts.Select) > 0 {
66                 // We need to know IsTrashed and TrashAt to implement
67                 // signing properly, even if the caller doesn't want
68                 // them.
69                 opts.Select = append([]string{"is_trashed", "trash_at"}, opts.Select...)
70         }
71         if opts.Attrs, err = conn.applyReplaceFilesOption(ctx, "", opts.Attrs, opts.ReplaceFiles); err != nil {
72                 return arvados.Collection{}, err
73         }
74         resp, err := conn.railsProxy.CollectionCreate(ctx, opts)
75         if err != nil {
76                 return resp, err
77         }
78         conn.signCollection(ctx, &resp)
79         return resp, nil
80 }
81
82 // CollectionUpdate defers to railsProxy for everything except blob
83 // signatures and vocabulary checking.
84 func (conn *Conn) CollectionUpdate(ctx context.Context, opts arvados.UpdateOptions) (arvados.Collection, error) {
85         err := conn.checkProperties(ctx, opts.Attrs["properties"])
86         if err != nil {
87                 return arvados.Collection{}, err
88         }
89         if len(opts.Select) > 0 {
90                 // We need to know IsTrashed and TrashAt to implement
91                 // signing properly, even if the caller doesn't want
92                 // them.
93                 opts.Select = append([]string{"is_trashed", "trash_at"}, opts.Select...)
94         }
95         if opts.Attrs, err = conn.applyReplaceFilesOption(ctx, opts.UUID, opts.Attrs, opts.ReplaceFiles); err != nil {
96                 return arvados.Collection{}, err
97         }
98         resp, err := conn.railsProxy.CollectionUpdate(ctx, opts)
99         if err != nil {
100                 return resp, err
101         }
102         conn.signCollection(ctx, &resp)
103         return resp, nil
104 }
105
106 func (conn *Conn) signCollection(ctx context.Context, coll *arvados.Collection) {
107         if coll.IsTrashed || coll.ManifestText == "" || !conn.cluster.Collections.BlobSigning {
108                 return
109         }
110         var token string
111         if creds, ok := auth.FromContext(ctx); ok && len(creds.Tokens) > 0 {
112                 token = creds.Tokens[0]
113         }
114         if token == "" {
115                 return
116         }
117         ttl := conn.cluster.Collections.BlobSigningTTL.Duration()
118         exp := time.Now().Add(ttl)
119         if coll.TrashAt != nil && !coll.TrashAt.IsZero() && coll.TrashAt.Before(exp) {
120                 exp = *coll.TrashAt
121         }
122         coll.ManifestText = arvados.SignManifest(coll.ManifestText, token, exp, ttl, []byte(conn.cluster.Collections.BlobSigningKey))
123 }
124
125 // If replaceFiles is non-empty, populate attrs["manifest_text"] by
126 // starting with the content of fromUUID (or an empty collection if
127 // fromUUID is empty) and applying the specified file/directory
128 // replacements.
129 //
130 // Return value is the (possibly modified) attrs map.
131 func (conn *Conn) applyReplaceFilesOption(ctx context.Context, fromUUID string, attrs map[string]interface{}, replaceFiles map[string]string) (map[string]interface{}, error) {
132         if len(replaceFiles) == 0 {
133                 return attrs, nil
134         } else if mtxt, ok := attrs["manifest_text"].(string); ok && len(mtxt) > 0 {
135                 return nil, httpserver.Errorf(http.StatusBadRequest, "ambiguous request: both 'replace_files' and attrs['manifest_text'] values provided")
136         }
137
138         // Load the current collection (if any) and set up an
139         // in-memory filesystem.
140         var dst arvados.Collection
141         if _, replacingRoot := replaceFiles["/"]; !replacingRoot && fromUUID != "" {
142                 src, err := conn.CollectionGet(ctx, arvados.GetOptions{UUID: fromUUID})
143                 if err != nil {
144                         return nil, err
145                 }
146                 dst = src
147         }
148         dstfs, err := dst.FileSystem(&arvados.StubClient{}, &arvados.StubClient{})
149         if err != nil {
150                 return nil, err
151         }
152
153         // Sort replacements by source collection to avoid redundant
154         // reloads when a source collection is used more than
155         // once. Note empty sources (which mean "delete target path")
156         // sort first.
157         dstTodo := make([]string, 0, len(replaceFiles))
158         {
159                 srcid := make(map[string]string, len(replaceFiles))
160                 for dst, src := range replaceFiles {
161                         dstTodo = append(dstTodo, dst)
162                         if i := strings.IndexRune(src, '/'); i > 0 {
163                                 srcid[dst] = src[:i]
164                         }
165                 }
166                 sort.Slice(dstTodo, func(i, j int) bool {
167                         return srcid[dstTodo[i]] < srcid[dstTodo[j]]
168                 })
169         }
170
171         // Reject attempt to replace a node as well as its descendant
172         // (e.g., a/ and a/b/), which is unsupported, except where the
173         // source for a/ is empty (i.e., delete).
174         for _, dst := range dstTodo {
175                 if dst != "/" && (strings.HasSuffix(dst, "/") ||
176                         strings.HasSuffix(dst, "/.") ||
177                         strings.HasSuffix(dst, "/..") ||
178                         strings.Contains(dst, "//") ||
179                         strings.Contains(dst, "/./") ||
180                         strings.Contains(dst, "/../") ||
181                         !strings.HasPrefix(dst, "/")) {
182                         return nil, httpserver.Errorf(http.StatusBadRequest, "invalid replace_files target: %q", dst)
183                 }
184                 for i := 0; i < len(dst)-1; i++ {
185                         if dst[i] != '/' {
186                                 continue
187                         }
188                         outerdst := dst[:i]
189                         if outerdst == "" {
190                                 outerdst = "/"
191                         }
192                         if outersrc := replaceFiles[outerdst]; outersrc != "" {
193                                 return nil, httpserver.Errorf(http.StatusBadRequest, "replace_files: cannot operate on target %q inside non-empty target %q", dst, outerdst)
194                         }
195                 }
196         }
197
198         var srcidloaded string
199         var srcfs arvados.FileSystem
200         // Apply the requested replacements.
201         for _, dst := range dstTodo {
202                 src := replaceFiles[dst]
203                 if src == "" {
204                         if dst == "/" {
205                                 // In this case we started with a
206                                 // blank manifest, so there can't be
207                                 // anything to delete.
208                                 continue
209                         }
210                         err := dstfs.RemoveAll(dst)
211                         if err != nil {
212                                 return nil, fmt.Errorf("RemoveAll(%s): %w", dst, err)
213                         }
214                         continue
215                 }
216                 srcspec := strings.SplitN(src, "/", 2)
217                 srcid, srcpath := srcspec[0], "/"
218                 if !arvadosclient.PDHMatch(srcid) {
219                         return nil, httpserver.Errorf(http.StatusBadRequest, "invalid source %q for replace_files[%q]: must be \"\" or \"PDH\" or \"PDH/path\"", src, dst)
220                 }
221                 if len(srcspec) == 2 && srcspec[1] != "" {
222                         srcpath = srcspec[1]
223                 }
224                 if srcidloaded != srcid {
225                         srcfs = nil
226                         srccoll, err := conn.CollectionGet(ctx, arvados.GetOptions{UUID: srcid})
227                         if err != nil {
228                                 return nil, err
229                         }
230                         // We use StubClient here because we don't
231                         // want srcfs to read/write any file data or
232                         // sync collection state to/from the database.
233                         srcfs, err = srccoll.FileSystem(&arvados.StubClient{}, &arvados.StubClient{})
234                         if err != nil {
235                                 return nil, err
236                         }
237                         srcidloaded = srcid
238                 }
239                 snap, err := arvados.Snapshot(srcfs, srcpath)
240                 if err != nil {
241                         return nil, httpserver.Errorf(http.StatusBadRequest, "error getting snapshot of %q from %q: %w", srcpath, srcid, err)
242                 }
243                 // Create intermediate dirs, in case dst is
244                 // "newdir1/newdir2/dst".
245                 for i := 1; i < len(dst)-1; i++ {
246                         if dst[i] == '/' {
247                                 err = dstfs.Mkdir(dst[:i], 0777)
248                                 if err != nil && !os.IsExist(err) {
249                                         return nil, httpserver.Errorf(http.StatusBadRequest, "error creating parent dirs for %q: %w", dst, err)
250                                 }
251                         }
252                 }
253                 err = arvados.Splice(dstfs, dst, snap)
254                 if err != nil {
255                         return nil, fmt.Errorf("error splicing snapshot onto path %q: %w", dst, err)
256                 }
257         }
258         mtxt, err := dstfs.MarshalManifest(".")
259         if err != nil {
260                 return nil, err
261         }
262         if attrs == nil {
263                 attrs = make(map[string]interface{}, 1)
264         }
265         attrs["manifest_text"] = mtxt
266         return attrs, nil
267 }