forked from git-pkgs/proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
1017 lines (900 loc) · 30.8 KB
/
Copy pathserver.go
File metadata and controls
1017 lines (900 loc) · 30.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package server provides the HTTP server and router for the proxy.
//
// The server mounts protocol handlers at their respective paths:
// - /npm/* - npm registry protocol
// - /cargo/* - Cargo registry protocol (sparse index)
// - /gem/* - RubyGems registry protocol
// - /go/* - Go module proxy protocol
// - /hex/* - Hex.pm registry protocol
// - /pub/* - pub.dev registry protocol
// - /pypi/* - PyPI registry protocol
// - /maven/* - Maven repository protocol
// - /gradle/* - Gradle HttpBuildCache protocol
// - /nuget/* - NuGet V3 API protocol
// - /composer/* - Composer/Packagist protocol
// - /conan/* - Conan C/C++ protocol
// - /conda/* - Conda/Anaconda protocol
// - /cran/* - CRAN (R) protocol
// - /julia/* - Julia Pkg server protocol
// - /v2/* - OCI/Docker container registry protocol
// - /debian/* - Debian/APT repository protocol
// - /rpm/* - RPM/Yum repository protocol
//
// Additional endpoints:
// - /health - Health check endpoint
// - /stats - Cache statistics (JSON)
// - /openapi.json - OpenAPI spec (JSON)
// - /metrics - Prometheus metrics
//
// Web UI (HTML), mounted under /ui so reverse proxies can gate it
// separately from the package endpoints:
// - /ui/ - Dashboard
// - /ui/install - Client configuration guide
// - /ui/packages - List all cached packages
// - /ui/search - Search packages
// - /ui/package/... - Package and version detail pages
// - /ui/api/browse/... - Archive browsing (used by the UI)
// - /ui/api/compare/... - Archive diffing (used by the UI)
//
// API endpoints for enrichment data:
// - GET /api/package/{ecosystem}/{name} - Package metadata
// - GET /api/package/{ecosystem}/{name}/{version} - Version metadata with vulns
// - GET /api/vulns/{ecosystem}/{name} - Package vulnerabilities
// - GET /api/vulns/{ecosystem}/{name}/{version} - Version vulnerabilities
// - POST /api/outdated - Check outdated packages
// - POST /api/bulk - Bulk package lookup
// - GET /api/packages - List cached packages (JSON)
package server
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
"github.com/git-pkgs/cooldown"
swaggerdoc "github.com/git-pkgs/proxy/docs/swagger"
"github.com/git-pkgs/proxy/internal/config"
"github.com/git-pkgs/proxy/internal/database"
"github.com/git-pkgs/proxy/internal/enrichment"
"github.com/git-pkgs/proxy/internal/handler"
"github.com/git-pkgs/proxy/internal/metrics"
"github.com/git-pkgs/proxy/internal/mirror"
"github.com/git-pkgs/proxy/internal/storage"
"github.com/git-pkgs/purl"
"github.com/git-pkgs/registries/fetch"
"github.com/git-pkgs/spdx"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
const (
serverReadTimeout = 30 * time.Second
serverWriteTimeout = 5 * time.Minute
serverIdleTimeout = 60 * time.Second
dashboardTopN = 10
hoursPerDay = 24
)
// Server is the main proxy server.
type Server struct {
cfg *config.Config
db *database.DB
storage storage.Storage
logger *slog.Logger
http *http.Server
templates *Templates
cancel context.CancelFunc
healthCache *healthCache
}
// New creates a new Server with the given configuration.
func New(cfg *config.Config, logger *slog.Logger) (*Server, error) {
// Initialize database
var db *database.DB
var err error
switch cfg.Database.Driver {
case "postgres":
db, err = database.OpenPostgresOrCreate(cfg.Database.URL)
default:
db, err = database.OpenOrCreate(cfg.Database.Path)
}
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
// Run schema migration to add missing columns
if err := db.MigrateSchema(); err != nil {
_ = db.Close()
return nil, fmt.Errorf("migrating database schema: %w", err)
}
// Initialize storage
storageURL := cfg.Storage.URL
if storageURL == "" {
// Fall back to file:// with Path
storageURL = "file://" + cfg.Storage.Path //nolint:staticcheck // backwards compat
}
store, err := storage.OpenBucket(context.Background(), storageURL)
if err != nil {
_ = db.Close()
return nil, fmt.Errorf("initializing storage: %w", err)
}
// Verify storage is accessible (catches bad S3 credentials/endpoints early).
// Exists returns (false, nil) for a missing key, so only real connectivity
// or permission errors surface here.
if _, err := store.Exists(context.Background(), ".health-check"); err != nil {
_ = store.Close()
_ = db.Close()
return nil, fmt.Errorf("verifying storage connectivity: %w", err)
}
hc, err := newHealthCache(store, cfg.Health.StorageProbeInterval, logger)
if err != nil {
_ = store.Close()
_ = db.Close()
return nil, fmt.Errorf("initializing health cache: %w", err)
}
return &Server{
cfg: cfg,
db: db,
storage: store,
logger: logger,
templates: &Templates{},
healthCache: hc,
}, nil
}
// Start starts the HTTP server.
func (s *Server) Start() error {
// Create shared components with circuit breaker
baseFetcher := fetch.NewFetcher(fetch.WithAuthFunc(s.authForURL))
fetcher := fetch.NewCircuitBreakerFetcher(baseFetcher)
resolver := fetch.NewResolver()
cd := &cooldown.Config{
Default: s.cfg.Cooldown.Default,
Ecosystems: s.cfg.Cooldown.Ecosystems,
Packages: s.cfg.Cooldown.Packages,
}
proxy := handler.NewProxy(s.db, s.storage, fetcher, resolver, s.logger)
proxy.Cooldown = cd
proxy.CacheMetadata = s.cfg.CacheMetadata
proxy.MetadataTTL = s.cfg.ParseMetadataTTL()
proxy.MetadataMaxSize = s.cfg.ParseMetadataMaxSize()
proxy.GradleReadOnly = s.cfg.Gradle.BuildCache.ReadOnly
proxy.GradleMaxUploadSize = s.cfg.ParseGradleBuildCacheMaxUploadSize()
proxy.DirectServe = s.cfg.Storage.DirectServe
proxy.DirectServeTTL = s.cfg.ParseDirectServeTTL()
proxy.DirectServeBaseURL = s.cfg.Storage.DirectServeBaseURL
// Create router with Chi
r := chi.NewRouter()
// Add middleware
r.Use(middleware.RequestID)
r.Use(RequestIDMiddleware)
r.Use(s.LoggerMiddleware)
r.Use(middleware.Recoverer)
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/metrics" {
metrics.IncrementActiveRequests()
defer metrics.DecrementActiveRequests()
}
next.ServeHTTP(w, r)
})
})
// Mount protocol handlers
npmHandler := handler.NewNPMHandler(proxy, s.cfg.BaseURL)
cargoHandler := handler.NewCargoHandler(proxy, s.cfg.BaseURL)
gemHandler := handler.NewGemHandler(proxy, s.cfg.BaseURL)
goHandler := handler.NewGoHandler(proxy, s.cfg.BaseURL)
hexHandler := handler.NewHexHandler(proxy, s.cfg.BaseURL)
pubHandler := handler.NewPubHandler(proxy, s.cfg.BaseURL)
pypiHandler := handler.NewPyPIHandler(proxy, s.cfg.BaseURL)
mavenHandler := handler.NewMavenHandler(
proxy,
s.cfg.BaseURL,
s.cfg.Upstream.Maven,
s.cfg.Upstream.GradlePluginPortal,
)
gradleHandler := handler.NewGradleBuildCacheHandler(proxy)
nugetHandler := handler.NewNuGetHandler(proxy, s.cfg.BaseURL)
composerHandler := handler.NewComposerHandler(proxy, s.cfg.BaseURL)
conanHandler := handler.NewConanHandler(proxy, s.cfg.BaseURL)
condaHandler := handler.NewCondaHandler(proxy, s.cfg.BaseURL)
cranHandler := handler.NewCRANHandler(proxy, s.cfg.BaseURL)
juliaHandler := handler.NewJuliaHandler(proxy, s.cfg.BaseURL)
dockerHandler := handler.NewDockerHubHandler(proxy, s.cfg.BaseURL)
registryK8sHandler := handler.NewContainerHandler(proxy, s.cfg.BaseURL, "registry.k8s.io")
debianHandler := handler.NewDebianHandler(proxy, s.cfg.BaseURL)
rpmHandler := handler.NewRPMHandler(proxy, s.cfg.BaseURL)
r.Mount("/npm", http.StripPrefix("/npm", npmHandler.Routes()))
r.Mount("/cargo", http.StripPrefix("/cargo", cargoHandler.Routes()))
r.Mount("/gem", http.StripPrefix("/gem", gemHandler.Routes()))
r.Mount("/go", http.StripPrefix("/go", goHandler.Routes()))
r.Mount("/hex", http.StripPrefix("/hex", hexHandler.Routes()))
r.Mount("/pub", http.StripPrefix("/pub", pubHandler.Routes()))
r.Mount("/pypi", http.StripPrefix("/pypi", pypiHandler.Routes()))
r.Mount("/maven", http.StripPrefix("/maven", mavenHandler.Routes()))
r.Mount("/gradle", http.StripPrefix("/gradle", gradleHandler.Routes()))
r.Mount("/nuget", http.StripPrefix("/nuget", nugetHandler.Routes()))
r.Mount("/composer", http.StripPrefix("/composer", composerHandler.Routes()))
r.Mount("/conan", http.StripPrefix("/conan", conanHandler.Routes()))
r.Mount("/conda", http.StripPrefix("/conda", condaHandler.Routes()))
r.Mount("/cran", http.StripPrefix("/cran", cranHandler.Routes()))
r.Mount("/julia", http.StripPrefix("/julia", juliaHandler.Routes()))
r.Mount("/v2", http.StripPrefix("/v2", dockerHandler.Routes()))
r.Mount("/v2/registry.k8s.io", http.StripPrefix("/v2/registry.k8s.io", registryK8sHandler.Routes()))
r.Mount("/debian", http.StripPrefix("/debian", debianHandler.Routes()))
r.Mount("/rpm", http.StripPrefix("/rpm", rpmHandler.Routes()))
// Health, stats, and metrics endpoints
r.Get("/health", s.handleHealth)
r.Get("/stats", s.handleStats)
r.Get("/openapi.json", s.handleOpenAPIJSON)
r.Get("/metrics", func(w http.ResponseWriter, r *http.Request) {
metrics.Handler().ServeHTTP(w, r)
})
// Web UI. Mounted under /ui so a reverse proxy can apply different
// access rules to it than to the package endpoints above (#123).
r.Route("/ui", func(ui chi.Router) {
ui.Mount("/static", http.StripPrefix("/ui/static/", staticHandler()))
ui.Get("/", s.handleRoot)
ui.Get("/install", s.handleInstall)
ui.Get("/search", s.handleSearch)
ui.Get("/packages", s.handlePackagesList)
ui.Get("/package/{ecosystem}/*", s.handlePackagePath)
ui.Get("/api/browse/{ecosystem}/*", s.handleBrowsePath)
ui.Get("/api/compare/{ecosystem}/*", s.handleComparePath)
})
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/ui/", http.StatusFound)
})
// API endpoints for enrichment data
enrichSvc := enrichment.New(s.logger)
apiHandler := NewAPIHandler(enrichSvc, s.db)
r.Get("/api/package/{ecosystem}/*", apiHandler.HandlePackagePath)
r.Get("/api/vulns/{ecosystem}/*", apiHandler.HandleVulnsPath)
r.Post("/api/outdated", apiHandler.HandleOutdated)
r.Post("/api/bulk", apiHandler.HandleBulkLookup)
r.Get("/api/search", apiHandler.HandleSearch)
r.Get("/api/packages", apiHandler.HandlePackagesList)
// Start background context (used by mirror jobs and cleanup)
bgCtx, bgCancel := context.WithCancel(context.Background())
s.cancel = bgCancel
s.startGradleBuildCacheEviction(bgCtx)
// Mirror API endpoints (opt-in via mirror_api config or PROXY_MIRROR_API env)
if s.cfg.MirrorAPI {
mirrorSvc := mirror.New(proxy, s.db, s.storage, s.logger, 4) //nolint:mnd // default concurrency
jobStore := mirror.NewJobStore(bgCtx, mirrorSvc)
mirrorAPI := NewMirrorAPIHandler(jobStore)
r.Post("/api/mirror", mirrorAPI.HandleCreate)
r.Get("/api/mirror/{id}", mirrorAPI.HandleGet)
r.Delete("/api/mirror/{id}", mirrorAPI.HandleCancel)
go jobStore.StartCleanup(bgCtx)
}
s.http = &http.Server{
Addr: s.cfg.Listen,
Handler: r,
ReadTimeout: serverReadTimeout,
WriteTimeout: serverWriteTimeout, // Large artifacts need time
IdleTimeout: serverIdleTimeout,
}
s.logger.Info("starting server",
"listen", s.cfg.Listen,
"base_url", s.cfg.BaseURL,
"ui_url", s.cfg.UIBaseURL,
"storage", s.storage.URL(),
"database", s.cfg.Database.String())
go s.updateCacheStatsMetrics()
go s.startEvictionLoop(bgCtx)
return s.http.ListenAndServe()
}
// updateCacheStatsMetrics periodically updates cache statistics in Prometheus metrics.
func (s *Server) updateCacheStatsMetrics() {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
// Update once immediately
s.updateCacheStats()
for range ticker.C {
s.updateCacheStats()
}
}
func (s *Server) updateCacheStats() {
stats, err := s.db.GetCacheStats()
if err != nil {
s.logger.Warn("failed to get cache stats for metrics", "error", err)
return
}
metrics.UpdateCacheStats(stats.TotalSize, stats.TotalArtifacts)
}
// Shutdown gracefully shuts down the server.
func (s *Server) Shutdown(ctx context.Context) error {
s.logger.Info("shutting down server")
if s.cancel != nil {
s.cancel()
}
var errs []error
if s.http != nil {
if err := s.http.Shutdown(ctx); err != nil {
errs = append(errs, fmt.Errorf("http shutdown: %w", err))
}
}
if s.storage != nil {
if err := s.storage.Close(); err != nil {
errs = append(errs, fmt.Errorf("storage close: %w", err))
}
}
if s.db != nil {
if err := s.db.Close(); err != nil {
errs = append(errs, fmt.Errorf("database close: %w", err))
}
}
if len(errs) > 0 {
return errs[0]
}
return nil
}
// authForURL returns the authentication header for a given URL based on config.
func (s *Server) authForURL(url string) (headerName, headerValue string) {
auth := s.cfg.Upstream.AuthForURL(url)
if auth == nil {
return "", ""
}
return auth.Header()
}
func (s *Server) handleRoot(w http.ResponseWriter, r *http.Request) {
// Get cache statistics
stats, err := s.db.GetCacheStats()
if err != nil {
s.logger.Error("failed to get cache stats", "error", err)
stats = &database.CacheStats{}
}
// Get enrichment statistics
enrichStats, err := s.db.GetEnrichmentStats()
if err != nil {
s.logger.Error("failed to get enrichment stats", "error", err)
enrichStats = &database.EnrichmentStats{}
}
// Get popular packages
popular, err := s.db.GetMostPopularPackages(dashboardTopN)
if err != nil {
s.logger.Error("failed to get popular packages", "error", err)
}
// Get recent packages
recent, err := s.db.GetRecentlyCachedPackages(dashboardTopN)
if err != nil {
s.logger.Error("failed to get recent packages", "error", err)
}
// Build dashboard data
data := DashboardData{
Layout: s.layoutFor(r),
Stats: DashboardStats{
CachedArtifacts: stats.TotalArtifacts,
TotalSize: formatSize(stats.TotalSize),
TotalPackages: stats.TotalPackages,
TotalVersions: stats.TotalVersions,
},
EnrichmentStats: EnrichmentStatsView{
EnrichedPackages: enrichStats.EnrichedPackages,
VulnSyncedPackages: enrichStats.VulnSyncedPackages,
TotalVulnerabilities: enrichStats.TotalVulnerabilities,
CriticalVulns: enrichStats.CriticalVulns,
HighVulns: enrichStats.HighVulns,
MediumVulns: enrichStats.MediumVulns,
LowVulns: enrichStats.LowVulns,
HasVulns: enrichStats.TotalVulnerabilities > 0,
},
}
for _, p := range popular {
pkgInfo := PackageInfo{
Ecosystem: p.Ecosystem,
Name: p.Name,
Hits: p.Hits,
Size: formatSize(p.Size),
}
// Fetch enrichment data for this package
if pkg, err := s.db.GetPackageByEcosystemName(p.Ecosystem, p.Name); err == nil && pkg != nil {
if pkg.License.Valid {
pkgInfo.License = pkg.License.String
pkgInfo.LicenseCategory = categorizeLicenseCSS(pkg.License.String)
}
if pkg.LatestVersion.Valid {
pkgInfo.LatestVersion = pkg.LatestVersion.String
}
}
// Get vulnerability count
if vulnCount, err := s.db.GetVulnCountForPackage(p.Ecosystem, p.Name); err == nil {
pkgInfo.VulnCount = vulnCount
}
data.PopularPackages = append(data.PopularPackages, pkgInfo)
}
for _, p := range recent {
pkgInfo := PackageInfo{
Ecosystem: p.Ecosystem,
Name: p.Name,
Version: p.Version,
Size: formatSize(p.Size),
CachedAt: formatTimeAgo(p.CachedAt),
}
// Fetch enrichment data for this package
if pkg, err := s.db.GetPackageByEcosystemName(p.Ecosystem, p.Name); err == nil && pkg != nil {
if pkg.License.Valid {
pkgInfo.License = pkg.License.String
pkgInfo.LicenseCategory = categorizeLicenseCSS(pkg.License.String)
}
if pkg.LatestVersion.Valid {
pkgInfo.LatestVersion = pkg.LatestVersion.String
pkgInfo.IsOutdated = p.Version != "" && pkg.LatestVersion.String != "" && p.Version != pkg.LatestVersion.String
}
}
// Get vulnerability count
if vulnCount, err := s.db.GetVulnCountForPackage(p.Ecosystem, p.Name); err == nil {
pkgInfo.VulnCount = vulnCount
}
data.RecentPackages = append(data.RecentPackages, pkgInfo)
}
if err := s.templates.Render(w, "dashboard", data); err != nil {
s.logger.Error("failed to render dashboard", "error", err)
}
}
func (s *Server) handleOpenAPIJSON(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_, _ = w.Write([]byte(swaggerdoc.SwaggerInfo.ReadDoc()))
}
func (s *Server) handleInstall(w http.ResponseWriter, r *http.Request) {
data := struct {
Layout
BaseURL string
Registries []RegistryConfig
}{
Layout: s.layoutFor(r),
BaseURL: s.cfg.BaseURL,
Registries: getRegistryConfigs(s.cfg.BaseURL),
}
if err := s.templates.Render(w, "install", data); err != nil {
s.logger.Error("failed to render install page", "error", err)
}
}
func (s *Server) handleSearch(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("q")
ecosystem := r.URL.Query().Get("ecosystem")
if query == "" {
http.Redirect(w, r, "/ui/", http.StatusSeeOther)
return
}
page := 1
if pageStr := r.URL.Query().Get("page"); pageStr != "" {
if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
page = p
}
}
limit := 50
results, err := s.db.SearchPackages(query, ecosystem, limit, (page-1)*limit)
if err != nil {
s.logger.Error("search failed", "error", err)
http.Error(w, "search failed", http.StatusInternalServerError)
return
}
total, err := s.db.CountSearchResults(query, ecosystem)
if err != nil {
s.logger.Error("failed to count search results", "error", err)
total = 0
}
items := make([]SearchResultItem, len(results))
for i, result := range results {
latestVersion := ""
if result.LatestVersion.Valid {
latestVersion = result.LatestVersion.String
}
license := ""
if result.License.Valid {
license = result.License.String
}
items[i] = SearchResultItem{
Ecosystem: result.Ecosystem,
Name: result.Name,
LatestVersion: latestVersion,
License: license,
Hits: result.Hits,
Size: result.Size,
SizeFormatted: formatSize(result.Size),
}
}
totalPages := int((total + int64(limit) - 1) / int64(limit))
data := SearchPageData{
Layout: s.layoutFor(r),
Query: query,
Ecosystem: ecosystem,
Results: items,
Count: int(total),
Page: page,
PerPage: limit,
TotalPages: totalPages,
}
if err := s.templates.Render(w, "search", data); err != nil {
s.logger.Error("failed to render search page", "error", err)
}
}
func (s *Server) handlePackagesList(w http.ResponseWriter, r *http.Request) {
ecosystem := r.URL.Query().Get("ecosystem")
sortBy := r.URL.Query().Get("sort")
if sortBy == "" {
sortBy = defaultSortBy
}
page := 1
if pageStr := r.URL.Query().Get("page"); pageStr != "" {
if p, err := strconv.Atoi(pageStr); err == nil && p > 0 {
page = p
}
}
limit := 50
packages, err := s.db.ListCachedPackages(ecosystem, sortBy, limit, (page-1)*limit)
if err != nil {
s.logger.Error("failed to list packages", "error", err)
http.Error(w, "failed to list packages", http.StatusInternalServerError)
return
}
total, err := s.db.CountCachedPackages(ecosystem)
if err != nil {
s.logger.Error("failed to count packages", "error", err)
total = 0
}
items := make([]SearchResultItem, len(packages))
for i, pkg := range packages {
latestVersion := ""
if pkg.LatestVersion.Valid {
latestVersion = pkg.LatestVersion.String
}
license := ""
if pkg.License.Valid {
license = pkg.License.String
}
cachedAt := ""
if pkg.CachedAt.Valid && pkg.CachedAt.String != "" {
if t, err := time.Parse("2006-01-02 15:04:05.999999999-07:00", pkg.CachedAt.String); err == nil {
cachedAt = formatTimeAgo(t)
}
}
items[i] = SearchResultItem{
Ecosystem: pkg.Ecosystem,
Name: pkg.Name,
LatestVersion: latestVersion,
License: license,
LicenseCategory: categorizeLicenseCSS(license),
Hits: pkg.Hits,
Size: pkg.Size,
SizeFormatted: formatSize(pkg.Size),
CachedAt: cachedAt,
VulnCount: pkg.VulnCount,
}
}
totalPages := int((total + int64(limit) - 1) / int64(limit))
data := PackagesListPageData{
Layout: s.layoutFor(r),
Ecosystem: ecosystem,
SortBy: sortBy,
Results: items,
Count: int(total),
Page: page,
PerPage: limit,
TotalPages: totalPages,
}
if err := s.templates.Render(w, "packages_list", data); err != nil {
s.logger.Error("failed to render packages list page", "error", err)
}
}
// handlePackagePath dispatches wildcard package routes to the appropriate handler.
// It resolves namespaced package names (e.g., Composer vendor/name) by consulting
// the database to determine which path segments are part of the package name.
//
// Supported paths:
//
// {name} -> package show
// {name}/{version} -> version show
// {name}/{version}/browse -> browse source
// {name}/compare/{v1}...{v2} -> compare versions
func (s *Server) handlePackagePath(w http.ResponseWriter, r *http.Request) {
ecosystem := chi.URLParam(r, "ecosystem")
wildcard := chi.URLParam(r, "*")
if err := validatePackagePath(wildcard); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
segments := splitWildcardPath(wildcard)
if ecosystem == "" || len(segments) == 0 {
http.Error(w, "ecosystem and package name required", http.StatusBadRequest)
return
}
// Check for compare route: {name}/compare/{versions}
for i, seg := range segments {
if seg == "compare" && i > 0 && i < len(segments)-1 {
name := strings.Join(segments[:i], "/")
versions := strings.Join(segments[i+1:], "/")
s.showComparePage(w, r, ecosystem, name, versions)
return
}
}
// Check for browse suffix
browse := false
if len(segments) > 1 && segments[len(segments)-1] == "browse" {
browse = true
segments = segments[:len(segments)-1]
}
// Resolve package name from the remaining segments using DB lookup.
name, rest := resolvePackageName(s.db, ecosystem, segments)
if name == "" {
// No package found in DB. Fall back to heuristic: assume the last
// segment is a version (if present) and everything else is the name.
if len(segments) == 1 {
// Single segment, no DB match: try package show (will 404).
s.showPackage(w, r, ecosystem, segments[0])
return
}
name = strings.Join(segments[:len(segments)-1], "/")
rest = segments[len(segments)-1:]
}
switch {
case len(rest) == 0 && !browse:
s.showPackage(w, r, ecosystem, name)
case len(rest) == 1 && browse:
s.showBrowseSource(w, r, ecosystem, name, rest[0])
case len(rest) == 1:
s.showVersion(w, r, ecosystem, name, rest[0])
default:
http.Error(w, "not found", http.StatusNotFound)
}
}
func (s *Server) showPackage(w http.ResponseWriter, r *http.Request, ecosystem, name string) {
pkg, err := s.db.GetPackageByEcosystemName(ecosystem, name)
if err != nil {
s.logger.Error("failed to get package", "error", err, "ecosystem", ecosystem, "name", name)
http.Error(w, "package not found", http.StatusNotFound)
return
}
if pkg == nil {
http.Error(w, "package not found", http.StatusNotFound)
return
}
versions, err := s.db.GetVersionsByPackagePURL(pkg.PURL)
if err != nil {
s.logger.Error("failed to get versions", "error", err)
versions = []database.Version{}
}
vulns, err := s.db.GetVulnerabilitiesForPackage(ecosystem, name)
if err != nil {
s.logger.Error("failed to get vulnerabilities", "error", err)
vulns = []database.Vulnerability{}
}
data := PackageShowData{
Layout: s.layoutFor(r),
Package: pkg,
Versions: versions,
Vulnerabilities: vulns,
LicenseCategory: categorizeLicense(pkg.License),
}
if err := s.templates.Render(w, "package_show", data); err != nil {
s.logger.Error("failed to render package show", "error", err)
}
}
func (s *Server) showVersion(w http.ResponseWriter, r *http.Request, ecosystem, name, version string) {
pkg, err := s.db.GetPackageByEcosystemName(ecosystem, name)
if err != nil || pkg == nil {
s.logger.Error("failed to get package", "error", err)
http.Error(w, "package not found", http.StatusNotFound)
return
}
versionPURL := purl.MakePURLString(ecosystem, name, version)
ver, err := s.db.GetVersionByPURL(versionPURL)
if err != nil || ver == nil {
s.logger.Error("failed to get version", "error", err)
http.Error(w, "version not found", http.StatusNotFound)
return
}
artifacts, err := s.db.GetArtifactsByVersionPURL(versionPURL)
if err != nil {
s.logger.Error("failed to get artifacts", "error", err)
artifacts = []database.Artifact{}
}
vulns, err := s.db.GetVulnerabilitiesForPackage(ecosystem, name)
if err != nil {
s.logger.Error("failed to get vulnerabilities", "error", err)
vulns = []database.Vulnerability{}
}
isOutdated := pkg.LatestVersion.Valid && pkg.LatestVersion.String != version
hasCached := false
for _, art := range artifacts {
if art.StoragePath.Valid {
hasCached = true
break
}
}
data := VersionShowData{
Layout: s.layoutFor(r),
Package: pkg,
Version: ver,
Artifacts: artifacts,
Vulnerabilities: vulns,
IsOutdated: isOutdated,
LicenseCategory: categorizeLicense(ver.License),
HasCachedArtifact: hasCached,
}
if err := s.templates.Render(w, "version_show", data); err != nil {
s.logger.Error("failed to render version show", "error", err)
}
}
func (s *Server) showBrowseSource(w http.ResponseWriter, r *http.Request, ecosystem, name, version string) {
data := BrowseSourceData{
Layout: s.layoutFor(r),
Ecosystem: ecosystem,
PackageName: name,
Version: version,
}
if err := s.templates.Render(w, "browse_source", data); err != nil {
s.logger.Error("failed to render browse source page", "error", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
}
}
func (s *Server) showComparePage(w http.ResponseWriter, r *http.Request, ecosystem, name, versions string) {
const compareVersionParts = 2
parts := strings.Split(versions, "...")
if len(parts) != compareVersionParts {
http.Error(w, "invalid version format, use: version1...version2", http.StatusBadRequest)
return
}
data := ComparePageData{
Layout: s.layoutFor(r),
Ecosystem: ecosystem,
PackageName: name,
FromVersion: parts[0],
ToVersion: parts[1],
}
if err := s.templates.Render(w, "compare_versions", data); err != nil {
s.logger.Error("failed to render compare page", "error", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
}
}
// handleHealth responds with a structured JSON health report.
//
// @Summary Health check
// @Tags meta
// @Produce json
// @Success 200 {object} HealthResponse
// @Failure 503 {object} HealthResponse
// @Router /health [get]
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
resp := HealthResponse{Status: "ok", Checks: map[string]HealthCheck{}}
// Database check (short-circuit; do not waste a storage probe call when DB is down).
// On DB failure the storage entry reports "skipped" rather than being omitted so
// the response always carries the same key set for monitors that expect it.
if _, err := s.db.SchemaVersion(); err != nil {
resp.Status = "error"
resp.Checks["database"] = HealthCheck{Status: "error", Error: err.Error()}
resp.Checks["storage"] = HealthCheck{Status: "skipped"}
w.WriteHeader(http.StatusServiceUnavailable)
_ = json.NewEncoder(w).Encode(resp)
return
}
resp.Checks["database"] = HealthCheck{Status: "ok"}
// Storage probe (via cache).
if err := s.healthCache.Check(); err != nil {
resp.Status = "error"
sc := HealthCheck{Status: "error", Error: err.Error()}
var pe *probeError
if errors.As(err, &pe) {
sc.Step = pe.step
}
resp.Checks["storage"] = sc
w.WriteHeader(http.StatusServiceUnavailable)
_ = json.NewEncoder(w).Encode(resp)
return
}
resp.Checks["storage"] = HealthCheck{Status: "ok"}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(resp)
}
// StatsResponse contains cache statistics.
type StatsResponse struct {
CachedArtifacts int64 `json:"cached_artifacts"`
TotalSize int64 `json:"total_size_bytes"`
TotalSizeHuman string `json:"total_size"`
StorageURL string `json:"storage_url"`
DatabasePath string `json:"database_path"`
}
// handleStats returns cache statistics.
// @Summary Cache statistics
// @Tags meta
// @Produce json
// @Success 200 {object} StatsResponse
// @Failure 500 {object} ErrorResponse
// @Router /stats [get]
func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
count, err := s.db.GetCachedArtifactCount()
if err != nil {
internalError(w, "failed to get artifact count")
return
}
size, err := s.db.GetTotalCacheSize()
if err != nil {
internalError(w, "failed to get cache size")
return
}
_ = ctx // Could use for storage.UsedSpace if needed
stats := StatsResponse{
CachedArtifacts: count,
TotalSize: size,
TotalSizeHuman: formatSize(size),
StorageURL: s.storage.URL(),
DatabasePath: s.cfg.Database.String(),
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(stats)
}
func formatSize(bytes int64) string {
const unit = 1024
if bytes < unit {
return fmt.Sprintf("%d B", bytes)
}
div, exp := int64(unit), 0
for n := bytes / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
}
func formatTimeAgo(t time.Time) string {
if t.IsZero() {
return ""
}
d := time.Since(t)
switch {
case d < time.Minute:
return "just now"
case d < time.Hour:
m := int(d.Minutes())
if m == 1 {
return "1 min ago"
}
return fmt.Sprintf("%d mins ago", m)
case d < hoursPerDay*time.Hour:
h := int(d.Hours())
if h == 1 {
return "1 hour ago"
}
return fmt.Sprintf("%d hours ago", h)
case d < 7*hoursPerDay*time.Hour:
days := int(d.Hours() / hoursPerDay)
if days == 1 {
return "1 day ago"
}
return fmt.Sprintf("%d days ago", days)
default:
return t.Format("Jan 2")
}
}
// categorizeLicenseCSS returns the CSS class suffix for a license category using the spdx module.
func categorizeLicenseCSS(license string) string {
if license == "" {
return licenseCategoryUnknown
}
if spdx.HasCopyleft(license) {
return "copyleft"
}
if spdx.IsFullyPermissive(license) {
return "permissive"
}
return licenseCategoryUnknown
}
// categorizeLicense is a helper that handles sql.NullString.