Debian Codegraph @

pkg/server/server.go

raw
1 // Copyright 2022-2024 The Archivista Contributors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package server
16
17 import (
18 "bytes"
19 "context"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "io"
24 "net/http"
25 "os"
26 "path/filepath"
27 "strconv"
28 "strings"
29
30 "entgo.io/contrib/entgql"
31 "github.com/99designs/gqlgen/graphql/handler"
32 "github.com/99designs/gqlgen/graphql/handler/transport"
33 "github.com/99designs/gqlgen/graphql/playground"
34 "github.com/edwarnicke/gitoid"
35 "github.com/gorilla/mux"
36 "github.com/in-toto/archivista"
37 _ "github.com/in-toto/archivista/docs"
38 "github.com/in-toto/archivista/ent"
39 "github.com/in-toto/archivista/pkg/api"
40 "github.com/in-toto/archivista/pkg/artifactstore"
41 "github.com/in-toto/archivista/pkg/config"
42 "github.com/in-toto/archivista/pkg/publisherstore"
43 "github.com/sirupsen/logrus"
44 httpSwagger "github.com/swaggo/http-swagger/v2"
45 )
46
47 type Server struct {
48 metadataStore Storer
49 objectStore StorerGetter
50 artifactStore artifactstore.Store
51 router *mux.Router
52 sqlClient *ent.Client
53 publisherStore []publisherstore.Publisher
54 }
55
56 type Storer interface {
57 Store(context.Context, string, []byte) error
58 }
59
60 type Getter interface {
61 Get(context.Context, string) (io.ReadCloser, error)
62 }
63
64 type StorerGetter interface {
65 Storer
66 Getter
67 }
68
69 type Option func(*Server)
70
71 func WithMetadataStore(metadataStore Storer) Option {
72 return func(s *Server) {
73 s.metadataStore = metadataStore
74 }
75 }
76
77 func WithObjectStore(objectStore StorerGetter) Option {
78 return func(s *Server) {
79 s.objectStore = objectStore
80 }
81 }
82
83 func WithEntSqlClient(sqlClient *ent.Client) Option {
84 return func(s *Server) {
85 s.sqlClient = sqlClient
86 }
87 }
88
89 func WithArtifactStore(wds artifactstore.Store) Option {
90 return func(s *Server) {
91 s.artifactStore = wds
92 }
93 }
94
95 func WithPublishers(pub []publisherstore.Publisher) Option {
96 return func(s *Server) {
97 s.publisherStore = pub
98 }
99 }
100
101 func New(cfg *config.Config, opts ...Option) (Server, error) {
102 r := mux.NewRouter()
103 s := Server{
104 router: r,
105 }
106
107 for _, opt := range opts {
108 opt(&s)
109 }
110
111 // TODO: remove from future version (v0.6.0) endpoint with version
112 r.HandleFunc("/download/{gitoid}", s.DownloadHandler)
113 r.HandleFunc("/upload", s.UploadHandler)
114 if cfg.EnableSQLStore && cfg.EnableGraphql {
115 r.Handle("/query", s.Query(s.sqlClient))
116 r.Handle("/v1/query", s.Query(s.sqlClient))
117 }
118
119 r.HandleFunc("/v1/download/{gitoid}", s.DownloadHandler)
120 r.HandleFunc("/v1/upload", s.UploadHandler)
121 if cfg.EnableSQLStore && cfg.EnableGraphql && cfg.GraphqlWebClientEnable {
122 r.Handle("/",
123 playground.Handler("Archivista", "/v1/query"),
124 )
125 }
126
127 if cfg.EnableArtifactStore {
128 r.HandleFunc("/v1/artifacts", s.AllArtifactsHandler)
129 r.HandleFunc("/v1/artifacts/{name}", s.ArtifactAllVersionsHandler)
130 r.HandleFunc("/v1/artifacts/{name}/{version}", s.ArtifactVersionHandler)
131 r.HandleFunc("/v1/download/artifact/{name}/{version}/{distribution}", s.DownloadArtifactHandler)
132 }
133
134 r.PathPrefix("/swagger/").Handler(httpSwagger.WrapHandler)
135 return s, nil
136 }
137
138 // @title Archivista API
139 // @description Archivista API
140 // @version v1
141 // @contact.name Archivista Contributors
142 // @contact.url https://github.com/in-toto/archivista/issues/new
143 // @license Apache 2
144 // @license.url https://opensource.org/licenses/Apache-2
145 // InitRoutes initializes the HTTP API routes for the server
146 func (s *Server) Router() *mux.Router {
147 return s.router
148 }
149
150 // @Summary Upload
151 // @Description stores an attestation
152 // @Produce json
153 // @Success 200 {object} api.StoreResponse
154 // @Tags attestation
155 // @Router /v1/upload [post]
156 func (s *Server) Upload(ctx context.Context, r io.Reader) (api.UploadResponse, error) {
157 payload, err := io.ReadAll(r)
158 if err != nil {
159 return api.UploadResponse{}, err
160 }
161
162 gid, err := gitoid.New(bytes.NewReader(payload), gitoid.WithContentLength(int64(len(payload))), gitoid.WithSha256())
163 if err != nil {
164 logrus.Errorf("failed to generate gitoid: %v", err)
165 return api.UploadResponse{}, err
166 }
167
168 if s.objectStore != nil {
169 if err := s.objectStore.Store(ctx, gid.String(), payload); err != nil {
170 logrus.Errorf("received error from object store: %+v", err)
171 return api.UploadResponse{}, err
172 }
173 }
174
175 if s.metadataStore != nil {
176 if err := s.metadataStore.Store(ctx, gid.String(), payload); err != nil {
177 logrus.Errorf("received error from metadata store: %+v", err)
178 return api.UploadResponse{}, err
179 }
180 }
181
182 if s.publisherStore != nil {
183 for _, publisher := range s.publisherStore {
184 // TODO: Make publish asynchrouns and use goroutine
185 if err := publisher.Publish(ctx, gid.String(), payload); err != nil {
186 logrus.Errorf("received error from publisher: %+v", err)
187 }
188 }
189 }
190
191 return api.UploadResponse{Gitoid: gid.String()}, nil
192 }
193
194 // @Summary Upload
195 // @Description stores an attestation
196 // @Produce json
197 // @Success 200 {object} api.StoreResponse
198 // @Router /upload [post]
199 // @Deprecated
200 func (s *Server) UploadHandler(w http.ResponseWriter, r *http.Request) {
201 if r.Method != http.MethodPost {
202 http.Error(w, fmt.Sprintf("%s is an unsupported method", r.Method), http.StatusBadRequest)
203 return
204 }
205
206 defer r.Body.Close()
207 resp, err := s.Upload(r.Context(), r.Body)
208 if err != nil {
209 http.Error(w, err.Error(), http.StatusInternalServerError)
210 return
211 }
212
213 encoder := json.NewEncoder(w)
214 if err := encoder.Encode(resp); err != nil {
215 logrus.Errorf("failed to copy storeresponse to response: %+v", err)
216 w.WriteHeader(http.StatusInternalServerError)
217 return
218 }
219
220 w.Header().Set("Content-Type", "application/json")
221 }
222
223 // @Summary Download
224 // @Description download an attestation
225 // @Produce json
226 // @Param gitoid path string true "gitoid"
227 // @Success 200 {object} dsse.Envelope
228 // @Failure 500 {object} string
229 // @Failure 404 {object} nil
230 // @Failure 400 {object} string
231 // @Tags attestation
232 // @Router /v1/download/{gitoid} [get]
233 func (s *Server) Download(ctx context.Context, gitoid string) (io.ReadCloser, error) {
234 if s.objectStore == nil {
235 return nil, errors.New("object store unavailable")
236 }
237
238 objReader, err := s.objectStore.Get(ctx, gitoid)
239 if err != nil {
240 logrus.Errorf("failed to get object: %+v", err)
241 }
242
243 return objReader, err
244 }
245
246 // @Summary Download
247 // @Description download an attestation
248 // @Produce json
249 // @Param gitoid path string true "gitoid"
250 // @Success 200 {object} dsse.Envelope
251 // @Failure 500 {object} string
252 // @Failure 404 {object} nil
253 // @Failure 400 {object} string
254 // @Deprecated
255 // @Router /download/{gitoid} [get]
256 func (s *Server) DownloadHandler(w http.ResponseWriter, r *http.Request) {
257 if r.Method != http.MethodGet {
258 http.Error(w, fmt.Sprintf("%s is an unsupported method", r.Method), http.StatusBadRequest)
259 return
260 }
261
262 vars := mux.Vars(r)
263 if vars == nil {
264 http.Error(w, "gitoid parameter is required", http.StatusBadRequest)
265 return
266 }
267 if len(strings.TrimSpace(vars["gitoid"])) == 0 {
268 http.Error(w, "gitoid parameter is required", http.StatusBadRequest)
269 return
270 }
271
272 attestationReader, err := s.Download(r.Context(), vars["gitoid"])
273 if err != nil {
274 http.Error(w, err.Error(), http.StatusInternalServerError)
275 return
276 }
277
278 defer attestationReader.Close()
279 if _, err := io.Copy(w, attestationReader); err != nil {
280 logrus.Errorf("failed to copy attestation to response: %+v", err)
281 w.WriteHeader(http.StatusNotFound)
282 return
283 }
284
285 w.Header().Set("Content-Type", "application/json")
286 }
287
288 // @Summary Query GraphQL
289 // @Description GraphQL query
290 // @Produce json
291 // @Success 200 {object} archivista.Resolver
292 // @Tags graphql
293 // @Router /v1/query [post]
294 func (s *Server) Query(sqlclient *ent.Client) *handler.Server {
295 srv := handler.New(archivista.NewSchema(sqlclient))
296 srv.AddTransport(transport.GET{})
297 srv.AddTransport(transport.POST{})
298 srv.Use(entgql.Transactioner{TxOpener: sqlclient})
299 return srv
300 }
301
302 // @Summary List all Artifacts
303 // @Description retrieves details about all available Artifacts
304 // @Produce json
305 // @Success 200 {object} map[string]artifactstore.Artifact
306 // @Failure 500 {object} string
307 // @Failure 400 {object} string
308 // @Tags Artifacts
309 // @Router /v1/artifacts [get]
310 func (s *Server) AllArtifactsHandler(w http.ResponseWriter, r *http.Request) {
311 if r.Method != http.MethodGet {
312 http.Error(w, fmt.Sprintf("%s is an unsupported method", r.Method), http.StatusBadRequest)
313 return
314 }
315
316 allArtifacts := s.artifactStore.Artifacts()
317 allArtifactsJson, err := json.Marshal(allArtifacts)
318 if err != nil {
319 http.Error(w, fmt.Errorf("could not marshal artifact versions: %w", err).Error(), http.StatusInternalServerError)
320 return
321 }
322
323 if _, err := io.Copy(w, bytes.NewReader(allArtifactsJson)); err != nil {
324 http.Error(w, fmt.Errorf("could not send json response: %w", err).Error(), http.StatusInternalServerError)
325 return
326 }
327
328 w.Header().Set("Content-Type", "application/json")
329 }
330
331 // @Summary List Artifact Versions
332 // @Description retrieves details about all available versions of a specified artifact
333 // @Produce json
334 // @Param name path string true "artifact name"
335 // @Success 200 {object} map[string]artifactstore.Version
336 // @Failure 500 {object} string
337 // @Failure 400 {object} string
338 // @Tags Artifacts
339 // @Router /v1/artifacts/{name} [get]
340 func (s *Server) ArtifactAllVersionsHandler(w http.ResponseWriter, r *http.Request) {
341 if r.Method != http.MethodGet {
342 http.Error(w, fmt.Sprintf("%s is an unsupported method", r.Method), http.StatusBadRequest)
343 return
344 }
345
346 vars := mux.Vars(r)
347 if vars == nil {
348 http.Error(w, "name parameter is required", http.StatusBadRequest)
349 return
350 }
351
352 artifactName := vars["name"]
353 if len(artifactName) == 0 {
354 http.Error(w, "name parameter is required", http.StatusBadRequest)
355 return
356 }
357
358 artifactVersions, ok := s.artifactStore.Versions(artifactName)
359 if !ok {
360 http.Error(w, "artifact not found", http.StatusNotFound)
361 return
362 }
363
364 artifactVersionsJson, err := json.Marshal(artifactVersions)
365 if err != nil {
366 http.Error(w, fmt.Errorf("could not marshal artifact versions: %w", err).Error(), http.StatusInternalServerError)
367 return
368 }
369
370 if _, err := io.Copy(w, bytes.NewReader(artifactVersionsJson)); err != nil {
371 http.Error(w, fmt.Errorf("could not send json response: %w", err).Error(), http.StatusInternalServerError)
372 return
373 }
374
375 w.Header().Set("Content-Type", "application/json")
376 }
377
378 // @Summary Artifact Version Details
379 // @Description retrieves details about a specified version of an artifact
380 // @Produce json
381 // @Param name path string true "artifact name"
382 // @Param version path string true "version of artifact"
383 // @Success 200 {object} artifactstore.Version
384 // @Failure 500 {objecpec} string
385 // @Failure 404 {object} nil
386 // @Failure 400 {object} string
387 // @Tags Artifacts
388 // @Router /v1/artifacts/{name}/{version} [get]
389 func (s *Server) ArtifactVersionHandler(w http.ResponseWriter, r *http.Request) {
390 if r.Method != http.MethodGet {
391 http.Error(w, fmt.Sprintf("%s is an unsupported method", r.Method), http.StatusBadRequest)
392 return
393 }
394
395 vars := mux.Vars(r)
396 if vars == nil {
397 http.Error(w, "name and version parameters are required", http.StatusBadRequest)
398 return
399 }
400
401 artifactString := vars["name"]
402 if len(artifactString) == 0 {
403 http.Error(w, "name parameter is required", http.StatusBadRequest)
404 return
405 }
406
407 versionString := vars["version"]
408 if len(versionString) == 0 {
409 http.Error(w, "version parameter is required", http.StatusBadRequest)
410 return
411 }
412
413 version, ok := s.artifactStore.Version(artifactString, versionString)
414 if !ok {
415 http.Error(w, "version not found", http.StatusNotFound)
416 return
417 }
418
419 versionJson, err := json.Marshal(version)
420 if err != nil {
421 http.Error(w, fmt.Errorf("could not marshal artifact distros: %w", err).Error(), http.StatusInternalServerError)
422 return
423 }
424
425 if _, err := io.Copy(w, bytes.NewReader(versionJson)); err != nil {
426 http.Error(w, fmt.Errorf("could not send json response: %w", err).Error(), http.StatusInternalServerError)
427 return
428 }
429
430 w.Header().Set("Content-Type", "application/json")
431 }
432
433 // @Summary Download Artifact
434 // @Description downloads a specified distribution of an artifact
435 // @Produce octet-stream
436 // @Param name path string true "name of artifact"
437 // @Param version path string true "version of artifact to download"
438 // @Param distribution path string true "distribution of artifact to download"
439 // @Success 200 {file} octet-stream
440 // @Failure 500 {object} string
441 // @Failure 404 {object} nil
442 // @Failure 400 {object} string
443 // @Tags Artifacts
444 // @Router /v1/download/artifact/{name}/{version}/{distribution} [get]
445 func (s *Server) DownloadArtifactHandler(w http.ResponseWriter, r *http.Request) {
446 if r.Method != http.MethodGet {
447 http.Error(w, fmt.Sprintf("%s is an unsupported method", r.Method), http.StatusBadRequest)
448 return
449 }
450
451 vars := mux.Vars(r)
452 if vars == nil {
453 http.Error(w, "version and distribution parameter is required", http.StatusBadRequest)
454 return
455 }
456
457 artifactString := vars["name"]
458 if len(artifactString) == 0 {
459 http.Error(w, "name parameter is required", http.StatusBadRequest)
460 return
461 }
462
463 versionString := vars["version"]
464 if len(versionString) == 0 {
465 http.Error(w, "version parameter is required", http.StatusBadRequest)
466 return
467 }
468
469 distroString := vars["distribution"]
470 if len(distroString) == 0 {
471 http.Error(w, "distribution parameter is required", http.StatusBadRequest)
472 return
473 }
474
475 distro, ok := s.artifactStore.Distribution(artifactString, versionString, distroString)
476 if !ok {
477 http.Error(w, "distribution of artifact not found", http.StatusNotFound)
478 return
479 }
480
481 file, err := os.Open(distro.FileLocation)
482 if err != nil {
483 http.Error(w, "could not read distribution file", http.StatusBadRequest)
484 return
485 }
486
487 defer func() {
488 if err := file.Close(); err != nil {
489 logrus.Errorf("failed to close artifact distribution file %s: %+v", distro.FileLocation, err)
490 }
491 }()
492
493 fileInfo, err := file.Stat()
494 if err != nil {
495 http.Error(w, "could not stat distribution file", http.StatusBadRequest)
496 return
497 }
498
499 fileName := filepath.Base(distro.FileLocation)
500 w.Header().Set("Content-Type", "application/octet-stream")
501 w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%v", fileName))
502 w.Header().Set("Content-Length", strconv.FormatInt(fileInfo.Size(), 10))
503 if _, err := io.Copy(w, file); err != nil {
504 http.Error(w, fmt.Errorf("could not send artifact distribution: %w", err).Error(), http.StatusInternalServerError)
505 return
506 }
507 }