-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathdependency_proxy_controller.go
More file actions
1430 lines (1222 loc) · 49.3 KB
/
dependency_proxy_controller.go
File metadata and controls
1430 lines (1222 loc) · 49.3 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
// Copyright 2025 l3montree GmbH.
// SPDX-License-Identifier: AGPL-3.0-or-later
package controllers
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/google/uuid"
"github.com/l3montree-dev/devguard/shared"
"github.com/l3montree-dev/devguard/utils"
"github.com/labstack/echo/v4"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
const (
npmRegistry = "https://registry.npmjs.org"
goProxyURL = "https://proxy.golang.org"
pypiRegistry = "https://pypi.org"
)
var depProxyTracer = otel.Tracer("devguard/dependency-proxy")
type ProxyType string
const (
NPMProxy ProxyType = "npm"
GoProxy ProxyType = "go"
PyPIProxy ProxyType = "pypi"
)
type DependencyProxyCache struct {
CacheDir string
}
type DependencyProxyConfigs struct {
Rules []string `json:"rules"`
MinReleaseTime int `json:"minReleaseTime"` // in hours
}
type DependencyProxyController struct {
assetRepository shared.AssetRepository
projectRepository shared.ProjectRepository
orgRepository shared.OrganizationRepository
dependencyProxyService shared.DependencyProxySecretService
maliciousChecker shared.MaliciousPackageChecker
cacheDir string
client *http.Client
}
// trimProxyPrefix strips the /api/v1/dependency-proxy/[secret/]<ecosystem> prefix from the path.
// The secret segment is optional to support routes with and without a secret.
func TrimProxyPrefix(path string, ecosystem ProxyType) string {
encodedPackage := regexp.MustCompile(`^/api/v1/dependency-proxy/(?:[^/]+/)?`+regexp.QuoteMeta(string(ecosystem))+`(?:/|$)`).ReplaceAllString(path, "")
decodedPackage, err := url.PathUnescape(encodedPackage)
if err != nil {
return encodedPackage
}
return decodedPackage
}
func NewDependencyProxyController(
dependencyProxyService shared.DependencyProxySecretService,
config DependencyProxyCache,
maliciousChecker shared.MaliciousPackageChecker,
assetRepository shared.AssetRepository,
projectRepository shared.ProjectRepository,
orgRepository shared.OrganizationRepository,
) *DependencyProxyController {
return &DependencyProxyController{
dependencyProxyService: dependencyProxyService,
maliciousChecker: maliciousChecker,
cacheDir: config.CacheDir,
assetRepository: assetRepository,
projectRepository: projectRepository,
orgRepository: orgRepository,
client: &http.Client{
Timeout: 60 * time.Second,
Transport: utils.EgressTransport,
},
}
}
func (d *DependencyProxyController) ProxyNPM(c shared.Context) error {
configs, err := d.GetDependencyProxyConfigs(c)
if err != nil {
slog.Error("Error getting dependency proxy configs", "error", err)
}
path := c.Request().URL.Path
// Get the full path after the prefix
requestPath := TrimProxyPrefix(path, NPMProxy)
ctx, span := depProxyTracer.Start(c.Request().Context(), "dependency-proxy.npm",
trace.WithAttributes(
attribute.String("proxy.ecosystem", "npm"),
attribute.String("proxy.path", requestPath),
attribute.String("http.method", c.Request().Method),
),
)
defer span.End()
c.SetRequest(c.Request().WithContext(ctx))
// Only allow GET and HEAD for regular npm requests
if c.Request().Method != http.MethodGet && c.Request().Method != http.MethodHead {
return echo.NewHTTPError(http.StatusMethodNotAllowed, "Method not allowed")
}
slog.Info("Proxy request", "proxy", "npm", "method", c.Request().Method, "path", requestPath)
cachePath := d.getCachePath(NPMProxy, requestPath)
packageName, version := d.ParsePackageFromPath(NPMProxy, requestPath)
hasExplicitVersion := version != "" || strings.HasSuffix(requestPath, ".tgz")
// Check for malicious packages
// For requests with explicit versions (e.g., .tgz files or package@version), check immediately
// For metadata requests (package info without version), we need to fetch first to see which version would be used
if hasExplicitVersion {
notAllowed, notAllowedReason := d.CheckNotAllowedPackage(ctx, NPMProxy, requestPath, configs)
if notAllowed {
return d.blockNotAllowedPackage(c, NPMProxy, requestPath, notAllowedReason)
}
hasMalicious, reason := d.checkMaliciousPackage(ctx, NPMProxy, requestPath)
if hasMalicious {
slog.Warn("Blocked malicious package", "proxy", "npm", "path", requestPath, "reason", reason)
// Also remove from cache if it exists to prevent serving cached malicious content
cachePath := d.getCachePath(NPMProxy, requestPath)
if err := os.Remove(cachePath); err == nil {
slog.Info("Removed malicious package from cache", "path", cachePath)
}
return d.blockMaliciousPackage(c, NPMProxy, requestPath, reason)
}
// Check cache
if d.isNPMCached(cachePath) {
slog.Debug("Cache hit", "proxy", "npm", "path", requestPath)
data, err := os.ReadFile(cachePath)
if err == nil {
// Verify cache integrity
if d.VerifyCacheIntegrity(cachePath, data) {
if configs.MinReleaseTime > 0 {
if releaseTime, ok := d.ReadCachedReleaseTime(cachePath); ok {
if time.Since(releaseTime) > time.Duration(configs.MinReleaseTime)*time.Hour {
return d.blockTooNewPackage(c, NPMProxy, requestPath, releaseTime, configs.MinReleaseTime)
}
span.SetAttributes(attribute.Bool("proxy.cache_hit", true))
return d.writeNPMResponse(c, data, requestPath, true)
}
// No cached release time - fall through to upstream to retrieve it
slog.Debug("No cached release time for MinReleaseTime check, refetching", "proxy", "npm", "path", requestPath)
} else {
span.SetAttributes(attribute.Bool("proxy.cache_hit", true))
return d.writeNPMResponse(c, data, requestPath, true)
}
} else {
slog.Warn("Cache integrity verification failed, refetching", "proxy", "npm", "path", requestPath)
// Remove corrupted cache
os.Remove(cachePath)
os.Remove(cachePath + ".sha256")
}
} else {
slog.Warn("Cache read error", "proxy", "npm", "error", err)
}
}
}
span.SetAttributes(attribute.Bool("proxy.cache_hit", false))
// Fetch from upstream
data, headers, statusCode, err := d.fetchFromUpstream(ctx, NPMProxy, npmRegistry, requestPath, c.Request().Header, nil)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
slog.Error("Error fetching from upstream", "proxy", "npm", "error", err)
return echo.NewHTTPError(http.StatusBadGateway, "Failed to fetch from upstream")
}
if statusCode != http.StatusOK {
slog.Debug("Upstream returned non-OK status", "proxy", "npm", "status", statusCode)
// Forward important headers
for key, values := range headers {
for _, value := range values {
c.Response().Header().Add(key, value)
}
}
return c.Blob(statusCode, headers.Get("Content-Type"), data)
}
resolvedVersion, releaseTime := d.ExtractNPMVersionAndReleaseTimeFromMetadata(data)
// For metadata requests without explicit version, check the resolved version against malicious database
if !hasExplicitVersion {
//check allowlist patterns before checking malicious database to prevent false positives on allowed packages
notAllowed, notAllowedReason := d.CheckNotAllowedPackage(ctx, NPMProxy, packageName+"@"+resolvedVersion, configs)
if notAllowed {
return d.blockNotAllowedPackage(c, NPMProxy, requestPath, notAllowedReason)
}
// Parse the JSON response to extract the version that would be installed
if resolvedVersion != "" && d.maliciousChecker != nil {
slog.Debug("Checking resolved version for malicious package", "package", packageName, "version", resolvedVersion)
isMalicious, entry, err := d.maliciousChecker.IsMalicious(ctx, "npm", packageName, resolvedVersion)
if err != nil {
slog.Error("Error checking malicious package", "proxy", "npm", "error", err)
return echo.NewHTTPError(500, "failed to check if package is malicious").WithInternal(err)
}
if isMalicious {
reason := fmt.Sprintf("Package %s@%s is flagged as malicious (ID: %s)", packageName, resolvedVersion, entry.ID)
if entry.Summary != "" {
reason += ": " + entry.Summary
}
slog.Warn("Blocked malicious package after version resolution", "proxy", "npm", "package", packageName, "version", resolvedVersion, "reason", reason)
return d.blockMaliciousPackage(c, NPMProxy, requestPath, reason)
}
}
}
// Check MinReleaseTime for metadata responses (non-tgz)
if configs.MinReleaseTime > 0 && !hasExplicitVersion && packageName != "" {
if time.Since(releaseTime) > time.Duration(configs.MinReleaseTime)*time.Hour {
return d.blockTooNewPackage(c, NPMProxy, requestPath, releaseTime, configs.MinReleaseTime)
}
}
// Cache successful responses with integrity verification
if err := d.CacheDataWithIntegrity(cachePath, data); err != nil {
slog.Warn("Failed to cache response", "proxy", "npm", "error", err)
}
// Store release time so MinReleaseTime can be enforced on future cache hits
if err := d.CacheReleaseTime(cachePath, releaseTime); err != nil {
slog.Warn("Failed to cache release time", "proxy", "npm", "error", err)
}
// Copy important headers from upstream
if contentType := headers.Get("Content-Type"); contentType != "" {
c.Response().Header().Set("Content-Type", contentType)
}
return d.writeNPMResponse(c, data, requestPath, false)
}
func (d *DependencyProxyController) ProxyNPMAudit(c shared.Context) error {
requestPath := strings.TrimPrefix(c.Request().URL.Path, "/api/v1/dependency-proxy/npm")
ctx, span := depProxyTracer.Start(c.Request().Context(), "dependency-proxy.npm-audit",
trace.WithAttributes(
attribute.String("proxy.ecosystem", "npm-audit"),
attribute.String("proxy.path", requestPath),
),
)
defer span.End()
c.SetRequest(c.Request().WithContext(ctx))
slog.Info("Proxy npm audit request", "method", c.Request().Method, "path", requestPath, "contentType", c.Request().Header.Get("Content-Type"))
// Read the request body
bodyBytes, err := io.ReadAll(c.Request().Body)
if err != nil {
slog.Error("Error reading request body", "proxy", "npm-audit", "error", err)
return echo.NewHTTPError(http.StatusBadRequest, "Failed to read request body")
}
slog.Info("Forwarding npm audit request", "path", requestPath, "bodySize", len(bodyBytes), "body", string(bodyBytes)[:min(len(bodyBytes), 500)])
// Fetch and forward directly without caching
data, headers, statusCode, err := d.fetchNPMAuditFromUpstream(ctx, requestPath, c.Request().Header, bodyBytes)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
slog.Error("Error fetching from upstream", "proxy", "npm-audit", "error", err)
return echo.NewHTTPError(http.StatusBadGateway, "Failed to fetch from upstream")
}
// Forward important headers
for key, values := range headers {
for _, value := range values {
c.Response().Header().Add(key, value)
}
}
fmt.Println(string(data))
return c.Blob(statusCode, headers.Get("Content-Type"), data)
}
func (d *DependencyProxyController) ProxyGo(c shared.Context) error {
path := c.Request().URL.Path
// Get the full path after the prefix
requestPath := TrimProxyPrefix(path, GoProxy)
ctx, span := depProxyTracer.Start(c.Request().Context(), "dependency-proxy.go",
trace.WithAttributes(
attribute.String("proxy.ecosystem", "go"),
attribute.String("proxy.path", requestPath),
attribute.String("http.method", c.Request().Method),
),
)
defer span.End()
c.SetRequest(c.Request().WithContext(ctx))
// Only allow GET and HEAD for Go proxy
if c.Request().Method != http.MethodGet && c.Request().Method != http.MethodHead {
return echo.NewHTTPError(http.StatusMethodNotAllowed, "Method not allowed")
}
configs, err := d.GetDependencyProxyConfigs(c)
if err != nil {
slog.Error("Error getting dependency proxy configs", "error", err)
}
slog.Info("Proxy request", "proxy", "go", "method", c.Request().Method, "path", requestPath)
cachePath := d.getCachePath(GoProxy, requestPath)
packageName, version := d.ParsePackageFromPath(GoProxy, requestPath)
hasExplicitVersion := version != ""
if hasExplicitVersion {
//check config for not allowed patterns before doing anything else to fail fast and avoid unnecessary processing
notAllowed, notAllowedReason := d.CheckNotAllowedPackage(ctx, GoProxy, requestPath, configs)
if notAllowed {
return d.blockNotAllowedPackage(c, GoProxy, requestPath, notAllowedReason)
}
// Check for malicious packages BEFORE checking cache to prevent cache poisoning
if d.maliciousChecker != nil {
if blocked, reason := d.checkMaliciousPackage(c.Request().Context(), GoProxy, requestPath); blocked {
slog.Warn("Blocked malicious package", "proxy", "go", "path", requestPath, "reason", reason)
// Also remove from cache if it exists to prevent serving cached malicious content
cachePath := d.getCachePath(GoProxy, requestPath)
if err := os.Remove(cachePath); err == nil {
slog.Info("Removed malicious package from cache", "path", cachePath)
}
return d.blockMaliciousPackage(c, GoProxy, requestPath, reason)
}
}
// Check cache
if d.isGoCached(cachePath) {
slog.Debug("Cache hit", "proxy", "go", "path", requestPath)
data, err := os.ReadFile(cachePath)
if err == nil {
// Verify cache integrity
if d.VerifyCacheIntegrity(cachePath, data) {
if configs.MinReleaseTime > 0 {
if releaseTime, ok := d.ReadCachedReleaseTime(cachePath); ok {
if time.Since(releaseTime) > time.Duration(configs.MinReleaseTime)*time.Hour {
return d.blockTooNewPackage(c, GoProxy, requestPath, releaseTime, configs.MinReleaseTime)
}
span.SetAttributes(attribute.Bool("proxy.cache_hit", true))
return d.writeGoResponse(c, data, requestPath, true)
}
// No cached release time - fall through to upstream to retrieve it
slog.Debug("No cached release time for MinReleaseTime check, refetching", "proxy", "go", "path", requestPath)
} else {
span.SetAttributes(attribute.Bool("proxy.cache_hit", true))
return d.writeGoResponse(c, data, requestPath, true)
}
} else {
slog.Warn("Cache integrity verification failed, refetching", "proxy", "go", "path", requestPath)
// Remove corrupted cache
os.Remove(cachePath)
os.Remove(cachePath + ".sha256")
}
} else {
slog.Warn("Cache read error", "proxy", "go", "error", err)
}
}
}
span.SetAttributes(attribute.Bool("proxy.cache_hit", false))
// Fetch from upstream
data, headers, statusCode, err := d.fetchFromUpstream(ctx, GoProxy, goProxyURL, requestPath, c.Request().Header, nil)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
slog.Error("Error fetching from upstream", "proxy", "go", "error", err)
return echo.NewHTTPError(http.StatusBadGateway, "Failed to fetch from upstream")
}
if statusCode != http.StatusOK {
slog.Debug("Upstream returned non-OK status", "proxy", "go", "status", statusCode)
// Forward important headers
for key, values := range headers {
for _, value := range values {
c.Response().Header().Add(key, value)
}
}
return c.Blob(statusCode, headers.Get("Content-Type"), data)
}
resolvedVersion, releaseTime, hasReleaseTime := d.ExtractGoVersionAndReleaseTime(data)
// For requests without an explicit version (e.g. /@latest), use the same logic as npm proxy:
// check the resolved version against the allowlist rules and malicious database
if !hasExplicitVersion && resolvedVersion != "" {
notAllowed, notAllowedReason := d.CheckNotAllowedPackage(ctx, GoProxy, packageName+"@"+resolvedVersion, configs)
if notAllowed {
return d.blockNotAllowedPackage(c, GoProxy, requestPath, notAllowedReason)
}
if d.maliciousChecker != nil {
slog.Debug("Checking resolved version for malicious package", "package", packageName, "version", resolvedVersion)
isMalicious, entry, err := d.maliciousChecker.IsMalicious(ctx, "go", packageName, resolvedVersion)
if err != nil {
slog.Error("Error checking malicious package", "proxy", "go", "error", err)
return echo.NewHTTPError(500, "failed to check if package is malicious").WithInternal(err)
}
if isMalicious {
reason := fmt.Sprintf("Package %s@%s is flagged as malicious (ID: %s)", packageName, resolvedVersion, entry.ID)
if entry.Summary != "" {
reason += ": " + entry.Summary
}
slog.Warn("Blocked malicious package after version resolution", "proxy", "go", "package", packageName, "version", resolvedVersion, "reason", reason)
return d.blockMaliciousPackage(c, GoProxy, requestPath, reason)
}
}
}
// Check MinReleaseTime for .info responses or resolved-version responses (e.g. /@latest)
if configs.MinReleaseTime > 0 && hasReleaseTime {
if strings.HasSuffix(requestPath, ".info") || (!hasExplicitVersion && resolvedVersion != "") {
if time.Since(releaseTime) > time.Duration(configs.MinReleaseTime)*time.Hour {
return d.blockTooNewPackage(c, GoProxy, requestPath, releaseTime, configs.MinReleaseTime)
}
}
}
// Cache successful responses with integrity verification
if err := d.CacheDataWithIntegrity(cachePath, data); err != nil {
slog.Warn("Failed to cache response", "proxy", "go", "error", err)
}
// Store release time so MinReleaseTime can be enforced on future cache hits
if hasReleaseTime && (strings.HasSuffix(requestPath, ".info") || (!hasExplicitVersion && resolvedVersion != "")) {
if err := d.CacheReleaseTime(cachePath, releaseTime); err != nil {
slog.Warn("Failed to cache release time", "proxy", "go", "error", err)
}
}
// Copy important headers from upstream
if contentType := headers.Get("Content-Type"); contentType != "" {
c.Response().Header().Set("Content-Type", contentType)
}
if dockerContentDigest := headers.Get("Docker-Content-Digest"); dockerContentDigest != "" {
c.Response().Header().Set("Docker-Content-Digest", dockerContentDigest)
}
return d.writeGoResponse(c, data, requestPath, false)
}
func (d *DependencyProxyController) ProxyPyPI(c shared.Context) error {
// Get the full path after the prefix
requestPath := TrimProxyPrefix(c.Request().URL.Path, PyPIProxy)
ctx, span := depProxyTracer.Start(c.Request().Context(), "dependency-proxy.pypi",
trace.WithAttributes(
attribute.String("proxy.ecosystem", "pypi"),
attribute.String("proxy.path", requestPath),
attribute.String("http.method", c.Request().Method),
),
)
defer span.End()
c.SetRequest(c.Request().WithContext(ctx))
// Only allow GET and HEAD for PyPI proxy
if c.Request().Method != http.MethodGet && c.Request().Method != http.MethodHead {
return echo.NewHTTPError(http.StatusMethodNotAllowed, "Method not allowed")
}
configs, err := d.GetDependencyProxyConfigs(c)
if err != nil {
slog.Error("Error getting dependency proxy configs", "error", err)
}
slog.Info("Proxy request", "proxy", "pypi", "method", c.Request().Method, "path", requestPath)
cachePath := d.getCachePath(PyPIProxy, requestPath)
pkgName, version := d.ParsePackageFromPath(PyPIProxy, requestPath)
hasExplicitVersion := version != ""
if hasExplicitVersion {
//check config for not allowed patterns before doing anything else to fail fast and avoid unnecessary processing
notAllowed, notAllowedReason := d.CheckNotAllowedPackage(ctx, PyPIProxy, requestPath, configs)
if notAllowed {
return d.blockNotAllowedPackage(c, PyPIProxy, requestPath, notAllowedReason)
}
// Check for malicious packages BEFORE checking cache to prevent cache poisoning
if d.maliciousChecker != nil {
if blocked, reason := d.checkMaliciousPackage(c.Request().Context(), PyPIProxy, requestPath); blocked {
slog.Warn("Blocked malicious package", "proxy", "pypi", "path", requestPath, "reason", reason)
// Also remove from cache if it exists to prevent serving cached malicious content
cachePath := d.getCachePath(PyPIProxy, requestPath)
if err := os.Remove(cachePath); err == nil {
slog.Info("Removed malicious package from cache", "path", cachePath)
}
return d.blockMaliciousPackage(c, PyPIProxy, requestPath, reason)
}
}
// Check cache
if d.isPyPICached(cachePath) {
slog.Debug("Cache hit", "proxy", "pypi", "path", requestPath)
data, err := os.ReadFile(cachePath)
if err == nil {
// Verify cache integrity
if d.VerifyCacheIntegrity(cachePath, data) {
if configs.MinReleaseTime > 0 {
if releaseTime, ok := d.ReadCachedReleaseTime(cachePath); ok {
if time.Since(releaseTime) > time.Duration(configs.MinReleaseTime)*time.Hour {
return d.blockTooNewPackage(c, PyPIProxy, requestPath, releaseTime, configs.MinReleaseTime)
}
span.SetAttributes(attribute.Bool("proxy.cache_hit", true))
return d.writePyPIResponse(c, data, requestPath, true)
}
// No cached release time - fall through to upstream to retrieve it
slog.Debug("No cached release time for MinReleaseTime check, refetching", "proxy", "pypi", "path", requestPath)
} else {
span.SetAttributes(attribute.Bool("proxy.cache_hit", true))
return d.writePyPIResponse(c, data, requestPath, true)
}
} else {
slog.Warn("Cache integrity verification failed, refetching", "proxy", "pypi", "path", requestPath)
// Remove corrupted cache
os.Remove(cachePath)
os.Remove(cachePath + ".sha256")
}
} else {
slog.Warn("Cache read error", "proxy", "pypi", "error", err)
}
}
}
span.SetAttributes(attribute.Bool("proxy.cache_hit", false))
// Fetch from upstream (forward User-Agent and Accept headers for PyPI)
data, headers, statusCode, err := d.fetchPyPIFromUpstream(ctx, requestPath, c.Request().Header)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
slog.Error("Error fetching from upstream", "proxy", "pypi", "error", err)
return echo.NewHTTPError(http.StatusBadGateway, "Failed to fetch from upstream")
}
if statusCode != http.StatusOK {
slog.Debug("Upstream returned non-OK status", "proxy", "pypi", "status", statusCode)
// Forward important headers
for key, values := range headers {
for _, value := range values {
c.Response().Header().Add(key, value)
}
}
return c.Blob(statusCode, headers.Get("Content-Type"), data)
}
// For simple/ requests (no explicit version), fetch the PyPI JSON API to get the resolved version —
// same logic as npm proxy: check allowlist rules and malicious database with the resolved version
var pypiReleaseTime time.Time
if !hasExplicitVersion {
resolvedVersion, releaseTime, ok := d.fetchPyPILatestVersionAndReleaseTime(ctx, pkgName)
if ok {
pypiReleaseTime = releaseTime
notAllowed, notAllowedReason := d.CheckNotAllowedPackage(ctx, PyPIProxy, pkgName+"@"+resolvedVersion, configs)
if notAllowed {
return d.blockNotAllowedPackage(c, PyPIProxy, requestPath, notAllowedReason)
}
if d.maliciousChecker != nil {
slog.Debug("Checking resolved version for malicious package", "package", pkgName, "version", resolvedVersion)
isMalicious, entry, err := d.maliciousChecker.IsMalicious(ctx, "pypi", pkgName, resolvedVersion)
if err != nil {
slog.Error("Error checking malicious package", "proxy", "pypi", "error", err)
return echo.NewHTTPError(500, "failed to check if package is malicious").WithInternal(err)
}
if isMalicious {
reason := fmt.Sprintf("Package %s@%s is flagged as malicious (ID: %s)", pkgName, resolvedVersion, entry.ID)
if entry.Summary != "" {
reason += ": " + entry.Summary
}
slog.Warn("Blocked malicious package after version resolution", "proxy", "pypi", "package", pkgName, "version", resolvedVersion, "reason", reason)
return d.blockMaliciousPackage(c, PyPIProxy, requestPath, reason)
}
}
if configs.MinReleaseTime > 0 {
if time.Since(releaseTime) > time.Duration(configs.MinReleaseTime)*time.Hour {
return d.blockTooNewPackage(c, PyPIProxy, requestPath, releaseTime, configs.MinReleaseTime)
}
}
}
}
// Cache successful responses with integrity verification
if err := d.CacheDataWithIntegrity(cachePath, data); err != nil {
slog.Warn("Failed to cache response", "proxy", "pypi", "error", err)
}
// Store release time so MinReleaseTime can be enforced on future cache hits
if !pypiReleaseTime.IsZero() {
if err := d.CacheReleaseTime(cachePath, pypiReleaseTime); err != nil {
slog.Warn("Failed to cache release time", "proxy", "pypi", "error", err)
}
}
// Copy important headers from upstream
if contentType := headers.Get("Content-Type"); contentType != "" {
c.Response().Header().Set("Content-Type", contentType)
}
return d.writePyPIResponse(c, data, requestPath, false)
}
func (d *DependencyProxyController) getCachePath(proxyType ProxyType, requestPath string) string {
cleanPath := strings.TrimPrefix(requestPath, "/")
subDir := string(proxyType)
return filepath.Join(d.cacheDir, subDir, cleanPath)
}
func (d *DependencyProxyController) isNPMCached(cachePath string) bool {
info, err := os.Stat(cachePath)
if err != nil {
return false
}
var maxAge time.Duration
if strings.HasSuffix(cachePath, ".tgz") {
maxAge = 24 * time.Hour
} else {
maxAge = 1 * time.Hour
}
return time.Since(info.ModTime()) < maxAge
}
func (d *DependencyProxyController) isGoCached(cachePath string) bool {
info, err := os.Stat(cachePath)
if err != nil {
return false
}
var maxAge time.Duration
if strings.Contains(cachePath, "/@v/") {
maxAge = 168 * time.Hour // 7 days
} else {
maxAge = 1 * time.Hour
}
return time.Since(info.ModTime()) < maxAge
}
func (d *DependencyProxyController) isPyPICached(cachePath string) bool {
info, err := os.Stat(cachePath)
if err != nil {
return false
}
var maxAge time.Duration
if strings.HasSuffix(cachePath, ".whl") || strings.HasSuffix(cachePath, ".tar.gz") {
maxAge = 168 * time.Hour // 7 days
} else {
maxAge = 1 * time.Hour
}
return time.Since(info.ModTime()) < maxAge
}
func (d *DependencyProxyController) fetchFromUpstream(ctx context.Context, proxyType ProxyType, upstreamURL, requestPath string, headers http.Header, body io.Reader) ([]byte, http.Header, int, error) {
// remove any trailing slashes from requestPath
requestPath = strings.TrimRight(requestPath, "/")
url, err := url.JoinPath(upstreamURL, requestPath)
if err != nil {
return nil, nil, 0, fmt.Errorf("failed to join URL: %w", err)
}
slog.Debug("Fetching from upstream", "proxy", proxyType, "url", url, "bodyPresent", body != nil)
// Determine HTTP method based on body presence
method := "GET"
if body != nil {
method = "POST"
}
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, nil, 0, fmt.Errorf("failed to create request: %w", err)
}
// Forward Content-Type for POST requests
if method == "POST" {
if contentType := headers.Get("Content-Type"); contentType != "" {
req.Header.Set("Content-Type", contentType)
}
}
resp, err := d.client.Do(req)
if err != nil {
return nil, nil, 0, fmt.Errorf("failed to fetch: %w", err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, resp.StatusCode, fmt.Errorf("failed to read response: %w", err)
}
return data, resp.Header, resp.StatusCode, nil
}
func (d *DependencyProxyController) fetchNPMAuditFromUpstream(ctx context.Context, requestPath string, headers http.Header, bodyBytes []byte) ([]byte, http.Header, int, error) {
// remove any trailing slashes from requestPath
requestPath = strings.TrimRight(requestPath, "/")
url, err := url.JoinPath(npmRegistry, requestPath)
if err != nil {
return nil, nil, 0, fmt.Errorf("failed to join URL: %w", err)
}
slog.Info("Fetching npm audit from upstream", "url", url, "bodySize", len(bodyBytes))
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(bodyBytes))
if err != nil {
return nil, nil, 0, fmt.Errorf("failed to create request: %w", err)
}
// Forward Content-Type and Content-Length
if contentType := headers.Get("Content-Type"); contentType != "" {
req.Header.Set("Content-Type", contentType)
} else {
req.Header.Set("Content-Type", "application/json")
}
req.ContentLength = int64(len(bodyBytes))
// Forward Content-Encoding (important for gzipped requests)
if contentEncoding := headers.Get("Content-Encoding"); contentEncoding != "" {
req.Header.Set("Content-Encoding", contentEncoding)
}
// Forward other important headers
if userAgent := headers.Get("User-Agent"); userAgent != "" {
req.Header.Set("User-Agent", userAgent)
}
if accept := headers.Get("Accept"); accept != "" {
req.Header.Set("Accept", accept)
}
if acceptEncoding := headers.Get("Accept-Encoding"); acceptEncoding != "" {
req.Header.Set("Accept-Encoding", acceptEncoding)
}
slog.Debug("Upstream request headers", "Content-Type", req.Header.Get("Content-Type"), "Content-Length", req.ContentLength, "Content-Encoding", req.Header.Get("Content-Encoding"))
resp, err := d.client.Do(req)
if err != nil {
slog.Error("Failed to fetch from npm registry", "error", err, "url", url)
return nil, nil, 0, fmt.Errorf("failed to fetch: %w", err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
slog.Error("Failed to read response body", "error", err, "statusCode", resp.StatusCode)
return nil, nil, resp.StatusCode, fmt.Errorf("failed to read response: %w", err)
}
slog.Info("Upstream response", "statusCode", resp.StatusCode, "responseSize", len(data))
if resp.StatusCode >= 400 {
slog.Error("Upstream error response", "statusCode", resp.StatusCode, "body", string(data)[:min(len(data), 1000)])
}
return data, resp.Header, resp.StatusCode, nil
}
func (d *DependencyProxyController) fetchPyPIFromUpstream(ctx context.Context, requestPath string, headers http.Header) ([]byte, http.Header, int, error) {
// remove any trailing slashes from requestPath
requestPath = strings.TrimRight(requestPath, "/")
url, err := url.JoinPath(pypiRegistry, requestPath)
if err != nil {
return nil, nil, 0, fmt.Errorf("failed to join URL: %w", err)
}
slog.Debug("Fetching from upstream", "proxy", "pypi", "url", url)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, nil, 0, fmt.Errorf("failed to create request: %w", err)
}
// Forward important headers for PyPI
if userAgent := headers.Get("User-Agent"); userAgent != "" {
req.Header.Set("User-Agent", userAgent)
}
if accept := headers.Get("Accept"); accept != "" {
req.Header.Set("Accept", accept)
}
resp, err := d.client.Do(req)
if err != nil {
return nil, nil, 0, fmt.Errorf("failed to fetch: %w", err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, resp.StatusCode, fmt.Errorf("failed to read response: %w", err)
}
return data, resp.Header, resp.StatusCode, nil
}
func (d *DependencyProxyController) cacheData(cachePath string, data []byte) error {
dir := filepath.Dir(cachePath)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
return os.WriteFile(cachePath, data, 0644)
}
// CacheDataWithIntegrity stores data and its SHA256 hash for integrity verification
func (d *DependencyProxyController) CacheDataWithIntegrity(cachePath string, data []byte) error {
// Write the data file
if err := d.cacheData(cachePath, data); err != nil {
return err
}
// Calculate and store SHA256 hash
hash := sha256.Sum256(data)
hashStr := hex.EncodeToString(hash[:])
hashPath := cachePath + ".sha256"
if err := os.WriteFile(hashPath, []byte(hashStr), 0644); err != nil {
slog.Warn("Failed to write integrity hash", "path", hashPath, "error", err)
return err
}
return nil
}
func (d *DependencyProxyController) GetDependencyProxyURLs(ctx shared.Context) error {
//get registry url from env
registryURL := os.Getenv("DEPENDENCY_PROXY_BASE_URL")
if registryURL == "" {
registryURL = "https://api.main.devguard.org/api/v1/dependency-proxy"
}
var secret uuid.UUID
reqCtx := ctx.Request().Context()
if asset, err := shared.MaybeGetAsset(ctx); err == nil {
proxy, err := d.dependencyProxyService.GetOrCreateByAssetID(reqCtx, asset.GetID())
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to get or create dependency proxy for asset: %v", err))
}
secret = proxy.Secret
} else if project, err := shared.MaybeGetProject(ctx); err == nil {
proxy, err := d.dependencyProxyService.GetOrCreateByProjectID(reqCtx, project.GetID())
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to get or create dependency proxy for project: %v", err))
}
secret = proxy.Secret
} else if org, err := shared.MaybeGetOrganization(ctx); err == nil {
proxy, err := d.dependencyProxyService.GetOrCreateByOrgID(reqCtx, org.GetID())
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to get or create dependency proxy for organization: %v", err))
}
secret = proxy.Secret
}
if secret == uuid.Nil {
return echo.NewHTTPError(http.StatusInternalServerError, "failed to determine scope for dependency proxy")
}
proxies := map[string]string{}
proxies["npm"] = registryURL + "/" + secret.String() + "/npm/"
proxies["go"] = registryURL + "/" + secret.String() + "/go/"
proxies["pypi"] = registryURL + "/" + secret.String() + "/pypi/simple/"
return ctx.JSON(http.StatusOK, proxies)
}
func (d *DependencyProxyController) GetDependencyProxyConfigs(c shared.Context) (DependencyProxyConfigs, error) {
var configs DependencyProxyConfigs
secret := c.Param("secret")
uuidSecret, err := uuid.Parse(secret)
if err != nil {
return configs, fmt.Errorf("invalid dependency proxy secret: %w", err)
}
scope, uuid, err := d.dependencyProxyService.GetModelBySecret(c.Request().Context(), uuidSecret)
if err != nil {
return configs, fmt.Errorf("failed to get dependency proxy model by secret: %w", err)
}
var configFilesJSON any
switch scope {
case "asset":
asset, err := d.assetRepository.Read(c.Request().Context(), nil, uuid)
if err != nil {
return configs, fmt.Errorf("failed to read asset: %w", err)
}
configFilesJSON = asset.ConfigFiles["dependency-proxy-configs"]
case "project":
project, err := d.projectRepository.Read(c.Request().Context(), nil, uuid)
if err != nil {
return configs, fmt.Errorf("failed to read project: %w", err)
}
configFilesJSON = project.ConfigFiles["dependency-proxy-configs"]
case "organization":
org, err := d.orgRepository.Read(c.Request().Context(), nil, uuid)
if err != nil {
return configs, fmt.Errorf("failed to read organization: %w", err)
}
configFilesJSON = org.ConfigFiles["dependency-proxy-configs"]
default:
return configs, fmt.Errorf("invalid proxy scope: %s", scope)
}
if configFilesJSON != nil {
s, ok := configFilesJSON.(string)
if !ok {
return configs, fmt.Errorf("unexpected config file json type: %T", configFilesJSON)
}
var raw struct {
Rules string `json:"rules"`
MinReleaseTime int `json:"minReleaseTime"`
}
if err := json.Unmarshal([]byte(s), &raw); err != nil {
return configs, fmt.Errorf("failed to unmarshal config file json into configs: %w", err)
}
configs.MinReleaseTime = raw.MinReleaseTime
for _, line := range strings.Split(raw.Rules, "\n") {
line = strings.TrimSpace(line)
if line != "" && !strings.HasPrefix(line, "#") {
configs.Rules = append(configs.Rules, line)
}
}
}
return configs, nil
}
// CacheReleaseTime stores the release time for a cached entry to enable MinReleaseTime checks on cache hits.
func (d *DependencyProxyController) CacheReleaseTime(cachePath string, releaseTime time.Time) error {
if releaseTime.IsZero() {
return nil
}
return os.WriteFile(cachePath+".releasetime", []byte(releaseTime.UTC().Format(time.RFC3339Nano)), 0644)
}
// ReadCachedReleaseTime reads the stored release time for a cached entry.
func (d *DependencyProxyController) ReadCachedReleaseTime(cachePath string) (time.Time, bool) {
data, err := os.ReadFile(cachePath + ".releasetime")
if err != nil {
return time.Time{}, false
}
t, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(string(data)))
if err != nil {
return time.Time{}, false
}
return t, true
}
// VerifyCacheIntegrity checks if the cached data matches its stored hash
func (d *DependencyProxyController) VerifyCacheIntegrity(cachePath string, data []byte) bool {
hashPath := cachePath + ".sha256"