-
Notifications
You must be signed in to change notification settings - Fork 692
/
RestoreCommand.cs
1657 lines (1404 loc) · 82.2 KB
/
RestoreCommand.cs
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 (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Commands.Restore.Utility;
using NuGet.Common;
using NuGet.DependencyResolver;
using NuGet.Frameworks;
using NuGet.LibraryModel;
using NuGet.Packaging.Core;
using NuGet.ProjectModel;
using NuGet.Protocol.Core.Types;
using NuGet.Repositories;
using NuGet.RuntimeModel;
using NuGet.Versioning;
namespace NuGet.Commands
{
public class RestoreCommand
{
private readonly RestoreCollectorLogger _logger;
private readonly RestoreRequest _request;
private readonly LockFileBuilderCache _lockFileBuilderCache;
private bool _success;
private Guid _operationId;
private readonly Dictionary<RestoreTargetGraph, Dictionary<string, LibraryIncludeFlags>> _includeFlagGraphs
= new Dictionary<RestoreTargetGraph, Dictionary<string, LibraryIncludeFlags>>();
public Guid ParentId { get; }
private const string ProjectRestoreInformation = nameof(ProjectRestoreInformation);
// status names for ProjectRestoreInformation
private const string ErrorCodes = nameof(ErrorCodes);
private const string WarningCodes = nameof(WarningCodes);
private const string RestoreSuccess = nameof(RestoreSuccess);
private const string ProjectFilePath = nameof(ProjectFilePath);
private const string IsCentralVersionManagementEnabled = nameof(IsCentralVersionManagementEnabled);
private const string TotalUniquePackagesCount = nameof(TotalUniquePackagesCount);
private const string NewPackagesInstalledCount = nameof(NewPackagesInstalledCount);
private const string SourcesCount = nameof(SourcesCount);
private const string HttpSourcesCount = nameof(HttpSourcesCount);
private const string LocalSourcesCount = nameof(LocalSourcesCount);
private const string FallbackFoldersCount = nameof(FallbackFoldersCount);
// no-op data names
private const string NoOpDuration = nameof(NoOpDuration);
private const string NoOpResult = nameof(NoOpResult);
private const string NoOpCacheFileEvaluateDuration = nameof(NoOpCacheFileEvaluateDuration);
private const string NoOpCacheFileEvaluationResult = nameof(NoOpCacheFileEvaluationResult);
private const string NoOpRestoreOutputEvaluationDuration = nameof(NoOpRestoreOutputEvaluationDuration);
private const string NoOpRestoreOutputEvaluationResult = nameof(NoOpRestoreOutputEvaluationResult);
private const string NoOpReplayLogsDuration = nameof(NoOpReplayLogsDuration);
private const string NoOpCacheFileAgeDays = nameof(NoOpCacheFileAgeDays);
// lock file data names
private const string EvaluateLockFileDuration = nameof(EvaluateLockFileDuration);
private const string ValidatePackagesShaDuration = nameof(ValidatePackagesShaDuration);
private const string IsLockFileEnabled = nameof(IsLockFileEnabled);
private const string ReadLockFileDuration = nameof(ReadLockFileDuration);
private const string ValidateLockFileDuration = nameof(ValidateLockFileDuration);
private const string IsLockFileValidForRestore = nameof(IsLockFileValidForRestore);
private const string LockFileEvaluationResult = nameof(LockFileEvaluationResult);
// core restore data names
private const string GenerateRestoreGraphDuration = nameof(GenerateRestoreGraphDuration);
private const string CreateRestoreTargetGraphDuration = nameof(CreateRestoreTargetGraphDuration);
private const string CreateAdditionalRestoreTargetGraphDuration = nameof(CreateAdditionalRestoreTargetGraphDuration);
private const string GenerateAssetsFileDuration = nameof(GenerateAssetsFileDuration);
private const string ValidateRestoreGraphsDuration = nameof(ValidateRestoreGraphsDuration);
private const string CreateRestoreResultDuration = nameof(CreateRestoreResultDuration);
private const string IsCentralPackageTransitivePinningEnabled = nameof(IsCentralPackageTransitivePinningEnabled);
private const string UseLegacyDependencyResolver = nameof(UseLegacyDependencyResolver);
private const string UsedLegacyDependencyResolver = nameof(UsedLegacyDependencyResolver);
// PackageSourceMapping names
private const string PackageSourceMappingIsMappingEnabled = "PackageSourceMapping.IsMappingEnabled";
// NuGetAudit names
private const string AuditEnabled = "Audit.Enabled";
private const string AuditLevel = "Audit.Level";
private const string AuditMode = "Audit.Mode";
private const string AuditSuppressedAdvisoriesDefinedCount = "Audit.SuppressedAdvisories.Defined.Count";
private const string AuditSuppressedAdvisoriesTotalWarningsSuppressedCount = "Audit.SuppressedAdvisories.TotalWarningsSuppressed.Count";
private const string AuditSuppressedAdvisoriesDistinctAdvisoriesSuppressedCount = "Audit.SuppressedAdvisories.DistinctAdvisoriesSuppressed.Count";
private const string AuditDataSources = "Audit.DataSources";
private const string AuditDirectVulnerabilitiesPackages = "Audit.Vulnerability.Direct.Packages";
private const string AuditDirectVulnerabilitiesCount = "Audit.Vulnerability.Direct.Count";
private const string AuditDirectVulnerabilitySev0 = "Audit.Vulnerability.Direct.Severity0";
private const string AuditDirectVulnerabilitySev1 = "Audit.Vulnerability.Direct.Severity1";
private const string AuditDirectVulnerabilitySev2 = "Audit.Vulnerability.Direct.Severity2";
private const string AuditDirectVulnerabilitySev3 = "Audit.Vulnerability.Direct.Severity3";
private const string AuditDirectVulnerabilitySevInvalid = "Audit.Vulnerability.Direct.SeverityInvalid";
private const string AuditTransitiveVulnerabilitiesPackages = "Audit.Vulnerability.Transitive.Packages";
private const string AuditTransitiveVulnerabilitiesCount = "Audit.Vulnerability.Transitive.Count";
private const string AuditTransitiveVulnerabilitySev0 = "Audit.Vulnerability.Transitive.Severity0";
private const string AuditTransitiveVulnerabilitySev1 = "Audit.Vulnerability.Transitive.Severity1";
private const string AuditTransitiveVulnerabilitySev2 = "Audit.Vulnerability.Transitive.Severity2";
private const string AuditTransitiveVulnerabilitySev3 = "Audit.Vulnerability.Transitive.Severity3";
private const string AuditTransitiveVulnerabilitySevInvalid = "Audit.Vulnerability.Transitive.SeverityInvalid";
private const string AuditDurationDownload = "Audit.Duration.Download";
private const string AuditDurationCheck = "Audit.Duration.Check";
private const string AuditDurationOutput = "Audit.Duration.Output";
private const string AuditDurationTotal = "Audit.Duration.Total";
private readonly bool _enableNewDependencyResolver;
private readonly bool _isLockFileEnabled;
public RestoreCommand(RestoreRequest request)
{
_request = request ?? throw new ArgumentNullException(nameof(request));
_lockFileBuilderCache = request.LockFileBuilderCache;
// Validate the lock file version requested
if (_request.LockFileVersion < 1 || _request.LockFileVersion > LockFileFormat.Version)
{
Debug.Fail($"Lock file version {_request.LockFileVersion} is not supported.");
throw new ArgumentOutOfRangeException(
paramName: nameof(request),
message: nameof(request.LockFileVersion));
}
var collectorLoggerHideWarningsAndErrors = request.Project.RestoreSettings.HideWarningsAndErrors
|| request.HideWarningsAndErrors;
var collectorLogger = new RestoreCollectorLogger(_request.Log, collectorLoggerHideWarningsAndErrors);
collectorLogger.ApplyRestoreInputs(_request.Project);
_logger = collectorLogger;
ParentId = request.ParentId;
_success = !request.AdditionalMessages?.Any(m => m.Level == LogLevel.Error) ?? true;
_isLockFileEnabled = PackagesLockFileUtilities.IsNuGetLockFileEnabled(_request.Project);
_enableNewDependencyResolver = _request.Project.RuntimeGraph.Supports.Count == 0 && !_isLockFileEnabled && !_request.Project.RestoreMetadata.UseLegacyDependencyResolver;
}
public Task<RestoreResult> ExecuteAsync()
{
return ExecuteAsync(CancellationToken.None);
}
public async Task<RestoreResult> ExecuteAsync(CancellationToken token)
{
using (var telemetry = TelemetryActivity.Create(parentId: ParentId, eventName: ProjectRestoreInformation))
{
telemetry.TelemetryEvent.AddPiiData(ProjectFilePath, _request.Project.FilePath);
bool isPackageSourceMappingEnabled = _request.PackageSourceMapping?.IsEnabled ?? false;
telemetry.TelemetryEvent[PackageSourceMappingIsMappingEnabled] = isPackageSourceMappingEnabled;
telemetry.TelemetryEvent[SourcesCount] = _request.DependencyProviders.RemoteProviders.Count;
int httpSourcesCount = _request.DependencyProviders.RemoteProviders.Where(e => e.IsHttp).Count();
telemetry.TelemetryEvent[HttpSourcesCount] = httpSourcesCount;
telemetry.TelemetryEvent[LocalSourcesCount] = _request.DependencyProviders.RemoteProviders.Count - httpSourcesCount;
telemetry.TelemetryEvent[FallbackFoldersCount] = _request.DependencyProviders.FallbackPackageFolders.Count;
telemetry.TelemetryEvent[IsLockFileEnabled] = _isLockFileEnabled;
telemetry.TelemetryEvent[UseLegacyDependencyResolver] = _request.Project.RestoreMetadata.UseLegacyDependencyResolver;
telemetry.TelemetryEvent[UsedLegacyDependencyResolver] = !_enableNewDependencyResolver;
_operationId = telemetry.OperationId;
var isCpvmEnabled = _request.Project.RestoreMetadata?.CentralPackageVersionsEnabled ?? false;
telemetry.TelemetryEvent[IsCentralVersionManagementEnabled] = isCpvmEnabled;
if (isCpvmEnabled)
{
var isCentralPackageTransitivePinningEnabled = _request.Project.RestoreMetadata?.CentralPackageTransitivePinningEnabled ?? false;
telemetry.TelemetryEvent[IsCentralPackageTransitivePinningEnabled] = isCentralPackageTransitivePinningEnabled;
}
var restoreTime = Stopwatch.StartNew();
// Local package folders (non-sources)
var localRepositories = new List<NuGetv3LocalRepository>
{
_request.DependencyProviders.GlobalPackages
};
localRepositories.AddRange(_request.DependencyProviders.FallbackPackageFolders);
var contextForProject = CreateRemoteWalkContext(_request, _logger);
CacheFile cacheFile = null;
using (telemetry.StartIndependentInterval(NoOpDuration))
{
if (NoOpRestoreUtilities.IsNoOpSupported(_request))
{
telemetry.StartIntervalMeasure();
bool noOp;
TimeSpan? cacheFileAge;
if (NuGetEventSource.IsEnabled) TraceEvents.CalcNoOpRestoreStart(_request.Project.FilePath);
(cacheFile, noOp, cacheFileAge) = EvaluateCacheFile();
if (NuGetEventSource.IsEnabled) TraceEvents.CalcNoOpRestoreStop(_request.Project.FilePath);
telemetry.TelemetryEvent[NoOpCacheFileEvaluationResult] = noOp;
telemetry.EndIntervalMeasure(NoOpCacheFileEvaluateDuration);
if (noOp)
{
telemetry.StartIntervalMeasure();
var noOpSuccess = NoOpRestoreUtilities.VerifyRestoreOutput(_request, cacheFile);
telemetry.EndIntervalMeasure(NoOpRestoreOutputEvaluationDuration);
telemetry.TelemetryEvent[NoOpRestoreOutputEvaluationResult] = noOpSuccess;
if (noOpSuccess)
{
telemetry.StartIntervalMeasure();
// Replay Warnings and Errors from an existing lock file in case of a no-op.
await MSBuildRestoreUtility.ReplayWarningsAndErrorsAsync(cacheFile.LogMessages, _logger);
telemetry.EndIntervalMeasure(NoOpReplayLogsDuration);
restoreTime.Stop();
telemetry.TelemetryEvent[NoOpResult] = true;
telemetry.TelemetryEvent[RestoreSuccess] = _success;
telemetry.TelemetryEvent[TotalUniquePackagesCount] = cacheFile.ExpectedPackageFilePaths?.Count ?? -1;
telemetry.TelemetryEvent[NewPackagesInstalledCount] = 0;
if (cacheFileAge.HasValue) { telemetry.TelemetryEvent[NoOpCacheFileAgeDays] = cacheFileAge.Value.TotalDays; }
return new NoOpRestoreResult(
_success,
_request.LockFilePath,
new Lazy<LockFile>(() => LockFileUtilities.GetLockFile(_request.LockFilePath, _logger)),
cacheFile,
_request.Project.RestoreMetadata.CacheFilePath,
_request.ProjectStyle,
restoreTime.Elapsed);
}
}
}
}
telemetry.TelemetryEvent[NoOpResult] = false; // Getting here means we did not no-op.
if (!await AreCentralVersionRequirementsSatisfiedAsync(_request, httpSourcesCount))
{
// the errors will be added to the assets file
_success = false;
}
if (_request.DependencyProviders.RemoteProviders != null)
{
foreach (var remoteProvider in _request.DependencyProviders.RemoteProviders)
{
var source = remoteProvider.Source;
if (source.IsHttp && !source.IsHttps && !source.AllowInsecureConnections)
{
var isErrorEnabled = SdkAnalysisLevelMinimums.IsEnabled(_request.Project.RestoreMetadata.SdkAnalysisLevel,
_request.Project.RestoreMetadata.UsingMicrosoftNETSdk,
SdkAnalysisLevelMinimums.HttpErrorSdkAnalysisLevelMinimumValue);
if (isErrorEnabled)
{
await _logger.LogAsync(RestoreLogMessage.CreateError(NuGetLogCode.NU1302,
string.Format(CultureInfo.CurrentCulture, Strings.Error_HttpSource_Single, "restore", source.Source)));
}
else
{
await _logger.LogAsync(RestoreLogMessage.CreateWarning(NuGetLogCode.NU1803,
string.Format(CultureInfo.CurrentCulture, Strings.Warning_HttpServerUsage, "restore", source.Source)));
}
}
}
}
_success &= HasValidPlatformVersions();
// evaluate packages.lock.json file
var packagesLockFilePath = PackagesLockFileUtilities.GetNuGetLockFilePath(_request.Project);
var isLockFileValid = false;
PackagesLockFile packagesLockFile = null;
var regenerateLockFile = true;
using (telemetry.StartIndependentInterval(EvaluateLockFileDuration))
{
bool result;
(result, isLockFileValid, packagesLockFile) = await EvaluatePackagesLockFileAsync(packagesLockFilePath, contextForProject, telemetry);
telemetry.TelemetryEvent[IsLockFileValidForRestore] = isLockFileValid;
telemetry.TelemetryEvent[LockFileEvaluationResult] = result;
regenerateLockFile = result; // Ensure that the lock file *does not* get rewritten, when the lock file is out of date and the status is false.
_success &= result;
}
IEnumerable<RestoreTargetGraph> graphs = null;
if (_success)
{
using (telemetry.StartIndependentInterval(GenerateRestoreGraphDuration))
{
if (NuGetEventSource.IsEnabled)
TraceEvents.BuildRestoreGraphStart(_request.Project.FilePath);
if (_enableNewDependencyResolver)
{
graphs = await ExecuteRestoreAsync(_request.DependencyProviders.GlobalPackages, _request.DependencyProviders.FallbackPackageFolders, contextForProject, token, telemetry);
}
else
{
// Restore using the legacy code path if the optimized dependency resolution is disabled.
graphs = await ExecuteLegacyRestoreAsync(_request.DependencyProviders.GlobalPackages, _request.DependencyProviders.FallbackPackageFolders, contextForProject, token, telemetry);
}
if (NuGetEventSource.IsEnabled)
TraceEvents.BuildRestoreGraphStop(_request.Project.FilePath);
}
}
else
{
// Being in an unsuccessful state before ExecuteRestoreAsync means there was a problem with the
// project or we're in locked mode and out of date.
// For example, project TFM or package versions couldn't be parsed. Although the minimal
// fake package spec generated has no packages requested, it also doesn't have any project TFMs
// and will generate validation errors if we tried to call ExecuteRestoreAsync. So, to avoid
// incorrect validation messages, don't try to restore. It is however, the responsibility for the
// caller of RestoreCommand to have provided at least one AdditionalMessage in RestoreArgs.
// The other scenario is when the lock file is not up to date and we're running locked mode.
// In that case we want to write a `target` for each target framework to avoid missing target errors from the SDK build tasks.
var frameworkRuntimePair = CreateFrameworkRuntimePairs(_request.Project, RequestRuntimeUtility.GetRestoreRuntimes(_request));
graphs = frameworkRuntimePair.Select(e =>
{
return RestoreTargetGraph.Create(_request.Project.RuntimeGraph, Enumerable.Empty<GraphNode<RemoteResolveResult>>(), contextForProject, _logger, e.Framework, e.RuntimeIdentifier);
});
}
bool auditEnabled = AuditUtility.ParseEnableValue(
_request.Project.RestoreMetadata?.RestoreAuditProperties,
_request.Project.FilePath,
_logger);
telemetry.TelemetryEvent[AuditEnabled] = auditEnabled ? "enabled" : "disabled";
bool auditRan = false;
if (auditEnabled)
{
auditRan = await PerformAuditAsync(graphs, telemetry, token);
}
telemetry.StartIntervalMeasure();
// Create assets file
if (NuGetEventSource.IsEnabled) TraceEvents.BuildAssetsFileStart(_request.Project.FilePath);
LockFile assetsFile = BuildAssetsFile(
_request.ExistingLockFile,
_request.Project,
graphs,
localRepositories,
contextForProject);
if (NuGetEventSource.IsEnabled) TraceEvents.BuildAssetsFileStop(_request.Project.FilePath);
telemetry.EndIntervalMeasure(GenerateAssetsFileDuration);
IList<CompatibilityCheckResult> checkResults = null;
telemetry.StartIntervalMeasure();
_success &= await ValidateRestoreGraphsAsync(graphs, _logger);
// Check package compatibility
checkResults = await VerifyCompatibilityAsync(
_request.Project,
_includeFlagGraphs,
localRepositories,
assetsFile,
graphs,
_request.ValidateRuntimeAssets,
_logger);
if (checkResults.Any(r => !r.Success))
{
_success = false;
}
telemetry.EndIntervalMeasure(ValidateRestoreGraphsDuration);
// Generate Targets/Props files
var msbuildOutputFiles = Enumerable.Empty<MSBuildOutputFile>();
string assetsFilePath = null;
string cacheFilePath = null;
using (telemetry.StartIndependentInterval(CreateRestoreResultDuration))
{
// Determine the lock file output path
assetsFilePath = GetAssetsFilePath(assetsFile);
// Determine the cache file output path
cacheFilePath = NoOpRestoreUtilities.GetCacheFilePath(_request, assetsFile);
// Tool restores are unique since the output path is not known until after restore
if (_request.LockFilePath == null
&& _request.ProjectStyle == ProjectStyle.DotnetCliTool)
{
_request.LockFilePath = assetsFilePath;
}
if (contextForProject.IsMsBuildBased)
{
msbuildOutputFiles = BuildAssetsUtils.GetMSBuildOutputFiles(
_request.Project,
assetsFile,
graphs,
localRepositories,
_request,
assetsFilePath,
_success,
_logger);
}
// If the request is for a lower lock file version, downgrade it appropriately
DowngradeLockFileIfNeeded(assetsFile);
// Revert to the original case if needed
await FixCaseForLegacyReaders(graphs, assetsFile, token);
// if lock file was still valid then validate package's sha512 hash or else write
// the file if enabled.
if (isLockFileValid)
{
telemetry.StartIntervalMeasure();
// validate package's SHA512
_success &= ValidatePackagesSha512(packagesLockFile, assetsFile);
telemetry.EndIntervalMeasure(ValidatePackagesShaDuration);
// clear out the existing lock file so that we don't over-write the same file
packagesLockFile = null;
}
else if (_isLockFileEnabled)
{
if (regenerateLockFile)
{
// generate packages.lock.json file if enabled
packagesLockFile = new PackagesLockFileBuilder()
.CreateNuGetLockFile(assetsFile);
}
else
{
packagesLockFile = null;
_logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.Log_SkippingPackagesLockFileGeneration, packagesLockFilePath));
}
}
// Write the logs into the assets file
var logsEnumerable = _logger.Errors
.Select(l => AssetsLogMessage.Create(l));
if (_request.AdditionalMessages != null)
{
logsEnumerable = logsEnumerable.Concat(_request.AdditionalMessages);
}
var logs = logsEnumerable
.ToList();
_success &= !logs.Any(l => l.Level == LogLevel.Error);
assetsFile.LogMessages = logs;
if (cacheFile != null)
{
cacheFile.Success = _success;
cacheFile.ProjectFilePath = _request.Project.FilePath;
cacheFile.LogMessages = assetsFile.LogMessages;
cacheFile.ExpectedPackageFilePaths = NoOpRestoreUtilities.GetRestoreOutput(_request, assetsFile);
telemetry.TelemetryEvent[TotalUniquePackagesCount] = cacheFile?.ExpectedPackageFilePaths.Count;
}
var errorCodes = ConcatAsString(new HashSet<NuGetLogCode>(logs.Where(l => l.Level == LogLevel.Error).Select(l => l.Code)));
var warningCodes = ConcatAsString(new HashSet<NuGetLogCode>(logs.Where(l => l.Level == LogLevel.Warning).Select(l => l.Code)));
if (!string.IsNullOrEmpty(errorCodes))
{
telemetry.TelemetryEvent[ErrorCodes] = errorCodes;
}
if (!string.IsNullOrEmpty(warningCodes))
{
telemetry.TelemetryEvent[WarningCodes] = warningCodes;
}
telemetry.TelemetryEvent[NewPackagesInstalledCount] = graphs.Where(g => !g.InConflict).SelectMany(g => g.Install).Distinct().Count();
telemetry.TelemetryEvent[RestoreSuccess] = _success;
}
restoreTime.Stop();
// Create result
return new RestoreResult(
_success,
graphs,
checkResults,
msbuildOutputFiles,
assetsFile,
_request.ExistingLockFile,
assetsFilePath,
cacheFile,
cacheFilePath,
packagesLockFilePath,
packagesLockFile,
dependencyGraphSpecFilePath: NoOpRestoreUtilities.GetPersistedDGSpecFilePath(_request),
dependencyGraphSpec: _request.DependencyGraphSpec,
_request.ProjectStyle,
restoreTime.Elapsed)
{
AuditRan = auditRan
};
}
}
/// <summary>Run NuGetAudit on the project's resolved restore graphs, and log messages and telemetry with the results.</summary>
/// <param name="graphs">The resolved package graphs, one for each project target framework.</param>
/// <param name="telemetry">The <see cref="TelemetryActivity"/> to log NuGetAudit telemetry to.</param>
/// <param name="token">A <see cref="CancellationToken"/> to cancel obtaining a vulnerability database. Once the database is downloaded, audit is quick to complete.</param>
/// <returns>False if no vulnerability database could be found (so packages were not scanned for vulnerabilities), true otherwise.</returns>
private async Task<bool> PerformAuditAsync(IEnumerable<RestoreTargetGraph> graphs, TelemetryActivity telemetry, CancellationToken token)
{
telemetry.StartIntervalMeasure();
var audit = new AuditUtility(
_request.Project.RestoreMetadata.RestoreAuditProperties,
_request.Project.FilePath,
graphs,
_request.DependencyProviders.VulnerabilityInfoProviders,
_logger);
bool auditRan = await audit.CheckPackageVulnerabilitiesAsync(token);
telemetry.TelemetryEvent[AuditLevel] = (int)audit.MinSeverity;
telemetry.TelemetryEvent[AuditMode] = AuditUtility.GetString(audit.AuditMode);
telemetry.TelemetryEvent[AuditSuppressedAdvisoriesDefinedCount] = audit.SuppressedAdvisories?.Count ?? 0;
telemetry.TelemetryEvent[AuditSuppressedAdvisoriesDistinctAdvisoriesSuppressedCount] = audit.DistinctAdvisoriesSuppressedCount;
telemetry.TelemetryEvent[AuditSuppressedAdvisoriesTotalWarningsSuppressedCount] = audit.TotalWarningsSuppressedCount;
if (audit.DirectPackagesWithAdvisory is not null) { AddPackagesList(telemetry, AuditDirectVulnerabilitiesPackages, audit.DirectPackagesWithAdvisory); }
telemetry.TelemetryEvent[AuditDirectVulnerabilitiesCount] = audit.DirectPackagesWithAdvisory?.Count ?? 0;
telemetry.TelemetryEvent[AuditDirectVulnerabilitySev0] = audit.Sev0DirectMatches;
telemetry.TelemetryEvent[AuditDirectVulnerabilitySev1] = audit.Sev1DirectMatches;
telemetry.TelemetryEvent[AuditDirectVulnerabilitySev2] = audit.Sev2DirectMatches;
telemetry.TelemetryEvent[AuditDirectVulnerabilitySev3] = audit.Sev3DirectMatches;
telemetry.TelemetryEvent[AuditDirectVulnerabilitySevInvalid] = audit.InvalidSevDirectMatches;
if (audit.TransitivePackagesWithAdvisory is not null) { AddPackagesList(telemetry, AuditTransitiveVulnerabilitiesPackages, audit.TransitivePackagesWithAdvisory); }
telemetry.TelemetryEvent[AuditTransitiveVulnerabilitiesCount] = audit.TransitivePackagesWithAdvisory?.Count ?? 0;
telemetry.TelemetryEvent[AuditTransitiveVulnerabilitySev0] = audit.Sev0TransitiveMatches;
telemetry.TelemetryEvent[AuditTransitiveVulnerabilitySev1] = audit.Sev1TransitiveMatches;
telemetry.TelemetryEvent[AuditTransitiveVulnerabilitySev2] = audit.Sev2TransitiveMatches;
telemetry.TelemetryEvent[AuditTransitiveVulnerabilitySev3] = audit.Sev3TransitiveMatches;
telemetry.TelemetryEvent[AuditTransitiveVulnerabilitySevInvalid] = audit.InvalidSevTransitiveMatches;
telemetry.TelemetryEvent[AuditDataSources] = audit.SourcesWithVulnerabilityData;
if (audit.DownloadDurationSeconds.HasValue) { telemetry.TelemetryEvent[AuditDurationDownload] = audit.DownloadDurationSeconds.Value; }
if (audit.CheckPackagesDurationSeconds.HasValue) { telemetry.TelemetryEvent[AuditDurationCheck] = audit.CheckPackagesDurationSeconds.Value; }
if (audit.GenerateOutputDurationSeconds.HasValue) { telemetry.TelemetryEvent[AuditDurationOutput] = audit.GenerateOutputDurationSeconds.Value; }
telemetry.EndIntervalMeasure(AuditDurationTotal);
return auditRan;
void AddPackagesList(TelemetryActivity telemetry, string eventName, List<string> packages)
{
List<TelemetryEvent> result = new List<TelemetryEvent>(packages.Count);
foreach (var package in packages)
{
TelemetryEvent packageData = new TelemetryEvent(eventName: string.Empty);
packageData.AddPiiData("id", package);
result.Add(packageData);
}
telemetry.TelemetryEvent.ComplexData[eventName] = result;
}
}
private bool HasValidPlatformVersions()
{
IEnumerable<NuGetFramework> badPlatforms = _request.Project.TargetFrameworks
.Select(frameworkInfo => frameworkInfo.FrameworkName)
.Where(framework => !string.IsNullOrEmpty(framework.Platform) && (framework.PlatformVersion == FrameworkConstants.EmptyVersion));
if (badPlatforms.Any())
{
_logger.Log(RestoreLogMessage.CreateError(
NuGetLogCode.NU1012,
string.Format(CultureInfo.CurrentCulture, Strings.Error_PlatformVersionNotPresent, string.Join(", ", badPlatforms))
));
return false;
}
else
{
return true;
}
}
private async Task<bool> AreCentralVersionRequirementsSatisfiedAsync(RestoreRequest restoreRequest, int httpSourcesCount)
{
if (restoreRequest?.Project?.RestoreMetadata == null || !restoreRequest.Project.RestoreMetadata.CentralPackageVersionsEnabled)
{
return true;
}
IEnumerable<LibraryDependency> dependenciesWithVersionOverride = restoreRequest.Project.TargetFrameworks.SelectMany(tfm => tfm.Dependencies.Where(d => !d.AutoReferenced && d.VersionOverride != null));
if (restoreRequest.Project.RestoreMetadata.CentralPackageVersionOverrideDisabled)
{
// Emit a error if VersionOverride was specified for a package reference but that functionality is disabled
bool hasVersionOverrides = false;
foreach (var item in dependenciesWithVersionOverride)
{
await _logger.LogAsync(RestoreLogMessage.CreateError(NuGetLogCode.NU1013, string.Format(CultureInfo.CurrentCulture, Strings.Error_CentralPackageVersions_VersionOverrideDisabled, item.Name)));
hasVersionOverrides = true;
}
if (hasVersionOverrides)
{
return false;
}
}
if (!restoreRequest.PackageSourceMapping.IsEnabled && httpSourcesCount > 1)
{
// Log a warning if there are more than one configured source and package source mapping is not enabled
await _logger.LogAsync(RestoreLogMessage.CreateWarning(NuGetLogCode.NU1507, string.Format(CultureInfo.CurrentCulture, Strings.Warning_CentralPackageVersions_MultipleSourcesWithoutPackageSourceMapping, httpSourcesCount, string.Join(", ", restoreRequest.DependencyProviders.RemoteProviders.Where(i => i.IsHttp).Select(i => i.Source.Name)))));
}
// The dependencies should not have versions explicitly defined if cpvm is enabled.
IEnumerable<LibraryDependency> dependenciesWithDefinedVersion = _request.Project.TargetFrameworks.SelectMany(tfm => tfm.Dependencies.Where(d => !d.VersionCentrallyManaged && !d.AutoReferenced && d.VersionOverride == null));
if (dependenciesWithDefinedVersion.Any())
{
await _logger.LogAsync(RestoreLogMessage.CreateError(NuGetLogCode.NU1008, string.Format(CultureInfo.CurrentCulture, Strings.Error_CentralPackageVersions_VersionsNotAllowed, string.Join(";", dependenciesWithDefinedVersion.Select(d => d.Name)))));
return false;
}
IEnumerable<LibraryDependency> autoReferencedAndDefinedInCentralFile = _request.Project.TargetFrameworks.SelectMany(tfm => tfm.Dependencies.Where(d => d.AutoReferenced && tfm.CentralPackageVersions.ContainsKey(d.Name)));
if (autoReferencedAndDefinedInCentralFile.Any())
{
await _logger.LogAsync(RestoreLogMessage.CreateError(NuGetLogCode.NU1009, string.Format(CultureInfo.CurrentCulture, Strings.Error_CentralPackageVersions_AutoreferencedReferencesNotAllowed, string.Join(";", autoReferencedAndDefinedInCentralFile.Select(d => d.Name)))));
return false;
}
IEnumerable<LibraryDependency> packageReferencedDependenciesWithoutCentralVersionDefined = _request.Project.TargetFrameworks.SelectMany(tfm => tfm.Dependencies.Where(d => d.LibraryRange.VersionRange == null));
if (packageReferencedDependenciesWithoutCentralVersionDefined.Any())
{
await _logger.LogAsync(RestoreLogMessage.CreateError(NuGetLogCode.NU1010, string.Format(CultureInfo.CurrentCulture, Strings.Error_CentralPackageVersions_MissingPackageVersion, string.Join(";", packageReferencedDependenciesWithoutCentralVersionDefined.Select(d => d.Name)))));
return false;
}
if (!restoreRequest.Project.RestoreMetadata.CentralPackageFloatingVersionsEnabled)
{
var floatingVersionDependencies = _request.Project.TargetFrameworks.SelectMany(tfm => tfm.CentralPackageVersions.Values).Where(cpv => cpv.VersionRange.IsFloating);
if (floatingVersionDependencies.Any())
{
await _logger.LogAsync(RestoreLogMessage.CreateError(NuGetLogCode.NU1011, Strings.Error_CentralPackageVersions_FloatingVersionsAreNotAllowed));
return false;
}
}
return true;
}
private string ConcatAsString<T>(IEnumerable<T> enumerable)
{
string result = null;
if (enumerable != null && enumerable.Any())
{
var builder = new StringBuilder();
foreach (var entry in enumerable)
{
builder.Append(entry.ToString());
builder.Append(";");
}
result = builder.ToString(0, builder.Length - 1);
}
return result;
}
/// <summary>
/// Accounts for using the restore commands on 2 projects living in the same path
/// </summary>
private bool VerifyCacheFileMatchesProject(CacheFile cacheFile)
{
if (_request.Project.RestoreMetadata.ProjectStyle == ProjectStyle.DotnetCliTool)
{
return true;
}
var pathComparer = PathUtility.GetStringComparerBasedOnOS();
return pathComparer.Equals(cacheFile.ProjectFilePath, _request.Project.FilePath);
}
private bool ValidatePackagesSha512(PackagesLockFile lockFile, LockFile assetsFile)
{
var librariesLookUp = lockFile.Targets
.SelectMany(t => t.Dependencies.Where(dep => dep.Type != PackageDependencyType.Project))
.Distinct(LockFileDependencyIdVersionComparer.Default)
.ToDictionary(dep => new PackageIdentity(dep.Id, dep.ResolvedVersion), val => val.ContentHash);
StringBuilder errorMessageBuilder = null;
foreach (var library in assetsFile.Libraries.Where(lib => lib.Type == LibraryType.Package))
{
var package = new PackageIdentity(library.Name, library.Version);
if (!librariesLookUp.TryGetValue(package, out var sha512) || sha512 != library.Sha512)
{
// raise validation error - validate every package regardless of whether we encounter a failure.
if (errorMessageBuilder == null)
{
errorMessageBuilder = new StringBuilder();
}
errorMessageBuilder.AppendLine(string.Format(CultureInfo.CurrentCulture, Strings.Error_PackageValidationFailed, package.ToString()));
_logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.Log_PackageContentHashValidationFailed, package.ToString(), sha512, library.Sha512));
}
}
if (errorMessageBuilder != null)
{
_logger.LogAsync(RestoreLogMessage.CreateError(NuGetLogCode.NU1403, errorMessageBuilder.ToString()));
return false;
}
return true;
}
/// <summary>
/// Evaluate packages.lock.json file if available and accordingly return result.
/// </summary>
/// <param name="packagesLockFilePath"></param>
/// <param name="contextForProject"></param>
/// <returns>result of packages.lock.json file evaluation where
/// success is whether the lock file is in a valid state (ex. locked mode, but not up to date)
/// isLockFileValid tells whether lock file is still valid to be consumed for this restore
/// packagesLockFile is the PackagesLockFile instance
/// </returns>
private async Task<(bool success, bool isLockFileValid, PackagesLockFile packagesLockFile)> EvaluatePackagesLockFileAsync(
string packagesLockFilePath,
RemoteWalkContext contextForProject,
TelemetryActivity lockFileTelemetry)
{
PackagesLockFile packagesLockFile = null;
var isLockFileValid = false;
var success = true;
var restorePackagesWithLockFile = _request.Project.RestoreMetadata?.RestoreLockProperties.RestorePackagesWithLockFile;
if (!MSBuildStringUtility.IsTrueOrEmpty(restorePackagesWithLockFile) && File.Exists(packagesLockFilePath))
{
success = false;
// invalid input since packages.lock.json file exists along with RestorePackagesWithLockFile is set to false.
var message = string.Format(CultureInfo.CurrentCulture, Strings.Error_InvalidLockFileInput, packagesLockFilePath);
// directly log to the request logger when we're not going to rewrite the assets file otherwise this log will
// be skipped for netcore projects.
await _request.Log.LogAsync(RestoreLogMessage.CreateError(NuGetLogCode.NU1005, message));
return (success, isLockFileValid, packagesLockFile);
}
// read packages.lock.json file if exists and RestoreForceEvaluate flag is not set to true
if (!_request.RestoreForceEvaluate && File.Exists(packagesLockFilePath))
{
lockFileTelemetry.StartIntervalMeasure();
packagesLockFile = PackagesLockFileFormat.Read(packagesLockFilePath, _logger);
lockFileTelemetry.EndIntervalMeasure(ReadLockFileDuration);
if (_request.DependencyGraphSpec != null)
{
// check if lock file is out of sync with project data
lockFileTelemetry.StartIntervalMeasure();
LockFileValidationResult lockFileResult = PackagesLockFileUtilities.IsLockFileValid(_request.DependencyGraphSpec, packagesLockFile);
isLockFileValid = lockFileResult.IsValid;
lockFileTelemetry.EndIntervalMeasure(ValidateLockFileDuration);
if (isLockFileValid)
{
// pass lock file details down to generate restore graph
foreach (var target in packagesLockFile.Targets)
{
var libraries = target.Dependencies
.Where(dep => dep.Type != PackageDependencyType.Project)
.Select(dep => new LibraryIdentity(dep.Id, dep.ResolvedVersion, LibraryType.Package))
.ToList();
// add lock file libraries into RemoteWalkContext so that it can be used during restore graph generation
contextForProject.LockFileLibraries.Add(new LockFileCacheKey(target.TargetFramework, target.RuntimeIdentifier), libraries);
}
}
else if (_request.IsRestoreOriginalAction && _request.Project.RestoreMetadata.RestoreLockProperties.RestoreLockedMode)
{
success = false;
var invalidReasons = string.Join(Environment.NewLine, lockFileResult.InvalidReasons);
// bail restore since it's the locked mode but required to update the lock file.
var message = RestoreLogMessage.CreateError(NuGetLogCode.NU1004,
string.Format(
CultureInfo.CurrentCulture,
string.Concat(invalidReasons,
Strings.Error_RestoreInLockedMode)));
await _logger.LogAsync(message);
}
}
}
return (success, isLockFileValid, packagesLockFile);
}
private (CacheFile cacheFile, bool noOp, TimeSpan? cacheFileAge) EvaluateCacheFile()
{
CacheFile cacheFile;
var noOp = false;
TimeSpan? cacheFileAge = null;
var noOpDgSpec = NoOpRestoreUtilities.GetNoOpDgSpec(_request);
if (_request.ProjectStyle == ProjectStyle.DotnetCliTool && _request.AllowNoOp)
{
// No need to attempt to resolve the tool if no-op is not allowed.
NoOpRestoreUtilities.UpdateRequestBestMatchingToolPathsIfAvailable(_request);
}
var newDgSpecHash = noOpDgSpec.GetHash();
// if --force-evaluate flag is passed then restore noop check will also be skipped.
// this will also help us to get rid of -force flag in near future.
// DgSpec doesn't contain log messages, so skip no-op if there are any, as it's not taken into account in the hash
if (_request.AllowNoOp &&
!_request.RestoreForceEvaluate &&
CacheFileExists(_request.Project.RestoreMetadata.CacheFilePath, out cacheFileAge))
{
cacheFile = FileUtility.SafeRead(_request.Project.RestoreMetadata.CacheFilePath, (stream, path) => CacheFileFormat.Read(stream, _logger, path));
if (cacheFile.IsValid && StringComparer.Ordinal.Equals(cacheFile.DgSpecHash, newDgSpecHash) && VerifyCacheFileMatchesProject(cacheFile))
{
_logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.Log_RestoreNoOpFinish, _request.Project.Name));
_success = true;
noOp = true;
}
else
{
cacheFile = new CacheFile(newDgSpecHash);
_logger.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.Log_RestoreNoOpDGChanged, _request.Project.Name));
}
}
else
{
cacheFile = new CacheFile(newDgSpecHash);
}
// DotnetCliTool restores are special because the the assets file location is not known until after the restore itself. So we just clean up.
if (_request.ProjectStyle == ProjectStyle.DotnetCliTool)
{
if (!noOp)
{
// Clean up to preserve the pre no-op behavior. This should not be used, but we want to be cautious.
_request.LockFilePath = null;
_request.Project.RestoreMetadata.CacheFilePath = null;
}
}
return (cacheFile, noOp, cacheFileAge);
static bool CacheFileExists(string path, out TimeSpan? cacheFileAge)
{
cacheFileAge = null;
if (path is null)
{
return false;
}
FileInfo fileInfo = new FileInfo(path);
if (fileInfo.Exists)
{
cacheFileAge = DateTime.UtcNow - fileInfo.LastWriteTimeUtc;
return fileInfo.Exists;
}
return false;
}
}
private string GetAssetsFilePath(LockFile lockFile)
{
var projectLockFilePath = _request.LockFilePath;
if (string.IsNullOrEmpty(projectLockFilePath))
{
if (_request.ProjectStyle == ProjectStyle.PackageReference
|| _request.ProjectStyle == ProjectStyle.DotnetToolReference
|| _request.ProjectStyle == ProjectStyle.Standalone)
{
projectLockFilePath = Path.Combine(_request.RestoreOutputPath, LockFileFormat.AssetsFileName);
}
else if (_request.ProjectStyle == ProjectStyle.DotnetCliTool)
{
var toolName = ToolRestoreUtility.GetToolIdOrNullFromSpec(_request.Project);
var lockFileLibrary = ToolRestoreUtility.GetToolTargetLibrary(lockFile, toolName);
if (lockFileLibrary != null)
{
var version = lockFileLibrary.Version;
var toolPathResolver = new ToolPathResolver(_request.PackagesDirectory);
projectLockFilePath = toolPathResolver.GetLockFilePath(
toolName,
version,
lockFile.Targets.First().TargetFramework);
}
}
else
{
projectLockFilePath = Path.Combine(_request.Project.BaseDirectory, LockFileFormat.LockFileName);
}
}
return Path.GetFullPath(projectLockFilePath);
}
private void DowngradeLockFileIfNeeded(LockFile lockFile)
{
if (_request.LockFileVersion <= 1)
{
DowngradeLockFileToV1(lockFile);
}
}
private async Task FixCaseForLegacyReaders(
IEnumerable<RestoreTargetGraph> graphs,
LockFile lockFile,
CancellationToken token)
{
// The main restore operation restores packages with lowercase ID and version. If the
// restore request is for lowercase packages, then take this additional post-processing
// step.
if (!_request.IsLowercasePackagesDirectory)
{
var originalCase = new OriginalCaseGlobalPackageFolder(_request, _operationId);
// Convert the case of all the packages used in the project restore
await originalCase.CopyPackagesToOriginalCaseAsync(graphs, token);
// Convert the project lock file contents.
originalCase.ConvertLockFileToOriginalCase(lockFile);
}
}
private LockFile BuildAssetsFile(
LockFile existingLockFile,
PackageSpec project,
IEnumerable<RestoreTargetGraph> graphs,
IReadOnlyList<NuGetv3LocalRepository> localRepositories,
RemoteWalkContext contextForProject)
{
// Build the lock file
var lockFile = new LockFileBuilder(_request.LockFileVersion, _logger, _includeFlagGraphs)
.CreateLockFile(
existingLockFile,
project,
graphs,
localRepositories,
contextForProject,
_lockFileBuilderCache);
return lockFile;
}
/// <summary>
/// Check if the given graphs are valid and log errors/warnings.
/// If fatal errors are encountered the rest of the errors/warnings
/// are not logged. This is to avoid flooding the log with long
/// dependency chains for every package.
/// </summary>
private async Task<bool> ValidateRestoreGraphsAsync(IEnumerable<RestoreTargetGraph> graphs, ILogger logger)
{
// Check for cycles
var success = await ValidateCyclesAsync(graphs, logger);
if (success)
{
// Check for conflicts if no cycles existed
success = await ValidateConflictsAsync(graphs, logger);
}
if (success)
{
// Log downgrades if everything else was successful
await LogDowngradeWarningsOrErrorsAsync(graphs, logger);
}
return success;