Repository navigation
Expand file tree
/
Copy pathmanager.go
More file actions
2026 lines (1777 loc) · 65.8 KB
/
Copy pathmanager.go
File metadata and controls
2026 lines (1777 loc) · 65.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package extensions
import (
"context"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash"
"io"
"log"
"maps"
"net/http"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Masterminds/semver/v3"
"github.com/azure/azure-dev/cli/azd/internal/tracing"
"github.com/azure/azure-dev/cli/azd/internal/tracing/events"
"github.com/azure/azure-dev/cli/azd/internal/tracing/fields"
"github.com/azure/azure-dev/cli/azd/pkg/config"
"github.com/azure/azure-dev/cli/azd/pkg/lazy"
"github.com/azure/azure-dev/cli/azd/pkg/osutil"
"github.com/azure/azure-dev/cli/azd/pkg/output"
"github.com/azure/azure-dev/cli/azd/pkg/rzip"
)
const (
extensionRegistryUrl = "https://aka.ms/azd/extensions/registry"
)
var (
ErrExtensionNotFound = errors.New("extension not found")
ErrInstalledExtensionNotFound = errors.New("extension not found")
ErrRegistryExtensionNotFound = errors.New("extension not found in registry")
ErrExtensionInstalled = errors.New("extension already installed")
)
// DependencyNotFoundError indicates that a required dependency of an extension
// could not be located in the parent source or the main azd registry.
type DependencyNotFoundError struct {
// DependencyId is the id of the dependency that could not be resolved.
DependencyId string
// ParentId is the id of the extension that declares the dependency.
ParentId string
}
func (e *DependencyNotFoundError) Error() string {
return fmt.Sprintf("dependency %s required by %s was not found", e.DependencyId, e.ParentId)
}
// Suggestion returns actionable guidance for installing the missing dependency.
func (e *DependencyNotFoundError) Suggestion() string {
return fmt.Sprintf(
"Install the required dependency first with azd extension install %s, then retry.",
e.DependencyId,
)
}
// DependencyVersionNotFoundError indicates that a required dependency exists
// but none of its versions satisfy the constraint declared by its parent.
type DependencyVersionNotFoundError struct {
// DependencyId is the id of the dependency without a matching version.
DependencyId string
// ParentId is the id of the extension that declares the dependency.
ParentId string
// Constraint is the version constraint that could not be satisfied.
Constraint string
}
func (e *DependencyVersionNotFoundError) Error() string {
return fmt.Sprintf(
"dependency %s required by %s was found, but no version satisfies constraint %q",
e.DependencyId, e.ParentId, e.Constraint,
)
}
// Suggestion returns actionable guidance for resolving the dependency constraint.
func (e *DependencyVersionNotFoundError) Suggestion() string {
return fmt.Sprintf(
"Install a version of %s that satisfies constraint %q before retrying, include a compatible version "+
"with %s, or update %s's dependency constraint.",
e.DependencyId, e.Constraint, e.ParentId, e.ParentId,
)
}
// DependencyAzdVersionIncompatibleError indicates that dependency versions
// satisfy the parent's constraint, but none support the running azd version.
type DependencyAzdVersionIncompatibleError struct {
// DependencyId is the id of the incompatible dependency.
DependencyId string
// ParentId is the id of the extension that declares the dependency.
ParentId string
// Constraint is the dependency version constraint declared by the parent.
Constraint string
// RequiredAzdVersion is the azd version constraint declared by the dependency.
RequiredAzdVersion string
}
func (e *DependencyAzdVersionIncompatibleError) Error() string {
return fmt.Sprintf(
"dependency %s required by %s has versions satisfying constraint %q, "+
"but none are compatible with the current azd version",
e.DependencyId, e.ParentId, e.Constraint,
)
}
// Suggestion returns actionable guidance for installing a compatible azd version.
func (e *DependencyAzdVersionIncompatibleError) Suggestion() string {
if e.RequiredAzdVersion == "" {
return "Use an azd version compatible with the dependency, then retry."
}
return fmt.Sprintf(
"Use an azd version that satisfies %q, then retry.",
e.RequiredAzdVersion,
)
}
// DependencyAmbiguousSourceError indicates that a required dependency of an
// extension was found in more than one configured source, so azd cannot decide
// which one to use. The caller must disambiguate by specifying an exact source.
type DependencyAmbiguousSourceError struct {
// DependencyId is the id of the dependency that matched multiple sources.
DependencyId string
// ParentId is the id of the extension that declares the dependency.
ParentId string
// Sources lists the source names the dependency was found in.
Sources []string
}
func (e *DependencyAmbiguousSourceError) Error() string {
if len(e.Sources) > 0 {
return fmt.Sprintf(
"dependency %s required by %s was found in multiple sources (%s); specify an exact source",
e.DependencyId, e.ParentId, strings.Join(e.Sources, ", "),
)
}
return fmt.Sprintf(
"dependency %s required by %s was found in multiple sources; specify an exact source",
e.DependencyId, e.ParentId,
)
}
// dependencySources returns the de-duplicated, sorted source names present in a
// set of extension matches. It is used to report which sources a dependency was
// found in when the match is ambiguous.
func dependencySources(matches []*ExtensionMetadata) []string {
seen := map[string]struct{}{}
for _, m := range matches {
if m.Source != "" {
seen[m.Source] = struct{}{}
}
}
return slices.Sorted(maps.Keys(seen))
}
// ResolveDependency selects metadata for a dependency using the running azd version, preferring
// the parent extension's source and falling back to the main azd registry.
func (m *Manager) ResolveDependency(
ctx context.Context,
parent *ExtensionMetadata,
dependency ExtensionDependency,
) (*ExtensionMetadata, error) {
return m.resolveDependency(ctx, parent, dependency, true, m.azdVersion)
}
func (m *Manager) resolveDependency(
ctx context.Context,
parent *ExtensionMetadata,
dependency ExtensionDependency,
allowMainRegistryFallback bool,
azdVersion *semver.Version,
) (*ExtensionMetadata, error) {
parentSource := parent.Source
if parentSource == "" {
parentSource = MainRegistryName
}
sources := []string{parentSource}
if allowMainRegistryFallback && !strings.EqualFold(parentSource, MainRegistryName) {
sources = append(sources, MainRegistryName)
}
foundWithoutMatchingVersion := false
var incompatibleVersion *ExtensionVersion
for _, source := range sources {
matches, err := m.FindExtensions(ctx, &FilterOptions{
Id: dependency.Id,
Source: source,
})
if err != nil {
return nil, fmt.Errorf("failed to find dependency %s: %w", dependency.Id, err)
}
if len(matches) > 1 {
return nil, &DependencyAmbiguousSourceError{
DependencyId: dependency.Id,
ParentId: parent.Id,
Sources: dependencySources(matches),
}
}
if len(matches) == 0 {
continue
}
publishedVersion := bestSatisfyingVersion(dependency.Version, matches[0].Versions)
if publishedVersion == nil {
foundWithoutMatchingVersion = true
continue
}
if bestSatisfyingVersionForAzd(dependency.Version, matches[0].Versions, azdVersion) != nil {
return matches[0], nil
}
incompatibleVersion = publishedVersion
}
if incompatibleVersion != nil {
return nil, &DependencyAzdVersionIncompatibleError{
DependencyId: dependency.Id,
ParentId: parent.Id,
Constraint: dependency.Version,
RequiredAzdVersion: incompatibleVersion.RequiredAzdVersion,
}
}
if foundWithoutMatchingVersion {
return nil, &DependencyVersionNotFoundError{
DependencyId: dependency.Id,
ParentId: parent.Id,
Constraint: dependency.Version,
}
}
return nil, &DependencyNotFoundError{DependencyId: dependency.Id, ParentId: parent.Id}
}
// FilterOptions controls raw catalogue lookup. It does not apply the manager's azd compatibility policy.
// Install-capable callers should use [InstallResolutionOptions].
type FilterOptions struct {
// Id filters by extension id.
Id string
// Namespace filters by extension namespace.
Namespace string
// Version requires any published version to match the version preference.
Version string
// Source filters by configured source name.
Source string
// SourceConfig restricts lookup to one source that is not persisted or cached.
// It takes precedence over Source.
SourceConfig *SourceConfig
// Tags requires all specified tags.
Tags []string
// Capability requires any published version to declare the capability.
Capability CapabilityType
// Provider requires the release selected without azd compatibility filtering to declare the provider.
Provider string
}
type sourceFilterPredicate func(config *SourceConfig) bool
type extensionFilterPredicate func(extension *ExtensionMetadata) bool
// IsVersionRange reports whether expr is a semver constraint.
// Exact versions, non-semver tags, an empty value, and "latest" are not ranges.
func IsVersionRange(expr string) bool {
if expr == "" || strings.EqualFold(expr, "latest") {
return false
}
if _, err := semver.NewVersion(expr); err == nil {
return false
}
hasWildcardPart := slices.ContainsFunc(strings.Split(expr, "."), func(part string) bool {
return part == "x" || part == "X" || part == "*"
})
return strings.ContainsAny(expr, "<>=^~*, ") ||
strings.Contains(expr, "||") ||
hasWildcardPart
}
// SatisfiesConstraint reports whether an installed version satisfies a declared dependency
// constraint. Empty, "latest", semver constraints, and exact non-semver tags are supported.
func SatisfiesConstraint(constraint, version string) bool {
return matchesVersionConstraint(constraint, version)
}
// matchesVersionConstraint reports whether candidate satisfies expr.
// Empty, "latest", semver constraints, and exact non-semver tags are supported.
func matchesVersionConstraint(expr, candidate string) bool {
if expr == "" || strings.EqualFold(expr, "latest") {
return true
}
constraint, err := semver.NewConstraint(expr)
if err != nil {
return strings.EqualFold(expr, candidate)
}
parsedVersion, err := semver.NewVersion(candidate)
if err != nil {
return strings.EqualFold(expr, candidate)
}
return constraint.Check(parsedVersion)
}
// isDowngrade reports whether moving from current to target is a version regression.
// Returns false if either version is not valid semver.
func isDowngrade(current, target string) bool {
currentSemver, err := semver.NewVersion(current)
if err != nil {
return false
}
targetSemver, err := semver.NewVersion(target)
if err != nil {
return false
}
return targetSemver.LessThan(currentSemver)
}
// bestSatisfyingVersion returns the highest published version satisfying expr.
// Empty or "latest" selects the latest version; non-semver tags use exact match.
func bestSatisfyingVersion(expr string, versions []ExtensionVersion) *ExtensionVersion {
if len(versions) == 0 {
return nil
}
if expr == "" || strings.EqualFold(expr, "latest") {
return LatestVersion(versions)
}
constraint, err := semver.NewConstraint(expr)
if err != nil {
// Non-semver expression: fall back to an exact tag match.
for i := range versions {
if strings.EqualFold(versions[i].Version, expr) {
return &versions[i]
}
}
return nil
}
var best *semver.Version
var bestIdx int
for i := range versions {
v, err := semver.NewVersion(versions[i].Version)
if err != nil {
continue
}
if !constraint.Check(v) {
continue
}
if best == nil || v.GreaterThan(best) {
best = v
bestIdx = i
}
}
if best == nil {
return nil
}
return &versions[bestIdx]
}
func bestSatisfyingVersionForAzd(
expr string,
versions []ExtensionVersion,
azdVersion *semver.Version,
) *ExtensionVersion {
if azdVersion == nil {
return bestSatisfyingVersion(expr, versions)
}
compatible := make([]ExtensionVersion, 0, len(versions))
for i := range versions {
if VersionIsCompatible(&versions[i], azdVersion) {
compatible = append(compatible, versions[i])
}
}
return bestSatisfyingVersion(expr, compatible)
}
// ResolveExtensionVersion selects the highest release that matches versionPreference and azdVersion.
func ResolveExtensionVersion(
extension *ExtensionMetadata,
versionPreference string,
azdVersion *semver.Version,
) (*ExtensionVersion, error) {
if extension == nil {
return nil, fmt.Errorf("extension metadata cannot be nil")
}
selected := bestSatisfyingVersionForAzd(versionPreference, extension.Versions, azdVersion)
if selected != nil {
return selected, nil
}
published := bestSatisfyingVersion(versionPreference, extension.Versions)
if published != nil {
return nil, &ExtensionAzdVersionIncompatibleError{
ExtensionId: extension.Id,
Version: versionPreference,
AzdVersion: azdVersion,
Matches: []*ExtensionMetadata{extension},
}
}
return nil, &ExtensionVersionNotFoundError{
ExtensionId: extension.Id,
Version: versionPreference,
Matches: []*ExtensionMetadata{extension},
AzdVersion: azdVersion,
}
}
// createExtensionFilter creates a comprehensive filter that checks ALL criteria with AND logic
func createExtensionFilter(options *FilterOptions) extensionFilterPredicate {
return func(extension *ExtensionMetadata) bool {
// Check Id filter
if options.Id != "" {
if !strings.EqualFold(extension.Id, options.Id) {
return false
}
}
// Check Namespace filter
if options.Namespace != "" {
if !strings.EqualFold(extension.Namespace, options.Namespace) {
return false
}
}
// Check Version filter - extension must have at least one matching version.
if options.Version != "" && !strings.EqualFold(options.Version, "latest") {
hasVersion := slices.ContainsFunc(extension.Versions, func(version ExtensionVersion) bool {
return matchesVersionConstraint(options.Version, version.Version)
})
if !hasVersion {
return false
}
}
// Check Source filter
if options.Source != "" {
if !strings.EqualFold(extension.Source, options.Source) {
return false
}
}
// Check Tags filter - extension must have ALL specified tags
if len(options.Tags) > 0 {
for _, optionTag := range options.Tags {
hasTag := slices.ContainsFunc(extension.Tags, func(extensionTag string) bool {
return strings.EqualFold(optionTag, extensionTag)
})
if !hasTag {
return false
}
}
}
// Catalogue capability queries match any published version.
if options.Capability != "" {
hasCapability := slices.ContainsFunc(extension.Versions, func(version ExtensionVersion) bool {
return slices.Contains(version.Capabilities, options.Capability)
})
if !hasCapability {
return false
}
}
// Provider queries use the release selected without azd compatibility filtering.
if options.Provider != "" {
selectedVersion, err := ResolveExtensionVersion(extension, options.Version, nil)
if err != nil {
return false
}
if !VersionProvidesProvider(selectedVersion, options.Capability, options.Provider) {
return false
}
}
// All criteria passed
return true
}
}
// Manager is responsible for managing extensions
type Manager struct {
sourceManager *SourceManager
sources []Source
installed map[string]*Extension
configManager config.UserConfigManager
userConfig config.Config
pipeline azruntime.Pipeline
azdVersion *semver.Version
// Lazy runner to avoid circular dependency issues since extension manager is used during command bootstrapping
lazyRunner *lazy.Lazy[*Runner]
}
// ManagerOptions controls extension manager compatibility policy.
type ManagerOptions struct {
// AzdVersion overrides the running azd version used for install resolution.
AzdVersion *semver.Version
// IgnoreAzdCompatibility disables azd compatibility checks.
IgnoreAzdCompatibility bool
}
// NewManager creates a new extension manager
func NewManager(
configManager config.UserConfigManager,
sourceManager *SourceManager,
lazyRunner *lazy.Lazy[*Runner],
transport policy.Transporter,
) (*Manager, error) {
return NewManagerWithOptions(
configManager,
sourceManager,
lazyRunner,
transport,
ManagerOptions{},
)
}
// NewManagerWithOptions creates an extension manager with explicit compatibility policy.
func NewManagerWithOptions(
configManager config.UserConfigManager,
sourceManager *SourceManager,
lazyRunner *lazy.Lazy[*Runner],
transport policy.Transporter,
options ManagerOptions,
) (*Manager, error) {
var azdVersion *semver.Version
if !options.IgnoreAzdCompatibility {
azdVersion = CurrentAzdVersion()
if options.AzdVersion != nil {
azdVersion = options.AzdVersion
}
}
userConfig, err := configManager.Load()
if err != nil {
return nil, err
}
pipeline := azruntime.NewPipeline("azd-extensions", "1.0.0", azruntime.PipelineOptions{}, &policy.ClientOptions{
Transport: transport,
})
return &Manager{
userConfig: userConfig,
configManager: configManager,
sourceManager: sourceManager,
lazyRunner: lazyRunner,
pipeline: pipeline,
azdVersion: azdVersion,
}, nil
}
// AzdVersion returns the version used for extension compatibility checks.
func (m *Manager) AzdVersion() *semver.Version {
return m.azdVersion
}
// ResolveVersion selects an extension release using the manager's compatibility policy.
func (m *Manager) ResolveVersion(
extension *ExtensionMetadata,
versionPreference string,
) (*ExtensionVersion, error) {
return ResolveExtensionVersion(extension, versionPreference, m.azdVersion)
}
// ListInstalled retrieves a list of installed extensions
func (m *Manager) ListInstalled() (map[string]*Extension, error) {
var extensions map[string]*Extension
if m.installed != nil {
return m.installed, nil
}
ok, err := m.userConfig.GetSection(installedConfigKey, &extensions)
if err != nil {
return nil, fmt.Errorf("failed to get extensions section: %w", err)
}
if !ok || extensions == nil {
extensions = map[string]*Extension{}
}
m.installed = extensions
return m.installed, nil
}
// GetInstalled retrieves an installed extension by filter criteria
func (m *Manager) GetInstalled(options FilterOptions) (*Extension, error) {
extensions, err := m.ListInstalled()
if err != nil {
return nil, err
}
isExtensionMatch := createExtensionFilter(&options)
// Convert installed extensions to ExtensionMetadata for filtering
for _, extension := range extensions {
// Create metadata representation for filtering
metadata := &ExtensionMetadata{
Id: extension.Id,
Namespace: extension.Namespace,
Source: extension.Source,
Tags: []string{}, // Installed extensions don't store tags
}
// Apply the same filter logic as other methods
if isExtensionMatch(metadata) {
return extension, nil
}
}
return nil, ErrInstalledExtensionNotFound
}
// IsOfficialRegistrySource verifies the configured source used by an
// installed extension before allowing it to report telemetry.
func (m *Manager) IsOfficialRegistrySource(ctx context.Context, name string) (bool, error) {
if strings.TrimSpace(name) == "" {
return false, nil
}
source, err := m.sourceManager.Get(ctx, name)
if err != nil {
if errors.Is(err, ErrSourceNotFound) {
return false, nil
}
return false, err
}
return IsOfficialMainRegistrySource(source), nil
}
// UpdateInstalled updates an installed extension's metadata in the config
func (m *Manager) UpdateInstalled(extension *Extension) error {
return m.updateInstalled(extension.Id, func(*Extension) *Extension { return extension })
}
// updateInstalled transforms freshly decoded metadata and invalidates the cache after saving.
func (m *Manager) updateInstalled(id string, update func(*Extension) *Extension) error {
var installed map[string]*Extension
_, err := m.userConfig.GetSection(installedConfigKey, &installed)
if err != nil {
return fmt.Errorf("failed to list installed extensions: %w", err)
}
current, exists := installed[id]
if !exists {
return ErrInstalledExtensionNotFound
}
installed[id] = update(current)
previous, _ := m.userConfig.Get(installedConfigKey)
if err := m.userConfig.Set(installedConfigKey, installed); err != nil {
return fmt.Errorf("failed to set extensions section: %w", err)
}
if err := m.configManager.Save(m.userConfig); err != nil {
if restoreErr := m.userConfig.Set(installedConfigKey, previous); restoreErr != nil {
return errors.Join(
fmt.Errorf("failed to save user config: %w", err),
fmt.Errorf("failed to restore installed extension metadata: %w", restoreErr),
)
}
return fmt.Errorf("failed to save user config: %w", err)
}
// Invalidate cache so subsequent calls reflect the updated extension
m.installed = nil
return nil
}
// FindExtensions performs a raw catalogue lookup without applying the manager's azd compatibility policy.
func (m *Manager) FindExtensions(ctx context.Context, options *FilterOptions) ([]*ExtensionMetadata, error) {
allExtensions := []*ExtensionMetadata{}
if options == nil {
options = &FilterOptions{}
}
var sourceFilterPredicate sourceFilterPredicate
if options.Source != "" {
sourceFilterPredicate = func(config *SourceConfig) bool {
return strings.EqualFold(config.Name, options.Source)
}
}
filterOptions := options
if options.SourceConfig != nil {
filterOptionsCopy := *options
filterOptionsCopy.Source = ""
filterOptions = &filterOptionsCopy
}
// Use the centralized extension filter
extensionFilter := createExtensionFilter(filterOptions)
var sources []Source
var err error
if options.SourceConfig != nil {
source, err := m.sourceManager.CreateSource(ctx, options.SourceConfig)
if err != nil {
if schemaErr, ok := errors.AsType[*ErrUnsupportedRegistrySchema](err); ok {
return nil, NewUnsupportedRegistrySchemaError(schemaErr)
}
return nil, fmt.Errorf("failed initializing extension source: %w", err)
}
sources = []Source{source}
} else {
sources, err = m.getSources(ctx, sourceFilterPredicate)
}
if err != nil {
return nil, fmt.Errorf("failed listing extensions: %w", err)
}
for _, source := range sources {
filteredExtensions := []*ExtensionMetadata{}
sourceExtensions, err := source.ListExtensions(ctx)
if err != nil {
return nil, fmt.Errorf("unable to list extension: %w", err)
}
for _, extension := range sourceExtensions {
if extensionFilter(extension) {
filteredExtensions = append(filteredExtensions, extension)
}
}
// Sort by source, then repository path and finally name
slices.SortFunc(filteredExtensions, func(a *ExtensionMetadata, b *ExtensionMetadata) int {
if a.Source != b.Source {
return strings.Compare(a.Source, b.Source)
}
return strings.Compare(a.Id, b.Id)
})
allExtensions = append(allExtensions, filteredExtensions...)
}
return allExtensions, nil
}
// Install installs an extension using the running azd version.
func (m *Manager) Install(
ctx context.Context,
extension *ExtensionMetadata,
versionPreference string,
) (*ExtensionVersion, error) {
return m.InstallWithOptions(ctx, extension, InstallOptions{
VersionPreference: versionPreference,
})
}
// InstallOptions controls how Manager.InstallWithOptions behaves.
type InstallOptions struct {
// VersionPreference is the version constraint or exact tag to install.
// Empty or "latest" selects the highest available version.
VersionPreference string
// SkipDependencies installs only the target extension, without resolving or
// installing its declared dependencies and without enforcing the installed
// dependency version constraints. It is used when the caller only needs the
// extension's own binary (e.g. generating command snapshots) and cannot
// guarantee that the registry's dependency graph is internally consistent.
SkipDependencies bool
// SkipMainRegistryDependencyFallback prevents dependencies missing from the
// parent source from falling back to the main azd registry. Self-contained
// bundle installs use this to remain isolated from network sources.
SkipMainRegistryDependencyFallback bool
}
// InstallWithOptions installs an extension using the supplied options.
func (m *Manager) InstallWithOptions(
ctx context.Context,
extension *ExtensionMetadata,
opts InstallOptions,
) (*ExtensionVersion, error) {
return m.installInternal(ctx, extension, opts, false, false, map[string]struct{}{})
}
// installInternal installs an extension and its dependencies.
// skipDependencyValidation bypasses the installed-dependency constraint check; it is set by the
// upgrade flow so dependency reconciliation can run after the parent has been reinstalled.
// asDependency records that the extension is being installed only because another extension
// requires it; the flag is preserved across upgrades and consulted by PlanUninstall.
// visited contains the ids currently in flight, which prevents dependency cycles.
func (m *Manager) installInternal(
ctx context.Context,
extension *ExtensionMetadata,
opts InstallOptions,
skipDependencyValidation bool,
asDependency bool,
visited map[string]struct{},
) (extVersion *ExtensionVersion, err error) {
if extension == nil {
return nil, fmt.Errorf("extension metadata cannot be nil")
}
if _, inFlight := visited[extension.Id]; inFlight {
return nil, fmt.Errorf(
"dependency cycle detected involving extension %s",
extension.Id,
)
}
visited[extension.Id] = struct{}{}
defer delete(visited, extension.Id)
ctx, span := tracing.Start(ctx, events.ExtensionInstallEvent)
// Set the extension id immediately so failure spans can be correlated to the
// extension being installed. The version is added later, once it has been resolved.
span.SetAttributes(
fields.ExtensionId.String(extension.Id),
fields.ExtensionSourceCategory.String(string(extension.SourceCategoryOrUnknown())),
)
defer func() {
span.EndWithStatus(err)
}()
installed, err := m.GetInstalled(FilterOptions{Id: extension.Id})
if err == nil && installed != nil {
return nil, fmt.Errorf("%s %w", extension.Id, ErrExtensionInstalled)
}
// Resolve to the latest published version that satisfies the preference.
selectedVersion, err := ResolveExtensionVersion(extension, opts.VersionPreference, m.azdVersion)
if err != nil {
return nil, err
}
// Record the resolved version on the span so failures during install
// (artifact download, checksum, copy, config save) still emit it.
span.SetAttributes(fields.ExtensionVersion.String(selectedVersion.Version))
// Binaries are optional as long as dependencies are provided
// This allows for extensions that are just extension packs
if len(selectedVersion.Artifacts) == 0 && len(selectedVersion.Dependencies) == 0 {
return nil, fmt.Errorf("no binaries or dependencies available for this version")
}
// Install dependencies unless the caller opted out. Skipping bypasses both the
// dependency install loop and the installed-dependency constraint check, so the
// target extension installs even when the registry's dependency graph is
// transiently inconsistent (e.g. during a coordinated multi-extension bump).
if !opts.SkipDependencies && len(selectedVersion.Dependencies) > 0 {
for _, dependency := range selectedVersion.Dependencies {
installedDependency, err := m.GetInstalled(FilterOptions{Id: dependency.Id})
if err == nil && installedDependency != nil {
if !skipDependencyValidation &&
dependency.Version != "" &&
!matchesVersionConstraint(dependency.Version, installedDependency.Version) {
return nil, fmt.Errorf(
"installed dependency %s version %s does not satisfy constraint %q",
dependency.Id, installedDependency.Version, dependency.Version,
)
}
continue
}
dependencyMetadata, err := m.resolveDependency(
ctx,
extension,
dependency,
!opts.SkipMainRegistryDependencyFallback,
m.azdVersion,
)
if err != nil {
return nil, err
}
dependencyOpts := InstallOptions{
VersionPreference: dependency.Version,
SkipMainRegistryDependencyFallback: opts.SkipMainRegistryDependencyFallback,
}
if _, err := m.installInternal(ctx, dependencyMetadata, dependencyOpts, false, true, visited); err != nil {
if !errors.Is(err, ErrExtensionInstalled) {
return nil, fmt.Errorf("failed to install dependency: %w", err)
}
}
}
}
hasArtifact := len(selectedVersion.Artifacts) > 0
var relativeExtensionPath string
var targetPath string
// Install the artifacts
if hasArtifact {
// Step 3: Find the artifact for the current OS
artifact, err := findArtifactForCurrentOS(selectedVersion)
if err != nil {
return nil, fmt.Errorf("failed to find artifact for current OS: %w", err)
}
// Step 4: Download the artifact to a temp location
tempFilePath, err := m.downloadArtifact(ctx, artifact.URL)
if err != nil {
return nil, fmt.Errorf("failed to download artifact: %w", err)
}
// Clean up the temp file after all scenarios
defer os.Remove(tempFilePath)
// Step 5: Validate the checksum if provided
if err := validateChecksum(tempFilePath, artifact.Checksum); err != nil {
return nil, fmt.Errorf("checksum validation failed: %w", err)
}
userConfigDir, err := config.GetUserConfigDir()
if err != nil {
return nil, fmt.Errorf("failed to get user config directory: %w", err)
}
targetDir := filepath.Join(userConfigDir, "extensions", extension.Id)
if err := os.MkdirAll(targetDir, os.ModePerm); err != nil {
return nil, fmt.Errorf("failed to create target directory: %w", err)
}
// Step 6: Copy the artifact to the target directory
// Check if artifact is a zip file, if so extract it to the target directory
if strings.HasSuffix(tempFilePath, ".zip") {
if err := rzip.ExtractToDirectory(tempFilePath, targetDir); err != nil {
return nil, fmt.Errorf("failed to extract zip file: %w", err)
}
} else if strings.HasSuffix(tempFilePath, ".tar.gz") {
if err := rzip.ExtractTarGzToDirectory(tempFilePath, targetDir); err != nil {
return nil, fmt.Errorf("failed to extract tar.gz file: %w", err)
}
} else {
targetPath = filepath.Join(targetDir, filepath.Base(tempFilePath))
if err := copyFile(tempFilePath, targetPath); err != nil {
return nil, fmt.Errorf("failed to copy artifact to target location: %w", err)
}
}
entryPoint := selectedVersion.EntryPoint
if platformEntryPoint, has := artifact.AdditionalMetadata["entryPoint"]; has {
entryPoint = fmt.Sprint(platformEntryPoint)
}
if entryPoint == "" {
switch runtime.GOOS {
case "windows":
entryPoint = fmt.Sprintf("%s.exe", extension.Id)
default:
entryPoint = extension.Id
}
}
targetPath := filepath.Join(targetDir, entryPoint)
// Prevent path traversal attacks by ensuring entryPoint stays within the extension install directory
if !osutil.IsPathContained(targetDir, targetPath) {
return nil, fmt.Errorf(
"invalid entry point path: entry point %q resolves outside extension directory. "+
"Use relative paths (e.g., 'bin/myext' or 'bin\\myext') without '..' sequences", entryPoint)
}
// Need to set the executable permission for the binary
// This change is specifically required for Linux but will apply consistently across all platforms
if err := os.Chmod(targetPath, osutil.PermissionExecutableFile); err != nil {
return nil, fmt.Errorf("failed to set executable permission: %w", err)
}
relativeExtensionPath, err = filepath.Rel(userConfigDir, targetPath)
if err != nil {
return nil, fmt.Errorf("failed to get relative path: %w", err)
}
}
// Step 7: Update the user config with the installed extension
extensions, err := m.ListInstalled()
if err != nil {
return nil, fmt.Errorf("failed to list installed extensions: %w", err)
}
extensions[extension.Id] = &Extension{
Id: extension.Id,
Capabilities: selectedVersion.Capabilities,
Namespace: extension.Namespace,
DisplayName: extension.DisplayName,
Description: extension.Description,
Version: selectedVersion.Version,
Usage: selectedVersion.Usage,
Path: relativeExtensionPath,