repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/findOlderVersions_test.go | provider/pkg/versioning/findOlderVersions_test.go | package versioning
import (
"testing"
"time"
"github.com/brianvoe/gofakeit/v6"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/stretchr/testify/assert"
)
func TestFindOlderVersions(t *testing.T) {
moduleA := openapi.ModuleName("moduleA")
resourceA := "resourceA"
resourceB := "resourceB"
olderVersion := fakeApiVersion(FakeApiVersion{})
versionA := fakeApiVersion(FakeApiVersion{GreaterThan: olderVersion})
versionB := fakeApiVersion(FakeApiVersion{GreaterThan: olderVersion})
specVersions := ModuleVersionResources{
moduleA: {
olderVersion: {resourceA: {}, resourceB: {}},
versionA: {resourceA: {}, resourceB: {}},
versionB: {resourceA: {}, resourceB: {}},
},
}
defaultVersions := openapi.DefaultVersions{
moduleA: {
resourceA: openapi.DefinitionVersion{ApiVersion: versionA},
resourceB: openapi.DefinitionVersion{ApiVersion: versionB},
},
}
olderVersions := findOlderVersions(specVersions, defaultVersions)
expected := openapi.ModuleVersionList{
moduleA: {
olderVersion,
},
}
assert.Equal(t, expected, olderVersions, "olderVersion=%s, versionA=%s, versionB=%s", olderVersion, versionA, versionB)
}
type FakeApiVersion struct {
LessThan openapi.ApiVersion
GreaterThan openapi.ApiVersion
}
const ApiVersionLayout = "2006-01-02"
func fakeApiVersion(spec FakeApiVersion) openapi.ApiVersion {
min, _ := time.Parse(ApiVersionLayout, "2000-01-01")
max, _ := time.Parse(ApiVersionLayout, "2100-01-01")
if spec.GreaterThan != "" {
min, _ = time.Parse(ApiVersionLayout, string(spec.GreaterThan))
min = min.AddDate(0, 0, 1)
}
if spec.LessThan != "" {
max, _ = time.Parse(ApiVersionLayout, string(spec.LessThan))
max = max.AddDate(0, 0, -1)
}
return openapi.ApiVersion(gofakeit.DateRange(min, max).Format(ApiVersionLayout))
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/build_schema_test.go | provider/pkg/versioning/build_schema_test.go | package versioning
import (
"fmt"
"os"
"path"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestExampleStability(t *testing.T) {
// These are examples of resources which have been unstable in the docs schema generation in the past.
// We disable these tests to avoid breaking the build. Re-enable them to continue investigating the issues.
t.Skip("Skipping unstable tests")
t.Run("AppPlatform_Deployment", func(t *testing.T) {
testExampleGeneration(t, "AppPlatform", "2023-05-01-preview", "Deployment")
})
t.Run("ApiManagement_WorkspaceApiRelease", func(t *testing.T) {
testExampleGeneration(t, "ApiManagement", "2022-09-01-preview", "WorkspaceApiRelease")
})
t.Run("Authorization_RoleManagementPolicyAssignment", func(t *testing.T) {
testExampleGeneration(t, "Authorization", "2020-10-01", "RoleManagementPolicyAssignment")
})
t.Run("AzureStackHci_UpdateRun", func(t *testing.T) {
testExampleGeneration(t, "AzureStackHCI", "2023-03-01", "UpdateRun")
})
t.Run("DataMigration_ServiceTask", func(t *testing.T) {
testExampleGeneration(t, "DataMigration", "2021-06-30", "ServiceTask")
})
t.Run("MachineLearningServices_LabelingJob", func(t *testing.T) {
// Often hangs - unclear why this is.
t.Skip("Skipping long-running test")
testExampleGeneration(t, "MachineLearningServices", "2023-04-01-preview", "LabelingJob")
})
t.Run("Network_NetworkInterface", func(t *testing.T) {
// Observed failing on 9th iteration
testExampleGeneration(t, "Network", "2023-02-01", "NetworkInterface")
})
}
func testExampleGeneration(t *testing.T, namespace, versionFilter, resource string) {
if t.Skipped() {
return
}
firstRun, err := generateResourceExamples(namespace, versionFilter, resource)
if err != nil {
t.Fatal(err)
}
for i := 0; i < 10; i++ {
secondRun, err := generateResourceExamples(namespace, versionFilter, resource)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, firstRun, secondRun, "Failed on iteration %d", i+1)
if t.Failed() {
return
}
}
}
func generateResourceExamples(namespace, versionFilter, resourceToken string) (string, error) {
wd, err := os.Getwd()
if err != nil {
return "", err
}
rootDir := path.Join(wd, "..", "..", "..")
buildSchemaResult, err := BuildSchema(BuildSchemaArgs{
RootDir: rootDir,
Specs: ReadSpecsArgs{
NamespaceFilter: namespace,
VersionsFilter: versionFilter,
},
ExcludeExplicitVersions: true,
ExampleLanguages: []string{"nodejs", "dotnet", "python", "go", "java", "yaml"},
Version: "2.0.0",
})
if err != nil {
return "", err
}
token := fmt.Sprintf("azure-native:%s:%s", strings.ToLower(namespace), resourceToken)
resource, ok := buildSchemaResult.PackageSpec.Resources[token]
if !ok {
return "", fmt.Errorf("resource %s not found", token)
}
return resource.Description, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/gen_bench_test.go | provider/pkg/versioning/gen_bench_test.go | package versioning
import (
"path"
"testing"
"github.com/blang/semver"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/gen"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
)
// BenchmarkGen benchmarks the generation of the Pulumi schema.
// Run by executing `go test -benchmem -run=^$ -tags all -bench ^BenchmarkGen github.com/pulumi/pulumi-azure-native/v2/provider/pkg/versioning -memprofile=gen.mem.pprof` in the provider folder.
// View results with `go tool pprof -http=: gen.mem.pprof`
func BenchmarkGen(b *testing.B) {
b.ReportAllocs()
rootDir := path.Join("..", "..", "..")
b.ResetTimer()
specs, _, err := openapi.ReadAzureModules(path.Join(rootDir, "azure-rest-api-specs"), "*", "")
if err != nil {
b.Fatal(err)
}
versionSources, err := ReadVersionSources(rootDir, specs, 2)
if err != nil {
b.Fatal(err)
}
versionMetadata, err := calculateVersionMetadata(versionSources)
if err != nil {
b.Fatal(err)
}
specs = openapi.ApplyTransformations(specs, versionMetadata.DefaultVersions, nil, versionSources.RemovedVersions, nil)
gen.PulumiSchema(rootDir, specs, versionMetadata, semver.MustParse("2.0.0"), false /* onlyExplicitVersions */)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/resourceRemoval_test.go | provider/pkg/versioning/resourceRemoval_test.go | // Copyright 2016-2020, Pulumi Corporation.
package versioning
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSqueezePreserve(t *testing.T) {
squeeze := ResourceRemovals{
"azure-native:provider/version1:resourceA": "azure-native:provider/version2:resourceA",
}
squeeze.PreserveResources([]string{
"azure-native:provider/version1:resourceA",
})
assert.Equal(t, squeeze, ResourceRemovals{})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/manualCuration_test.go | provider/pkg/versioning/manualCuration_test.go | package versioning
import (
"testing"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/stretchr/testify/assert"
)
func TestIsExcluded_NoProviders(t *testing.T) {
var curations = make(Curations)
isExcluded, err := curations.IsExcluded("Compute", "someResource", "2020-01-01")
assert.False(t, isExcluded)
assert.Nil(t, err)
}
func TestIsExcluded_NoProviderExclusions(t *testing.T) {
var curations = make(Curations)
curations["Compute"] = moduleCuration{}
isExcluded, err := curations.IsExcluded("Compute", "someResource", "2020-01-01")
assert.False(t, isExcluded)
assert.Nil(t, err)
}
func TestIsExcluded_OtherExclusion(t *testing.T) {
var curations = make(Curations)
curations["Compute"] = moduleCuration{Exclusions: map[string]openapi.ApiVersion{"anotherResource": "*"}}
isExcluded, err := curations.IsExcluded("Compute", "someResource", "2020-01-01")
assert.False(t, isExcluded)
assert.Nil(t, err)
}
func TestIsExcluded_WildcardExclusion(t *testing.T) {
var curations = make(Curations)
curations["Compute"] = moduleCuration{Exclusions: map[string]openapi.ApiVersion{"someResource": "*"}}
isExcluded, err := curations.IsExcluded("Compute", "someResource", "2020-01-01")
assert.True(t, isExcluded)
assert.Nil(t, err)
}
func TestIsExcluded_ExactExclusion(t *testing.T) {
var curations = make(Curations)
curations["Compute"] = moduleCuration{Exclusions: map[string]openapi.ApiVersion{"someResource": "2020-01-01"}}
isExcluded, err := curations.IsExcluded("Compute", "someResource", "2020-01-01")
assert.True(t, isExcluded)
assert.Nil(t, err)
}
func TestIsExcluded_OverExclusion(t *testing.T) {
var curations = make(Curations)
curations["Compute"] = moduleCuration{Exclusions: map[string]openapi.ApiVersion{"someResource": "2022-12-12"}}
isExcluded, err := curations.IsExcluded("Compute", "someResource", "2020-01-01")
assert.True(t, isExcluded)
assert.Nil(t, err)
}
func TestIsExcluded_UnderExclusion(t *testing.T) {
var curations = make(Curations)
curations["Compute"] = moduleCuration{Exclusions: map[string]openapi.ApiVersion{"someResource": "2000-01-01"}}
isExcluded, err := curations.IsExcluded("Compute", "someResource", "2020-01-01")
assert.False(t, isExcluded)
assert.Error(t, err)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/findNewerVersions.go | provider/pkg/versioning/findNewerVersions.go | package versioning
import (
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/collections"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
)
func FindNewerVersions(specVersions ModuleVersionResources, defaultVersions openapi.DefaultVersions) openapi.ModuleVersionList {
olderModuleVersions := openapi.ModuleVersionList{}
for moduleName, versions := range specVersions {
newerVersions := collections.NewOrderableSet[openapi.ApiVersion]()
defaultResourceVersions := defaultVersions[moduleName]
maxCuratedVersion := findMaxDefaultVersion(defaultResourceVersions)
for version := range versions {
if version == "" || version <= maxCuratedVersion {
continue
}
newerVersions.Add(version)
}
olderModuleVersions[moduleName] = newerVersions.SortedValues()
}
return olderModuleVersions
}
func findMaxDefaultVersion(resourceVersions map[openapi.DefinitionName]openapi.DefinitionVersion) openapi.ApiVersion {
// We currently use empty string to represent when there is no version available which must be handled above.
// This might be better being represented as a nil value.
minVersion := openapi.ApiVersion("")
for _, version := range resourceVersions {
if minVersion == "" || version.ApiVersion < minVersion {
minVersion = version.ApiVersion
}
}
return minVersion
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versioning/defaultVersion_test.go | provider/pkg/versioning/defaultVersion_test.go | package versioning
import (
"testing"
"time"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/collections"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/providerlist"
"github.com/stretchr/testify/assert"
)
func TestFindMinimalVersionSet(t *testing.T) {
t.Run("empty", func(t *testing.T) {
actual := findMinimalVersionSet(VersionResources{})
expected := collections.NewOrderableSet[openapi.ApiVersion]()
assert.Equal(t, expected, actual)
})
t.Run("latest superset", func(t *testing.T) {
actual := findMinimalVersionSet(VersionResources{
"2020-01-01": {
"Resource A": {},
},
"2021-02-02": {
"Resource A": {},
"Resource B": {},
},
})
expected := collections.NewOrderableSet[openapi.ApiVersion](
"2021-02-02",
)
assert.Equal(t, expected, actual)
})
t.Run("rollup", func(t *testing.T) {
actual := findMinimalVersionSet(VersionResources{
"2020-01-01": {
"Resource A": {},
"Resource B": {},
},
"2021-02-02": {
"Resource A": {},
},
})
expected := collections.NewOrderableSet[openapi.ApiVersion](
"2020-01-01", "2021-02-02",
)
assert.Equal(t, expected, actual)
})
}
func TestFilterCandidateVersions(t *testing.T) {
emptyBuilder := moduleSpecBuilder{
moduleName: "",
activeVersionChecker: providerlist.ProviderList{}.Index(),
}
someResources := map[openapi.DefinitionName]openapi.DefinitionVersion{
"ResourceA": {
RpNamespace: "Microsoft.Fake",
},
}
t.Run("empty spec", func(t *testing.T) {
actual := emptyBuilder.filterCandidateVersions(VersionResources{}, "")
expected := collections.NewOrderableSet[openapi.ApiVersion]()
assert.Equal(t, expected, actual)
})
t.Run("skips recent preview after recent stable", func(t *testing.T) {
twoMonthsAgo := openapi.ApiVersion(time.Now().Add(-time.Hour * 24 * 30).Format("2006-01-02"))
oneMonthAgo := openapi.ApiVersion(time.Now().Add(-time.Hour * 24 * 30).Format("2006-01-02"))
recentPreview := oneMonthAgo + "-preview"
actual := emptyBuilder.filterCandidateVersions(VersionResources{
twoMonthsAgo: someResources,
recentPreview: someResources,
}, "")
expected := collections.NewOrderableSet(twoMonthsAgo)
assert.Equal(t, expected, actual)
})
t.Run("skips preview which is now stable", func(t *testing.T) {
actual := emptyBuilder.filterCandidateVersions(VersionResources{
"2020-01-01": someResources,
"2020-01-01-preview": someResources,
"2022-02-02": someResources,
}, "")
expected := collections.NewOrderableSet[openapi.ApiVersion]("2020-01-01", "2022-02-02")
assert.Equal(t, expected, actual)
})
t.Run("skips multiple previews recently after a stable", func(t *testing.T) {
actual := emptyBuilder.filterCandidateVersions(VersionResources{
"2020-01-01": someResources,
"2020-01-01-preview": someResources,
"2020-06-01-preview": someResources,
"2022-02-02": someResources,
}, "")
expected := collections.NewOrderableSet[openapi.ApiVersion]("2020-01-01", "2022-02-02")
assert.Equal(t, expected, actual)
})
t.Run("single preview", func(t *testing.T) {
actual := emptyBuilder.filterCandidateVersions(VersionResources{
"2020-01-01-preview": someResources,
}, "")
expected := collections.NewOrderableSet[openapi.ApiVersion]("2020-01-01-preview")
assert.Equal(t, expected, actual)
})
t.Run("only previews", func(t *testing.T) {
actual := emptyBuilder.filterCandidateVersions(VersionResources{
"2020-01-01-preview": someResources,
"2021-01-01-preview": someResources,
}, "")
expected := collections.NewOrderableSet[openapi.ApiVersion]("2020-01-01-preview", "2021-01-01-preview")
assert.Equal(t, expected, actual)
})
t.Run("remove private previews", func(t *testing.T) {
actual := emptyBuilder.filterCandidateVersions(VersionResources{
"2015-01-14-preview": someResources,
"2015-01-14-privatepreview": someResources,
}, "")
expected := collections.NewOrderableSet[openapi.ApiVersion]("2015-01-14-preview")
assert.Equal(t, expected, actual)
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/pcl/utils.go | provider/pkg/pcl/utils.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package pcl
import (
"unicode"
"unicode/utf8"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
"github.com/zclconf/go-cty/cty"
)
// Camel replaces the first contiguous string of upper case runes in the given string with its lower-case equivalent.
func Camel(s string) string {
c, sz := utf8.DecodeRuneInString(s)
if sz == 0 || unicode.IsLower(c) {
return s
}
// The first rune is not lowercase. Iterate until we find a rune that is.
var word []rune
for {
s = s[sz:]
n, nsz := utf8.DecodeRuneInString(s)
if nsz == 0 {
word = append(word, unicode.ToLower(c))
return string(word)
}
if unicode.IsLower(n) {
if len(word) == 0 {
c = unicode.ToLower(c)
}
word = append(word, c)
return string(word) + s
}
c, sz, word = n, nsz, append(word, unicode.ToLower(c))
}
}
// PlainLit returns an unquoted string literal expression.
func PlainLit(v string) *model.LiteralValueExpression {
return &model.LiteralValueExpression{Value: cty.StringVal(v)}
}
// QuotedLit returns a quoted string literal expression.
func QuotedLit(v string) *model.TemplateExpression {
return &model.TemplateExpression{Parts: []model.Expression{PlainLit(v)}}
}
// ObjectConsItem returns a new ObjectConsItem with the given key and value.
func ObjectConsItem(key string, value model.Expression) model.ObjectConsItem {
var keyExpr model.Expression = PlainLit(key)
if !hclsyntax.ValidIdentifier(key) {
keyExpr = QuotedLit(key)
}
return model.ObjectConsItem{
Key: keyExpr,
Value: value,
}
}
// Invoke returns a new function call expression which invokes the specified function.
func Invoke(token string, inputs ...model.ObjectConsItem) *model.FunctionCallExpression {
args := []model.Expression{QuotedLit(token)}
if len(inputs) != 0 {
args = append(args, &model.ObjectConsExpression{Items: inputs})
}
return &model.FunctionCallExpression{
Name: "invoke",
Args: args,
}
}
// RelativeTraversal returns a new RelativeTraversalExpression that accesses the given attribute of the source
// expression.
func RelativeTraversal(source model.Expression, attr string) *model.RelativeTraversalExpression {
return &model.RelativeTraversalExpression{
Source: source,
Traversal: hcl.Traversal{hcl.TraverseAttr{Name: attr}},
Parts: []model.Traversable{model.DynamicType, model.DynamicType},
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/pcl/formatter.go | provider/pkg/pcl/formatter.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package pcl
import (
"strings"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/syntax"
"github.com/zclconf/go-cty/cty"
)
// a formatter formats PCL into a canonical style.
type formatter struct {
indentLevel int
}
// space returns a TriviaList composed of a single space.
func (f *formatter) space() syntax.TriviaList {
return syntax.TriviaList{syntax.NewWhitespace(' ')}
}
// newline returns a TriviaList composed of a single newline.
func (f *formatter) newline() syntax.TriviaList {
return syntax.TriviaList{syntax.NewWhitespace('\n')}
}
// indent returns a TriviaList composed of whitespace that corresponds to the current indent level.
func (f *formatter) indent() syntax.TriviaList {
return syntax.TriviaList{syntax.NewWhitespace([]byte(strings.Repeat("\t", f.indentLevel))...)}
}
// indented increments the indent level, runs the provided function, then decrements the indent level.
func (f *formatter) indented(fn func()) {
f.indentLevel++
defer func() { f.indentLevel-- }()
fn()
}
// formatObjectCons formats an object construction expression.
// - An object with no elements is formatted as `{}`
// - An object with elements is formatted as
//
// {
// key0 = value0,
// ...
// keyN = valueN
// }
//
func (f *formatter) formatObjectCons(x *model.ObjectConsExpression) {
x.Tokens = syntax.NewObjectConsTokens(len(x.Items))
if len(x.Items) == 0 {
x.Tokens.CloseBrace.LeadingTrivia = nil
} else {
x.Tokens.OpenBrace.TrailingTrivia = f.newline()
f.indented(func() {
for i, item := range x.Items {
f.formatExpression(item.Key)
item.Key.SetLeadingTrivia(f.indent())
x.Tokens.Items[i].Equals.LeadingTrivia = f.space()
x.Tokens.Items[i].Equals.TrailingTrivia = f.space()
f.formatExpression(item.Value)
if x.Tokens.Items[i].Comma == nil {
item.Value.SetTrailingTrivia(f.newline())
} else {
x.Tokens.Items[i].Comma.TrailingTrivia = f.newline()
}
}
})
x.Tokens.CloseBrace.LeadingTrivia = f.indent()
}
}
// formatTupleCons formats a tuple construction expression.
// - A tuple with no elements is formatted as `[]`
// - A tuple with one element is formatted as `[value]`
// - A tuple with more than one element is formatted as
//
// [
// value0,
// ...
// valueN
// ]
//
func (f *formatter) formatTupleCons(x *model.TupleConsExpression) {
x.Tokens = syntax.NewTupleConsTokens(len(x.Expressions))
switch len(x.Expressions) {
case 0:
x.Tokens.CloseBracket.LeadingTrivia = nil
case 1:
f.formatExpression(x.Expressions[0])
x.Expressions[0].SetLeadingTrivia(nil)
x.Expressions[0].SetTrailingTrivia(nil)
default:
x.Tokens.OpenBracket.TrailingTrivia = f.newline()
f.indented(func() {
for i, item := range x.Expressions {
f.formatExpression(item)
item.SetLeadingTrivia(f.indent())
if i < len(x.Tokens.Commas) {
x.Tokens.Commas[i].TrailingTrivia = f.newline()
} else {
item.SetTrailingTrivia(f.newline())
}
}
})
x.Tokens.CloseBracket.LeadingTrivia = f.indent()
}
}
// formatExpression formats an expression. Extraneous leading and trailing whitespace is eliminated, and single spaces
// are inserted around specific tokens.
func (f *formatter) formatExpression(x model.Expression) model.Expression {
x.SetLeadingTrivia(nil)
x.SetTrailingTrivia(nil)
switch x := x.(type) {
case *model.AnonymousFunctionExpression:
f.formatExpression(x.Body)
case *model.BinaryOpExpression:
x.Tokens = syntax.NewBinaryOpTokens(x.Operation)
f.formatExpression(x.LeftOperand)
f.formatExpression(x.RightOperand).SetLeadingTrivia(f.space())
case *model.ConditionalExpression:
x.Tokens = syntax.NewConditionalTokens()
f.formatExpression(x.Condition)
f.formatExpression(x.TrueResult).SetLeadingTrivia(f.space())
f.formatExpression(x.FalseResult).SetLeadingTrivia(f.space())
case *model.ForExpression:
keyName := ""
if x.KeyVariable != nil {
keyName = x.KeyVariable.Name
}
x.Tokens = syntax.NewForTokens(keyName, x.ValueVariable.Name, x.Key != nil, x.Group, x.Condition != nil)
f.formatExpression(x.Collection).SetLeadingTrivia(f.space())
if x.Key != nil {
f.formatExpression(x.Key).SetLeadingTrivia(f.space())
}
f.formatExpression(x.Value).SetLeadingTrivia(f.space())
if x.Condition != nil {
f.formatExpression(x.Condition).SetLeadingTrivia(f.space())
}
case *model.FunctionCallExpression:
x.Tokens = syntax.NewFunctionCallTokens(x.Name, len(x.Args))
for i, x := range x.Args {
f.formatExpression(x)
if i > 0 {
x.SetLeadingTrivia(f.space())
}
}
case *model.IndexExpression:
x.Tokens = syntax.NewIndexTokens()
f.formatExpression(x.Collection)
f.formatExpression(x.Key)
case *model.RelativeTraversalExpression:
x.Tokens = syntax.NewRelativeTraversalTokens(x.Traversal)
f.formatExpression(x.Source)
case *model.ScopeTraversalExpression:
x.Tokens = syntax.NewScopeTraversalTokens(x.Traversal)
case *model.SplatExpression:
x.Tokens = syntax.NewSplatTokens(false)
f.formatExpression(x.Source)
f.formatExpression(x.Each)
case *model.TemplateExpression:
x.Tokens = syntax.NewTemplateTokens()
for i, part := range x.Parts {
f.formatExpression(part)
if lit, ok := part.(*model.LiteralValueExpression); ok && lit.Value.Type() == cty.String {
if i > 0 {
part.SetLeadingTrivia(syntax.TriviaList{syntax.NewTemplateDelimiter(hclsyntax.TokenTemplateSeqEnd)})
}
if i < len(x.Parts)-1 {
part.SetTrailingTrivia(syntax.TriviaList{syntax.NewTemplateDelimiter(hclsyntax.TokenTemplateInterp)})
}
}
}
case *model.TemplateJoinExpression:
f.formatExpression(x.Tuple)
case *model.UnaryOpExpression:
x.Tokens = syntax.NewUnaryOpTokens(x.Operation)
f.formatExpression(x.Operand)
case *model.ObjectConsExpression:
f.formatObjectCons(x)
case *model.TupleConsExpression:
f.formatTupleCons(x)
}
return x
}
// formatBlock formats a PCL block as
//
// type labels... {
// item0
// ...
// itemN
// }
//
// Unless the block is the first in its containing body, a newline is inserted before the block.
func (f *formatter) formatBlock(block *model.Block, first bool) {
block.Tokens = syntax.NewBlockTokens(block.Type, block.Labels...)
leadingTrivia := f.indent()
if !first {
leadingTrivia = append(f.newline(), leadingTrivia...)
}
block.Tokens.Type.LeadingTrivia = leadingTrivia
f.indented(func() {
f.formatBody(block.Body)
})
block.Tokens.CloseBrace.LeadingTrivia = f.indent()
block.Tokens.CloseBrace.TrailingTrivia = f.newline()
}
// formatAttribute formats a PCL attribute as
//
// name = value
//
// If the attribute follows a block, a newline is inserted before the attribute.
func (f *formatter) formatAttribute(attr *model.Attribute, afterBlock bool) {
attr.Tokens = syntax.NewAttributeTokens(attr.Name)
leadingTrivia := f.indent()
if afterBlock {
leadingTrivia = append(f.newline(), leadingTrivia...)
}
attr.Tokens.Name.LeadingTrivia = leadingTrivia
f.formatExpression(attr.Value)
attr.Value.SetLeadingTrivia(f.space())
attr.Value.SetTrailingTrivia(f.newline())
}
// formatBody formats a PCL body.
func (f *formatter) formatBody(body *model.Body) {
first, afterBlock := true, false
for _, item := range body.Items {
switch item := item.(type) {
case *model.Block:
f.formatBlock(item, first)
afterBlock = true
case *model.Attribute:
f.formatAttribute(item, afterBlock)
afterBlock = false
}
first = false
}
}
// FormatBody formats a PCL body.
func FormatBody(body *model.Body) {
var f formatter
f.formatBody(body)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/pcl/pcl.go | provider/pkg/pcl/pcl.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package pcl
import (
"reflect"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/zclconf/go-cty/cty"
)
// null represents PCL's builtin `null` variable
var null = &model.Variable{
Name: "null",
VariableType: model.NoneType,
}
// RenderValue renders an object that represents a json value into PCL. Most nodes are rendered as one
// would expect (e.g. sequences -> tuple construction, maps -> object construction, etc.).
func RenderValue(node interface{}) (model.Expression, error) {
if node == nil {
return model.VariableReference(null), nil
}
typ := reflect.TypeOf(node)
val := reflect.ValueOf(node)
kind := typ.Kind()
switch kind {
case reflect.Slice:
var expressions []model.Expression
for i := 0; i < val.Len(); i++ {
e, err := RenderValue(val.Index(i).Interface())
if err != nil {
return nil, err
}
expressions = append(expressions, e)
}
return &model.TupleConsExpression{
Expressions: expressions,
}, nil
case reflect.Bool:
b := reflect.ValueOf(node).Bool()
return &model.LiteralValueExpression{
Value: cty.BoolVal(b),
}, nil
case reflect.Float32, reflect.Float64:
return &model.LiteralValueExpression{
Value: cty.NumberFloatVal(val.Float()),
}, nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return &model.LiteralValueExpression{Value: cty.NumberIntVal(val.Int())}, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return &model.LiteralValueExpression{Value: cty.NumberUIntVal(val.Uint())}, nil
case reflect.String:
return QuotedLit(val.String()), nil
case reflect.Map:
consItems := map[string]model.Expression{}
iter := val.MapRange()
for iter.Next() {
k := iter.Key()
v := iter.Value()
rendered, err := RenderValue(v.Interface())
if err != nil {
return nil, err
}
consItems[k.String()] = rendered
}
var items []model.ObjectConsItem
for k, v := range util.MapOrdered(consItems) {
items = append(items, ObjectConsItem(k, v))
}
return &model.ObjectConsExpression{
Items: items,
}, nil
case reflect.Ptr:
nodeExpr, ok := node.(model.Expression)
if !ok {
// only expect model.Expression as the embedded interface
panic(val)
}
return nodeExpr, nil
default:
contract.Failf("unexpected type %T", node)
return nil, nil
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/client.go | provider/pkg/azure/client.go | package azure
import (
"context"
)
type AzureDeleter interface {
Delete(ctx context.Context, id, apiVersion, asyncStyle string, queryParams map[string]any) error
}
type AzureClient interface {
AzureDeleter
CanCreate(ctx context.Context, id, path, apiVersion, readMethod string, isSingletonResource, hasDefaultBody bool, isDefaultResponse func(map[string]any) bool) error
Get(ctx context.Context, id string, apiVersion string, queryParams map[string]any) (map[string]any, error)
Head(ctx context.Context, id string, apiVersion string) error
Patch(ctx context.Context, id string, bodyProps map[string]interface{}, queryParameters map[string]interface{}, asyncStyle string) (map[string]interface{}, bool, error)
Post(ctx context.Context, id string, bodyProps map[string]interface{}, queryParameters map[string]interface{}) (any, error)
Put(ctx context.Context, id string, bodyProps map[string]interface{}, queryParameters map[string]interface{}, asyncStyle string) (map[string]interface{}, bool, error)
}
// MockAzureClient implements the AzureClient interface for tests.
type MockAzureClient struct {
// Resource ids that were retrieved via Get, in order
GetIds []string
// API versions that were used in Get, in order
GetApiVersions []string
// If set, this response will be returned for all Get requests; otherwise nil.
GetResponse map[string]any
GetResponseErr error
// Resource ids that were used in Post, in order
PostIds []string
// Bodies that were sent via Post, in order
PostBodies []map[string]any
// Resource ids that were used in Put, in order
PutIds []string
// Bodies that were sent via Put, in order
PutBodies []map[string]any
PutResponseErr error
QueryParamsOfLastDelete map[string]any
}
func (m *MockAzureClient) Delete(ctx context.Context, id, apiVersion, asyncStyle string, queryParams map[string]any) error {
m.QueryParamsOfLastDelete = queryParams
return nil
}
func (m *MockAzureClient) CanCreate(ctx context.Context, id, path, apiVersion, readMethod string, isSingletonResource, hasDefaultBody bool, isDefaultResponse func(map[string]any) bool) error {
return nil
}
func (m *MockAzureClient) Get(ctx context.Context, id string, apiVersion string, queryParams map[string]any) (map[string]any, error) {
m.GetIds = append(m.GetIds, id)
m.GetApiVersions = append(m.GetApiVersions, apiVersion)
return m.GetResponse, m.GetResponseErr
}
func (m *MockAzureClient) Head(ctx context.Context, id string, apiVersion string) error {
return nil
}
func (m *MockAzureClient) Patch(ctx context.Context, id string, bodyProps map[string]interface{}, queryParameters map[string]interface{}, asyncStyle string) (map[string]interface{}, bool, error) {
return nil, false, nil
}
func (m *MockAzureClient) Post(ctx context.Context, id string, bodyProps map[string]interface{}, queryParameters map[string]interface{}) (any, error) {
m.PostIds = append(m.PostIds, id)
m.PostBodies = append(m.PostBodies, bodyProps)
return map[string]any{}, nil
}
func (m *MockAzureClient) Put(ctx context.Context, id string, bodyProps map[string]interface{}, queryParameters map[string]interface{}, asyncStyle string) (map[string]interface{}, bool, error) {
m.PutIds = append(m.PutIds, id)
m.PutBodies = append(m.PutBodies, bodyProps)
return nil, false, m.PutResponseErr
}
func (m *MockAzureClient) IsNotFound(err error) bool {
return false
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/client_azcore.go | provider/pkg/azure/client_azcore.go | // Copyright 2016-2024, Pulumi Corporation.
package azure
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/fake"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/version"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
type azCoreClient struct {
host string
pipeline runtime.Pipeline
extraUserAgent string
// Exposed internally for tests, to set it at the minimum value for fast tests.
deletePollingIntervalSeconds int64
updatePollingIntervalSeconds int64
// Serialization for resources that have hit "exclusive lock" 429 errors.
// Maps serialization key (e.g., App Service Plan ID) to a mutex that serializes operations.
// This allows parallel operations across different App Service Plans while serializing
// operations within the same App Service Plan.
serializationsMap map[string]*sync.Mutex
serializationsMapMutex sync.Mutex
}
func initPipelineOpts(azureCloud cloud.Configuration, opts *arm.ClientOptions) *arm.ClientOptions {
if opts == nil {
opts = &arm.ClientOptions{
ClientOptions: policy.ClientOptions{
Cloud: azureCloud,
Telemetry: policy.TelemetryOptions{
ApplicationID: fmt.Sprintf("pulumi-azure-native/%s", version.Version),
},
},
}
}
// azcore logging will only happen at log level 9.
opts.Logging.IncludeBody = true
// We're trying to configure retries to be similar to the previous Autorest client. The backoff
// algorithms are hard-coded so they can't be identical.
// The previous backoff sequence was 30s, 60s, 120s.
// The new backoff sequence is 20s, 60s, 120s.
// It's notable, however, that the azcore default backoff sequence is only 1s, 3s, 7s. We might
// consider moving a bit towards a faster sequence, e.g. 10s, 30s, 70s.
opts.Retry.RetryDelay = 20 * time.Second
opts.Retry.MaxRetryDelay = 120 * time.Second
// These are the same as the default values in sdk/azcore/runtime/policy_retry.go setDefaults
retryableStatusCodes := []int{
http.StatusRequestTimeout, // 408
http.StatusTooManyRequests, // 429
http.StatusInternalServerError, // 500
http.StatusBadGateway, // 502
http.StatusServiceUnavailable, // 503
http.StatusGatewayTimeout, // 504
}
opts.Retry.ShouldRetry = func(resp *http.Response, err error) bool {
if err != nil {
return true
}
// Replicate default retry behaviour first.
if runtime.HasStatusCode(resp, retryableStatusCodes...) {
return true
}
if shouldRetryConflict(resp) {
return true
}
return false
}
return opts
}
// NewAzCoreClient creates a new AzureClient using the azcore SDK. For general use, leave userOpts
// nil to use the default options. If you do set it, make sure to set its ClientOptions.Cloud field.
func NewAzCoreClient(tokenCredential azcore.TokenCredential, extraUserAgent string, azureCloud cloud.Configuration, userOpts *arm.ClientOptions,
) (AzureClient, error) {
// Hook our logging up to the azcore logger.
log.SetListener(func(event log.Event, msg string) {
// Retry logging is very verbose and the number of the retry attempt is already contained
// in the response event.
if event != log.EventRetryPolicy {
logging.V(9).Infof("[azcore] %v: %s", event, msg)
}
})
opts := initPipelineOpts(azureCloud, userOpts)
pipeline, err := armruntime.NewPipeline("azcore", "v1.17.0", tokenCredential,
runtime.PipelineOptions{}, opts)
if err != nil {
return nil, err
}
return &azCoreClient{
host: azureCloud.Services[cloud.ResourceManager].Endpoint,
pipeline: pipeline,
extraUserAgent: extraUserAgent,
deletePollingIntervalSeconds: 30, // same as autorest.DefaultPollingDelay
updatePollingIntervalSeconds: 10,
serializationsMap: make(map[string]*sync.Mutex),
}, nil
}
func shouldRetryConflict(resp *http.Response) bool {
if runtime.HasStatusCode(resp, http.StatusConflict) {
err := runtime.NewResponseError(resp)
if responseErr, ok := err.(*azcore.ResponseError); ok {
if responseErr.ErrorCode == "AnotherOperationInProgress" {
return true
}
// Azure doesn't allow concurrent creation of FederatedIdentityCredential for a given managed identity
// https://github.com/pulumi/pulumi-azure-native/issues/4343
if responseErr.ErrorCode == "ConcurrentFederatedIdentityCredentialsWritesForSingleManagedIdentity" {
return true
}
}
}
return false
}
func (c *azCoreClient) setHeaders(req *policy.Request, contentTypeJson bool) {
req.Raw().Header.Set("Accept", "application/json")
req.Raw().Header.Set("User-Agent", c.extraUserAgent) // note: azure-sdk-for-go will append standard info to this header
if contentTypeJson {
req.Raw().Header.Set("Content-Type", "application/json; charset=utf-8")
}
}
func (c *azCoreClient) initRequest(ctx context.Context, method, id string, queryParams map[string]any) (*policy.Request, error) {
req, err := runtime.NewRequest(ctx, method, runtime.JoinPaths(c.host, id))
if err != nil {
return nil, err
}
c.setHeaders(req, method == http.MethodPost || method == http.MethodPut || method == http.MethodPatch)
urlValues := MapToValues(queryParams)
// URL-unescape each value before encoding the URL (which encodes all values). Presumably, this
// prevents double-encoding. It's not clear to me that this is necessary but Autorest does it and
// we want to match behavior here as closely as possible.
for key, value := range urlValues {
for i := range value {
d, err := url.QueryUnescape(value[i])
if err != nil {
return nil, err
}
value[i] = d
}
urlValues[key] = value
}
req.Raw().URL.RawQuery = urlValues.Encode()
return req, nil
}
func (c *azCoreClient) Get(ctx context.Context, id, apiVersion string, queryParams map[string]any) (map[string]any, error) {
queryParameters := map[string]any{
"api-version": apiVersion,
}
for k, v := range queryParams {
queryParameters[k] = v
}
req, err := c.initRequest(ctx, http.MethodGet, id, queryParameters)
if err != nil {
return nil, err
}
resp, err := c.pipeline.Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(resp, http.StatusOK) {
return nil, newResponseError(resp)
}
var responseBody map[string]any
if err := runtime.UnmarshalAsJSON(resp, &responseBody); err != nil {
return nil, handleAzCoreResponseError(err, resp)
}
return responseBody, nil
}
func (c *azCoreClient) Delete(ctx context.Context, id, apiVersion, asyncStyle string, queryParams map[string]any,
) error {
queryParameters := map[string]interface{}{
"api-version": apiVersion,
}
for k, v := range queryParams {
queryParameters[k] = v
}
// See if we need to serialize requests due to parallelization limitations in the AZ Core SDK.
serializationMutex := c.checkForSerializationDelete(ctx, id, apiVersion, queryParameters)
req, err := c.initRequest(ctx, http.MethodDelete, id, queryParameters)
if err != nil {
return err
}
if serializationMutex != nil {
serializationMutex.Lock()
defer serializationMutex.Unlock()
}
err = func() error {
resp, err := c.pipeline.Do(req)
if err != nil {
return err
}
if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
return runtime.NewResponseError(resp)
}
// Some APIs are explicitly marked `x-ms-long-running-operation` and we should only do the
// poll for the deletion result in that case.
if asyncStyle != "" {
pt, err := runtime.NewPoller[any](resp, c.pipeline, nil)
if err != nil {
return err
}
_, err = pt.PollUntilDone(ctx, &runtime.PollUntilDoneOptions{
Frequency: time.Duration(c.deletePollingIntervalSeconds * int64(time.Second)),
})
return err
}
return nil
}()
if err, ok := err.(*azcore.ResponseError); ok {
if err.StatusCode == http.StatusNotFound {
// If the resource is already deleted, we don't want to return an error.
return nil
}
return newResponseError(err.RawResponse)
}
return err
}
func (c *azCoreClient) Put(ctx context.Context, id string, bodyProps map[string]interface{},
queryParameters map[string]interface{}, asyncStyle string,
) (map[string]interface{}, bool, error) {
return c.putOrPatch(ctx, http.MethodPut, id, bodyProps, queryParameters, asyncStyle)
}
func (c *azCoreClient) Patch(ctx context.Context, id string, bodyProps map[string]interface{},
queryParameters map[string]interface{}, asyncStyle string,
) (map[string]interface{}, bool, error) {
return c.putOrPatch(ctx, http.MethodPatch, id, bodyProps, queryParameters, asyncStyle)
}
func (c *azCoreClient) putOrPatch(ctx context.Context, method string, id string, bodyProps map[string]any,
queryParameters map[string]any, asyncStyle string,
) (map[string]any, bool, error) {
if method != http.MethodPut && method != http.MethodPatch {
return nil, false, fmt.Errorf("method must be PUT or PATCH, got %s. Please report this issue", method)
}
// See if we need to serialize requests due to parallelization limitations in the AZ Core SDK.
serializationMutex := c.checkForSerializationPutOrPatch(id, bodyProps)
req, err := c.initRequest(ctx, method, id, queryParameters)
if err != nil {
return nil, false, err
}
if bodyProps != nil {
err = runtime.MarshalAsJSON(req, bodyProps)
if err != nil {
return nil, false, err
}
}
if serializationMutex != nil {
serializationMutex.Lock()
defer serializationMutex.Unlock()
}
resp, err := c.pipeline.Do(req)
if err != nil {
return nil, false, err
}
if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated, http.StatusAccepted) {
return nil, false, newResponseError(resp)
}
var outputs map[string]any
if err := runtime.UnmarshalAsJSON(resp, &outputs); err != nil {
return nil, false, handleAzCoreResponseError(err, resp)
}
// Some APIs are explicitly marked `x-ms-long-running-operation` and we are only supposed to poll
// for the result in that case. However, if we get 202, we don't want to
// consider this a failure - so try following the awaiting protocol in case the service hasn't marked
// its API as long-running by an oversight.
created := false
if asyncStyle != "" || resp.StatusCode == http.StatusAccepted {
created = resp.StatusCode < 400
apiVersion := queryParameters["api-version"].(string)
normalizeLocationHeader(c.host, apiVersion, resp.Header)
pt, err := runtime.NewPoller[map[string]any](resp, c.pipeline, nil)
if err != nil {
return nil, created, err
}
outputs, err = pt.PollUntilDone(ctx, &runtime.PollUntilDoneOptions{
Frequency: time.Duration(c.updatePollingIntervalSeconds * int64(time.Second)),
})
if err != nil {
if err, ok := err.(*azcore.ResponseError); ok {
return nil, created, newResponseError(err.RawResponse)
}
return nil, created, err
}
}
return outputs, true, nil
}
// The azcore location header Poller validates that the location header is a valid absolute URL.
// In some cases, like user-assigned identities, the location header in the PUT response is a
// relative URL "/subscriptions/...", which we try to make absolute.
// Also, add the api version query param if missing.
func normalizeLocationHeader(host, apiVersion string, headers http.Header) {
locUrlStr := headers.Get("Location")
if locUrlStr == "" {
return
}
locUrl, err := url.Parse(locUrlStr)
if err != nil {
logging.V(3).Infof("Location header '%s' is not a valid URL: %v", locUrlStr, err)
return
}
// Relative polling URLs should never happen since the Azure RPC spec requires absolute polling
// URLs. We have observed it once, though. We will try to make it absolute in that case.
// https://github.com/Azure/azure-sdk-for-go/issues/23385
if !locUrl.IsAbs() {
locUrl.Host = host
absUrlStr := runtime.JoinPaths(host, locUrlStr)
absUrl, err := url.Parse(absUrlStr)
if err != nil {
logging.V(3).Infof("Location header '%s' is not an absolute URL, failed to make absolute: %s", locUrlStr, absUrlStr)
} else {
locUrl = absUrl
logging.V(9).Infof("Location header '%s' is not an absolute URL, added host '%s'", locUrlStr, host)
}
}
if locUrl.Query().Get("api-version") == "" {
q := locUrl.Query()
q.Add("api-version", apiVersion)
locUrl.RawQuery = q.Encode()
}
headers.Set("Location", locUrl.String())
}
func (c *azCoreClient) Post(ctx context.Context, id string, bodyProps map[string]any, queryParameters map[string]any) (any, error) {
req, err := c.initRequest(ctx, http.MethodPost, id, queryParameters)
if err != nil {
return nil, err
}
err = runtime.MarshalAsJSON(req, bodyProps)
if err != nil {
return nil, err
}
resp, err := c.pipeline.Do(req)
if err != nil {
return nil, err
}
if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) {
return nil, newResponseError(resp)
}
return readResponse(resp)
}
func readResponse(resp *http.Response) (any, error) {
var responseBody any
err := runtime.UnmarshalAsJSON(resp, &responseBody)
return responseBody, handleAzCoreResponseError(err, resp)
}
func (c *azCoreClient) Head(ctx context.Context, id string, apiVersion string) error {
queryParams := map[string]any{"api-version": apiVersion}
req, err := c.initRequest(ctx, http.MethodHead, id, queryParams)
if err != nil {
return err
}
resp, err := c.pipeline.Do(req)
if err != nil {
return err
}
if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) {
return newResponseError(resp)
}
return nil
}
// CanCreate asserts that a resource with a given ID and API version can be created
// or returns an error otherwise.
func (c *azCoreClient) CanCreate(ctx context.Context, id, path, apiVersion, readMethod string,
isSingletonResource, hasDefaultBody bool, isDefaultResponse func(map[string]any) bool,
) error {
queryParams := map[string]any{"api-version": apiVersion}
req, err := c.initRequest(ctx, readMethod, id+path, queryParams)
if err != nil {
return err
}
resp, err := c.pipeline.Do(req)
if err != nil {
return err
}
switch {
case http.StatusOK == resp.StatusCode && isSingletonResource:
// Singleton resources always exist, so OK is expected.
return nil
case http.StatusOK == resp.StatusCode && hasDefaultBody:
// This resource is automatically created with a parent and set to its default state. It can be deleted though.
// Validate that its current shape is in the default state to avoid unintended adoption and destructive
// actions.
// NOTE: We may reconsider and relax this restriction when we get more examples of such resources.
// The difference between "take any singleton resource as-is" and "require default body for deletable resources"
// isn't very principled but is based on what subjectively feels best for the current examples.
var outputs map[string]interface{}
if err := runtime.UnmarshalAsJSON(resp, &outputs); err != nil {
return handleAzCoreResponseError(err, resp)
}
if !isDefaultResponse(outputs) {
return fmt.Errorf("cannot create already existing subresource '%s'", id)
}
return nil
case http.StatusNoContent == resp.StatusCode:
if readMethod == "HEAD" {
return fmt.Errorf("cannot create already existing resource '%s'", id)
}
// A few "linking" resources, like private endpoint connections, return 204 as "does not exist" status code.
// Treat them as such unless it's a HEAD method treated above.
return nil
case http.StatusOK == resp.StatusCode:
// Usually, 200 means that the resource already exists and we shouldn't try to create it.
// However, unfortunately, some APIs return 200 with an empty body for non-existing resources.
// Our strategy here is to try to parse the response body and see if it's a valid non-empty JSON.
// If it is, we assume the resource exists.
var outputs map[string]interface{}
err := runtime.UnmarshalAsJSON(resp, &outputs)
if err == nil && len(outputs) > 0 {
return fmt.Errorf("cannot create already existing resource '%s'", id)
}
return nil
case http.StatusNotFound == resp.StatusCode:
return nil
default:
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("cannot check existence of resource '%s': status code %d, %s", id, resp.StatusCode, body)
}
}
// handleAzCoreResponseError checks for certain kinds of errors and returns a more informative error message.
// Most of the time, it will return the original error.
func handleAzCoreResponseError(err error, resp *http.Response) error {
if err == nil {
return nil
}
if strings.Contains(err.Error(), "unmarshalling type ") {
// The service returned a non-JSON response, which is unexpected. The JSON unmarshaling error is not
// useful; return the response body and the HTTP status as an error.
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("unexpected response from Azure: '%s', HTTP status: %s", body, resp.Status)
}
return err
}
// from go-autorest v0.11.29, utility.go
func ensureValueString(value interface{}) string {
if value == nil {
return ""
}
switch v := value.(type) {
case string:
return v
case []byte:
return string(v)
default:
return fmt.Sprintf("%v", v)
}
}
// MapToValues method converts map[string]interface{} to url.Values.
// from go-autorest v0.11.29, utility.go
func MapToValues(m map[string]interface{}) url.Values {
v := url.Values{}
for key, value := range m {
x := reflect.ValueOf(value)
if x.Kind() == reflect.Array || x.Kind() == reflect.Slice {
for i := 0; i < x.Len(); i++ {
v.Add(key, ensureValueString(x.Index(i)))
}
} else {
v.Add(key, ensureValueString(value))
}
}
return v
}
// CreateTestClient creates a test AzureClient wthat doesn't actually execute requests but instead
// runs the given assertions against them.
func CreateTestClient(t *testing.T, assertions func(t *testing.T, req *http.Request)) (AzureClient, error) {
transp := &requestAssertingTransporter{
t: t,
assertions: assertions,
}
opts := arm.ClientOptions{
ClientOptions: policy.ClientOptions{
Retry: policy.RetryOptions{MaxRetries: -1}, // speeds up the tests
Telemetry: policy.TelemetryOptions{Disabled: true},
Transport: transp,
},
DisableRPRegistration: true,
}
return NewAzCoreClient(&fake.TokenCredential{}, "pid-12345", cloud.AzurePublic, &opts)
}
type requestAssertingTransporter struct {
t *testing.T
assertions func(*testing.T, *http.Request)
}
func (r *requestAssertingTransporter) Do(req *http.Request) (*http.Response, error) {
r.assertions(r.t, req)
return nil, nil
}
// newResponseError replaces an azcore.ResponseError, created from the given response, with a more concise error type (#3778).
func newResponseError(resp *http.Response) error {
err := runtime.NewResponseError(resp)
azcoreErr, ok := err.(*azcore.ResponseError)
if !ok {
return err
}
body, err2 := runtime.Payload(resp)
if err2 != nil {
return err
}
var payload map[string]any
if err2 := json.Unmarshal(body, &payload); err2 != nil {
return err
}
errMsg := string(body)
if e, ok := util.GetInnerMap(payload, "error"); ok {
if msg, ok := e["message"]; ok {
errMsg = msg.(string)
}
}
return &PulumiAzcoreResponseError{
StatusCode: resp.StatusCode,
ErrorCode: azcoreErr.ErrorCode,
Message: errMsg,
}
}
// We use this error type instead of azcore.ResponseError because the latter has a very verbose error message (#3778).
type PulumiAzcoreResponseError struct {
StatusCode int
ErrorCode string
Message string
}
func (e *PulumiAzcoreResponseError) Error() string {
if e.ErrorCode == "" {
return fmt.Sprintf(`Status=%d Message="%s"`, e.StatusCode, e.Message)
}
return fmt.Sprintf(`Status=%d Code="%s" Message="%s"`, e.StatusCode, e.ErrorCode, e.Message)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/azure_test.go | provider/pkg/azure/azure_test.go | // Copyright 2016-2024, Pulumi Corporation.
package azure
import (
"encoding/base64"
"encoding/json"
"net/http"
"os"
"regexp"
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/stretchr/testify/assert"
)
func TestBuildUserAgent(t *testing.T) {
tests := []struct {
name string
partnerID string
ExtraUA string
wantRegex string
}{
{
name: "default",
wantRegex: ``,
},
{
name: "PartnerID",
partnerID: "12345",
wantRegex: `pid-12345`,
},
{
name: "UserAgentPassthrough",
ExtraUA: "a/1.2.3 b-c",
wantRegex: `a/(.+) b-c`,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
os.Setenv("AZURE_HTTP_USER_AGENT", tc.ExtraUA)
ua := BuildUserAgent(tc.partnerID)
matched, err := regexp.MatchString(tc.wantRegex, ua)
if err != nil || !matched {
t.Errorf("user agent mismatch, expected %q: got %q", tc.wantRegex, ua)
}
})
}
}
func TestIsNotFound(t *testing.T) {
t.Run("azcore with valid error code", func(t *testing.T) {
// Test all valid "not found" error codes
validCodes := []string{"NotFound", "ResourceNotFound", "ResourceGroupNotFound"}
for _, code := range validCodes {
assert.True(t, IsNotFound(&azcore.ResponseError{
StatusCode: http.StatusNotFound,
ErrorCode: code,
}), "Should return true for error code: "+code)
}
})
t.Run("azcore with 404 but no error code", func(t *testing.T) {
// 404 without ErrorCode (e.g., proxy/WAF response)
assert.False(t, IsNotFound(&azcore.ResponseError{
StatusCode: http.StatusNotFound,
ErrorCode: "",
}))
})
t.Run("azcore with 404 but invalid error code", func(t *testing.T) {
// 404 with non-matching error code
assert.False(t, IsNotFound(&azcore.ResponseError{
StatusCode: http.StatusNotFound,
ErrorCode: "SomeOtherError",
}))
})
t.Run("azcore with non-404 status", func(t *testing.T) {
assert.False(t, IsNotFound(&azcore.ResponseError{
StatusCode: http.StatusForbidden,
ErrorCode: "ResourceNotFound",
}))
})
t.Run("provider with valid error code", func(t *testing.T) {
// Test all valid "not found" error codes
validCodes := []string{"NotFound", "ResourceNotFound", "ResourceGroupNotFound"}
for _, code := range validCodes {
assert.True(t, IsNotFound(&PulumiAzcoreResponseError{
StatusCode: http.StatusNotFound,
ErrorCode: code,
}), "Should return true for error code: "+code)
}
})
t.Run("provider with 404 but no error code", func(t *testing.T) {
// 404 without ErrorCode (e.g., proxy/WAF response)
assert.False(t, IsNotFound(&PulumiAzcoreResponseError{
StatusCode: http.StatusNotFound,
ErrorCode: "",
}))
})
t.Run("provider with 404 but invalid error code", func(t *testing.T) {
// 404 with non-matching error code
assert.False(t, IsNotFound(&PulumiAzcoreResponseError{
StatusCode: http.StatusNotFound,
ErrorCode: "SomeOtherError",
}))
})
t.Run("provider with non-404 status", func(t *testing.T) {
assert.False(t, IsNotFound(&PulumiAzcoreResponseError{
StatusCode: http.StatusForbidden,
ErrorCode: "Unauthorized",
}))
})
}
func TestParseClaims(t *testing.T) {
// Create a Claims struct and marshal it to JSON
expectedClaims := Claims{
Audience: "audience",
Issuer: "issuer",
IdentityProvider: "idp",
ObjectId: "objectid",
Roles: []string{"role1", "role2"},
Scopes: "scope",
Subject: "subject",
TenantRegionScope: "region",
TenantId: "tenantid",
Version: "1.0",
AppDisplayName: "appdisplayname",
AppId: "appid",
IdType: "idtype",
}
payload, err := json.Marshal(expectedClaims)
assert.NoError(t, err)
// JWT: header.payload.signature (all base64url, but only payload matters)
header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none"}`))
payloadEnc := base64.RawURLEncoding.EncodeToString(payload)
tokenStr := header + "." + payloadEnc + ".signature"
token := azcore.AccessToken{Token: tokenStr}
claims, err := ParseClaims(token)
assert.NoError(t, err)
assert.Equal(t, expectedClaims, claims)
}
func TestParseClaims_InvalidToken(t *testing.T) {
// Token with not enough segments
token := azcore.AccessToken{Token: "invalidtoken"}
_, err := ParseClaims(token)
assert.Error(t, err)
// Token with invalid base64 payload
token = azcore.AccessToken{Token: "a.b@d!.c"}
_, err = ParseClaims(token)
assert.Error(t, err)
// Token with invalid JSON in payload
badPayload := base64.RawURLEncoding.EncodeToString([]byte("notjson"))
token = azcore.AccessToken{Token: "a." + badPayload + ".c"}
_, err = ParseClaims(token)
assert.Error(t, err)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/client_azcore_test.go | provider/pkg/azure/client_azcore_test.go | // Copyright 2016-2024, Pulumi Corporation.
package azure
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"testing"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/fake"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/version"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestInitPipelineOpts(t *testing.T) {
t.Run("retry delays", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
assert.InDelta(t, 20*time.Second, opts.Retry.RetryDelay, 10.0)
assert.InDelta(t, 120*time.Second, opts.Retry.MaxRetryDelay, 30.0)
})
t.Run("cloud is public", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
assert.Equal(t, cloud.AzurePublic, opts.ClientOptions.Cloud)
})
t.Run("cloud is usgov", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzureGovernment, nil)
assert.Equal(t, cloud.AzureGovernment, opts.ClientOptions.Cloud)
})
t.Run("cloud is china", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzureChina, nil)
assert.Equal(t, cloud.AzureChina, opts.ClientOptions.Cloud)
})
t.Run("should retry", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
assert.NotNil(t, opts.Retry.ShouldRetry)
})
t.Run("retries on 408 timeout", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
assert.True(t, opts.Retry.ShouldRetry(&http.Response{StatusCode: http.StatusRequestTimeout}, nil))
})
t.Run("retries on 409 conflict when another operation is in progress", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
header := http.Header{}
header.Add("x-ms-error-code", "AnotherOperationInProgress")
assert.True(t, opts.Retry.ShouldRetry(&http.Response{
StatusCode: http.StatusConflict,
Header: header,
}, nil))
})
t.Run("doesn't retry on 409 conflict when no other operation is in progress", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
assert.False(t, opts.Retry.ShouldRetry(&http.Response{StatusCode: http.StatusConflict}, nil))
})
t.Run("retries on 429 too many requests", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
assert.True(t, opts.Retry.ShouldRetry(&http.Response{StatusCode: http.StatusTooManyRequests}, nil))
})
t.Run("retries on 500 internal server error", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
assert.True(t, opts.Retry.ShouldRetry(&http.Response{StatusCode: http.StatusInternalServerError}, nil))
})
t.Run("retries on 502 bad gateway", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
assert.True(t, opts.Retry.ShouldRetry(&http.Response{StatusCode: http.StatusBadGateway}, nil))
})
t.Run("retries on 503 service unavailable", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
assert.True(t, opts.Retry.ShouldRetry(&http.Response{StatusCode: http.StatusServiceUnavailable}, nil))
})
t.Run("retries on 504 gateway timeout", func(t *testing.T) {
opts := initPipelineOpts(cloud.AzurePublic, nil)
assert.True(t, opts.Retry.ShouldRetry(&http.Response{StatusCode: http.StatusGatewayTimeout}, nil))
})
}
func TestNormalizeLocationHeader(t *testing.T) {
const host = "https://management.azure.com"
const apiVersion = "2022-09-01"
for testName, loc := range map[string]string{
"RelativeUrl": "/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm",
"RelativeUrlWithApiVersion": "/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm?api-version=" + apiVersion,
"FullUrl": "https://management.azure.com/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm",
"FullUrlWithApiVersion": "https://management.azure.com/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm?api-version=" + apiVersion,
} {
t.Run(testName, func(t *testing.T) {
headers := http.Header{}
headers.Add("Location", loc)
normalizeLocationHeader(host, apiVersion, headers)
assert.Equal(t,
host+"/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm?api-version="+apiVersion,
headers.Get("Location"))
})
}
for testName, loc := range map[string]string{
"MalformedUrl": "foo[:",
"EmptyUrl": "",
} {
t.Run(testName, func(t *testing.T) {
headers := http.Header{}
headers.Add("Location", loc)
normalizeLocationHeader(host, apiVersion, headers)
assert.Equal(t, loc, headers.Get("Location"))
})
}
t.Run("NoLocationHeader", func(t *testing.T) {
headers := http.Header{}
normalizeLocationHeader(host, apiVersion, headers)
assert.Empty(t, headers.Get("Location"))
})
}
func TestInitRequestQueryParams(t *testing.T) {
c, err := NewAzCoreClient(&fake.TokenCredential{}, "", cloud.AzurePublic, nil)
require.NoError(t, err)
client := c.(*azCoreClient)
queryParams := map[string]any{
"api-version": "2022-09-01",
"string_with_unescaped_slash": "a/path",
"string_with_escaped_slash": "a%2Fpath",
"bool": true,
"int": 42,
"slice": []string{"a", "b"},
}
req, err := client.initRequest(context.Background(), http.MethodGet, "/subscriptions/123", queryParams)
require.NoError(t, err)
query := req.Raw().URL.Query()
assert.Len(t, query, len(queryParams))
assert.Equal(t, "2022-09-01", query.Get("api-version"))
assert.Equal(t, "a/path", query.Get("string_with_unescaped_slash"))
assert.Equal(t, "a/path", query.Get("string_with_escaped_slash"))
assert.Equal(t, "true", query.Get("bool"))
assert.Equal(t, "42", query.Get("int"))
assert.Equal(t, "a", query.Get("slice"))
assert.Equal(t, []string{"a", "b"}, query["slice"])
}
func TestInitRequestHeaders(t *testing.T) {
c, err := NewAzCoreClient(&fake.TokenCredential{}, "extra", cloud.AzurePublic, nil)
require.NoError(t, err)
client := c.(*azCoreClient)
queryParams := map[string]any{"api-version": "2022-09-01"}
for method, contentType := range map[string]string{
http.MethodGet: "",
http.MethodDelete: "",
http.MethodPost: "application/json; charset=utf-8",
http.MethodPut: "application/json; charset=utf-8",
http.MethodPatch: "application/json; charset=utf-8",
} {
req, err := client.initRequest(context.Background(), method, "/subscriptions/123", queryParams)
require.NoError(t, err)
headers := req.Raw().Header
assert.Equal(t, "extra", headers.Get("User-Agent"))
assert.Equal(t, "application/json", headers.Get("Accept"))
assert.Equal(t, contentType, headers.Get("Content-Type"))
}
}
func createTestClient(t *testing.T, handler func(t *testing.T, req *http.Request)) AzureClient {
client, err := CreateTestClient(t, handler)
require.NoError(t, err)
return client
}
func TestRequestQueryParams(t *testing.T) {
const resourceId = "/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm"
t.Run("GET adds API version to query", func(t *testing.T) {
client := createTestClient(t, func(t *testing.T, req *http.Request) {
q := req.URL.Query()
assert.Equal(t, "2022-02-02", q.Get("api-version"))
})
client.Get(context.Background(), resourceId, "2022-02-02", nil)
})
t.Run("GET with query params adds API version to query", func(t *testing.T) {
client := createTestClient(t, func(t *testing.T, req *http.Request) {
q := req.URL.Query()
assert.Equal(t, "2022-02-02", q.Get("api-version"))
assert.Equal(t, "bar", q.Get("foo"))
})
client.Get(context.Background(), resourceId, "2022-02-02", map[string]any{"foo": "bar"})
})
t.Run("DELETE adds API version to query", func(t *testing.T) {
client := createTestClient(t, func(t *testing.T, req *http.Request) {
q := req.URL.Query()
assert.Equal(t, "2022-02-02", q.Get("api-version"))
})
client.Delete(context.Background(), resourceId, "2022-02-02", "", nil)
})
t.Run("DELETE combines API version with other query params", func(t *testing.T) {
client := createTestClient(t, func(t *testing.T, req *http.Request) {
q := req.URL.Query()
assert.Equal(t, "2022-02-02", q.Get("api-version"))
assert.Equal(t, "bar", q.Get("foo"))
})
client.Delete(context.Background(), resourceId, "2022-02-02", "", map[string]any{"foo": "bar"})
})
t.Run("POST adds all query params", func(t *testing.T) {
client := createTestClient(t, func(t *testing.T, req *http.Request) {
q := req.URL.Query()
assert.Equal(t, "2022-02-02", q.Get("api-version"))
assert.Equal(t, "11", q.Get("foo"))
})
client.Post(context.Background(), resourceId, nil,
map[string]any{
"api-version": "2022-02-02",
"foo": 11,
})
})
t.Run("PUT adds all query params", func(t *testing.T) {
client := createTestClient(t, func(t *testing.T, req *http.Request) {
q := req.URL.Query()
assert.Equal(t, "2022-02-02", q.Get("api-version"))
assert.Equal(t, "11", q.Get("foo"))
})
client.Put(context.Background(), resourceId, nil,
map[string]any{
"api-version": "2022-02-02",
"foo": 11,
}, "")
})
}
func TestRequestUserAgent(t *testing.T) {
fake := &fakeTransporter{
responses: []*http.Response{{StatusCode: 200}},
}
client := newClientWithFakeTransport(fake)
_, err := client.Post(context.Background(), "/subscriptions/123", nil, map[string]any{"api-version": "2022-09-01"})
require.NoError(t, err)
require.Regexp(t, `^pulumi-azure-native/(.+) azsdk-go-azcore/(.+) \(.+\) pid-12345$`, fake.requests[0].Header.Get("User-Agent"))
}
func TestErrorStatusCodes(t *testing.T) {
t.Run("POST ok", func(t *testing.T) {
for _, statusCode := range []int{200, 201} {
client := newClientWithPreparedResponses([]*http.Response{{StatusCode: statusCode}})
resp, err := client.Post(context.Background(), "/subscriptions/123", nil, map[string]any{"api-version": "2022-09-01"})
require.NoError(t, err, statusCode)
require.Empty(t, resp, statusCode)
}
})
t.Run("POST error", func(t *testing.T) {
for _, statusCode := range []int{202, 204, 400, 401, 403, 404, 409, 410, 500, 502, 503, 504} {
client := newClientWithPreparedResponses([]*http.Response{{StatusCode: statusCode}})
_, err := client.Post(context.Background(), "/subscriptions/123", nil, map[string]any{"api-version": "2022-09-01"})
require.Error(t, err, statusCode)
}
})
t.Run("GET ok", func(t *testing.T) {
client := newClientWithPreparedResponses([]*http.Response{{StatusCode: 200}})
resp, err := client.Get(context.Background(), "/subscriptions/123", "2022-09-01", nil)
require.NoError(t, err)
require.Empty(t, resp)
})
t.Run("GET error", func(t *testing.T) {
for _, statusCode := range []int{201, 202, 204, 400, 401, 403, 404, 409, 410, 500, 502, 503, 504} {
client := newClientWithPreparedResponses([]*http.Response{{StatusCode: statusCode}})
_, err := client.Get(context.Background(), "/subscriptions/123", "2022-09-01", nil)
require.Error(t, err, statusCode)
}
})
t.Run("PUT, PATCH ok", func(t *testing.T) {
for _, statusCode := range []int{200, 201} {
client := newClientWithPreparedResponses([]*http.Response{{StatusCode: statusCode}})
resp, created, err := client.Put(context.Background(), "/subscriptions/123", nil, map[string]any{"api-version": "2022-09-01"}, "")
require.NoError(t, err, statusCode)
assert.True(t, created)
require.Empty(t, resp, statusCode)
}
})
// This test does not cover long-running operations with polling, only the handling of the first response.
t.Run("PUT, PATCH error", func(t *testing.T) {
for _, statusCode := range []int{202, 204, 400, 401, 403, 404, 409, 410, 500, 502, 503, 504} {
client := newClientWithPreparedResponses([]*http.Response{{
StatusCode: statusCode,
Body: io.NopCloser(strings.NewReader(``)),
Request: &http.Request{Method: http.MethodPut, URL: &url.URL{Path: "/subscriptions/123"}},
}})
_, created, err := client.Put(context.Background(), "/subscriptions/123", nil, map[string]any{"api-version": "2022-09-01"}, "")
assert.Equal(t, statusCode < 203, created, statusCode)
require.Error(t, err, statusCode)
}
})
t.Run("DELETE ok", func(t *testing.T) {
for _, statusCode := range []int{200, 202, 204, 404} {
client := newClientWithPreparedResponses([]*http.Response{{StatusCode: statusCode}})
err := client.Delete(context.Background(), "/subscriptions/123", "2022-09-01", "", nil)
require.NoError(t, err, statusCode)
}
})
t.Run("DELETE error", func(t *testing.T) {
for _, statusCode := range []int{201, 400, 401, 403, 409, 410, 500, 502, 503, 504} {
client := newClientWithPreparedResponses([]*http.Response{{StatusCode: statusCode}})
err := client.Delete(context.Background(), "/subscriptions/123", "2022-09-01", "", nil)
require.Error(t, err, statusCode)
}
})
t.Run("HEAD ok", func(t *testing.T) {
for _, statusCode := range []int{200, 204} {
client := newClientWithPreparedResponses([]*http.Response{{StatusCode: statusCode}})
err := client.Head(context.Background(), "/subscriptions/123", "2022-09-01")
require.NoError(t, err, statusCode)
}
})
t.Run("HEAD error", func(t *testing.T) {
for _, statusCode := range []int{201, 202, 400, 401, 403, 409, 410, 500, 502, 503, 504} {
client := newClientWithPreparedResponses([]*http.Response{{StatusCode: statusCode}})
err := client.Head(context.Background(), "/subscriptions/123", "2022-09-01")
require.Error(t, err, statusCode)
}
})
t.Run("PUT polling success after 202 response", func(t *testing.T) {
client := newClientWithPreparedResponses([]*http.Response{
{
StatusCode: 202,
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "InProgress"}`)),
},
{
StatusCode: 502, // temporary failure
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "Bad Gateway"}`)),
},
{
StatusCode: 503, // temporary failure
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "Unavailable"}`)),
},
{
StatusCode: 202,
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "InProgress"}`)),
},
{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(`{"status": "Succeeded"}`)),
},
})
_, found, err := client.Put(context.Background(), "/subscriptions/123/rg/rg", nil, map[string]any{"api-version": "2022-09-01"}, "")
require.NoError(t, err)
assert.True(t, found)
})
t.Run("PUT polling success when asyncStyle is given", func(t *testing.T) {
client := newClientWithPreparedResponses([]*http.Response{
{
StatusCode: 201, // created
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "InProgress"}`)),
},
{
StatusCode: 502, // temporary failure
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "Bad Gateway"}`)),
},
{
StatusCode: 503, // temporary failure
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "Unavailable"}`)),
},
{
StatusCode: 201,
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "InProgress"}`)),
},
{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(`{"status": "Succeeded"}`)),
},
})
_, found, err := client.Put(context.Background(), "/subscriptions/123/rg/rg", nil, map[string]any{"api-version": "2022-09-01"},
"the actual value doesn't matter!")
require.NoError(t, err)
assert.True(t, found)
})
t.Run("DELETE polling success when asyncStyle is given", func(t *testing.T) {
client := newClientWithPreparedResponses([]*http.Response{
{
StatusCode: 202,
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "InProgress"}`)),
},
{
StatusCode: 503, // temporary failure
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"error": {"code": "Unavailable"}}`)),
},
{
StatusCode: 200,
Body: io.NopCloser(strings.NewReader(`{"status": "Succeeded"}`)),
},
})
err := client.Delete(context.Background(), "/subscriptions/123/rg/rg", "2022-09-01", "the actual value doesn't matter!", nil)
require.NoError(t, err)
})
t.Run("DELETE initial success on 404 when asyncStyle is given", func(t *testing.T) {
client := newClientWithPreparedResponses([]*http.Response{
{
StatusCode: 404,
Body: io.NopCloser(strings.NewReader(`{"error": {"code": "ResourceNotFound"}}`)),
},
})
err := client.Delete(context.Background(), "/subscriptions/123/rg/rg", "2022-09-01", "the actual value doesn't matter!", nil)
require.NoError(t, err)
})
t.Run("DELETE polling success on 404 when asyncStyle is given", func(t *testing.T) {
client := newClientWithPreparedResponses([]*http.Response{
{
StatusCode: 202,
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "InProgress"}`)),
},
{
StatusCode: 404,
Body: io.NopCloser(strings.NewReader(`{"error": {"code": "ResourceNotFound"}}`)),
},
})
err := client.Delete(context.Background(), "/subscriptions/123/rg/rg", "2022-09-01", "the actual value doesn't matter!", nil)
require.NoError(t, err)
})
t.Run("DELETE initial failure when asyncStyle is given", func(t *testing.T) {
client := newClientWithPreparedResponses([]*http.Response{
{
StatusCode: 400,
Body: io.NopCloser(strings.NewReader(`{"error": {"code": "BadRequest"}}`)),
},
})
err := client.Delete(context.Background(), "/subscriptions/123/rg/rg", "2022-09-01", "the actual value doesn't matter!", nil)
require.Error(t, err)
require.IsType(t, &PulumiAzcoreResponseError{}, err)
require.Equal(t, "BadRequest", err.(*PulumiAzcoreResponseError).ErrorCode)
})
t.Run("DELETE polling failure when asyncStyle is given", func(t *testing.T) {
client := newClientWithPreparedResponses([]*http.Response{
{
StatusCode: 202,
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"status": "InProgress"}`)),
},
{
StatusCode: 503, // temporary failure
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"error": {"code": "Unavailable"}}`)),
},
{
StatusCode: 400,
Header: http.Header{"Location": []string{"https://management.azure.com/operation"}},
Body: io.NopCloser(strings.NewReader(`{"error": {"code": "BadRequest"}}`)),
},
})
err := client.Delete(context.Background(), "/subscriptions/123/rg/rg", "2022-09-01", "the actual value doesn't matter!", nil)
require.Error(t, err)
require.IsType(t, &PulumiAzcoreResponseError{}, err)
require.Equal(t, "BadRequest", err.(*PulumiAzcoreResponseError).ErrorCode)
})
}
func TestCanCreateUsesResourcePath(t *testing.T) {
canCreate := func(client AzureClient, path string) {
client.CanCreate(context.Background(),
"/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm",
path,
"2022-09-01", http.MethodGet, false, false, nil)
}
t.Run("no path", func(t *testing.T) {
client := createTestClient(t, func(t *testing.T, req *http.Request) {
assert.Equal(t, http.MethodGet, req.Method)
assert.Equal(t, "/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm", req.URL.Path)
})
canCreate(client, "")
})
t.Run("path", func(t *testing.T) {
client := createTestClient(t, func(t *testing.T, req *http.Request) {
assert.Equal(t, http.MethodGet, req.Method)
assert.Equal(t, "/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm/extraPath", req.URL.Path)
})
canCreate(client, "/extraPath")
})
}
func TestCanCreate_Responses(t *testing.T) {
id := "/subscriptions/123/resourceGroups/rg"
type testCase struct {
responseStatus int
response string
id string
readMethod string
isSingletonResource bool // if true and 200 OK -> true
hasDefaultBody bool // if true and 200 OK -> isDefaultResponse
isDefaultResponse bool
}
t.Run("200 OK", func(t *testing.T) {
// HTTP method makes no difference when the response is 200 OK.
for _, method := range []string{http.MethodGet, http.MethodHead} {
// Success cases
for _, tc := range []testCase{
{responseStatus: 200, id: id, readMethod: method, isSingletonResource: false, hasDefaultBody: false, isDefaultResponse: false},
{responseStatus: 200, id: id, readMethod: method, isSingletonResource: true, hasDefaultBody: false, isDefaultResponse: false},
{responseStatus: 200, id: id, readMethod: method, isSingletonResource: true, hasDefaultBody: false, isDefaultResponse: true},
{responseStatus: 200, id: id, readMethod: method, isSingletonResource: false, hasDefaultBody: true, isDefaultResponse: true},
{responseStatus: 200, id: id, readMethod: method, isSingletonResource: false, hasDefaultBody: false, isDefaultResponse: false},
} {
client := newClientWithPreparedResponses([]*http.Response{{
StatusCode: tc.responseStatus,
Body: io.NopCloser(strings.NewReader(tc.response)),
}})
err := client.CanCreate(context.Background(), tc.id, "" /* path */, "2022-09-01", tc.readMethod,
tc.isSingletonResource, tc.hasDefaultBody, func(map[string]any) bool { return tc.isDefaultResponse })
require.NoError(t, err)
}
// Error cases
for _, tc := range []testCase{
// This resource has a default state but the response we got is not that state, i.e., it's been modified already.
{responseStatus: 200, id: id, readMethod: method, isSingletonResource: false, hasDefaultBody: true, isDefaultResponse: false},
// 200 OK with a reponse body means a resource exists, so we can't create it.
{responseStatus: 200, response: `{"foo": 1}`, id: id, readMethod: method, isSingletonResource: false, hasDefaultBody: false, isDefaultResponse: false},
} {
client := newClientWithPreparedResponses([]*http.Response{{
StatusCode: tc.responseStatus,
Body: io.NopCloser(strings.NewReader(tc.response)),
}})
err := client.CanCreate(context.Background(), tc.id, "" /* path */, "2022-09-01", tc.readMethod,
tc.isSingletonResource, tc.hasDefaultBody, func(map[string]any) bool { return tc.isDefaultResponse })
require.Error(t, err)
}
}
})
// 404 always means "can create"
t.Run("404 Not Found", func(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodHead} {
for _, resp := range []string{``, `{"foo": 1}`} {
for _, isSingleton := range []bool{true, false} {
for _, hasDefault := range []bool{true, false} {
for _, isDefault := range []bool{true, false} {
client := newClientWithPreparedResponses([]*http.Response{{
StatusCode: 404,
Body: io.NopCloser(strings.NewReader(resp)),
}})
err := client.CanCreate(context.Background(), id, "" /* path */, "2022-09-01", method,
isSingleton, hasDefault, func(map[string]any) bool { return isDefault })
require.NoError(t, err)
}
}
}
}
}
})
// 204 No Content always means "can create" when read via GET, but never when read via HEAD
t.Run("204 No Content", func(t *testing.T) {
for _, resp := range []string{``, `{"foo": 1}`} {
for _, isSingleton := range []bool{true, false} {
for _, hasDefault := range []bool{true, false} {
for _, isDefault := range []bool{true, false} {
client := newClientWithPreparedResponses([]*http.Response{{
StatusCode: 204,
Body: io.NopCloser(strings.NewReader(resp)),
}})
err := client.CanCreate(context.Background(), id, "" /* path */, "2022-09-01", "GET",
isSingleton, hasDefault, func(map[string]any) bool { return isDefault })
require.NoError(t, err)
}
}
}
}
for _, resp := range []string{``, `{"foo": 1}`} {
for _, isSingleton := range []bool{true, false} {
for _, hasDefault := range []bool{true, false} {
for _, isDefault := range []bool{true, false} {
client := newClientWithPreparedResponses([]*http.Response{{
StatusCode: 204,
Body: io.NopCloser(strings.NewReader(resp)),
}})
err := client.CanCreate(context.Background(), id, "" /* path */, "2022-09-01", "HEAD",
isSingleton, hasDefault, func(map[string]any) bool { return isDefault })
require.Error(t, err)
}
}
}
}
})
// Other HTTP status codes are always an error.
t.Run("other HTTP statuses", func(t *testing.T) {
for _, status := range []int{201, 202, 400, 401, 403, 409, 410, 500, 502, 503, 504} {
for _, method := range []string{http.MethodGet, http.MethodHead} {
for _, resp := range []string{``, `{"foo": 1}`} {
for _, isSingleton := range []bool{true, false} {
for _, hasDefault := range []bool{true, false} {
for _, isDefault := range []bool{true, false} {
client := newClientWithPreparedResponses([]*http.Response{{
StatusCode: status,
Body: io.NopCloser(strings.NewReader(resp)),
}})
err := client.CanCreate(context.Background(), id, "" /* path */, "2022-09-01", method,
isSingleton, hasDefault, func(map[string]any) bool { return isDefault })
require.Error(t, err)
}
}
}
}
}
}
})
}
// Implements azcore's policy.Transporter by returning the given responses in order.
type fakeTransporter struct {
requests []*http.Request
responses []*http.Response
index int
}
func (f *fakeTransporter) Do(req *http.Request) (*http.Response, error) {
f.requests = append(f.requests, req)
cur := f.responses[f.index]
f.index++
return cur, nil
}
func newClientWithFakeTransport(transport *fakeTransporter) *azCoreClient {
opts := arm.ClientOptions{
ClientOptions: policy.ClientOptions{
Transport: transport,
Retry: policy.RetryOptions{MaxRetries: -1},
Cloud: cloud.AzurePublic,
Telemetry: policy.TelemetryOptions{
ApplicationID: fmt.Sprintf("pulumi-azure-native/%s", version.GetVersion()),
},
},
}
client, _ := NewAzCoreClient(&fake.TokenCredential{}, "pid-12345", cloud.AzurePublic, &opts)
azCoreClient := client.(*azCoreClient)
azCoreClient.updatePollingIntervalSeconds = 1
azCoreClient.deletePollingIntervalSeconds = 1
return azCoreClient
}
func newClientWithPreparedResponses(responses []*http.Response) *azCoreClient {
return newClientWithFakeTransport(&fakeTransporter{
responses: responses,
})
}
func TestHandleResponseError(t *testing.T) {
t.Run("Cannot unmarshal JSON", func(t *testing.T) {
resp := http.Response{
Body: io.NopCloser(strings.NewReader("not JSON")),
Status: "400 Bad Request",
}
var outputs map[string]any
err := runtime.UnmarshalAsJSON(&resp, &outputs)
handledErr := handleAzCoreResponseError(err, &resp)
require.Error(t, handledErr)
assert.Contains(t, handledErr.Error(), "not JSON")
assert.Contains(t, handledErr.Error(), "400 Bad Request")
})
t.Run("no changes to error", func(t *testing.T) {
resp := http.Response{
Body: io.NopCloser(strings.NewReader(`{"status": "ok"}`)),
}
err := errors.New("some error unrelated to unmarshaling")
handledErr := handleAzCoreResponseError(err, &resp)
assert.Same(t, err, handledErr)
})
}
func TestPutPatchRequestBody(t *testing.T) {
qp := map[string]any{"api-version": "2022-09-01"}
t.Run("PUT", func(t *testing.T) {
client := createTestClient(t, func(t *testing.T, req *http.Request) {
body, err := io.ReadAll(req.Body)
require.NoError(t, err)
assert.Equal(t, `{"foo":"bar"}`, string(body))
})
client.Put(context.Background(), "/subscriptions/123", map[string]any{"foo": "bar"}, qp, "")
})
t.Run("PATCH", func(t *testing.T) {
client := createTestClient(t, func(t *testing.T, req *http.Request) {
body, err := io.ReadAll(req.Body)
require.NoError(t, err)
assert.Equal(t, `{"foo":{"bar":11}}`, string(body))
})
client.Patch(context.Background(), "/subscriptions/123",
map[string]any{"foo": map[string]any{"bar": 11}},
qp, "")
})
}
func TestShouldRetryConflict(t *testing.T) {
shouldRetry := func(status int, body string) bool {
resp := http.Response{
StatusCode: status,
Body: io.NopCloser(strings.NewReader(body)),
}
return shouldRetryConflict(&resp)
}
t.Run("Not a conflict", func(t *testing.T) {
assert.False(t, shouldRetry(200, ""))
})
t.Run("Blank body", func(t *testing.T) {
assert.False(t, shouldRetry(409, ""))
})
t.Run("Unreadable body", func(t *testing.T) {
resp := http.Response{
StatusCode: 409,
Body: errorReadCloser{},
}
assert.False(t, shouldRetryConflict(&resp))
})
t.Run("empty json", func(t *testing.T) {
assert.False(t, shouldRetry(409, "{}"))
})
t.Run("wrong error type", func(t *testing.T) {
assert.False(t, shouldRetry(409, `{"error": "Conflict"}`))
})
t.Run("no error code", func(t *testing.T) {
assert.False(t, shouldRetry(409, `{"error": {"message": "Conflict"}}`))
})
t.Run("other error code", func(t *testing.T) {
assert.False(t, shouldRetry(409, `{"error": {"code": "Conflict"}}`))
})
t.Run("AnotherOperationInProgress", func(t *testing.T) {
assert.True(t, shouldRetry(409, `{"error": {"code": "AnotherOperationInProgress"}}`))
})
t.Run("ConcurrentFederatedIdentityCredentialsWritesForSingleManagedIdentity", func(t *testing.T) {
assert.True(t, shouldRetry(409, `{"error": {"code": "ConcurrentFederatedIdentityCredentialsWritesForSingleManagedIdentity"}}`))
})
}
type errorReadCloser struct{}
func (errorReadCloser) Read(p []byte) (n int, err error) {
return 0, errors.New("read error")
}
func (errorReadCloser) Close() error {
return nil
}
func TestPostResponsesCanBeAnything(t *testing.T) {
t.Run("string", func(t *testing.T) {
resp := &http.Response{
Body: io.NopCloser(strings.NewReader(`"hello"`)),
}
val, err := readResponse(resp)
require.NoError(t, err)
assert.Equal(t, "hello", val)
})
t.Run("object", func(t *testing.T) {
resp := &http.Response{
Body: io.NopCloser(strings.NewReader(`{"k": 1}`)),
}
val, err := readResponse(resp)
require.NoError(t, err)
assert.Equal(t, map[string]any{"k": 1.0}, val)
})
}
func TestNewResponseError(t *testing.T) {
t.Run("standard azcore error", func(t *testing.T) {
resp := &http.Response{
StatusCode: 409,
Body: io.NopCloser(strings.NewReader(`{"error": {"message": "Foo already exists"}}`)),
Header: http.Header{"X-Ms-Error-Code": []string{"Conflict"}},
}
err := newResponseError(resp)
require.Error(t, err)
assert.Equal(t, "Status=409 Code=\"Conflict\" Message=\"Foo already exists\"", err.Error())
})
t.Run("no message", func(t *testing.T) {
resp := &http.Response{
StatusCode: 409,
Body: io.NopCloser(strings.NewReader(`{"error": {"code": "Conflict"}}`)),
Header: http.Header{"X-Ms-Error-Code": []string{"Conflict"}},
}
err := newResponseError(resp)
require.Error(t, err)
assert.Equal(t, `Status=409 Code="Conflict" Message="{"error": {"code": "Conflict"}}"`, err.Error())
})
t.Run("unknown error", func(t *testing.T) {
resp := &http.Response{
StatusCode: 409,
Body: io.NopCloser(strings.NewReader(`{"foo": "bar"}`)),
}
err := newResponseError(resp)
require.Error(t, err)
assert.Equal(t, `Status=409 Message="{"foo": "bar"}"`, err.Error())
})
t.Run("404 with valid error code is recognized by IsNotFound", func(t *testing.T) {
resp := &http.Response{
StatusCode: 404,
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | true |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/azure.go | provider/pkg/azure/azure.go | // Copyright 2016-2024, Pulumi Corporation.
package azure
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
_ "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
// BuildUserAgent composes a User Agent string with the provided partner ID.
// see: https://azure.github.io/azure-sdk/general_azurecore.html#telemetry-policy
func BuildUserAgent(partnerID string) (userAgent string) {
// azure-sdk-for-go sets a user agent string as per the telemetry policy, resembling:
// pulumi-azure-native/3.0.0 azsdk-go-azcore/1.0.0 go/1.16.5 (darwin; amd64)
// Anything we add here will be appended to that.
// append the CloudShell version to the user agent if it exists
// https://github.com/Azure/azure-cli/issues/21808
if azureAgent := os.Getenv("AZURE_HTTP_USER_AGENT"); azureAgent != "" {
userAgent = strings.TrimSpace(fmt.Sprintf("%s %s", userAgent, azureAgent))
}
// Append partner ID, if it's defined.
if partnerID != "" {
userAgent = strings.TrimSpace(fmt.Sprintf("%s pid-%s", userAgent, partnerID))
}
logging.V(9).Infof("AzureNative User Agent: %s", userAgent)
return
}
// IsNotFound returns true if the error is a HTTP 404 with a valid Azure "not found" error code.
// This helps distinguish legitimate Azure "not found" responses from proxy/WAF 404 responses.
func IsNotFound(err error) bool {
validNotFoundCodes := map[string]bool{
"NotFound": true,
"ResourceNotFound": true,
"ResourceGroupNotFound": true,
}
if responseError, ok := err.(*azcore.ResponseError); ok {
if responseError.StatusCode == http.StatusNotFound {
// Check if ErrorCode contains a valid Azure error code
if validNotFoundCodes[responseError.ErrorCode] {
return true
}
logging.V(3).Infof("Received HTTP 404 without valid Azure error code (ErrorCode=%q). "+
"This may indicate a proxy/WAF response rather than a legitimate Azure resource not found error.",
responseError.ErrorCode)
return false
}
}
if responseError, ok := err.(*PulumiAzcoreResponseError); ok {
if responseError.StatusCode == http.StatusNotFound {
// Check if ErrorCode contains a valid Azure error code
if validNotFoundCodes[responseError.ErrorCode] {
return true
}
logging.V(3).Infof("Received HTTP 404 without valid Azure error code (ErrorCode=%q). "+
"This may indicate a proxy/WAF response rather than a legitimate Azure resource not found error.",
responseError.ErrorCode)
return false
}
}
return false
}
// AzureError catches common errors and substitutes them with more user-friendly ones.
func AzureError(err error) error {
if errors.Is(err, context.DeadlineExceeded) {
return errors.New("operation timed out")
}
return err
}
// Claims is used to unmarshall the claims from a JWT issued by the Microsoft Identity Platform.
type Claims struct {
Audience string `json:"aud"`
Issuer string `json:"iss"`
IdentityProvider string `json:"idp"`
ObjectId string `json:"oid"`
Roles []string `json:"roles"`
Scopes string `json:"scp"`
Subject string `json:"sub"`
TenantRegionScope string `json:"tenant_region_scope"`
TenantId string `json:"tid"`
Version string `json:"ver"`
AppDisplayName string `json:"app_displayname,omitempty"`
AppId string `json:"appid,omitempty"`
IdType string `json:"idtyp,omitempty"`
}
// ParseClaims retrieves and parses the claims from a JWT issued by the Microsoft Identity Platform.
func ParseClaims(token azcore.AccessToken) (Claims, error) {
jwt := strings.Split(token.Token, ".")
if len(jwt) != 3 {
return Claims{}, errors.New("unexpected token format: does not have 3 parts")
}
payload, err := base64.RawURLEncoding.DecodeString(jwt[1])
if err != nil {
return Claims{}, err
}
var claims Claims
err = json.Unmarshal(payload, &claims)
return claims, err
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/serialize.go | provider/pkg/azure/serialize.go | package azure
import (
"context"
"strings"
"sync"
)
// Resource type patterns that require serialization due to exclusive lock constraints
var (
// Web Apps require serialization due to limitations on handling hardware infrastructure in the AZ Core SDK.
webAppResourcePattern = "/providers/Microsoft.Web/sites/"
)
// needsSerialization returns true for any resource that needs to be serialized.
func needsSerialization(resourceID string) bool {
switch {
case strings.Contains(resourceID, webAppResourcePattern):
return true
default:
return false
}
}
// extractSerializationKeyForDelete extracts the serialization key for DELETE operations.
func (c *azCoreClient) extractSerializationKeyForDelete(ctx context.Context, id, apiVersion string, queryParams map[string]any) string {
switch {
case strings.Contains(id, webAppResourcePattern):
// Web Apps: fetch resource to get App Service Plan ID
webAppProps, err := c.Get(ctx, id, apiVersion, queryParams)
if err == nil && webAppProps != nil {
appServicePlanID := extractAppServicePlanID(webAppProps)
if appServicePlanID != "" {
return appServicePlanID
}
}
// Fall back to resource group if we can't get App Service Plan ID
return extractResourceGroupFromID(id)
default:
return ""
}
}
// extractSerializationKeyForPutOrPatch extracts the serialization key for PUT/PATCH operations using bodyProps if available.
func extractSerializationKeyForPutOrPatch(id string, bodyProps map[string]any) string {
switch {
case strings.Contains(id, webAppResourcePattern):
// Web Apps: extract App Service Plan ID from bodyProps
return extractAppServicePlanID(bodyProps)
default:
return ""
}
}
func extractResourceGroupFromID(resourceID string) string {
// Azure resource IDs follow the pattern:
// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/...
parts := strings.Split(resourceID, "/")
for i, part := range parts {
if part == "resourceGroups" && i+1 < len(parts) {
return parts[i+1]
}
}
return ""
}
// extractAppServicePlanID extracts the App Service Plan ID from a request body or resource properties.
// For Web Apps, the App Service Plan ID is stored at properties.serverFarmId.
func extractAppServicePlanID(bodyProps map[string]any) string {
if bodyProps == nil {
return ""
}
// properties.serverFarmId is the App Service Plan.
if properties, ok := bodyProps["properties"].(map[string]any); ok {
if serverFarmId, ok := properties["serverFarmId"].(string); ok && serverFarmId != "" {
return serverFarmId
}
}
return ""
}
// getSerializationMutex returns a mutex for the given serialization key, creating it if needed.
// This mutex is used to serialize operations for resources that require serialization.
func (c *azCoreClient) getSerializationMutex(serializationKey string) *sync.Mutex {
if serializationKey == "" {
return nil
}
c.serializationsMapMutex.Lock()
defer c.serializationsMapMutex.Unlock()
if mutex, ok := c.serializationsMap[serializationKey]; ok {
return mutex
}
mutex := &sync.Mutex{}
c.serializationsMap[serializationKey] = mutex
return mutex
}
// checkForSerializationDelete returns a mutex if the resource requires serialization.
func (c *azCoreClient) checkForSerializationDelete(ctx context.Context, id, apiVersion string, queryParams map[string]any) *sync.Mutex {
if !needsSerialization(id) {
return nil
}
serializationKey := c.extractSerializationKeyForDelete(ctx, id, apiVersion, queryParams)
if serializationKey == "" {
return nil
}
// Get mutex for this specific serialization key (e.g., App Service Plan ID)
return c.getSerializationMutex(serializationKey)
}
// checkForSerializationPutOrPatch returns a mutex if the resource requires serialization.
func (c *azCoreClient) checkForSerializationPutOrPatch(id string, bodyProps map[string]any) *sync.Mutex {
if !needsSerialization(id) {
return nil
}
serializationKey := extractSerializationKeyForPutOrPatch(id, bodyProps)
if serializationKey == "" {
return nil
}
// Get mutex for this specific serialization key (e.g., App Service Plan ID)
return c.getSerializationMutex(serializationKey)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/cloud/cloud.go | provider/pkg/azure/cloud/cloud.go | // Copyright 2016-2024, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cloud
import (
"context"
"fmt"
"strings"
azcloud "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud/metadata"
)
// Configuration extends azcore/cloud.Configuration with additional properties.
type Configuration struct {
azcloud.Configuration
Name string
Endpoints ConfigurationEndpoints
Suffixes ConfigurationSuffixes
}
type ConfigurationEndpoints struct {
MicrosoftGraph string
}
type ConfigurationSuffixes struct {
StorageEndpoint string
KeyVaultDNS string
}
var (
// AzurePublic contains the settings for the public Azure cloud.
AzurePublic Configuration
// AzureChina contains the settings for the Azure China cloud.
AzureChina Configuration
// AzureGovernment contains the settings for the Azure Government cloud.
AzureGovernment Configuration
)
func init() {
// Azure Public Cloud
AzurePublic = Configuration{
Name: "AzureCloud",
Configuration: azcloud.AzurePublic,
Endpoints: ConfigurationEndpoints{
MicrosoftGraph: "https://graph.microsoft.com/",
},
Suffixes: ConfigurationSuffixes{
StorageEndpoint: "core.windows.net",
KeyVaultDNS: ".vault.azure.net",
},
}
// Azure China Cloud
AzureChina = Configuration{
Name: "AzureChinaCloud",
Configuration: azcloud.AzureChina,
Endpoints: ConfigurationEndpoints{
MicrosoftGraph: "https://microsoftgraph.chinacloudapi.cn",
},
Suffixes: ConfigurationSuffixes{
StorageEndpoint: "core.chinacloudapi.cn",
KeyVaultDNS: ".vault.azure.cn",
},
}
// Azure Government Cloud
AzureGovernment = Configuration{
Name: "AzureUSGovernment",
Configuration: azcloud.AzureGovernment,
Endpoints: ConfigurationEndpoints{
MicrosoftGraph: "https://graph.microsoft.us/",
},
Suffixes: ConfigurationSuffixes{
StorageEndpoint: "core.usgovcloudapi.net",
KeyVaultDNS: ".vault.usgovcloudapi.net",
},
}
}
// FromName returns the azure-sdk-for-go/sdk/azcore/cloud configuration for the given cloud.
// Valid names are as documented in the provider's installation & configuration guide, currently
// public, china, usgovernment, or the empty value for public.
// If the cloud name is unknown, it falls back to AzurePublic and returns false.
func FromName(cloudName string) (Configuration, bool) {
switch strings.ToLower(cloudName) {
case "public", "azurecloud":
return AzurePublic, true
case "china", "azurechinacloud":
return AzureChina, true
case "usgov", "usgovernment", "azureusgovernment", "azureusgovernmentcloud", "usgovernmentl4":
return AzureGovernment, true
}
return AzurePublic, false
}
// FromMetadataEndpoint returns the azure-sdk-for-go/sdk/azcore/cloud configuration from the given metadata endpoint.
func FromMetadataEndpoint(ctx context.Context, endpoint string) (Configuration, error) {
if !strings.Contains(endpoint, "://") {
endpoint = "https://" + endpoint
}
client := metadata.NewClientWithEndpoint(endpoint)
metadata, err := client.GetMetaData(ctx)
if err != nil {
return Configuration{}, fmt.Errorf("failed to get Azure environment metadata from %s: %w", endpoint, err)
}
return Configuration{
Name: metadata.Name, // note: if using CLI authentication, this name must match the CLI's active cloud.
Configuration: azcloud.Configuration{
ActiveDirectoryAuthorityHost: metadata.Authentication.LoginEndpoint,
Services: map[azcloud.ServiceName]azcloud.ServiceConfiguration{
azcloud.ResourceManager: {
Audience: metadata.Authentication.Audiences[0],
Endpoint: metadata.ResourceManagerEndpoint,
},
},
},
Endpoints: ConfigurationEndpoints{
MicrosoftGraph: metadata.ResourceIdentifiers.MicrosoftGraph,
},
Suffixes: ConfigurationSuffixes{
StorageEndpoint: metadata.DnsSuffixes.Storage,
KeyVaultDNS: metadata.DnsSuffixes.KeyVault,
},
}, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/cloud/cloud_test.go | provider/pkg/azure/cloud/cloud_test.go | // Copyright 2016-2024, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cloud
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestFromName(t *testing.T) {
for _, tc := range []struct {
name string
expected Configuration
ok bool
}{
{name: "public", expected: AzurePublic, ok: true},
{name: "AzureCloud", expected: AzurePublic, ok: true},
{name: "china", expected: AzureChina, ok: true},
{name: "azurechinacloud", expected: AzureChina, ok: true},
{name: "AzureChinaCloud", expected: AzureChina, ok: true},
{name: "usgov", expected: AzureGovernment, ok: true},
{name: "usgovernment", expected: AzureGovernment, ok: true},
{name: "azureusgovernment", expected: AzureGovernment, ok: true},
{name: "AzureUSGovernment", expected: AzureGovernment, ok: true},
{name: "azureusgovernmentcloud", expected: AzureGovernment, ok: true},
{name: "AzureUSGovernmentCloud", expected: AzureGovernment, ok: true},
{name: "MyCloud", expected: AzurePublic, ok: false},
} {
actual, ok := FromName(tc.name)
assert.Equal(t, tc.ok, ok, tc.name)
assert.Equal(t, tc.expected, actual, tc.name)
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/cloud/metadata/models.go | provider/pkg/azure/cloud/metadata/models.go | // Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package metadata
type MetaData struct {
Authentication Authentication
DnsSuffixes DnsSuffixes
Name string
ResourceIdentifiers ResourceIdentifiers
ResourceManagerEndpoint string
}
type Authentication struct {
Audiences []string
LoginEndpoint string
IdentityProvider string
Tenant string
}
type DnsSuffixes struct {
Attestation string
ContainerRegistry string
DataLakeStore string
FrontDoor string
KeyVault string
ManagedHSM string
MariaDB string
MySql string
Postgresql string
SqlServer string
Storage string
StorageSync string
Synapse string
}
type ResourceIdentifiers struct {
Attestation string
Batch string
DataLake string
LogAnalytics string
Media string
MicrosoftGraph string
OSSRDBMS string
Synapse string
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/cloud/metadata/client.go | provider/pkg/azure/cloud/metadata/client.go | // Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package metadata
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"runtime"
"time"
)
type Client struct {
endpoint string
}
func NewClientWithEndpoint(endpoint string) *Client {
return &Client{
endpoint: endpoint,
}
}
// GetMetaData connects to the ARM metadata service at the configured endpoint, to retrieve information about the
// current environment. We currently only support the 2022-09-01 metadata schema.
func (c *Client) GetMetaData(ctx context.Context) (*MetaData, error) {
tlsConfig := tls.Config{
MinVersion: tls.VersionTLS12,
}
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
d := &net.Dialer{Resolver: &net.Resolver{}}
return d.DialContext(ctx, network, addr)
},
TLSClientConfig: &tlsConfig,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ForceAttemptHTTP2: true,
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1,
},
}
uri := fmt.Sprintf("%s/metadata/endpoints?api-version=2022-09-01", c.endpoint)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return nil, fmt.Errorf("preparing request: %+v", err)
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("performing request: %+v", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("performing request: expected 200 OK but got %d %s", resp.StatusCode, resp.Status)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("parsing response body: %+v", err)
}
resp.Body.Close()
// Trim away a BOM if present
respBody = bytes.TrimPrefix(respBody, []byte("\xef\xbb\xbf"))
var metadata *metaDataResponse
if err := json.Unmarshal(respBody, &metadata); err != nil {
log.Printf("[DEBUG] Unrecognized metadata response for %s: %s", uri, respBody)
return nil, fmt.Errorf("unmarshaling response: %+v", err)
}
return &MetaData{
Authentication: Authentication{
Audiences: metadata.Authentication.Audiences,
LoginEndpoint: metadata.Authentication.LoginEndpoint,
IdentityProvider: metadata.Authentication.IdentityProvider,
Tenant: metadata.Authentication.Tenant,
},
DnsSuffixes: DnsSuffixes{
Attestation: metadata.Suffixes.AttestationEndpoint,
ContainerRegistry: metadata.Suffixes.AcrLoginServer,
DataLakeStore: metadata.Suffixes.AzureDataLakeStoreFileSystem,
FrontDoor: metadata.Suffixes.AzureFrontDoorEndpointSuffix,
KeyVault: metadata.Suffixes.KeyVaultDns,
ManagedHSM: metadata.Suffixes.MhsmDns,
MariaDB: metadata.Suffixes.MariadbServerEndpoint,
MySql: metadata.Suffixes.MysqlServerEndpoint,
Postgresql: metadata.Suffixes.PostgresqlServerEndpoint,
SqlServer: metadata.Suffixes.SqlServerHostname,
Storage: metadata.Suffixes.Storage,
StorageSync: metadata.Suffixes.StorageSyncEndpointSuffix,
Synapse: metadata.Suffixes.SynapseAnalytics,
},
Name: metadata.Name,
ResourceIdentifiers: ResourceIdentifiers{
Attestation: normalizeResourceId(metadata.AttestationResourceId),
Batch: normalizeResourceId(metadata.Batch),
DataLake: normalizeResourceId(metadata.ActiveDirectoryDataLake),
LogAnalytics: normalizeResourceId(metadata.LogAnalyticsResourceId),
Media: normalizeResourceId(metadata.Media),
MicrosoftGraph: normalizeResourceId(metadata.MicrosoftGraphResourceId),
OSSRDBMS: normalizeResourceId(metadata.OssrDbmsResourceId),
Synapse: normalizeResourceId(metadata.SynapseAnalyticsResourceId),
},
ResourceManagerEndpoint: metadata.ResourceManager,
}, nil
}
type metaDataResponse struct {
Portal string `json:"portal"`
Authentication struct {
LoginEndpoint string `json:"loginEndpoint"`
Audiences []string `json:"audiences"`
Tenant string `json:"tenant"`
IdentityProvider string `json:"identityProvider"`
} `json:"authentication"`
Media string `json:"media"`
GraphAudience string `json:"graphAudience"`
Graph string `json:"graph"`
Name string `json:"name"`
Suffixes struct {
AzureDataLakeStoreFileSystem string `json:"azureDataLakeStoreFileSystem"`
AcrLoginServer string `json:"acrLoginServer"`
SqlServerHostname string `json:"sqlServerHostname"`
AzureDataLakeAnalyticsCatalogAndJob string `json:"azureDataLakeAnalyticsCatalogAndJob"`
KeyVaultDns string `json:"keyVaultDns"`
Storage string `json:"storage"`
AzureFrontDoorEndpointSuffix string `json:"azureFrontDoorEndpointSuffix"`
StorageSyncEndpointSuffix string `json:"storageSyncEndpointSuffix"`
MhsmDns string `json:"mhsmDns"`
MysqlServerEndpoint string `json:"mysqlServerEndpoint"`
PostgresqlServerEndpoint string `json:"postgresqlServerEndpoint"`
MariadbServerEndpoint string `json:"mariadbServerEndpoint"`
SynapseAnalytics string `json:"synapseAnalytics"`
AttestationEndpoint string `json:"attestationEndpoint"`
} `json:"suffixes"`
Batch string `json:"batch"`
ResourceManager string `json:"resourceManager"`
VmImageAliasDoc string `json:"vmImageAliasDoc"`
ActiveDirectoryDataLake string `json:"activeDirectoryDataLake"`
SqlManagement string `json:"sqlManagement"`
MicrosoftGraphResourceId string `json:"microsoftGraphResourceId"`
AppInsightsResourceId string `json:"appInsightsResourceId"`
AppInsightsTelemetryChannelResourceId string `json:"appInsightsTelemetryChannelResourceId"`
AttestationResourceId string `json:"attestationResourceId"`
SynapseAnalyticsResourceId string `json:"synapseAnalyticsResourceId"`
LogAnalyticsResourceId string `json:"logAnalyticsResourceId"`
OssrDbmsResourceId string `json:"ossrDbmsResourceId"`
Gallery string `json:"gallery"`
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/cloud/metadata/client_test.go | provider/pkg/azure/cloud/metadata/client_test.go | // Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package metadata_test
import (
"context"
"fmt"
"log"
"net"
"net/http"
"reflect"
"testing"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud/metadata"
)
var (
metadata20150101 = `{"galleryEndpoint":"https://gallery.azure.com/","graphEndpoint":"https://graph.windows.net/","portalEndpoint":"https://portal.azure.com/","authentication":{"loginEndpoint":"https://login.microsoftonline.com/","audiences":["https://management.core.windows.net/","https://management.azure.com/"]}}`
metadata20180101 = `{"galleryEndpoint":"https://gallery.azure.com/","graphEndpoint":"https://graph.windows.net/","portalEndpoint":"https://portal.azure.com/","graphAudience":"https://graph.windows.net/","authentication":{"loginEndpoint":"https://login.microsoftonline.com/","audiences":["https://management.core.windows.net/","https://management.azure.com/"],"tenant":"common","identityProvider":"AAD"},"cloudEndpoint":{"public":{"endpoint":"management.azure.com","locations":["australiacentral","australiacentral2","australiaeast","australiasoutheast","brazilsouth","brazilsoutheast","brazilus","canadacentral","canadaeast","centralindia","centralus","centraluseuap","eastasia","eastus","eastus2","eastus2euap","francecentral","francesouth","germanynorth","germanywestcentral","japaneast","japanwest","jioindiacentral","jioindiawest","koreacentral","koreasouth","northcentralus","northeurope","norwayeast","norwaywest","qatarcentral","southafricanorth","southafricawest","southcentralus","southeastasia","southindia","swedencentral","swedensouth","switzerlandnorth","switzerlandwest","uaecentral","uaenorth","uksouth","ukwest","westcentralus","westeurope","westindia","westus","westus2","westus3","israelcentral","italynorth","malaysiasouth","polandcentral","taiwannorth","taiwannorthwest"]},"chinaCloud":{"endpoint":"management.chinacloudapi.cn","locations":["chinaeast","chinanorth","chinanorth2","chinaeast2","chinanorth3","chinaeast3"]},"usGovCloud":{"endpoint":"management.usgovcloudapi.net","locations":["usgovvirginia","usgoviowa","usdodeast","usdodcentral","usgovtexas","usgovarizona"]},"germanCloud":{"endpoint":"management.microsoftazure.de","locations":["germanycentral","germanynortheast"]}}}`
metadata20190501 = `[{"portal":"https://portal.azure.com","authentication":{"loginEndpoint":"https://login.microsoftonline.com/","audiences":["https://management.core.windows.net/","https://management.azure.com/"],"tenant":"common","identityProvider":"AAD"},"media":"https://rest.media.azure.net","graphAudience":"https://graph.windows.net/","graph":"https://graph.windows.net/","name":"AzureCloud","suffixes":{"azureDataLakeStoreFileSystem":"azuredatalakestore.net","acrLoginServer":"azurecr.io","sqlServerHostname":"database.windows.net","azureDataLakeAnalyticsCatalogAndJob":"azuredatalakeanalytics.net","keyVaultDns":"vault.azure.net","storage":"core.windows.net","azureFrontDoorEndpointSuffix":"azurefd.net"},"batch":"https://batch.core.windows.net/","resourceManager":"https://management.azure.com/","vmImageAliasDoc":"https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/arm-compute/quickstart-templates/aliases.json","activeDirectoryDataLake":"https://datalake.azure.net/","sqlManagement":"https://management.core.windows.net:8443/","gallery":"https://gallery.azure.com/"},{"portal":"https://portal.azure.cn","authentication":{"loginEndpoint":"https://login.chinacloudapi.cn","audiences":["https://management.core.chinacloudapi.cn","https://management.chinacloudapi.cn"],"tenant":"common","identityProvider":"AAD"},"media":"https://rest.media.chinacloudapi.cn","graphAudience":"https://graph.chinacloudapi.cn","graph":"https://graph.chinacloudapi.cn","name":"AzureChinaCloud","suffixes":{"acrLoginServer":"azurecr.cn","sqlServerHostname":"database.chinacloudapi.cn","keyVaultDns":"vault.azure.cn","storage":"core.chinacloudapi.cn","azureFrontDoorEndpointSuffix":""},"batch":"https://batch.chinacloudapi.cn","resourceManager":"https://management.chinacloudapi.cn","vmImageAliasDoc":"https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/arm-compute/quickstart-templates/aliases.json","sqlManagement":"https://management.core.chinacloudapi.cn:8443","gallery":"https://gallery.chinacloudapi.cn"},{"portal":"https://portal.azure.us","authentication":{"loginEndpoint":"https://login.microsoftonline.us","audiences":["https://management.core.usgovcloudapi.net","https://management.usgovcloudapi.net"],"tenant":"common","identityProvider":"AAD"},"media":"https://rest.media.usgovcloudapi.net","graphAudience":"https://graph.windows.net","graph":"https://graph.windows.net","name":"AzureUSGovernment","suffixes":{"acrLoginServer":"azurecr.us","sqlServerHostname":"database.usgovcloudapi.net","keyVaultDns":"vault.usgovcloudapi.net","storage":"core.usgovcloudapi.net","azureFrontDoorEndpointSuffix":""},"batch":"https://batch.core.usgovcloudapi.net","resourceManager":"https://management.usgovcloudapi.net","vmImageAliasDoc":"https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/arm-compute/quickstart-templates/aliases.json","sqlManagement":"https://management.core.usgovcloudapi.net:8443","gallery":"https://gallery.usgovcloudapi.net"},{"portal":"https://portal.microsoftazure.de","authentication":{"loginEndpoint":"https://login.microsoftonline.de","audiences":["https://management.core.cloudapi.de","https://management.microsoftazure.de"],"tenant":"common","identityProvider":"AAD"},"media":"https://rest.media.cloudapi.de","graphAudience":"https://graph.cloudapi.de","graph":"https://graph.cloudapi.de","name":"AzureGermanCloud","suffixes":{"sqlServerHostname":"database.cloudapi.de","keyVaultDns":"vault.microsoftazure.de","storage":"core.cloudapi.de","azureFrontDoorEndpointSuffix":""},"batch":"https://batch.cloudapi.de","resourceManager":"https://management.microsoftazure.de","vmImageAliasDoc":"https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/arm-compute/quickstart-templates/aliases.json","sqlManagement":"https://management.core.cloudapi.de:8443","gallery":"https://gallery.cloudapi.de"}]`
metadata20220901 = `{"portal":"https://portal.azure.com","authentication":{"loginEndpoint":"https://login.microsoftonline.com","audiences":["https://management.core.windows.net/","https://management.azure.com/"],"tenant":"common","identityProvider":"AAD"},"media":"https://rest.media.azure.net","graphAudience":"https://graph.windows.net/","graph":"https://graph.windows.net/","name":"AzureCloud","suffixes":{"azureDataLakeStoreFileSystem":"azuredatalakestore.net","acrLoginServer":"azurecr.io","sqlServerHostname":"database.windows.net","azureDataLakeAnalyticsCatalogAndJob":"azuredatalakeanalytics.net","keyVaultDns":"vault.azure.net","storage":"core.windows.net","azureFrontDoorEndpointSuffix":"azurefd.net","storageSyncEndpointSuffix":"afs.azure.net","mhsmDns":"managedhsm.azure.net","mysqlServerEndpoint":"mysql.database.azure.com","postgresqlServerEndpoint":"postgres.database.azure.com","mariadbServerEndpoint":"mariadb.database.azure.com","synapseAnalytics":"dev.azuresynapse.net","attestationEndpoint":"attest.azure.net"},"batch":"https://batch.core.windows.net/","resourceManager":"https://management.azure.com/","vmImageAliasDoc":"https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/arm-compute/quickstart-templates/aliases.json","activeDirectoryDataLake":"https://datalake.azure.net/","sqlManagement":"https://management.core.windows.net:8443/","microsoftGraphResourceId":"https://graph.microsoft.com/","appInsightsResourceId":"https://api.applicationinsights.io","appInsightsTelemetryChannelResourceId":"https://dc.applicationinsights.azure.com/v2/track","attestationResourceId":"https://attest.azure.net","synapseAnalyticsResourceId":"https://dev.azuresynapse.net","logAnalyticsResourceId":"https://api.loganalytics.io","ossrDbmsResourceId":"https://ossrdbms-aad.database.windows.net"}`
)
func TestGetMetaData(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
addr := metadataStubServer(ctx)
defer func() {
cancel()
}()
client := metadata.NewClientWithEndpoint(fmt.Sprintf("http://%s", addr))
if client == nil {
t.Fatal("client was nil")
}
expected := metadata.MetaData{
Authentication: metadata.Authentication{
Audiences: []string{
"https://management.core.windows.net/",
"https://management.azure.com/",
},
LoginEndpoint: "https://login.microsoftonline.com",
IdentityProvider: "AAD",
Tenant: "common",
},
DnsSuffixes: metadata.DnsSuffixes{
Attestation: "attest.azure.net",
ContainerRegistry: "azurecr.io",
DataLakeStore: "azuredatalakestore.net",
FrontDoor: "azurefd.net",
KeyVault: "vault.azure.net",
ManagedHSM: "managedhsm.azure.net",
MariaDB: "mariadb.database.azure.com",
MySql: "mysql.database.azure.com",
Postgresql: "postgres.database.azure.com",
SqlServer: "database.windows.net",
Storage: "core.windows.net",
StorageSync: "afs.azure.net",
Synapse: "dev.azuresynapse.net",
},
Name: "AzureCloud",
ResourceIdentifiers: metadata.ResourceIdentifiers{
Attestation: "https://attest.azure.net",
Batch: "https://batch.core.windows.net",
DataLake: "https://datalake.azure.net",
LogAnalytics: "https://api.loganalytics.io",
Media: "https://rest.media.azure.net",
MicrosoftGraph: "https://graph.microsoft.com",
OSSRDBMS: "https://ossrdbms-aad.database.windows.net",
Synapse: "https://dev.azuresynapse.net",
},
ResourceManagerEndpoint: "https://management.azure.com/",
}
m, err := client.GetMetaData(ctx)
if err != nil {
t.Fatalf("error received: %+v", err)
} else if m == nil {
t.Fatal("metadata result was nil")
} else if !reflect.DeepEqual(*m, expected) {
t.Fatalf("unexpected Metadata{} result.\nexpected:\n\n%#v\n\nreceived:\n\n%#v\n", expected, *m)
}
}
func metadataStubServer(ctx context.Context) net.Addr {
handler := http.NewServeMux()
handler.HandleFunc("/metadata/endpoints", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
apiVersion := q.Get("api-version")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
switch apiVersion {
case "1.0", "2015-01-01":
fmt.Fprint(w, metadata20150101)
case "2018-01-01":
fmt.Fprint(w, metadata20180101)
case "2019-05-01":
fmt.Fprint(w, metadata20190501)
case "2022-09-01":
fmt.Fprint(w, metadata20220901)
default:
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `{"error":"unrecognized api-version"}`)
return
}
})
var lc net.ListenConfig
listener, err := lc.Listen(ctx, "tcp", "localhost:0")
if err != nil {
panic(fmt.Sprintf("could not start listener: %s", err))
}
server := &http.Server{
Addr: listener.Addr().String(),
Handler: handler,
}
go func() {
if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Printf("server error: %s\n", err)
}
log.Printf("ARM Metadata Stub Service stopped\n")
}()
go func() {
<-ctx.Done()
err := server.Shutdown(ctx)
if err != nil {
log.Printf("failed to gracefully shut down ARM Metadata stub server: %v", err)
}
}()
log.Printf("ARM Metadata Stub Service listening on %s\n", listener.Addr())
return listener.Addr()
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/cloud/metadata/helpers.go | provider/pkg/azure/cloud/metadata/helpers.go | // Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package metadata
import "strings"
func normalizeResourceId(resourceId string) string {
return strings.TrimRight(resourceId, "/")
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/azure/cloud/metadata/server/main.go | provider/pkg/azure/cloud/metadata/server/main.go | // Copyright 2016-2024, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"flag"
"fmt"
"log"
"net/http"
)
var (
metadata20220901 = `{"portal":"https://portal.azure.com","authentication":{"loginEndpoint":"https://login.microsoftonline.com","audiences":["https://management.core.windows.net/","https://management.azure.com/"],"tenant":"common","identityProvider":"AAD"},"media":"https://rest.media.azure.net","graphAudience":"https://graph.windows.net/","graph":"https://graph.windows.net/","name":"AzureCloud","suffixes":{"azureDataLakeStoreFileSystem":"azuredatalakestore.net","acrLoginServer":"azurecr.io","sqlServerHostname":"database.windows.net","azureDataLakeAnalyticsCatalogAndJob":"azuredatalakeanalytics.net","keyVaultDns":"vault.azure.net","storage":"core.windows.net","azureFrontDoorEndpointSuffix":"azurefd.net","storageSyncEndpointSuffix":"afs.azure.net","mhsmDns":"managedhsm.azure.net","mysqlServerEndpoint":"mysql.database.azure.com","postgresqlServerEndpoint":"postgres.database.azure.com","mariadbServerEndpoint":"mariadb.database.azure.com","synapseAnalytics":"dev.azuresynapse.net","attestationEndpoint":"attest.azure.net"},"batch":"https://batch.core.windows.net/","resourceManager":"https://management.azure.com/","vmImageAliasDoc":"https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/arm-compute/quickstart-templates/aliases.json","activeDirectoryDataLake":"https://datalake.azure.net/","sqlManagement":"https://management.core.windows.net:8443/","microsoftGraphResourceId":"https://graph.microsoft.com/","appInsightsResourceId":"https://api.applicationinsights.io","appInsightsTelemetryChannelResourceId":"https://dc.applicationinsights.azure.com/v2/track","attestationResourceId":"https://attest.azure.net","synapseAnalyticsResourceId":"https://dev.azuresynapse.net","logAnalyticsResourceId":"https://api.loganalytics.io","ossrDbmsResourceId":"https://ossrdbms-aad.database.windows.net"}`
)
func main() {
var (
addr = flag.String("addr", ":8080", "address to listen on")
cert = flag.String("cert", "", "path to TLS certificate file (PEM format)")
key = flag.String("key", "", "path to TLS private key file (PEM format)")
)
flag.Parse()
http.HandleFunc("/metadata/endpoints", func(w http.ResponseWriter, r *http.Request) {
apiVersion := r.URL.Query().Get("api-version")
log.Printf("Metadata request received for API Version: %s", apiVersion)
if apiVersion != "2022-09-01" {
http.Error(w, "Unsupported API version", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprint(w, metadata20220901)
})
if *cert != "" && *key != "" {
log.Printf("Local Azure Metadata Service listening with HTTPS on %s", *addr)
if err := http.ListenAndServeTLS(*addr, *cert, *key, nil); err != nil {
log.Fatalf("HTTPS server failed: %v", err)
}
} else {
log.Printf("Local Azure Metadata Service listening with HTTP on %s (no TLS cert/key provided)", *addr)
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatalf("HTTP server failed: %v", err)
}
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/gen_aliases_test.go | provider/pkg/gen/gen_aliases_test.go | package gen
import (
"os"
"path"
"testing"
"github.com/blang/semver"
"github.com/gkampitakis/go-snaps/snaps"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
)
func TestAliasesGen(t *testing.T) {
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
// We take a snapshot of the schema as we're focusing on testing how we parse the spec
// To update the specifications run in the repo root:
// 1. rm -rf provider/pkg/gen/test-data/aliases/azure-rest-api-specs/specification/common-types/resource-management/v1/
// 2. rm -rf provider/pkg/gen/test-data/aliases/azure-rest-api-specs/specification/azureactivedirectory/resource-manager/Microsoft.Aadiam/stable/2020-03-01/
// 3. cp -r azure-rest-api-specs/specification/common-types/resource-management/v1 provider/pkg/gen/test-data/aliases/azure-rest-api-specs/specification/common-types/resource-management/
// 4. cp -r azure-rest-api-specs/specification/azureactivedirectory/resource-manager/Microsoft.Aadiam/stable/2020-03-01 provider/pkg/gen/test-data/aliases/azure-rest-api-specs/specification/azureactivedirectory/resource-manager/Microsoft.Aadiam/stable/
// 5. rm -rf provider/pkg/gen/test-data/aliases/azure-rest-api-specs/specification/azureactivedirectory/resource-manager/Microsoft.Aadiam/stable/2020-03-01/examples/
rootDir := path.Join(wd, "test-data", "aliases")
// azure-rest-api-specs/specification/common-types/resource-management/v1
modules, _, err := openapi.ReadAzureModules(path.Join(rootDir, "azure-rest-api-specs"), "Aadiam", "2020-03-01")
if err != nil {
t.Fatal(err)
}
t.Run("v2", func(t *testing.T) {
generationResult, err := PulumiSchema(rootDir, modules, versioningStub{}, semver.MustParse("2.0.0"), false /* onlyExplicitVersions */)
if err != nil {
t.Fatal(err)
}
s := snaps.WithConfig(snaps.Filename("gen_aliases_test_v2"))
s.MatchJSON(t, generationResult.Schema)
s.MatchJSON(t, generationResult.Metadata)
})
t.Run("v3", func(t *testing.T) {
versioning := versioningStub{
// These are extracted from versions/v2-token-paths.json
previousTokenPaths: map[string]string{
"azure-native:aadiam/v20200301:PrivateEndpointConnection": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.aadiam/privateLinkForAzureAd/{policyName}/privateEndpointConnections/{privateEndpointConnectionName}",
"azure-native:aadiam:PrivateEndpointConnection": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.aadiam/privateLinkForAzureAd/{policyName}/privateEndpointConnections/{privateEndpointConnectionName}",
"azure-native:aadiam:PrivateLinkForAzureAd": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.aadiam/privateLinkForAzureAd/{policyName}",
"azure-native:aadiam/v20200301preview:PrivateLinkForAzureAd": "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.aadiam/privateLinkForAzureAd/{policyName}",
},
}
generationResult, err := PulumiSchema(rootDir, modules, versioning, semver.MustParse("3.0.0"), false /* onlyExplicitVersions */)
if err != nil {
t.Fatal(err)
}
s := snaps.WithConfig(snaps.Filename("gen_aliases_test_v3"))
s.MatchJSON(t, generationResult.Schema)
s.MatchJSON(t, generationResult.Metadata)
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/merging_test.go | provider/pkg/gen/merging_test.go | // Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gen
import (
"testing"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/stretchr/testify/assert"
)
func Test_mergeTypes(t *testing.T) {
type args struct {
t1 schema.ComplexTypeSpec
t2 schema.ComplexTypeSpec
isOutput bool
}
tests := []struct {
name string
args args
want schema.ComplexTypeSpec
wantErr bool
}{
{
name: "object and enum",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: schema.TypeSpec{
Type: "number",
},
},
}),
t2: schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Type: "string",
},
Enum: []schema.EnumValueSpec{
{Value: "foo"},
},
},
},
wantErr: true,
},
{
name: "integer and number becomes number",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: schema.TypeSpec{
Type: "number",
},
},
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: schema.TypeSpec{
Type: "integer",
},
},
}),
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: schema.TypeSpec{
Type: "number",
},
},
}),
},
{
name: "includes both distinct properties",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": stringPropertySpec(),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"bar": stringPropertySpec(),
}),
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": stringPropertySpec(),
"bar": stringPropertySpec(),
}),
},
{
name: "fails if requiredness differs for inputs",
args: args{
t1: requiredObjectComplexType(map[string]schema.PropertySpec{
"foo": stringPropertySpec(),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": stringPropertySpec(),
}),
isOutput: false,
},
wantErr: true,
},
{
name: "requiredness differs for outputs",
args: args{
t1: requiredObjectComplexType(map[string]schema.PropertySpec{
"foo": stringPropertySpec(),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": stringPropertySpec(),
}),
isOutput: true,
},
want: requiredObjectComplexType(map[string]schema.PropertySpec{
"foo": stringPropertySpec(),
}),
},
{
name: "matching refs",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": refPropertySpec("#/definitions/ResourceId"),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": refPropertySpec("#/definitions/ResourceId"),
}),
isOutput: true,
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": refPropertySpec("#/definitions/ResourceId"),
}),
},
{
name: "non-matching refs",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": refPropertySpec("#/definitions/A"),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": refPropertySpec("#/definitions/B"),
}),
isOutput: true,
},
wantErr: true,
},
{
name: "output oneOf merged with ref",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": refPropertySpec("#/definitions/ResourceId"),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/ResourceId"), stringType()),
},
}),
isOutput: true,
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/ResourceId"), stringType()),
},
}),
},
{
name: "union two oneOf outputs",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/FooA"), stringType()),
},
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/FooB"), stringType()),
},
}),
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/FooA"), stringType(), refType("#/definitions/FooB")),
},
}),
},
{
name: "union two identical oneOf inputs",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/FooA"), refType("#/definitions/FooB")),
},
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/FooA"), refType("#/definitions/FooB")),
},
}),
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/FooA"), refType("#/definitions/FooB")),
},
}),
},
{
name: "union two identical discriminated types",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: discriminatedType("prop", map[string]string{"a": "#/definitions/FooA", "b": "#/definitions/FooB"}, refType("#/definitions/FooA"), refType("#/definitions/FooB")),
},
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: discriminatedType("prop", map[string]string{"a": "#/definitions/FooA", "b": "#/definitions/FooB"}, refType("#/definitions/FooA"), refType("#/definitions/FooB")),
},
}),
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: discriminatedType("prop", map[string]string{"a": "#/definitions/FooA", "b": "#/definitions/FooB"}, refType("#/definitions/FooA"), refType("#/definitions/FooB")),
},
}),
},
{
name: "union two different discriminated types",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: discriminatedType("prop", map[string]string{"a": "#/definitions/FooA", "b": "#/definitions/FooB"}, refType("#/definitions/FooA"), refType("#/definitions/FooB")),
},
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: discriminatedType("prop", map[string]string{"a": "#/definitions/FooA", "c": "#/definitions/FooC"}, refType("#/definitions/FooA"), refType("#/definitions/FooC")),
},
}),
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: discriminatedType("prop", map[string]string{"a": "#/definitions/FooA", "b": "#/definitions/FooB", "c": "#/definitions/FooC"}, refType("#/definitions/FooA"), refType("#/definitions/FooB"), refType("#/definitions/FooC")),
},
}),
},
{
name: "union discriminated and non-discriminated types fails",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: discriminatedType("prop", map[string]string{"a": "#/definitions/FooA", "b": "#/definitions/FooB"}, refType("#/definitions/FooA"), refType("#/definitions/FooB")),
},
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/FooA"), refType("#/definitions/FooC")),
},
}),
},
wantErr: true,
},
{
name: "array of refs",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": arrayPropertySpec(refType("#/definitions/ResourceId")),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": arrayPropertySpec(refType("#/definitions/ResourceId")),
}),
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": arrayPropertySpec(refType("#/definitions/ResourceId")),
}),
},
{
name: "array of incompatible refs",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": arrayPropertySpec(refType("#/definitions/A")),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": arrayPropertySpec(refType("#/definitions/B")),
}),
},
wantErr: true,
},
{
name: "map of strings",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": objectPropertySpec(stringType()),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": objectPropertySpec(stringType()),
}),
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": objectPropertySpec(stringType()),
}),
},
{
name: "map of incompatible types",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": objectPropertySpec(refType("#/definitions/A")),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": objectPropertySpec(refType("#/definitions/B")),
}),
},
wantErr: true,
},
{
name: "non-mergable types",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": objectPropertySpec(refType("#/definitions/A")),
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": arrayPropertySpec(refType("#/definitions/A")),
}),
},
wantErr: true,
},
{
name: "merge oneOf with primative",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/A"), refType("#/definitions/B")),
},
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": stringPropertySpec(),
}),
},
want: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/A"), refType("#/definitions/B"), stringType()),
},
}),
},
{
name: "merge oneOfs with different discriminators",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: discriminatedType("a", map[string]string{"a": "#/definitions/A", "b": "#/definitions/B"}, refType("#/definitions/A"), refType("#/definitions/B")),
},
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: discriminatedType("b", map[string]string{"a": "#/definitions/A", "c": "#/definitions/C"}, refType("#/definitions/A"), refType("#/definitions/C")),
},
}),
},
wantErr: true,
},
{
name: "merge oneOfs with array",
args: args{
t1: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: oneOfType(refType("#/definitions/A"), refType("#/definitions/B"), stringType()),
},
}),
t2: objectComplexType(map[string]schema.PropertySpec{
"foo": {
TypeSpec: arrayType(refType("#/definitions/A")),
},
}),
},
// cannot union oneOf with specified type
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := mergeTypes(tt.args.t1, tt.args.t2, tt.args.isOutput)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
if !assert.NotNil(t, got) {
return
}
assert.Equal(t, tt.want, *got)
})
}
}
func objectComplexType(properties map[string]schema.PropertySpec) schema.ComplexTypeSpec {
return schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Type: "object",
Properties: properties,
},
}
}
func requiredObjectComplexType(properties map[string]schema.PropertySpec) schema.ComplexTypeSpec {
required := make([]string, 0, len(properties))
for k := range properties {
required = append(required, k)
}
return schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Type: "object",
Properties: properties,
Required: required,
},
}
}
func stringPropertySpec() schema.PropertySpec {
return schema.PropertySpec{
TypeSpec: stringType(),
}
}
func refPropertySpec(ref string) schema.PropertySpec {
return schema.PropertySpec{
TypeSpec: refType(ref),
}
}
func arrayPropertySpec(items schema.TypeSpec) schema.PropertySpec {
return schema.PropertySpec{
TypeSpec: arrayType(items),
}
}
func objectPropertySpec(additionalProperties schema.TypeSpec) schema.PropertySpec {
return schema.PropertySpec{
TypeSpec: objectType(additionalProperties),
}
}
func oneOfType(types ...schema.TypeSpec) schema.TypeSpec {
return schema.TypeSpec{
OneOf: types,
}
}
func discriminatedType(propertyName string, mapping map[string]string, types ...schema.TypeSpec) schema.TypeSpec {
return schema.TypeSpec{
OneOf: types,
Discriminator: &schema.DiscriminatorSpec{
PropertyName: propertyName,
Mapping: mapping,
},
}
}
func refType(ref string) schema.TypeSpec {
return schema.TypeSpec{
Ref: ref,
}
}
func stringType() schema.TypeSpec {
return schema.TypeSpec{
Type: "string",
}
}
func arrayType(items schema.TypeSpec) schema.TypeSpec {
return schema.TypeSpec{
Type: "array",
Items: &items,
}
}
func objectType(additionalProperties schema.TypeSpec) schema.TypeSpec {
return schema.TypeSpec{
Type: "object",
AdditionalProperties: &additionalProperties,
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/readParams.go | provider/pkg/gen/readParams.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package gen
// Map of "azure-native:foo:Bar" -> map of URL params and values, to be used in GET requests.
// When the spec defines optional query parameters for GET requests, the provider doesn't use them
// by default. Add them here to be used by default.
var defaultReadQueryParams = map[string]map[string]any{
"azure-native:sqlvirtualmachine:SqlVirtualMachine": {
"$expand": "*", // #3581: without this parameter, GET requests only return a subset of properties
},
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/exclude.go | provider/pkg/gen/exclude.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package gen
import (
"regexp"
)
// excludeResourcePatterns lists resources being skipped due to known codegen issues.
var excludeResourcePatterns = []string{
"azure-native:chaos:Experiment",
"azure-native:datafactory:Pipeline", // go codegen goes full CPU and doesn't return
"azure-native:hybridcompute:GuestConfigurationHCRPAssignment", // python name mismatch
}
var excludeRegexes []*regexp.Regexp
func init() {
for _, pattern := range excludeResourcePatterns {
excludeRegexes = append(excludeRegexes, regexp.MustCompile(pattern))
}
}
func ShouldExclude(pulumiToken string) bool {
for _, re := range excludeRegexes {
if re.MatchString(pulumiToken) {
return true
}
}
return false
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/compatibleTypes_test.go | provider/pkg/gen/compatibleTypes_test.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package gen
import (
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/stretchr/testify/assert"
"testing"
)
func TestComplexTypeMerge(t *testing.T) {
t.Run("Empty output", func(t *testing.T) {
t1 := schema.ComplexTypeSpec{}
t2 := schema.ComplexTypeSpec{}
actual, err := mergeTypes(t1, t2, false)
expected := schema.ComplexTypeSpec{}
assert.NoError(t, err)
assert.Equal(t, expected, *actual)
})
t.Run("Single Property", func(t *testing.T) {
t1 := schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Type: "object",
Properties: map[string]schema.PropertySpec{
"a": {
TypeSpec: schema.TypeSpec{
Type: "string",
},
},
},
},
}
t2 := t1
actual, err := mergeTypes(t1, t2, false)
expected := t1
assert.NoError(t, err)
assert.Equal(t, expected, *actual)
})
t.Run("Diff optional property", func(t *testing.T) {
t1 := schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Type: "object",
Properties: map[string]schema.PropertySpec{
"a": {
TypeSpec: schema.TypeSpec{
Type: "string",
},
},
},
},
}
t2 := schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Type: "object",
Properties: map[string]schema.PropertySpec{
"b": {
TypeSpec: schema.TypeSpec{
Type: "string",
},
},
},
},
}
actual, err := mergeTypes(t1, t2, false)
expected := schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Type: "object",
Properties: map[string]schema.PropertySpec{
"a": {
TypeSpec: schema.TypeSpec{
Type: "string",
},
},
"b": {
TypeSpec: schema.TypeSpec{
Type: "string",
},
},
},
},
}
assert.NoError(t, err)
assert.Equal(t, expected, *actual)
})
t.Run("Diff required property", func(t *testing.T) {
t1 := schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Type: "object",
Properties: map[string]schema.PropertySpec{
"a": {
TypeSpec: schema.TypeSpec{
Type: "string",
},
},
},
Required: []string{"a"},
},
}
t2 := schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Type: "object",
Properties: map[string]schema.PropertySpec{
"b": {
TypeSpec: schema.TypeSpec{
Type: "string",
},
},
},
},
}
_, err := mergeTypes(t1, t2, false)
assert.Error(t, err)
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/types_test.go | provider/pkg/gen/types_test.go | package gen
import (
"testing"
"github.com/go-openapi/spec"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestEnumExtensionCaseCollapsing(t *testing.T) {
generator := moduleGenerator{
pkg: &schema.PackageSpec{
Name: "azure-native",
Types: map[string]schema.ComplexTypeSpec{},
},
module: "MyModule",
}
// Doesn't return the enum - it's added to the Types map
schema := &spec.Schema{
SchemaProps: spec.SchemaProps{},
}
enumExtensions := map[string]interface{}{"name": "myProp", "values": []interface{}{
map[string]interface{}{"value": "foo", "name": "Foo"},
map[string]interface{}{"value": "Foo", "name": "Foo"},
map[string]interface{}{"value": "bar", "name": "Bar"},
}}
_, err := generator.genEnumType(schema, &openapi.ReferenceContext{}, enumExtensions, "unusedPropertyName")
require.NoError(t, err)
assert.Len(t, generator.pkg.Types, 1)
require.Contains(t, generator.pkg.Types, "azure-native:MyModule:MyProp")
require.Len(t, generator.pkg.Types["azure-native:MyModule:MyProp"].Enum, 2)
assert.Equal(t, generator.pkg.Types["azure-native:MyModule:MyProp"].Enum[0].Value, "foo")
assert.Equal(t, generator.pkg.Types["azure-native:MyModule:MyProp"].Enum[1].Value, "bar")
}
func TestEnumNonExtensionCaseCollapsing(t *testing.T) {
generator := moduleGenerator{
pkg: &schema.PackageSpec{
Name: "azure-native",
Types: map[string]schema.ComplexTypeSpec{},
},
module: "MyModule",
}
// Doesn't return the enum - it's added to the Types map
_, err := generator.genEnumType(&spec.Schema{
SchemaProps: spec.SchemaProps{
Enum: []interface{}{
"foo",
"Foo",
"bar",
},
},
}, &openapi.ReferenceContext{}, map[string]interface{}{"name": "myProp"}, "unusedPropertyName")
require.NoError(t, err)
assert.Len(t, generator.pkg.Types, 1)
require.Contains(t, generator.pkg.Types, "azure-native:MyModule:MyProp")
require.Len(t, generator.pkg.Types["azure-native:MyModule:MyProp"].Enum, 2)
assert.Equal(t, generator.pkg.Types["azure-native:MyModule:MyProp"].Enum[0].Value, "foo")
assert.Equal(t, generator.pkg.Types["azure-native:MyModule:MyProp"].Enum[1].Value, "bar")
}
func TestEnumNameFallbackToPropertyNames(t *testing.T) {
generator := moduleGenerator{
pkg: &schema.PackageSpec{
Name: "azure-native",
Types: map[string]schema.ComplexTypeSpec{},
},
module: "MyModule",
}
schema := &spec.Schema{
SchemaProps: spec.SchemaProps{},
}
enumExtensions := map[string]interface{}{"values": []interface{}{
map[string]interface{}{"value": "foo", "name": "Foo"},
}}
const propertyName = "myProp"
_, err := generator.genEnumType(schema, &openapi.ReferenceContext{}, enumExtensions, propertyName)
require.NoError(t, err)
assert.Len(t, generator.pkg.Types, 1)
require.Contains(t, generator.pkg.Types, "azure-native:MyModule:MyProp")
require.Len(t, generator.pkg.Types["azure-native:MyModule:MyProp"].Enum, 1)
assert.Equal(t, generator.pkg.Types["azure-native:MyModule:MyProp"].Enum[0].Value, "foo")
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/examples_test.go | provider/pkg/gen/examples_test.go | // Copyright 2022, Pulumi Corporation. All rights reserved.
package gen
import (
"testing"
"github.com/segmentio/encoding/json"
"github.com/stretchr/testify/assert"
)
func TestExtractResponseNameId(t *testing.T) {
// from connectedvmware/resource-manager/Microsoft.ConnectedVMwarevSphere/preview/2020-10-01-preview/examples/CreateResourcePool.json
var createExample = []byte(`{
"parameters": {},
"responses": {
"200": {
"body": {
"id": "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/HRPool",
"name": "HRPool"
}
},
"201": {
"body": {
"id": "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/ContosoAgent",
"name": "ContosoAgent"
}
}
}
}`)
exampleJSON := parse(createExample, t)
responseId, responseName := extractExampleResponseNameId(exampleJSON)
assert.Equal(t, "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/HRPool", responseId)
assert.Equal(t, "HRPool", responseName)
}
func TestExtractResponseNameIdInOrder(t *testing.T) {
// lowest status code first regardless of order in the example
var createExample = []byte(`{
"parameters": {},
"responses": {
"201": {
"body": {
"id": "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/ContosoAgent",
"name": "ContosoAgent"
}
},
"200": {
"body": {
"id": "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/HRPool",
"name": "HRPool"
}
}
}
}`)
exampleJSON := parse(createExample, t)
responseId, responseName := extractExampleResponseNameId(exampleJSON)
assert.Equal(t, "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/HRPool", responseId)
assert.Equal(t, "HRPool", responseName)
}
func TestCanHaveOnlyId(t *testing.T) {
var createExample = []byte(`{
"parameters": {},
"responses": {
"200": {
"body": {
"id": "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/HRPool"
}
},
"201": {
"body": {
"name": "ContosoAgent"
}
}
}
}`)
exampleJSON := parse(createExample, t)
responseId, responseName := extractExampleResponseNameId(exampleJSON)
assert.Equal(t, "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/HRPool", responseId)
assert.Empty(t, responseName)
}
func TestPicksNameIdPairIfPresent(t *testing.T) {
// lowest status code first regardless of order in the example
var createExample = []byte(`{
"parameters": {},
"responses": {
"200": {
"body": {
"id": "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/ContosoAgent"
}
},
"201": {
"body": {
"name": "ContosoAgent"
}
},
"202": {
"body": {
"id": "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/HRPool",
"name": "HRPool"
}
}
}
}`)
exampleJSON := parse(createExample, t)
responseId, responseName := extractExampleResponseNameId(exampleJSON)
assert.Equal(t, "/subscriptions/fd3c3665-1729-4b7b-9a38-238e83b0f98b/resourceGroups/testrg/providers/Microsoft.ConnectedVMwarevSphere/ResourcePools/HRPool", responseId)
assert.Equal(t, "HRPool", responseName)
}
func parse(jsonStr []byte, t *testing.T) map[string]interface{} {
var exampleJSON map[string]interface{}
if err := json.Unmarshal(jsonStr, &exampleJSON); err != nil {
t.Fatalf("Could not parse example JSON: %v", err)
}
return exampleJSON
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/types.go | provider/pkg/gen/types.go | // Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gen
import (
"fmt"
"strings"
"github.com/go-openapi/spec"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/convert"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/version"
"github.com/pulumi/pulumi/pkg/v3/codegen"
pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
)
func (m *moduleGenerator) genTypeSpec(propertyName string, schema *spec.Schema, context *openapi.ReferenceContext, isOutput bool) (*pschema.TypeSpec, error) {
resolvedSchema, err := context.ResolveSchema(schema)
if err != nil {
return nil, fmt.Errorf("failed to resolve schema: %w", err)
}
// Type specification specifies either a primitive type (e.g. 'string') or a reference to a separately defined
// strongly-typed object. Either `primitiveTypeName` or `referencedTypeName` should be filled, but not both.
var primitiveTypeName string
if len(resolvedSchema.Type) > 0 {
primitiveTypeName = resolvedSchema.Type[0]
if primitiveTypeName == "integer" && resolvedSchema.Format == "int64" {
// Pulumi schema's integer is limited to 32 bits. Model a 64-bit integer as a number.
primitiveTypeName = "number"
}
}
// If this is an enum and it's an input type, generate the enum type definition.
enumExtension, isEnum := resolvedSchema.Extensions[extensionEnum].(map[string]interface{})
if !isOutput && isEnum && resolvedSchema.Enum != nil &&
// There are some boolean-, integer-, and number- based definitions but they aren't allowed by the Azure specs.
// Ignore both to preserve over-the-wire format even if they say it's an enum to be modelled as a string.
primitiveTypeName != "boolean" && primitiveTypeName != "integer" && primitiveTypeName != "number" {
return m.genEnumType(schema, context, enumExtension, propertyName)
}
switch {
case len(resolvedSchema.Properties) > 0 || len(resolvedSchema.AllOf) > 0:
ptr := schema.Ref.GetPointer()
var tok string
if ptr != nil && !ptr.IsEmpty() {
tok = m.typeName(resolvedSchema.ReferenceContext, isOutput)
} else {
// Inline properties have no type in the Open API schema, so we use parent type's name + property name.
tok = m.typeName(context, isOutput) + m.inlineTypeName(context, propertyName)
}
// If an object type is referenced, add its definition to the type map.
discriminatedType, ok, err := m.genDiscriminatedType(resolvedSchema, isOutput)
if err != nil {
return nil, fmt.Errorf("failed to generate discriminated type: %w", err)
}
if ok {
return discriminatedType, nil
}
tok = m.caseSensitiveTypes.normalizeTokenCase(tok)
if _, ok := m.visitedTypes[tok]; !ok {
m.visitedTypes[tok] = true
props, err := m.genProperties(resolvedSchema, genPropertiesVariant{
isOutput: isOutput,
isType: true,
isResponse: false,
})
if err != nil {
return nil, err
}
// Don't generate a type definition for a typed object with zero properties.
if len(props.specs) == 0 {
delete(m.visitedTypes, tok)
return nil, nil
}
// Describe special syntax for relative self-references of sub-resources.
if strings.HasSuffix(tok, ":SubResource") {
if prop, ok := props.specs["id"]; ok {
prop.Description = `Sub-resource ID. Both absolute resource ID and a relative resource ID are accepted.
An absolute ID starts with /subscriptions/ and contains the entire ID of the parent resource and the ID of the sub-resource in the end.
A relative ID replaces the ID of the parent resource with a token '$self', followed by the sub-resource ID itself.
Example of a relative ID: $self/frontEndConfigurations/my-frontend.`
props.specs["id"] = prop
}
}
// incompatible type "azure-native:network:SecurityRule" for resource "LoadBalancer" ("azure-native:network:LoadBalancer"): required properties do not match: only required in A: priority
if tok == "azure-native:network:SecurityRule" {
props.requiredProperties.Delete("priority")
props.requiredSpecs.Delete("priority")
}
// incompatible type "azure-native:containerinstance:Container" for resource "ContainerGroupProfile"
// ("azure-native:containerinstance:ContainerGroupProfile"): required properties do not match: only
// required in B: image,resources
if tok == "azure-native:containerinstance:Container" {
props.requiredProperties.Delete("image")
props.requiredSpecs.Delete("image")
props.requiredProperties.Delete("resources")
props.requiredSpecs.Delete("resources")
}
spec := pschema.ComplexTypeSpec{
ObjectTypeSpec: pschema.ObjectTypeSpec{
Description: resolvedSchema.Description,
Type: "object",
Properties: props.specs,
Required: props.requiredSpecs.SortedValues(),
},
}
if existing, has := m.pkg.Types[tok]; has {
merged, err := mergeTypes(spec, existing, isOutput)
if err != nil {
return nil, fmt.Errorf("incompatible type %q for resource %q (%q): %w", tok, m.resourceName,
m.resourceToken, err)
}
spec = *merged
}
m.pkg.Types[tok] = spec
m.metadata.Types[tok] = resources.AzureAPIType{
Properties: props.properties,
RequiredProperties: props.requiredProperties.SortedValues(),
}
}
return &pschema.TypeSpec{
Type: "object",
Ref: fmt.Sprintf("#/types/%s", tok),
}, nil
case len(resolvedSchema.Enum) > 0:
if primitiveTypeName == "" || primitiveTypeName == "object" {
// Default Enum properties to strings if the type isn't specified.
primitiveTypeName = "string"
}
return &pschema.TypeSpec{Type: primitiveTypeName}, nil
case resolvedSchema.Items != nil && resolvedSchema.Items.Schema != nil:
// Special case for VirtualMachineScaleSet.diskControllerType. The property is erroneously
// defined as a string _and_ array in the spec. Primitive string is correct. #2639,
// upstream issue Azure/azure-rest-api-specs/issues/25202.
// Note: as of 2024-08, going with the primitive type over the array for all such
// properties causes a large diff in the azurestackhci SDK, so we opted not to do that.
if primitiveTypeName != "array" && m.resourceName == "VirtualMachineScaleSet" && propertyName == "diskControllerType" {
return &pschema.TypeSpec{Type: primitiveTypeName}, nil
}
// Resolve the element type for array types.
property := resolvedSchema.Properties[propertyName]
resolvedProperty, err := resolvedSchema.ResolveSchema(&property)
if err != nil {
return nil, fmt.Errorf("failed to resolve schema for array element: %w", err)
}
itemsSpec, _, err := m.genProperty(propertyName, resolvedSchema.Items.Schema, context, resolvedProperty, genPropertiesVariant{
isOutput: isOutput,
isType: true,
})
if err != nil {
return nil, fmt.Errorf("failed to generate type spec for array element: %w", err)
}
// Don't generate a type definition for a typed array with empty item type.
if itemsSpec == nil {
return nil, nil
}
return &pschema.TypeSpec{
Type: "array",
Items: &itemsSpec.TypeSpec,
}, nil
case resolvedSchema.AdditionalProperties != nil && resolvedSchema.AdditionalProperties.Schema != nil:
schema := resolvedSchema.AdditionalProperties.Schema
// special case for userAssignedIdentities where element type is an array of objects,
// e.g. for `Microsoft.DBforMySQL/MySQLServerIdentity`.
if propertyName == "userAssignedIdentities" && resolvedSchema.AdditionalProperties.Schema.Items != nil {
schema = resolvedSchema.AdditionalProperties.Schema.Items.Schema
}
// Define the type of maps (untyped objects).
additionalProperties, err := m.genTypeSpec(propertyName, schema, resolvedSchema.ReferenceContext, isOutput)
if err != nil {
return nil, fmt.Errorf("failed to generate type spec for additional properties: %w", err)
}
return &pschema.TypeSpec{
Type: "object",
AdditionalProperties: additionalProperties,
}, nil
case primitiveTypeName == "" || primitiveTypeName == "object":
// Open API v2:
// > A schema without a type matches any data type – numbers, strings, objects, and so on.
// Azure uses a 'naked' object type for the same purpose: to specify 'any' type.
return &pschema.TypeSpec{
Ref: convert.TypeAny,
}, nil
default:
// Primitive type ('string', 'integer', etc.)
return &pschema.TypeSpec{Type: primitiveTypeName}, nil
}
}
// inlineTypeName returns a type name suffix to be used as a type name for properties defined inline in the spec.
// It defaults to the TitleCased property name but it also keeps a map of potential collisions. If a collision occurs,
// (i.e. an inline property `foo` has inline properties and one of them is also `foo`, that can also be down several
// levels), then the property name is duplicated (to get `FooFoo` in this example).
func (m *moduleGenerator) inlineTypeName(ctx *openapi.ReferenceContext, propertyName string) string {
result := strings.Title(propertyName)
if ex, ok := m.inlineTypes[ctx]; ok {
for {
if !ex.Has(result) {
break
}
result += strings.Title(propertyName)
}
} else {
m.inlineTypes[ctx] = codegen.NewStringSet()
}
m.inlineTypes[ctx].Add(result)
return result
}
// genEnumType generates the enum type. The propertyName serves as a fallback for the enum's name
// if none is given via the `name` attribute.
func (m *moduleGenerator) genEnumType(schema *spec.Schema, context *openapi.ReferenceContext,
enumExtension map[string]interface{}, propertyName string,
) (*pschema.TypeSpec, error) {
resolvedSchema, err := context.ResolveSchema(schema)
if err != nil {
return nil, fmt.Errorf("failed to resolve schema for enum: %w", err)
}
description, err := getPropertyDescription(schema, context, false /* maintainSubResourceIfUnset */)
if err != nil {
return nil, fmt.Errorf("failed to get property description: %w", err)
}
var enumName string
if name, ok := enumExtension["name"].(string); ok {
enumName = name
} else if propertyName != "" {
enumName = propertyName
} else {
return nil, fmt.Errorf("name key missing from enum metadata and no property name available")
}
enumName = m.typeNameOverride(ToUpperCamel(enumName))
tok := fmt.Sprintf("%s:%s:%s", m.pkg.Name, m.module, enumName)
enumSpec := &pschema.ComplexTypeSpec{
Enum: []pschema.EnumValueSpec{},
ObjectTypeSpec: pschema.ObjectTypeSpec{
Description: description,
Type: "string", // This provider only has string enums
},
}
// Ignore additional enum values that only vary by case as this isn't supported by Pulumi.
enumExists := func(enumVal pschema.EnumValueSpec) bool {
for _, existing := range enumSpec.Enum {
if strings.EqualFold(existing.Value.(string), enumVal.Value.(string)) {
return true
}
}
return false
}
// We prefer the enumExtension if available as it also provides the name and description.
if values, ok := enumExtension["values"].([]interface{}); ok {
for _, val := range values {
if val, ok := val.(map[string]interface{}); ok {
enumVal := pschema.EnumValueSpec{
Value: fmt.Sprintf("%v", val["value"]),
}
if name, ok := val["name"].(string); ok {
enumVal.Name = name
}
if description, ok := val["description"].(string); ok {
enumVal.Description = description
}
if !enumExists(enumVal) {
enumSpec.Enum = append(enumSpec.Enum, enumVal)
}
}
}
} else {
// Fall back to the enum values defined in the schema if enumExtensions not available.
for _, val := range resolvedSchema.Enum {
enumVal := pschema.EnumValueSpec{Value: fmt.Sprintf("%v", val)}
// Override the name for the values for this Enum since it contains unfortunately
// named values like `Input` and `Output` which collide especially for Go Codegen.
if strings.HasPrefix(string(m.module), "datafactory") && enumName == "ScriptActivityParameterDirection" {
enumVal.Name = fmt.Sprintf("Value%s", val)
}
if !enumExists(enumVal) {
enumSpec.Enum = append(enumSpec.Enum, enumVal)
}
}
}
m.pkg.Types[tok] = *enumSpec
referencedTypeName := fmt.Sprintf("#/types/%s", tok)
modelAsString, ok := enumExtension["modelAsString"].(bool)
if !ok || modelAsString {
return &pschema.TypeSpec{
OneOf: []pschema.TypeSpec{
{Type: "string"},
{Ref: referencedTypeName},
},
}, nil
}
return &pschema.TypeSpec{
Ref: referencedTypeName,
}, nil
}
// genDiscriminatedType generates polymorphic types (base type and subtypes) if the schema specifies a discriminator property.
// If no error occurs, the bool result indicates whether a discriminated (union) type is detected. If true, the TypeSpec
// result points to the specification of the union type.
func (m *moduleGenerator) genDiscriminatedType(resolvedSchema *openapi.Schema, isOutput bool) (*pschema.TypeSpec, bool, error) {
if resolvedSchema.Discriminator == "" {
return nil, false, nil
}
discriminator := resolvedSchema.Discriminator
if _, ok := resolvedSchema.Properties[discriminator]; !ok {
return nil, false, nil
}
prop := resolvedSchema.Properties[discriminator]
if prop.ReadOnly && !isOutput {
return nil, false, nil
}
var oneOf []pschema.TypeSpec
mapping := map[string]string{}
subtypes, err := resolvedSchema.FindSubtypes()
if err != nil {
return nil, false, err
}
for _, subtype := range subtypes {
typ, err := m.genTypeSpec("", subtype, resolvedSchema.ReferenceContext, isOutput)
if err != nil {
return nil, false, err
}
oneOf = append(oneOf, *typ)
subtypeSchema, err := resolvedSchema.ResolveSchema(subtype)
if err != nil {
return nil, false, err
}
discriminatorValue := getDiscriminatorValue(subtypeSchema)
mapping[discriminatorValue] = typ.Ref
}
switch len(oneOf) {
case 0:
// Type specifies a discriminator but doesn't have actual subtypes. Ignore the discriminator in this case.
return nil, false, nil
case 1:
// There is just one subtype specified: use it as a definite type.
return &oneOf[0], true, nil
default:
sdkDiscriminator := discriminator
if clientName, ok := prop.Extensions.GetString(extensionClientName); ok {
sdkDiscriminator = clientName
}
sdkDiscriminator = ToLowerCamel(sdkDiscriminator)
// Union type for two or more types.
return &pschema.TypeSpec{
OneOf: oneOf,
Discriminator: &pschema.DiscriminatorSpec{
PropertyName: sdkDiscriminator,
Mapping: mapping,
},
}, true, nil
}
}
// typeNameOverrides is a manually-maintained map of alternative names when a type name represents two or more
// distinct types in the same module. This can happen if there are multiple Open API spec files
// for the same RP and version, and each of those files has its own definition of the type under the same name.
// That happens a lot (there are many files for several RPs) but most of the time the definitions are similar
// enough to treat them as same. The following map lists all exceptions from this rule.
// If a new mismatch is introduced in a newly published spec, our codegen will catch the difference
// (see compatibleTypes) and fail. We will have to extend the list below with a new exception to unblock codegen.
var typeNameOverrides = map[string]string{
// Upstream commit 1a49c263cc introduced AwsConnector.EmrCluster(Summary) and .AwsEksClusterProperties which
// both have ClusterStatus, but of different types.
"AwsConnector.EmrCluster.ClusterStatus": "EmrClusterStatus",
"AwsConnector.EmrClusterSummary.ClusterStatus": "EmrClusterStatus",
// Upstream commit 1a49c263cc introduced several resources that all have an "Endpoint" property. Some are
// strings, the ones below are objects, all of them slightly different.
"AwsConnector.DaxCluster.Endpoint": "DaxClusterEndpoint",
"AwsConnector.RdsDbCluster.Endpoint": "RdsDbClusterEndpoint",
"AwsConnector.RdsDbInstance.Endpoint": "RdsDbInstanceEndpoint",
"AwsConnector.RedshiftCluster.Endpoint": "RedshiftClusterEndpoint",
// Upstream commit 1a49c263cc introduced TODO
"AwsConnector.DaxCluster.NotificationConfiguration": "DaxClusterNotificationConfiguration",
"AwsConnector.AutoScalingAutoScalingGroup.NotificationConfiguration": "AutoScalingGroupNotificationConfiguration",
// SKU for Redis Enterprise is different from SKU for Redis. Keep them as separate types.
"Cache.RedisEnterprise.Sku": "EnterpriseSku",
// This one is not a disambiguation but a fix for a type name "String" that is not descriptive and leads to
// generating invalid Java.
"DatabaseWatcher.Target.String": "TargetCollectionStatus",
// SingleServer is different from just "Server", see the exception in resources.go ResourceName().
"DBforPostgreSQL.SingleServer.Sku": "SingleServerSku",
// Devices RP comes from "deviceprovisioningservices" and "iothub" which are similar but slightly different.
// In particular, the IP Filter Rule has more properties in the DPS version.
"Devices.IotDpsResource.IpFilterRule": "TargetIpFilterRule",
// See the exception for Microsoft.HDInsight in resources.go ResourceName().
"HDInsight.ClusterPoolCluster.Sku": "ClusterPoolSku",
"HDInsight.ClusterPoolCluster.ComputeProfile": "ClusterPoolComputeProfile",
"HDInsight.ClusterPoolCluster.SshProfile": "ClusterPoolSshProfile",
"HybridContainerService.ClusterInstanceAgentPool.Status": "AgentPoolProvisioningStatus",
// Workbook vs. MyWorkbook types are slightly different. Probably, a bug in the spec, but we have to disambiguate.
"Insights.MyWorkbook.ManagedIdentity": "MyManagedIdentity",
"Insights.MyWorkbook.UserAssignedIdentities": "MyUserAssignedIdentities",
"ManagedNetworkFabric.NetworkFabric.OptionBProperties": "FabricOptionBProperties",
// Experiment's endpoint is a much narrower type compared to endpoints in other network resources.
"Network.Experiment.Endpoint": "ExperimentEndpoint",
// These are all FrontDoor types. FrontDoor shares a bunch of type names with generate Network provider,
// but defines them in its own way.
"Network.Policy.ManagedRuleGroupOverride": "FrontDoorManagedRuleGroupOverride",
"Network.Policy.ManagedRuleOverride": "FrontDoorManagedRuleOverride",
"Network.Policy.ManagedRuleSet": "FrontDoorManagedRuleSet",
"Network.Policy.MatchCondition": "FrontDoorMatchCondition",
"Network.Policy.MatchVariable": "FrontDoorMatchVariable",
"Network.Policy.PolicySettings": "FrontDoorPolicySettings",
// IpConfigurationResponse conflicts with IPConfigurationResponse used for existing networking resources.
// This avoids Dotnet SDK failing to build since codegen currently elides the IPConfigurationResponse
// output types since it assumes the existing one is sufficient.
"Network.InboundEndpoint.IpConfiguration": "InboundEndpointIPConfiguration",
// The following two types are read-only, while the same types in another spec are writable.
"RecoveryServices.Vault.PrivateEndpointConnection": "VaultPrivateEndpointConnection",
"RecoveryServices.Vault.PrivateLinkServiceConnectionState": "VaultPrivateLinkServiceConnectionState",
// Watchlist resources only appear in a preview spec and not in stable specs. Anyway, the shapes of their
// types are slightly different from later specs, so we have to disambiguate for top-level resources.
"SecurityInsights.Watchlist.UserInfo": "WatchlistUserInfo",
"SecurityInsights.WatchlistItem.UserInfo": "WatchlistUserInfo",
// These generate enums which conflict with other resource types.
"BillingBenefits.Discount.DiscountTypeProductFamily": "DiscountProductFamily",
"BillingBenefits.Discount.DiscountTypeProduct": "DiscountProduct",
"BillingBenefits.Discount.DiscountTypeCustomPrice": "DiscountCustomPrice",
"BillingBenefits.Discount.DiscountTypeCustomPriceMultiCurrency": "DiscountCustomPriceMultiCurrency",
}
var typeNameOverridesV3 = map[string]string{
"CosmosDB.MongoCluster.CreateMode": "MongoClusterCreateMode",
// DocumentDB.MongoCluster from /mongocluster uses a different private endpoint connection.
// The MongoCluster resource has the same name in v2 and v3, but the private endpoint connection was disambiguated in v3.
"DocumentDB.MongoCluster.PrivateEndpointConnection": "MongoClusterPrivateEndpointConnection",
"DBforMySQL.SingleServer.ServerVersion": "SingleServerVersion",
"DBforMySQL.SingleServer.SkuTier": "SingleServerSkuTier",
"DBforPostgreSQL.ServerGroupCluster.AuthConfig": "ServerGroupClusterAuthConfig",
"DBforPostgreSQL.ServerGroupCluster.DataEncryption": "ServerGroupClusterDataEncryption",
"DBforPostgreSQL.ServerGroupCluster.MaintenanceWindow": "ServerGroupClusterMaintenanceWindow",
"DBforPostgreSQL.SingleServer.CreateMode": "SingleServerCreateMode",
"DBforPostgreSQL.SingleServer.IdentityType": "SingleServerIdentityProperties",
"DBforPostgreSQL.SingleServer.PrincipalType": "SingleServerPrincipalType",
"DBforPostgreSQL.SingleServer.ServerVersion": "SingleServerVersion",
"DBforPostgreSQL.SingleServer.SkuTier": "SingleServerSkuTier",
"Migrate.AssessmentProjectsAssessmentsOperation.AzureOfferCode": "AssessmentProjectsAssessmentsOperationAzureOfferCode",
"Migrate.AssessmentProjectsAssessmentsOperation.AzureVmFamily": "AssessmentProjectsAssessmentsOperationAzureVmFamily",
"Migrate.AssessmentProjectsAssessmentsOperation.AvsAssessmentProperties": "AssessmentProjectsAssessmentsOperationAvsAssessmentProperties",
}
func (m *moduleGenerator) typeNameOverride(typeName string) string {
key := fmt.Sprintf("%s.%s.%s", m.moduleName, m.resourceName, typeName)
if v, ok := typeNameOverrides[key]; ok {
return v
}
if version.GetVersion().Major >= 3 {
if v, ok := typeNameOverridesV3[key]; ok {
return v
}
}
return typeName
}
func (m *moduleGenerator) typeName(ctx *openapi.ReferenceContext, isOutput bool) string {
suffix := ""
if isOutput {
suffix = "Response"
}
standardName := ToUpperCamel(MakeLegalIdentifier(ctx.ReferenceName))
referenceName := m.typeNameOverride(standardName)
return fmt.Sprintf("azure-native:%s:%s%s", m.module, referenceName, suffix)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/propertyDefaults_test.go | provider/pkg/gen/propertyDefaults_test.go | package gen
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestDefaultsForStorageAccount(t *testing.T) {
def := propertyDefaults("storage", "StorageAccount")
assert.NotNil(t, def)
assert.Contains(t, def, "networkRuleSet")
assert.Equal(t, 1, len(def))
}
func TestDefaultsAreSpecificToStorageAccount(t *testing.T) {
assert.NotNil(t, propertyDefaults("storage", "StorageAccount"))
assert.NotNil(t, propertyDefaults("storage/v20210501", "StorageAccount"))
assert.Nil(t, propertyDefaults("storagecache", "StorageAccount"))
assert.Nil(t, propertyDefaults("storage", "StorageSomething"))
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/docs_test.go | provider/pkg/gen/docs_test.go | package gen
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCanLookupExtraDocs(t *testing.T) {
rootDir := t.TempDir()
docsDir := filepath.Join(rootDir, "docs", "resources")
require.NoError(t, os.MkdirAll(docsDir, 0755))
for _, docs := range []struct {
tok string
filename string
}{
{"azure-native:containerservice.ManagedCluster", "containerservice-ManagedCluster.md"},
{"azure-native:sql.Server", "sql-Server.md"},
} {
require.NoError(t, os.WriteFile(filepath.Join(docsDir, docs.filename), []byte{'y'}, 0644))
content := getAdditionalDocs(rootDir, docs.tok)
require.NotNil(t, content, docs.tok)
assert.Equal(t, "y", *content, docs.tok)
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/propertyDefaults.go | provider/pkg/gen/propertyDefaults.go | package gen
import "strings"
// In some cases, we need to set default values for properties that are not given as inputs.
// One case is when the property was set and is then removed from the input, but Azure treats
// the omission as "no change" instead of removing the value.
// propertyDefaults returns a map of property names to default values for the given module
// and resource, for recording in metadata for later use.
func propertyDefaults(module TokenModule, resourceName string) map[string]interface{} {
if resourceName == "StorageAccount" && (module == "storage" || strings.HasPrefix(string(module), "storage/")) {
return map[string]interface{}{
"networkRuleSet": map[string]interface{}{
"bypass": "AzureServices",
"defaultAction": "Allow",
"ipRules": []interface{}{},
"virtualNetworkRules": []interface{}{},
},
}
}
return nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/compatibleTokens.go | provider/pkg/gen/compatibleTokens.go | package gen
import (
"fmt"
"strings"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/collections"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi/paths"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
)
type Token string
type ModuleLowered string
type ResourceLowered string
type NormalizedPath string
// CompatibleTokensLookup is a lookup table for compatible tokens based on either name matches or their URI paths in Azure.
// Comparisons are done using normalisation for casing and path parameter naming.
type CompatibleTokensLookup struct {
byLoweredModuleResourceName map[ModuleLowered]map[ResourceLowered]map[Token]struct{}
byNormalizedPath map[NormalizedPath]map[Token]struct{}
}
// NewCompatibleTokensLookup creates a new CompatibleResourceLookup from the collection of tokens mapping to their Azure path.
// Note: tokenPaths are outputted for the current provider within the reports directory.
func NewCompatibleTokensLookup(tokenPaths map[string]string) (*CompatibleTokensLookup, error) {
lookup := CompatibleTokensLookup{
byLoweredModuleResourceName: map[ModuleLowered]map[ResourceLowered]map[Token]struct{}{},
byNormalizedPath: map[NormalizedPath]map[Token]struct{}{},
}
if tokenPaths == nil {
return &lookup, nil
}
for token, path := range util.MapOrdered(tokenPaths) {
moduleName, _, resourceName, err := resources.ParseToken(token)
if err != nil {
return nil, fmt.Errorf("failed to parse token for CompatibleTokensLookup %s: %w", token, err)
}
lookup.add(openapi.ModuleName(moduleName), resourceName, path, token)
}
return &lookup, nil
}
func (lookup *CompatibleTokensLookup) add(moduleName openapi.ModuleName, resourceName openapi.ResourceName, path string, token string) {
normalizedPath := NormalizedPath(paths.NormalizePath(path))
moduleLowered := ModuleLowered(moduleName.Lowered())
resourceLowered := ResourceLowered(strings.ToLower(resourceName))
typedToken := Token(token)
if _, ok := lookup.byLoweredModuleResourceName[moduleLowered]; !ok {
lookup.byLoweredModuleResourceName[moduleLowered] = map[ResourceLowered]map[Token]struct{}{}
}
if _, ok := lookup.byLoweredModuleResourceName[moduleLowered][resourceLowered]; !ok {
lookup.byLoweredModuleResourceName[moduleLowered][resourceLowered] = map[Token]struct{}{}
}
lookup.byLoweredModuleResourceName[moduleLowered][resourceLowered][typedToken] = struct{}{}
if _, ok := lookup.byNormalizedPath[normalizedPath]; !ok {
lookup.byNormalizedPath[normalizedPath] = map[Token]struct{}{}
}
lookup.byNormalizedPath[normalizedPath][typedToken] = struct{}{}
}
func (lookup *CompatibleTokensLookup) IsPopulated() bool {
return lookup != nil && len(lookup.byLoweredModuleResourceName) > 0 && len(lookup.byNormalizedPath) > 0
}
// FindCompatibleTokens returns a list of all compatible resource tokens for a given module, resource, and path based on the names or path matching.
func (lookup *CompatibleTokensLookup) FindCompatibleTokens(moduleName openapi.ModuleName, resourceName openapi.ResourceName, path string) []string {
if lookup == nil || lookup.byLoweredModuleResourceName == nil || lookup.byNormalizedPath == nil {
return nil
}
matches := collections.NewOrderableSet[string]()
moduleLowered := ModuleLowered(moduleName.Lowered())
resourceLowered := ResourceLowered(strings.ToLower(resourceName))
normalizedPath := NormalizedPath(paths.NormalizePath(path))
if byLoweredResourceName, ok := lookup.byLoweredModuleResourceName[moduleLowered]; ok {
if tokens, ok := byLoweredResourceName[resourceLowered]; ok {
for token := range tokens {
matches.Add(string(token))
}
}
}
if resource, ok := lookup.byNormalizedPath[normalizedPath]; ok {
for token := range resource {
matches.Add(string(token))
}
}
return matches.SortedValues()
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/utilities.go | provider/pkg/gen/utilities.go | // Copyright 2016-2020, Pulumi Corporation.
package gen
import (
"strings"
"unicode"
)
var legalIdentifierReplacer *strings.Replacer
// MakeLegalIdentifier removes characters that are not allowed in identifiers.
func MakeLegalIdentifier(s string) string {
if legalIdentifierReplacer == nil {
legalIdentifierReplacer = strings.NewReplacer("-", "", "[", "", "]", "")
}
return legalIdentifierReplacer.Replace(s)
}
// firstToLower returns a string with the first character lowercased (`HelloWorld` => `helloWorld`).
func firstToLower(s string) string {
if s == "" {
return ""
}
runes := []rune(s)
return string(append([]rune{unicode.ToLower(runes[0])}, runes[1:]...))
}
var commonPrefixReplacements = map[rune]string{
'*': "asterisk",
'0': "zero",
'1': "one",
'2': "two",
'3': "three",
'4': "four",
'5': "five",
'6': "six",
'7': "seven",
'8': "eight",
'9': "nine",
'_': "",
}
// ToLowerCamel converts a string to lowerCamelCase.
// The code is adopted from https://github.com/iancoleman/strcase but changed in several ways to handle
// all the cases that are found in Azure in a most user-friendly way.
func ToLowerCamel(s string) string {
if s == "" {
return s
}
if uppercaseAcronym[s] {
s = strings.ToLower(s)
}
r := []rune(s)
if prefix, found := commonPrefixReplacements[r[0]]; found {
if len(r) > 1 {
s = prefix + strings.ToUpper(string(r[1])) + string(r[2:])
} else {
s = prefix
}
}
if r := rune(s[0]); r >= 'A' && r <= 'Z' {
s = strings.ToLower(string(r)) + s[1:]
}
return toCamelInitCase(s, false)
}
// ToUpperCamel converts a string to UpperCamelCase.
func ToUpperCamel(s string) string {
return toCamelInitCase(s, true)
}
func toCamelInitCase(s string, initCase bool) string {
s = strings.Trim(s, " ")
n := ""
capNext := initCase
for _, v := range s {
if v >= 'A' && v <= 'Z' {
n += string(v)
}
if v >= '0' && v <= '9' {
n += string(v)
}
if v >= 'a' && v <= 'z' {
if capNext {
n += strings.ToUpper(string(v))
} else {
n += string(v)
}
}
if v == '_' || v == ' ' || v == '-' || v == '.' {
capNext = true
} else {
capNext = false
}
}
return n
}
var uppercaseAcronym = map[string]bool{
"ID": true,
"TTL": true,
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/gen_dashboard_test.go | provider/pkg/gen/gen_dashboard_test.go | package gen
import (
"os"
"path"
"testing"
"github.com/blang/semver"
"github.com/gkampitakis/go-snaps/snaps"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/stretchr/testify/assert"
)
func TestPortalDashboardGen(t *testing.T) {
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
// We take a snapshot of the schema as we're focusing on testing how we parse and modify the spec
// To update the specifications run in the repo root:
// rm -rf provider/pkg/gen/test-data/dashboard/azure-rest-api-specs/specification/portal/resource-manager/Microsoft.Portal/preview/2020-09-01-preview/
// rm -rf provider/pkg/gen/test-data/dashboard/azure-rest-api-specs/specification/common-types/resource-management/v5/
// cp -r azure-rest-api-specs/specification/portal/resource-manager/Microsoft.Portal/preview/2020-09-01-preview/ provider/pkg/gen/test-data/dashboard/azure-rest-api-specs/specification/portal/resource-manager/Microsoft.Portal/preview/2020-09-01-preview/
// cp -r azure-rest-api-specs/specification/common-types/resource-management/v5/ provider/pkg/gen/test-data/dashboard/azure-rest-api-specs/specification/common-types/resource-management/v5/
// rm -rf provider/pkg/gen/test-data/dashboard/azure-rest-api-specs/specification/portal/resource-manager/Microsoft.Portal/preview/2020-09-01-preview/examples/
rootDir := path.Join(wd, "test-data", "dashboard")
modules, _, err := openapi.ReadAzureModules(path.Join(rootDir, "azure-rest-api-specs"), "Portal", "2020-09-01-preview")
if err != nil {
t.Fatal(err)
}
modules = openapi.ApplyTransformations(modules, openapi.DefaultVersions{
"Portal": {
"Dashboard": {
ApiVersion: "2020-09-01-preview",
},
},
}, openapi.DefaultVersions{}, nil, nil)
versioning := versioningStub{
// These are extracted from versions/v2-token-paths.json
previousTokenPaths: map[string]string{
"azure-native:portal/v20190101preview:Dashboard": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}",
"azure-native:portal/v20200901preview:Dashboard": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}",
"azure-native:portal/v20221201preview:Dashboard": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}",
"azure-native:portal:Dashboard": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Portal/dashboards/{dashboardName}",
},
}
generationResult, err := PulumiSchema(rootDir, modules, versioning, semver.MustParse("3.0.0"), false /* onlyExplicitVersions */)
if err != nil {
t.Fatal(err)
}
// Ensure the dashboard resource is present in schema and metadata
// and snapshot the generation result so we can see the impact of future refactors.
assert.NotNil(t, generationResult.Schema.Resources["azure-native:portal:Dashboard"])
snaps.MatchJSON(t, generationResult.Schema.Resources["azure-native:portal:Dashboard"])
assert.NotNil(t, generationResult.Metadata.Resources["azure-native:portal:Dashboard"])
snaps.MatchJSON(t, generationResult.Metadata.Resources["azure-native:portal:Dashboard"])
snaps.MatchJSON(t, generationResult.Schema.Types)
snaps.MatchJSON(t, generationResult.Metadata.Types)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/properties_test.go | provider/pkg/gen/properties_test.go | package gen
import (
"testing"
"github.com/go-openapi/spec"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func makeSchema(mutability ...string) *openapi.Schema {
mutabilityInterface := make([]interface{}, len(mutability))
for i, m := range mutability {
mutabilityInterface[i] = m
}
return &openapi.Schema{
Schema: &spec.Schema{
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
extensionMutability: mutabilityInterface,
},
},
},
ReferenceContext: &openapi.ReferenceContext{
ReferenceName: "foo",
},
}
}
func TestPropChangeForcesRecreate(t *testing.T) {
t.Run("no extensions", func(t *testing.T) {
schema := &openapi.Schema{
Schema: &spec.Schema{},
}
hasMutabilityInfo, forcesRecreate := propChangeForcesRecreate(schema)
assert.False(t, hasMutabilityInfo)
assert.False(t, forcesRecreate)
})
t.Run("create only", func(t *testing.T) {
schema := makeSchema(extensionMutabilityCreate)
hasMutabilityInfo, forcesRecreate := propChangeForcesRecreate(schema)
assert.True(t, hasMutabilityInfo)
assert.True(t, forcesRecreate)
})
t.Run("create and update", func(t *testing.T) {
schema := makeSchema(extensionMutabilityCreate, extensionMutabilityUpdate)
hasMutabilityInfo, forcesRecreate := propChangeForcesRecreate(schema)
assert.True(t, hasMutabilityInfo)
assert.False(t, forcesRecreate)
})
t.Run("create and read", func(t *testing.T) {
schema := makeSchema(extensionMutabilityCreate, extensionMutabilityRead)
hasMutabilityInfo, forcesRecreate := propChangeForcesRecreate(schema)
assert.True(t, hasMutabilityInfo)
assert.True(t, forcesRecreate)
})
t.Run("read only", func(t *testing.T) {
schema := makeSchema(extensionMutabilityRead)
hasMutabilityInfo, forcesRecreate := propChangeForcesRecreate(schema)
assert.True(t, hasMutabilityInfo)
assert.False(t, forcesRecreate)
})
t.Run("all", func(t *testing.T) {
schema := makeSchema(extensionMutabilityCreate, extensionMutabilityUpdate, extensionMutabilityRead)
hasMutabilityInfo, forcesRecreate := propChangeForcesRecreate(schema)
assert.True(t, hasMutabilityInfo)
assert.False(t, forcesRecreate)
})
}
func TestForceNew(t *testing.T) {
m := moduleGenerator{
moduleName: "foo",
}
t.Run("forceNew", func(t *testing.T) {
forceNewMetadata := m.forceNew(makeSchema(extensionMutabilityCreate), "prop", false)
assert.Equal(t, forceNew, forceNewMetadata)
})
t.Run("noForceNew, mutability spec", func(t *testing.T) {
forceNewMetadata := m.forceNew(makeSchema(extensionMutabilityCreate, extensionMutabilityUpdate), "prop", false)
assert.Equal(t, noForceNew, forceNewMetadata)
})
t.Run("noForceNew, no mutability spec", func(t *testing.T) {
forceNewMetadata := m.forceNew(makeSchema(), "prop", false)
assert.Equal(t, noForceNew, forceNewMetadata)
})
t.Run("forceNew, is type", func(t *testing.T) {
forceNewMetadata := m.forceNew(makeSchema(extensionMutabilityCreate), "prop", true)
assert.Equal(t, forceNewSetOnReferencedType, forceNewMetadata)
})
t.Run("noForceNew, mutability spec, is type", func(t *testing.T) {
forceNewMetadata := m.forceNew(makeSchema(extensionMutabilityCreate, extensionMutabilityUpdate), "prop", true)
assert.Equal(t, noForceNew, forceNewMetadata)
})
t.Run("noForceNew, no mutability spec, is type", func(t *testing.T) {
forceNewMetadata := m.forceNew(makeSchema(), "prop", true)
assert.Equal(t, noForceNew, forceNewMetadata)
})
}
func TestNonObjectInvokeResponses(t *testing.T) {
m := moduleGenerator{
moduleName: "foo",
}
resolvedSchema := &openapi.Schema{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"string"},
},
},
}
t.Run("string type, response properties requested", func(t *testing.T) {
variant := genPropertiesVariant{
isOutput: true,
isType: false,
isResponse: true,
}
props, err := m.genProperties(resolvedSchema, variant)
require.NoError(t, err)
require.Len(t, props.specs, 1)
assert.Contains(t, props.specs, resources.SingleValueProperty)
require.Len(t, props.properties, 1)
assert.Contains(t, props.properties, resources.SingleValueProperty)
})
t.Run("string type, response properties not requested", func(t *testing.T) {
variant := genPropertiesVariant{
isOutput: true,
isType: false,
isResponse: false,
}
props, err := m.genProperties(resolvedSchema, variant)
require.NoError(t, err)
require.Len(t, props.specs, 0)
require.Len(t, props.properties, 0)
})
t.Run("object type, response properties requested", func(t *testing.T) {
schema := &openapi.Schema{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"object"},
},
},
}
variant := genPropertiesVariant{
isOutput: true,
isType: false,
isResponse: true,
}
props, err := m.genProperties(schema, variant)
require.NoError(t, err)
require.Len(t, props.specs, 0)
require.Len(t, props.properties, 0)
})
t.Run("string type, response properties requested but there are other properties", func(t *testing.T) {
schema := &openapi.Schema{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"string"},
Properties: map[string]spec.Schema{
"foo": {
SchemaProps: spec.SchemaProps{},
},
},
},
},
}
variant := genPropertiesVariant{
isOutput: true,
isType: false,
isResponse: true,
}
props, err := m.genProperties(schema, variant)
require.NoError(t, err)
require.Len(t, props.specs, 1)
assert.NotContains(t, props.specs, resources.SingleValueProperty)
require.Len(t, props.properties, 1)
assert.NotContains(t, props.properties, resources.SingleValueProperty)
})
}
func TestPropertyIntersection(t *testing.T) {
t.Run("no conflict", func(t *testing.T) {
outer := propertyBag{properties: map[string]resources.AzureAPIProperty{
"foo": {},
}}
inner := propertyBag{properties: map[string]resources.AzureAPIProperty{
"bar": {},
"foo2": {},
}}
assert.Empty(t, outer.propertyIntersection(&inner))
})
t.Run("conflict", func(t *testing.T) {
outer := propertyBag{properties: map[string]resources.AzureAPIProperty{
"foo": {},
"foo2": {},
"bla": {},
}}
inner := propertyBag{properties: map[string]resources.AzureAPIProperty{
"foo": {},
"bar": {},
}}
assert.Equal(t, []string{"foo"}, outer.propertyIntersection(&inner))
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/params.go | provider/pkg/gen/params.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package gen
import (
"fmt"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/convert"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/debug"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
)
// FlattenParams takes the parameters specified in Azure API specs/ARM templates and
// flattens them to match the desired format for the Pulumi schema.
// resourceParams is a mapping of API parameter names to provider.AzureApiParameter
// and types is a mapping for the API type names to provider.AzureApiType.
// The latter two can be derived from the metadata generated during schema generation.
func FlattenParams(
input map[string]interface{},
resourceParams map[string]resources.AzureAPIParameter,
types map[string]resources.AzureAPIType,
) (map[string]interface{}, error) {
out := map[string]interface{}{}
converter := convert.NewSdkShapeConverterFull(types)
// Sort the keys to ensure consistent ordering
for k, v := range util.MapOrdered(input) {
switch k {
case "If-Match": // TODO: Not handled in schema
continue
case "api-version", "apiVersion", "subscriptionId":
continue // No need to emit these since we auto inject them
}
paramMetadata, ok := resourceParams[k]
if !ok {
debug.Log("missing item '%s' from resource metadata for resource, skipping", k)
continue
}
// body parameters are folded in
if paramMetadata.Body != nil {
inBody, ok := v.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("expect body for param %s to be a map, received %T", k, v)
}
flattened := converter.ResponseBodyToSdkOutputs(paramMetadata.Body.Properties, inBody)
mergeMap(out, flattened)
continue
}
// replace param name with value in SdkName if provided.
if paramMetadata.Value != nil && paramMetadata.Value.SdkName != "" {
k = paramMetadata.Value.SdkName
}
out[k] = v
}
return out, nil
}
func mergeMap(dst map[string]interface{}, src map[string]interface{}) {
for k, v := range src {
dst[k] = v
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/docs.go | provider/pkg/gen/docs.go | package gen
import (
"os"
"path/filepath"
"regexp"
"strings"
)
func getAdditionalDocs(rootDir, resourceTok string) *string {
withoutPrefix := strings.TrimPrefix(resourceTok, "azure-native:")
filename := regexp.MustCompile(`[^a-zA-Z0-9]`).ReplaceAllString(withoutPrefix, "-")
file, err := os.ReadFile(filepath.Join(rootDir, "docs", "resources", filename+".md"))
if os.IsNotExist(err) {
return nil
}
if err != nil {
panic(err)
}
content := string(file)
return &content
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/emitFiles.go | provider/pkg/gen/emitFiles.go | package gen
import (
"encoding/json"
"os"
"path"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"gopkg.in/yaml.v3"
)
type FilePath = string
type FileData = interface{}
type FileMap = map[FilePath]FileData
func EmitFiles(outDir string, files FileMap) ([]string, error) {
var written []string
for filename, data := range files {
outPath := path.Join(outDir, filename)
err := EmitFile(outPath, data)
if err != nil {
return nil, err
}
written = append(written, outPath)
}
return written, nil
}
func EmitFile(outputPath string, data FileData) error {
var formatted []byte
var err error
if bytes, ok := data.([]byte); ok {
formatted = bytes
} else if strings.HasSuffix(outputPath, ".yaml") {
formatted, err = yaml.Marshal(data)
// Prepend with warning to not edit the file
formatted = append([]byte("# WARNING: This file was generated by provider/pkg/gen/emitFiles.go. Edits might be overwritten.\n\n"), formatted...)
if err != nil {
return errors.Wrapf(err, "marshaling YAML for %v", outputPath)
}
} else {
formatted, err = json.MarshalIndent(data, "", " ")
if err != nil {
return errors.Wrapf(err, "marshaling JSON for %v", outputPath)
}
}
if err := os.MkdirAll(path.Dir(outputPath), 0o700); err != nil {
return errors.Wrapf(err, "creating directory %v", path.Dir(outputPath))
}
f, err := os.Create(outputPath)
if err != nil {
return errors.Wrapf(err, "creating file %v", outputPath)
}
defer contract.IgnoreClose(f)
_, err = f.Write(formatted)
if err != nil {
return errors.Wrapf(err, "writing file %v", outputPath)
}
return err
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/properties.go | provider/pkg/gen/properties.go | // Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gen
import (
"fmt"
"sort"
"strconv"
"strings"
"github.com/go-openapi/spec"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/convert"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/version"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
// propertyBag keeps the schema and metadata properties for a single API type.
type propertyBag struct {
description string
specs map[string]pschema.PropertySpec
properties map[string]resources.AzureAPIProperty
requiredSpecs codegen.StringSet
requiredProperties codegen.StringSet
requiredContainers RequiredContainers
}
// propertyIntersection returns the property names that are present in both bags.
func (p *propertyBag) propertyIntersection(other *propertyBag) []string {
result := []string{}
for propName := range p.properties {
if _, ok := other.properties[propName]; ok {
result = append(result, propName)
}
}
return result
}
type RequiredContainers [][]string
// genPropertiesVariant is a set of flags that control the behavior of property generation
// in genProperties and genProperty
type genPropertiesVariant struct {
// isOutput indicates that the properties are being generated for an output type.
isOutput bool
// isType indicates that the properties are being generated for a type definition.
isType bool
// isResponse indicates that the properties are being generated for a response type.
isResponse bool
// isTopLevel indicates that the properties are being generated for a top-level resource rather than a referenced type.
isTopLevel bool
}
// nestedWithoutResponse returns a new copy of the variant with isResponse set to false.
func (v *genPropertiesVariant) nestedWithoutResponse() genPropertiesVariant {
return genPropertiesVariant{
isTopLevel: false,
isOutput: v.isOutput,
isType: v.isType,
isResponse: false,
}
}
func (m *moduleGenerator) genProperties(resolvedSchema *openapi.Schema, variants genPropertiesVariant) (*propertyBag, error) {
result := newPropertyBag()
if version.GetVersion().Major >= 3 {
if variants.isTopLevel && variants.isOutput {
// Emit the actual apiVersion of the resource as a output property.
result.specs["azureApiVersion"] = pschema.PropertySpec{
Description: "The Azure API version of the resource.",
TypeSpec: pschema.TypeSpec{
Type: "string",
},
WillReplaceOnChanges: false,
}
result.requiredSpecs.Add("azureApiVersion")
}
}
// Sort properties to make codegen deterministic.
var names []string
for name := range resolvedSchema.Properties {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
property := resolvedSchema.Properties[name]
resolvedProperty, err := resolvedSchema.ResolveSchema(&property)
if err != nil {
return nil, fmt.Errorf("failed to resolve property %q: %w", name, err)
}
if name == "etag" && !variants.isType && !variants.isOutput {
// ETags may be defined as inputs to PUT endpoints, but we should never model them as
// resource inputs because they are a protocol implementation detail rather than
// a meaningful desired-state property.
continue
}
// TODO: Workaround for https://github.com/pulumi/pulumi/issues/12629 - remove once merged
if (name == "conditionSets" && property.Items.Schema.Ref.String() == "#/definitions/GovernanceRuleConditionSets") ||
(name == "conditionSets" && property.Items.Schema.Ref.String() == "#/definitions/ApplicationConditionSets") {
continue
}
// Workaround for https://github.com/Azure/azure-rest-api-specs/issues/9432
if m.moduleName == "KeyVault" && m.resourceName == "Vault" {
if name == "vaultUri" || name == "provisioningState" {
resolvedProperty.ReadOnly = true
}
}
sdkName := name
if clientName, ok := resolvedProperty.Extensions.GetString(extensionClientName); ok {
sdkName = firstToLower(clientName)
}
// Urn is a reserved word in our SDKs so we should avoid it on the resource itself.
if sdkName == "urn" && variants.isTopLevel {
sdkName = "urnValue"
}
// Change the name to lowerCamelCase.
sdkName = ToLowerCamel(sdkName)
flatten, ok := property.Extensions.GetBool(extensionClientFlatten)
// Flattened properties aren't modelled in the SDK explicitly: their sub-properties are merged directly to the parent.
// If the type is marked as a dictionary, ignore the extension and proceed with modeling this property explicitly.
// We can't flatten dictionaries in a type-safe manner.
isDict := resolvedProperty.AdditionalProperties != nil
// TODO: Remove when https://github.com/Azure/azure-rest-api-specs/pull/14550 is rolled back
workaroundDelegatedNetworkBreakingChange := property.Ref.String() == "#/definitions/OrchestratorResourceProperties" ||
property.Ref.String() == "#/definitions/DelegatedSubnetProperties" ||
property.Ref.String() == "#/definitions/DelegatedControllerProperties"
// See #3556 and https://github.com/Azure/azure-rest-api-specs/issues/30443
// It's ok if a new API version is fixed, this is a no-op then.
if m.resourceName == "CIAMTenant" && name == "tier" && strings.HasPrefix(string(m.module), "azureactivedirectory") {
flatten = false
}
if version.GetVersion().Major < 3 {
// Prevent a property collision due to flattening. From v3, we detect and avoid this case automatically.
if m.resourceName == "DefenderForStorage" && (name == "malwareScanning" || name == "sensitiveDataDiscovery") {
flatten = false
}
if (ok && flatten && !isDict) || workaroundDelegatedNetworkBreakingChange {
bag, err := m.genProperties(resolvedProperty, variants.nestedWithoutResponse())
if err != nil {
return nil, err
}
// Check that none of the inner properties already exists on the outer type. This
// causes a conflict when flattening, and will probably need to be handled in v3.
for _, propName := range result.propertyIntersection(bag) {
m.flattenedPropertyConflicts[fmt.Sprintf("%s.%s", name, propName)] = struct{}{}
}
flattenProperties(bag, name, resolvedSchema)
result.merge(bag)
continue
}
} else { // v3+: don't flatten when there are conflicts
if (ok && flatten && !isDict) || workaroundDelegatedNetworkBreakingChange {
bag, err := m.genProperties(resolvedProperty, variants.nestedWithoutResponse())
if err != nil {
return nil, err
}
// Check that none of the inner properties already exists on the outer type.
conflictingProperties := result.propertyIntersection(bag)
if len(conflictingProperties) == 0 {
flattenProperties(bag, name, resolvedSchema)
result.merge(bag)
continue
} else {
for _, propName := range conflictingProperties {
m.flattenedPropertyConflicts[fmt.Sprintf("%s.%s", name, propName)] = struct{}{}
}
}
}
}
// Skip read-only properties for input types and write-only properties for output types.
if resolvedProperty.ReadOnly && !variants.isOutput {
continue
}
if variants.isOutput && isWriteOnly(resolvedProperty) {
continue
}
propertySpec, apiProperty, err := m.genProperty(name, &property, resolvedSchema.ReferenceContext, resolvedProperty, variants)
if err != nil {
return nil, fmt.Errorf("failed to generate property %q: %w", name, err)
}
// Skip properties that yield degenerate types (e.g., when an input type has only read-only properties).
if propertySpec == nil {
continue
}
if variants.isOutput && resolvedProperty.ReadOnly {
result.requiredSpecs.Add(sdkName)
}
if sdkName != name {
apiProperty.SdkName = sdkName
}
result.properties[name] = *apiProperty
result.specs[sdkName] = *propertySpec
}
for i, s := range resolvedSchema.AllOf {
allOfSchema, err := resolvedSchema.ResolveSchema(&s)
if err != nil {
return nil, fmt.Errorf("failed to resolve allOf schema %d: %w", i, err)
}
allOfProperties, err := m.genProperties(allOfSchema, variants.nestedWithoutResponse())
if err != nil {
return nil, fmt.Errorf("failed to generate allOf properties %d: %w", i, err)
}
// For a derived type, set the discriminator property to the const value, if any.
discriminator, discriminatorDesc, isDU, err := m.getDiscriminator(allOfSchema)
if err != nil {
return nil, fmt.Errorf("failed to get discriminator for allOf schema %d: %w", i, err)
}
if isDU {
prop := allOfProperties.properties[discriminator]
sdkDiscriminator := discriminator
if prop.SdkName != "" {
sdkDiscriminator = prop.SdkName
}
propSpec := allOfProperties.specs[sdkDiscriminator]
discriminatorValue := getDiscriminatorValue(resolvedSchema)
propSpec.Const = discriminatorValue
propSpec.Type = "string"
propSpec.Ref = ""
propSpec.OneOf = nil
// Add the discriminator value to the property description to help users fill it.
propSpec.Description = fmt.Sprintf("%s\nExpected value is '%s'.", discriminatorDesc, discriminatorValue)
allOfProperties.specs[sdkDiscriminator] = propSpec
prop.Const = discriminatorValue
allOfProperties.properties[discriminator] = prop
}
result.merge(allOfProperties)
}
for _, name := range resolvedSchema.Required {
if prop, ok := result.properties[name]; ok {
if prop.SdkName != "" {
result.requiredSpecs.Add(prop.SdkName)
} else {
result.requiredSpecs.Add(name)
}
result.requiredProperties.Add(name)
}
}
// If the schema has no properties but is a primitive output, we include it as a property so invokes can be generated.
// Ideally we'd just represent it as a primitive type and use FunctionSpec.ReturnType to specify this, but pulumi/pulumi
// #15739 and #15738 prevent this.
if len(names) == 0 && len(result.specs) == 0 && variants.isResponse && len(resolvedSchema.Type) == 1 && resolvedSchema.Type[0] != "object" {
result.specs[resources.SingleValueProperty] = pschema.PropertySpec{
TypeSpec: pschema.TypeSpec{
Type: resolvedSchema.Type[0],
},
Description: result.description,
}
result.properties[resources.SingleValueProperty] = resources.AzureAPIProperty{
Type: resolvedSchema.Type[0],
}
}
return result, nil
}
// flattenProperties marks every property as flattened and updates the requiredContainers. Modifies `bag` in place.
func flattenProperties(bag *propertyBag, name string, resolvedSchema *openapi.Schema) {
// Adjust every property to mark them as flattened.
newProperties := map[string]resources.AzureAPIProperty{}
for n, value := range bag.properties {
// The order of containers is important, so we prepend the outermost name.
value.Containers = append([]string{name}, value.Containers...)
newProperties[n] = value
}
bag.properties = newProperties
newRequiredContainers := make(RequiredContainers, len(bag.requiredContainers))
for i, containers := range bag.requiredContainers {
newRequiredContainers[i] = append([]string{name}, containers...)
}
for _, requiredName := range resolvedSchema.Required {
if requiredName == name {
newRequiredContainers = append(newRequiredContainers, []string{name})
}
}
bag.requiredContainers = newRequiredContainers
}
func (m *moduleGenerator) genProperty(name string, schema *spec.Schema, context *openapi.ReferenceContext, resolvedProperty *openapi.Schema, variants genPropertiesVariant) (*pschema.PropertySpec, *resources.AzureAPIProperty, error) {
// Identify properties which are also available as standalone resources and mark them to be maintained if not specified inline.
// Ignore types as we only support top-level resource properties
// Ignore outputs as this is only affecting the input args of a resource, not the resource outputs.
// We only consider arrays (with Items) because in order for the sub-resource to be a standalone resource it must be able to have many instances.
// There is other kinds of sub-resources where there's only a single instance within the parent resource but these are not handled here.
// They are currently handled by the openapi.default module - where we have to add a special case for them *because* they're not managed by the parent and don't have their own delete method.
maintainSubResourceIfUnset := false
if !variants.isType && !variants.isOutput && schema.Items != nil && schema.Items.Schema != nil {
itemsRef := schema.Items.Schema.Ref.String()
for _, nestedRef := range m.nestedResourceBodyRefs {
if itemsRef == nestedRef {
maintainSubResourceIfUnset = true
}
}
}
// Special case for KeyVault access policies - they are a resource that can be defined inline in Vaults or
// stand-alone. The logic above cannot detect that because they are defined as a custom resource. #594
if m.resourceName == "Vault" && m.moduleName == "KeyVault" && name == "accessPolicies" {
maintainSubResourceIfUnset = true
}
description, err := getPropertyDescription(schema, context, maintainSubResourceIfUnset)
if err != nil {
return nil, nil, err
}
typeSpec, err := m.genTypeSpec(name, schema, context, variants.isOutput)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate type spec for property %q: %w", name, err)
}
// Nil type means empty: e.g., when an input type has only read-only properties. Bubble the nil up.
if typeSpec == nil {
return nil, nil, nil
}
// TODO: Remove this switch if https://github.com/Azure/azure-rest-api-specs/issues/13167 is fixed
defaultValue := schema.Default
if defaultValue != nil && typeSpec.Type == "object" {
logging.V(5).Infof("Default value '%v' can't be specified for an object property %q\n", schema.Default, name)
defaultValue = nil
}
// #2187 - there are array properties with default value '[]' in the schema which we don't support
if defaultValue != nil && typeSpec.Type == "array" {
logging.V(5).Infof("Default value '%v' can't be specified for an array property %q\n", schema.Default, name)
defaultValue = nil
}
// Convert default values which are represented using strings instead of their actual types
switch schema.Default.(type) {
case string:
defaultString := schema.Default.(string)
switch typeSpec.Type {
case "boolean":
defaultValue, err = strconv.ParseBool(defaultString)
case "number":
defaultValue, err = strconv.ParseFloat(defaultString, 32)
case "integer":
defaultValue, err = strconv.ParseInt(defaultString, 10, 32)
}
if err != nil {
defaultValue = nil
}
// TODO: Find a better way of detecting when we won't support a default value:
// E.g. #/types/azure-native:machinelearningservices%2Fv20220601preview:LabelingJobResponse/properties/mlAssistConfiguration/default:
// type Union<azure-native:machinelearningservices/v20220601preview:MLAssistConfigurationDisabledResponse, azure-native:machinelearningservices/v20220601preview:MLAssistConfigurationEnabledResponse>
// cannot have a constant value; only booleans, integers, numbers and strings may have constant values;
// HACK: Check if the default value looks like JSON and remove it.
if strings.HasPrefix(defaultString, "{") {
logging.V(5).Infof("Default value '%v' appears to be an object %q\n", schema.Default, name)
defaultValue = nil
}
}
// If there's no object value type, then it's just a set of strings which we'll represent as a string
// array in the SDK, but leave the metadata to indicate we need to convert it.
isStringSet := typeSpec.Type == "object" && typeSpec.AdditionalProperties == nil && typeSpec.Ref == ""
forceNewSpec := noForceNew
if !variants.isOutput {
forceNewSpec = m.forceNew(resolvedProperty, name, variants.isType)
}
schemaProperty := pschema.PropertySpec{
Description: description,
Default: defaultValue,
TypeSpec: *typeSpec,
WillReplaceOnChanges: forceNewSpec == forceNew,
}
if isStringSet {
schemaProperty.Type = "array"
schemaProperty.AdditionalProperties = nil
schemaProperty.Items = &pschema.TypeSpec{
Type: "string",
}
}
metadataProperty := resources.AzureAPIProperty{
OneOf: m.getOneOfValues(typeSpec),
Ref: schemaProperty.Ref,
Items: m.itemTypeToProperty(typeSpec.Items),
AdditionalProperties: m.itemTypeToProperty(typeSpec.AdditionalProperties),
ForceNew: forceNewSpec == forceNew,
ForceNewInferredFromReferencedTypes: forceNewSpec == forceNewSetOnReferencedType,
IsStringSet: isStringSet,
Default: defaultValue,
MaintainSubResourceIfUnset: maintainSubResourceIfUnset,
}
if identifiers, ok := schema.Extensions.GetStringSlice(extensionIdentifiers); ok && typeSpec.Type == "array" {
metadataProperty.ArrayIdentifiers = identifiers
}
// Input types only get extra information attached
if !variants.isOutput {
if m.isEnum(&schemaProperty.TypeSpec) {
metadataProperty = resources.AzureAPIProperty{
Type: "string",
Default: defaultValue,
ForceNew: forceNewSpec == forceNew,
}
} else {
// Set additional properties when it's an input
metadataProperty.Type = typeSpec.Type
metadataProperty.Minimum = resolvedProperty.Minimum
metadataProperty.Maximum = resolvedProperty.Maximum
metadataProperty.MinLength = resolvedProperty.MinLength
metadataProperty.MaxLength = resolvedProperty.MaxLength
metadataProperty.Pattern = resolvedProperty.Pattern
}
}
return &schemaProperty, &metadataProperty, nil
}
func newPropertyBag() *propertyBag {
return &propertyBag{
specs: map[string]pschema.PropertySpec{},
properties: map[string]resources.AzureAPIProperty{},
requiredSpecs: codegen.NewStringSet(),
requiredProperties: codegen.NewStringSet(),
}
}
func (bag *propertyBag) merge(other *propertyBag) {
for key, value := range other.specs {
bag.specs[key] = value
}
for key, value := range other.properties {
bag.properties[key] = value
}
for key := range other.requiredSpecs {
bag.requiredSpecs.Add(key)
}
for key := range other.requiredProperties {
bag.requiredProperties.Add(key)
}
bag.requiredContainers = mergeRequiredContainers(bag.requiredContainers, other.requiredContainers)
}
func mergeRequiredContainers(a, b RequiredContainers) RequiredContainers {
if len(a) == 0 && len(b) == 0 {
return nil
}
result := make(RequiredContainers, 0, len(a)+len(b))
// Index each container by concatenating its elements with a separator.
// This is necessary because we can't compare slices directly.
index := map[string]bool{}
for _, containers := range a {
index[strings.Join(containers, ".")] = true
result = append(result, containers)
}
for _, containers := range b {
if _, ok := index[strings.Join(containers, ".")]; !ok {
result = append(result, containers)
}
}
return result
}
type forceNewMetadata string
const (
forceNew forceNewMetadata = "ForceNew"
forceNewSetOnReferencedType forceNewMetadata = "ForceNewSetOnReferencedType"
noForceNew forceNewMetadata = "NoForceNew"
)
// forceNew returns true if a change to a given property requires a replacement in the resource
// that is currently being generated, based on forceNewMap and the "x-ms-mutability" API spec extension.
// The second return value is true if the property forcing replacement is a property in a referenced type
// (i.e., a property of a property).
func (m *moduleGenerator) forceNew(schema *openapi.Schema, propertyName string, isType bool) forceNewMetadata {
// Mutability extension signals whether a property can be updated in-place. Lack of the extension means
// updatable by default.
// Note: a non-updatable property at a subtype level (a property of a property of a resource) does not
// mandate the replacement of the whole resource.
// Example: `StorageAccount.encryption.services.blob.keyType` is non-updatable, but a user can remove `blob`
// and then re-add it with the new `keyType` without replacing the whole storage account (which would be
// very disruptive).
if resourceMap, ok := noForceNewMap[m.moduleName]; ok {
if properties, ok := resourceMap[m.resourceName]; ok {
if properties.Has(propertyName) {
return noForceNew
}
}
}
hasMutabilityInfo, forcesRecreate := propChangeForcesRecreate(schema)
if hasMutabilityInfo && forcesRecreate {
if isType {
m.forceNewTypes = append(m.forceNewTypes, ForceNewType{
VersionedModule: m.module,
Module: m.moduleName,
ResourceName: m.resourceName,
ReferenceName: schema.ReferenceContext.ReferenceName,
Property: propertyName,
})
return forceNewSetOnReferencedType
}
return forceNew
}
if resourceMap, ok := forceNewMap[m.moduleName]; ok {
if properties, ok := resourceMap[m.resourceName]; ok {
if properties.Has(propertyName) {
return forceNew
}
}
}
return noForceNew
}
// propChangeForcesRecreate returns two booleans.
// The first one indicates whether the schema has mutability extension.
// The second one indicates whether the property requires recreation to change.
func propChangeForcesRecreate(schema *openapi.Schema) (bool, bool) {
hasUpdate, hasCreate := false, false
if mutability, ok := schema.Extensions.GetStringSlice(extensionMutability); ok {
for _, v := range mutability {
switch v {
case extensionMutabilityCreate:
hasCreate = true
case extensionMutabilityUpdate:
hasUpdate = true
}
}
if hasCreate && !hasUpdate {
return true, true // has mutability info and is forces recreation
}
return true, false // has mutability info but is not updatable
}
return false, false // does not have mutability info
}
// itemTypeToProperty converts a type of an element in an array or a dictionary to a corresponding
// API property definition of that element type. It only converts the relevant subset of properties,
// and does so recursively.
func (m *moduleGenerator) itemTypeToProperty(typ *schema.TypeSpec) *resources.AzureAPIProperty {
if typ == nil || typ.Ref == convert.TypeAny {
return nil
}
if m.isEnum(typ) {
return &resources.AzureAPIProperty{Type: "string"}
}
var oneOf []string
for _, subType := range typ.OneOf {
if subType.Ref != "" {
oneOf = append(oneOf, subType.Ref)
} else {
oneOf = append(oneOf, subType.Type)
}
}
return &resources.AzureAPIProperty{
Type: typ.Type,
Ref: typ.Ref,
OneOf: oneOf,
Items: m.itemTypeToProperty(typ.Items),
AdditionalProperties: m.itemTypeToProperty(typ.AdditionalProperties),
}
}
func (m *moduleGenerator) isEnum(typ *schema.TypeSpec) bool {
for _, subType := range typ.OneOf {
if m.isEnum(&subType) {
return true
}
}
if typ.Ref == "" {
return false
}
typeName := strings.TrimPrefix(typ.Ref, "#/types/")
refTyp := m.pkg.Types[typeName]
return len(refTyp.Enum) > 0
}
func (m *moduleGenerator) getOneOfValues(property *pschema.TypeSpec) (values []string) {
for _, value := range property.OneOf {
values = append(values, value.Ref)
}
return
}
// isWriteOnly return true for properties which are annotated with mutability extension that contain no 'read' value.
func isWriteOnly(schema *openapi.Schema) bool {
mutability, has := schema.Extensions.GetStringSlice(extensionMutability)
if !has {
return false
}
for _, v := range mutability {
if v == extensionMutabilityRead {
return false
}
}
return true
}
// getDiscriminator returns a property name and description for a discriminator if it's defined on the schema.
// The boolean return flag is true when a discriminator is found.
func (m *moduleGenerator) getDiscriminator(resolvedSchema *openapi.Schema) (string, string, bool, error) {
if resolvedSchema.Discriminator != "" {
property := resolvedSchema.Properties[resolvedSchema.Discriminator]
resolvedProperty, err := resolvedSchema.ResolveSchema(&property)
if err != nil {
return "", "", false, err
}
return resolvedSchema.Discriminator, resolvedProperty.Description, true, nil
}
for _, s := range resolvedSchema.AllOf {
parentSchema, err := resolvedSchema.ResolveSchema(&s)
if err != nil {
return "", "", false, err
}
parentDiscriminator, parentDescription, has, err := m.getDiscriminator(parentSchema)
if err != nil {
return "", "", false, err
}
if has {
return parentDiscriminator, parentDescription, true, nil
}
}
return "", "", false, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/gen_vnet_test.go | provider/pkg/gen/gen_vnet_test.go | package gen
import (
"os"
"path"
"testing"
"github.com/blang/semver"
"github.com/gkampitakis/go-snaps/snaps"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
)
func TestVnetGen(t *testing.T) {
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
// We take a snapshot of the schema as we're focusing on testing how we parse the spec
// To update the specifications run in the repo root:
// 1. rm -rf provider/pkg/gen/test-data/vnet/azure-rest-api-specs/specification/network/resource-manager/Microsoft.Network/stable/2023-02-01/
// 2. cp -r azure-rest-api-specs/specification/network/resource-manager/Microsoft.Network/stable/2023-02-01 provider/pkg/gen/test-data/vnet/azure-rest-api-specs/specification/network/resource-manager/Microsoft.Network/stable/
// 3. rm -rf provider/pkg/gen/test-data/vnet/azure-rest-api-specs/specification/network/resource-manager/Microsoft.Network/stable/2023-02-01/examples/
rootDir := path.Join(wd, "test-data", "vnet")
modules, _, err := openapi.ReadAzureModules(path.Join(rootDir, "azure-rest-api-specs"), "Network", "2023-02-01")
if err != nil {
t.Fatal(err)
}
generationResult, err := PulumiSchema(rootDir, modules, versioningStub{}, semver.MustParse("2.0.0"), false /* onlyExplicitVersions */)
if err != nil {
t.Fatal(err)
}
snaps.MatchJSON(t, generationResult.Schema)
snaps.MatchJSON(t, generationResult.Metadata)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/examples.go | provider/pkg/gen/examples.go | // Copyright 2022, Pulumi Corporation. All rights reserved.
package gen
import (
"fmt"
"log"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"text/template"
"time"
"github.com/segmentio/encoding/json"
"github.com/hashicorp/hcl/v2"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/debug"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/pcl"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"github.com/pulumi/pulumi-java/pkg/codegen/java"
yaml "github.com/pulumi/pulumi-yaml/pkg/pulumiyaml/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/dotnet"
gogen "github.com/pulumi/pulumi/pkg/v3/codegen/go"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/syntax"
"github.com/pulumi/pulumi/pkg/v3/codegen/nodejs"
hcl2 "github.com/pulumi/pulumi/pkg/v3/codegen/pcl"
"github.com/pulumi/pulumi/pkg/v3/codegen/python"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/schollz/progressbar/v3"
)
type description string
type programText string
type language string
type languageToExampleProgram map[language]programText
type exampleRenderData struct {
ExampleDescription description
LanguageToExampleProgram languageToExampleProgram
}
type resourceExamplesRenderData struct {
Data []exampleRenderData
}
type resourceImportRenderData struct {
Token string
SampleResID string
SampleResName string
}
// Examples renders Azure API examples to the pkgSpec for the specified list of languages.
func Examples(rootDir string, pkgSpec *schema.PackageSpec, metadata *resources.AzureAPIMetadata,
resExamples map[string][]resources.AzureAPIExample, languages []string) error {
sortedKeys := util.SortedKeys(pkgSpec.Resources) // To generate in deterministic order
// Use a progress bar to show progress since this can be a long running process
bar := progressbar.Default(int64(len(sortedKeys)), "Resources processed:")
// cache to speed up code generation
hcl2Cache := hcl2.Cache(hcl2.NewPackageCache())
pkg, err := schema.ImportSpec(*pkgSpec, nil, schema.ValidationOptions{
AllowDanglingReferences: true,
})
if err != nil {
return err
}
loaderOption := hcl2.Loader(InMemoryPackageLoader(map[string]*schema.Package{
"azure-native": pkg,
}))
for _, pulumiToken := range sortedKeys {
err := bar.Add(1)
if err != nil {
log.Printf("error in the progress bar %v", err)
}
if ShouldExclude(pulumiToken) {
log.Printf("Skipping '%s' since it matches exclusion pattern", pulumiToken)
continue
}
debug.Log("Processing '%s'", pulumiToken)
resource := metadata.Resources[pulumiToken]
seen := codegen.NewStringSet()
split := strings.Split(pulumiToken, ":")
if len(split) == 0 {
return fmt.Errorf("invalid resourcename: %s", pulumiToken)
}
resourceName := pcl.Camel(split[len(split)-1])
examplesRenderData := resourceExamplesRenderData{}
importRenderData := resourceImportRenderData{
Token: pulumiToken,
// The name and ID will be overridden later if we find an example that contains a sample response.
SampleResName: "myresource1",
SampleResID: resource.Path,
}
if resourceExamples, ok := resExamples[pulumiToken]; ok {
for _, example := range resourceExamples {
var items []model.BodyItem
if seen.Has(example.Location) {
continue
}
seen.Add(example.Location)
f, err := os.Open(filepath.Join(rootDir, example.Location))
if err != nil {
return err
}
var exampleJSON map[string]interface{}
if err = json.NewDecoder(f).Decode(&exampleJSON); err != nil {
return err
}
if err = f.Close(); err != nil {
return err
}
if _, ok := exampleJSON["parameters"]; !ok {
return fmt.Errorf("example %s missing expected key: 'parameters'", example.Location)
}
resourceParams := map[string]resources.AzureAPIParameter{}
for _, param := range resource.PutParameters {
resourceParams[param.Name] = param
}
if _, ok := exampleJSON["parameters"].(map[string]interface{}); !ok {
fmt.Printf("Expect parameters to be a map, received: %T for resource: %s, skipping.",
exampleJSON["parameters"], pulumiToken)
continue
}
exampleParams := exampleJSON["parameters"].(map[string]interface{})
// Due to https://github.com/Azure/azure-rest-api-specs/issues/28404
if strings.HasSuffix(example.Location, "Microsoft.Security/preview/2020-01-01-preview/examples/Connectors/CreateUpdateAwsCredConnectorSubscription_example.json") {
if authenticationDetails, ok := util.GetInnerMap(exampleParams, "connectorSetting", "properties", "authenticationDetails"); ok {
authenticationDetails["awsAccessKeyId"] = "<awsAccessKeyId>"
}
}
// Fill in sample name and ID for the import section.
responseId, responseName := extractExampleResponseNameId(exampleJSON)
if responseName != "" {
importRenderData.SampleResName = responseName
}
if responseId != "" {
importRenderData.SampleResID = responseId
}
flattened, err := FlattenParams(exampleParams, resourceParams, metadata.Types)
if err != nil {
fmt.Printf("transforming input for example %s for resource %s: %v", example.Description, pulumiToken, err)
continue
}
for k, v := range util.MapOrdered(flattened) {
val, err := pcl.RenderValue(v)
if err != nil {
return err
}
items = append(items, &model.Attribute{
Name: k,
Value: val,
})
}
block := model.Block{
Type: "resource",
Body: &model.Body{Items: items},
Labels: []string{resourceName, pulumiToken},
}
body := &model.Body{Items: []model.BodyItem{&block}}
pcl.FormatBody(body)
languageExample, err := generateExamplePrograms(example, body, languages, hcl2Cache, loaderOption, hcl2.AllowMissingVariables, hcl2.AllowMissingProperties)
if err != nil {
fmt.Printf("skipping example %s for resource %s: %v", example.Description, pulumiToken, err)
continue
}
examplesRenderData.Data = append(examplesRenderData.Data,
exampleRenderData{
ExampleDescription: description(example.Description),
LanguageToExampleProgram: languageExample,
})
}
if len(examplesRenderData.Data) > 0 {
err := renderExampleToSchema(pkgSpec, pulumiToken, &examplesRenderData)
if err != nil {
return err
}
}
}
// Reset in case an example overwrote this path.
importRenderData.SampleResID = resource.Path
err = renderImportToSchema(pkgSpec, pulumiToken, &importRenderData)
if err != nil {
return err
}
metadata.Resources[pulumiToken] = resource
}
return nil
}
// extractExampleResponseNameId extracts ID, name from the first example response that has both.
// If no response has both but one has either, it returns that ID or name, with the other one being empty.
// Else, it returns empty id and name.
func extractExampleResponseNameId(exampleJSON map[string]interface{}) (string, string) {
if exampleResponses, ok := exampleJSON["responses"].(map[string]interface{}); ok {
responseBodies := make([]map[string]interface{}, len(exampleResponses))
// Sort to deterministically pick the same response for reproducable schemas.
for _, response := range util.MapOrdered(exampleResponses) {
if responseMap, ok := response.(map[string]interface{}); ok {
if body, ok := responseMap["body"].(map[string]interface{}); ok {
responseBodies = append(responseBodies, body)
}
}
}
for _, body := range responseBodies {
exampleID, hasId := body["id"].(string)
exampleName, hasName := body["name"].(string)
if hasId && hasName {
return exampleID, exampleName
}
}
for _, body := range responseBodies {
exampleName, hasName := body["name"].(string)
if hasName {
return "", exampleName
}
exampleID, hasId := body["id"].(string)
if hasId {
return exampleID, ""
}
}
}
return "", ""
}
type programGenFn func(*hcl2.Program) (map[string][]byte, hcl.Diagnostics, error)
func generateExamplePrograms(example resources.AzureAPIExample, body *model.Body, languages []string,
bindOptions ...hcl2.BindOption) (languageToExampleProgram, error) {
programBody := fmt.Sprintf("%v", body)
writeDebugProgram("pp", programBody, example.Location)
debug.Log("Generating example programs for %s\n%s\n", example.Location, programBody)
parser := syntax.NewParser()
if err := parser.ParseFile(strings.NewReader(programBody), "program.pp"); err != nil {
return nil, fmt.Errorf("failed to parse IR - file: %s: %v", example.Location, err)
}
if parser.Diagnostics.HasErrors() {
debug.Log("%s", programBody)
err := parser.NewDiagnosticWriter(os.Stderr, 0, true).WriteDiagnostics(parser.Diagnostics)
if err != nil {
log.Printf("failed to write diagnostics: %v", err)
}
}
languageExample := languageToExampleProgram{}
for _, lang := range languages {
program, diags, err := hcl2.BindProgram(parser.Files, bindOptions...)
if err != nil {
return nil, fmt.Errorf("failed to bind program for example %s. %v", example.Location, err)
}
if diags.HasErrors() {
log.Print(programBody)
err := program.NewDiagnosticWriter(os.Stderr, 0, true).WriteDiagnostics(diags)
if err != nil {
log.Printf("failed to write diagnostics: %v", err)
}
}
var files map[string][]byte
switch lang {
case "dotnet":
files, err = recoverableProgramGen(programBody, program, dotnet.GenerateProgram)
case "go":
files, err = recoverableProgramGen(programBody, program, GeneratePatchedGoProgram)
case "nodejs":
files, err = recoverableProgramGen(programBody, program, nodejs.GenerateProgram)
case "python":
files, err = recoverableProgramGen(programBody, program, python.GenerateProgram)
case "yaml":
files, err = recoverableProgramGen(programBody, program, yaml.GenerateProgram)
case "java":
files, err = recoverableProgramGen(programBody, program, java.GenerateProgram)
default:
continue
}
if err != nil {
log.Printf("Program generation failed for language: %s for example %s, continuing", lang, example.Location)
continue
}
buf := strings.Builder{}
for _, f := range files {
_, err := buf.Write(f)
if err != nil {
return nil, err
}
}
languageExample[language(lang)] = programText(buf.String())
debug.Log("Generated %s equivalent for %s", lang, example.Location)
debug.Log("%s", buf.String())
writeDebugProgram(lang, buf.String(), example.Location)
}
return languageExample, nil
}
// writeDebugProgram writes the given example program to DEBUG_CODEGEN_EXAMPLE_<LANG>/ as a file if
// the exampleLocation path matches the value of DEBUG_CODEGEN_EXAMPLE_<LANG>. Paths are from the
// root of the provider repository. Wildcards are allowed. Set the path to '*' to write all examples.
// Example: DEBUG_CODEGEN_EXAMPLE_HCL=azure-rest-api-specs/specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2023-08-01/examples/ManagedClustersCreate_*
func writeDebugProgram(lang, programBody, exampleLocation string) {
envVar := fmt.Sprintf("DEBUG_CODEGEN_EXAMPLE_%s", strings.ToUpper(lang))
debugExamplesPath := os.Getenv(envVar)
match, err := path.Match(debugExamplesPath, exampleLocation)
if debugExamplesPath == "*" {
match = true
}
if err != nil {
log.Printf("\nMalformed DEBUG_CODEGEN_EXAMPLE_HCL %s: %v", debugExamplesPath, err)
return
}
if match {
log.Printf("\nGenerated HCL for %s:\n%s\n", exampleLocation, programBody)
// Switch path from azure-rest-api-specs/specification/provider/... to DEBUG_CODEGEN_EXAMPLE_HCL/provider/...
parts := strings.Split(exampleLocation, "/")
newParts := make([]string, len(parts))
newParts = append(newParts, envVar)
newParts = append(newParts, parts[2:]...)
ext := lang
switch lang {
case "dotnet":
ext = "cs"
case "nodejs":
ext = "ts"
case "python":
ext = "py"
}
newParts[len(newParts)-1] = newParts[len(newParts)-1] + "." + ext
dest := filepath.Join(newParts...)
log.Printf("Writing example %s to %s", exampleLocation, dest)
os.MkdirAll(filepath.Dir(dest), 0755)
err := os.WriteFile(dest, []byte(programBody), 0644)
if err != nil {
log.Printf("\nFailed to write example to %s: %v", dest, err)
}
}
}
func recoverableProgramGen(name string, program *hcl2.Program, fn programGenFn) (files map[string][]byte, err error) {
const timeout = 3 * time.Minute
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic recovered during generation: %v", r)
}
}()
type programGenResult struct {
files map[string][]byte
d hcl.Diagnostics
err error
}
c := make(chan programGenResult, 1)
go func() {
var d hcl.Diagnostics
files, d, err = fn(program)
c <- programGenResult{files, d, err}
}()
select {
case res := <-c:
if res.err != nil {
return nil, res.err
}
files = res.files
if res.d.HasErrors() {
err = program.NewDiagnosticWriter(os.Stderr, 0, true).WriteDiagnostics(res.d)
if err != nil {
log.Printf("failed to write diagnostics: %v", err)
}
}
case <-time.After(timeout):
msg := fmt.Sprintf("%s timed out after %v", name, timeout)
log.Println(msg) // caller doesn't print error due to verbosity
err = fmt.Errorf("%s", msg)
break
}
return
}
func renderExampleToSchema(pkgSpec *schema.PackageSpec, resourceName string,
examplesRenderData *resourceExamplesRenderData) error {
const tmpl = `
{{"{{% examples %}}"}}
## Example Usage
{{- range .Data }}
{{ "{{% example %}}" }}
### {{ .ExampleDescription }}
{{- range $lang, $example := .LanguageToExampleProgram }}
{{ beginLanguage $lang }}
{{ $example }}
{{ endLanguage }}
{{ end }}
{{"{{% /example %}}"}}
{{- end }}
{{"{{% /examples %}}"}}
`
res, ok := pkgSpec.Resources[resourceName]
if !ok {
return fmt.Errorf("missing resource from schema: %s", resourceName)
}
t, err := template.New("examples").Funcs(template.FuncMap{
"beginLanguage": func(lang interface{}) string {
l := fmt.Sprintf("%s", lang)
switch l {
case "nodejs":
l = "typescript"
case "dotnet":
l = "csharp"
}
return fmt.Sprintf("```%s", l)
},
"endLanguage": func() string {
return "```"
},
}).Parse(tmpl)
if err != nil {
return err
}
b := strings.Builder{}
if err = t.Execute(&b, examplesRenderData); err != nil {
return err
}
res.Description += b.String()
pkgSpec.Resources[resourceName] = res
return nil
}
func renderImportToSchema(pkgSpec *schema.PackageSpec, resourceName string,
importRenderData *resourceImportRenderData) error {
const tmpl = `
## Import
An existing resource can be imported using its type token, name, and identifier, e.g.
` + "```" + `sh
$ pulumi import {{ .Token }} {{ .SampleResName }} {{ .SampleResID }}
` + "```\n"
res, ok := pkgSpec.Resources[resourceName]
if !ok {
return fmt.Errorf("missing resource from schema: %s", resourceName)
}
t, err := template.New("import").Parse(tmpl)
if err != nil {
return err
}
b := strings.Builder{}
if err = t.Execute(&b, importRenderData); err != nil {
return err
}
res.Description += b.String()
pkgSpec.Resources[resourceName] = res
return nil
}
// GeneratePatchedGoProgram generates a Go program from the given HCL2 program, but patches the
// generated import paths to adjust for the submodules being their own modules. For example:
// "github.com/pulumi/pulumi-azure-native-sdk/v2/resources" -> "github.com/pulumi/pulumi-azure-native-sdk/resources/v2"
// "github.com/pulumi/pulumi-azure-native-sdk/v2/resources/v20210203" -> "github.com/pulumi/pulumi-azure-native-sdk/resources/v2/v20210203"
func GeneratePatchedGoProgram(program *hcl2.Program) (map[string][]byte, hcl.Diagnostics, error) {
prog, diags, err := gogen.GenerateProgram(program)
if err != nil {
return nil, diags, err
}
// Match prefix: github.com/pulumi/pulumi-azure-native-sdk
// Capture version segment `\/v\d+`
// Capture next path segment: `/[^"\/]*`
// Capture rest of path: `[^"]*"`
matchModuleImports := regexp.MustCompile(`"github\.com\/pulumi\/pulumi-azure-native-sdk(\/v\d+)(\/[^"\/]*)([^"]*)"`)
for k, v := range prog {
// Move version to after the module segment
prog[k] = matchModuleImports.ReplaceAll(v, []byte(`"github.com/pulumi/pulumi-azure-native-sdk${2}${1}${3}"`))
}
return prog, diags, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/params_test.go | provider/pkg/gen/params_test.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package gen
import (
"fmt"
"os"
"strings"
"testing"
"github.com/segmentio/encoding/json"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/stretchr/testify/require"
)
func TestFlattenParams(t *testing.T) {
var metadata resources.AzureAPIMetadata
// TODO - Requires `make schema` to be run first. Turn this into a proper unit test instead.
f, err := os.Open("../../../bin/metadata-compact.json")
require.NoError(t, err)
require.NoError(t, json.NewDecoder(f).Decode(&metadata))
f.Close()
resourceID := func(s string) string {
return fmt.Sprintf("/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/%s", s)
}
for _, test := range []struct {
name string
inputFunc func(t *testing.T) map[string]interface{}
input map[string]interface{}
resourceName string
expected map[string]interface{}
err error
}{
{
name: "ContainersInBody",
resourceName: "azure-native:compute/v20230301:VirtualMachine",
input: map[string]interface{}{
"parameters": map[string]interface{}{
"resourceGroupName": "myResourceGroup",
"vmName": "myVM",
"parameters": map[string]interface{}{
"location": "westus",
"properties": map[string]interface{}{
"hardwareProfile": map[string]interface{}{
"vmSize": "Standard_D1_v2",
},
"storageProfile": map[string]interface{}{
"imageReference": map[string]interface{}{
"sku": "2016-Datacenter",
"publisher": "MicrosoftWindowsServer",
"version": "latest",
"offer": "WindowsServer",
},
"osDisk": map[string]interface{}{
"caching": "ReadWrite",
"managedDisk": map[string]interface{}{
"storageAccountType": "Standard_LRS",
},
"name": "myVMosdisk",
"createOption": "FromImage",
},
},
"networkProfile": map[string]interface{}{
"networkInterfaces": []map[string]interface{}{{
"id": resourceID("Microsoft.Network/networkInterfaces/{existing-nic-name}"),
"properties": map[string]interface{}{
"primary": true,
},
}},
},
"osProfile": map[string]interface{}{
"adminUsername": "{your-username}",
"computerName": "myVM",
"adminPassword": "{your-password}",
},
"availabilitySet": map[string]interface{}{
"id": resourceID("Microsoft.Compute/availabilitySets/{existing-availability-set-name}"),
},
},
},
},
},
expected: map[string]interface{}{
"vmName": "myVM",
"resourceGroupName": "myResourceGroup",
"availabilitySet": map[string]interface{}{
"id": resourceID("Microsoft.Compute/availabilitySets/{existing-availability-set-name}"),
},
"hardwareProfile": map[string]interface{}{
"vmSize": "Standard_D1_v2",
},
"networkProfile": map[string]interface{}{
"networkInterfaces": []map[string]interface{}{
{
"id": resourceID("Microsoft.Network/networkInterfaces/{existing-nic-name}"),
"primary": true,
},
},
},
"location": "westus",
"osProfile": map[string]interface{}{
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerName": "myVM",
},
"storageProfile": map[string]interface{}{
"imageReference": map[string]interface{}{
"offer": "WindowsServer",
"publisher": "MicrosoftWindowsServer",
"sku": "2016-Datacenter",
"version": "latest",
},
"osDisk": map[string]interface{}{
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": map[string]interface{}{
"storageAccountType": "Standard_LRS",
},
"name": "myVMosdisk",
},
},
},
},
{
name: "Props",
input: map[string]interface{}{
"parameters": map[string]interface{}{
"subscriptionId": "subscription-id",
"resourceGroupName": "OneResourceGroupName",
"api-version": "2020-06-02",
"resourceName": "samplebotname",
"connectionName": "sampleConnection",
"parameters": map[string]interface{}{
"location": "West US",
"etag": "etag1",
"properties": map[string]interface{}{
"clientId": "sampleclientid",
"clientSecret": "samplesecret",
"scopes": "samplescope",
"serviceProviderId": "serviceproviderid",
"parameters": []map[string]interface{}{
{
"key": "key1",
"value": "value1",
},
{
"key": "key2",
"value": "value2",
},
},
},
},
},
},
resourceName: "azure-native:botservice/v20220915:BotConnection",
expected: map[string]interface{}{
"resourceGroupName": "OneResourceGroupName",
"resourceName": "samplebotname",
"connectionName": "sampleConnection",
"location": "West US",
"properties": map[string]interface{}{
"clientId": "sampleclientid",
"clientSecret": "samplesecret",
"scopes": "samplescope",
"serviceProviderId": "serviceproviderid",
"parameters": []map[string]interface{}{
{
"key": "key1",
"value": "value1",
},
{
"key": "key2",
"value": "value2",
},
},
},
},
},
{
name: "MoreProps",
input: map[string]interface{}{
"parameters": map[string]interface{}{
"serviceName": "apimService1",
"resourceGroupName": "rg1",
"api-version": "2017-03-01",
"subscriptionId": "subid",
"backendid": "proxybackend",
"parameters": map[string]interface{}{
"properties": map[string]interface{}{
"description": "description5308",
"url": "https://backendname2644/",
"protocol": "http",
"tls": map[string]interface{}{
"validateCertificateChain": true,
"validateCertificateName": true,
},
"proxy": map[string]interface{}{
"url": "http://192.168.1.1:8080",
"username": "Contoso\\admin",
"password": "opensesame",
},
"credentials": map[string]interface{}{
"query": map[string]interface{}{
"sv": []string{
"xx",
"bb",
"cc",
},
},
"header": map[string]interface{}{
"x-my-1": []string{
"val1",
"val2",
},
},
"authorization": map[string]interface{}{
"scheme": "Basic",
"parameter": "opensesma",
},
},
},
},
},
},
resourceName: "azure-native:apimanagement:Backend",
expected: map[string]interface{}{
"serviceName": "apimService1",
"resourceGroupName": "rg1",
"description": "description5308",
"url": "https://backendname2644/",
"protocol": "http",
"tls": map[string]interface{}{
"validateCertificateChain": true,
"validateCertificateName": true,
},
"proxy": map[string]interface{}{
"url": "http://192.168.1.1:8080",
"username": "Contoso\\admin",
"password": "opensesame",
},
"credentials": map[string]interface{}{
"query": map[string]interface{}{
"sv": []string{
"xx",
"bb",
"cc",
},
},
"header": map[string]interface{}{
"x-my-1": []string{
"val1",
"val2",
},
},
"authorization": map[string]interface{}{
"scheme": "Basic",
"parameter": "opensesma",
},
},
},
},
{
name: "ServiceFabric",
input: map[string]interface{}{
"parameters": map[string]interface{}{
"serviceName": "apimService1",
"resourceGroupName": "rg1",
"api-version": "2017-03-01",
"subscriptionId": "subid",
"backendid": "sfbackend",
"parameters": map[string]interface{}{
"properties": map[string]interface{}{
"description": "Service Fabric Test App 1",
"protocol": "http",
"url": "fabric:/mytestapp/mytestservice",
"properties": map[string]interface{}{
"serviceFabricCluster": map[string]interface{}{
"managementEndpoints": []interface{}{
"https://somecluster.com",
},
"clientCertificatethumbprint": "EBA029198AA3E76EF0D70482626E5BCF148594A6",
"serverX509Names": []map[string]interface{}{
{
"name": "ServerCommonName1",
"issuerCertificateThumbprint": "IssuerCertificateThumbprint1",
},
},
"maxPartitionResolutionRetries": 5,
},
},
},
},
},
},
resourceName: "azure-native:apimanagement:Backend",
expected: map[string]interface{}{
"serviceName": "apimService1",
"resourceGroupName": "rg1",
"description": "Service Fabric Test App 1",
"protocol": "http",
"url": "fabric:/mytestapp/mytestservice",
"properties": map[string]interface{}{
"serviceFabricCluster": map[string]interface{}{
"managementEndpoints": []interface{}{
"https://somecluster.com",
},
"clientCertificatethumbprint": "EBA029198AA3E76EF0D70482626E5BCF148594A6",
"serverX509Names": []map[string]interface{}{
{
"name": "ServerCommonName1",
"issuerCertificateThumbprint": "IssuerCertificateThumbprint1",
},
},
"maxPartitionResolutionRetries": 5,
},
},
},
},
{
name: "DeepNesting",
input: map[string]interface{}{
"parameters": map[string]interface{}{
"networkSecurityGroupName": "rancher-security-group",
"location": "westus2",
"parameters": map[string]interface{}{
"properties": map[string]interface{}{
"securityRules": []map[string]interface{}{
{
"name": "SSH",
"properties": map[string]interface{}{
"description": "SSH",
"protocol": "*",
"sourcePortRange": "*",
"destinationPortRange": "22",
"sourceAddressPrefix": "*",
"destinationAddressPrefix": "*",
"access": "Allow",
"priority": 100,
"direction": "Inbound",
"sourcePortRanges": []interface{}{
"22",
"80",
},
"destinationPortRanges": []interface{}{
"22",
"80",
},
"sourceAddressPrefixes": []interface{}{
"192.168.0.1",
},
"destinationAddressPrefixes": []interface{}{
"192.168.0.1",
},
},
},
},
},
},
},
},
resourceName: "azure-native:network/v20230201:NetworkSecurityGroup",
expected: map[string]interface{}{
"networkSecurityGroupName": "rancher-security-group",
"securityRules": []interface{}{
map[string]interface{}{
"access": "Allow",
"description": "SSH",
"destinationAddressPrefix": "*",
"destinationAddressPrefixes": []interface{}{"192.168.0.1"},
"destinationPortRange": "22",
"destinationPortRanges": []interface{}{"22", "80"},
"direction": "Inbound",
"name": "SSH",
"priority": 100,
"protocol": "*",
"sourceAddressPrefix": "*",
"sourceAddressPrefixes": []interface{}{"192.168.0.1"},
"sourcePortRange": "*",
"sourcePortRanges": []interface{}{"22", "80"},
},
},
},
},
{
name: "NestedObject",
inputFunc: serialize(npe),
resourceName: "azure-native:automation/v20170515preview:SoftwareUpdateConfigurationByName",
expected: map[string]interface{}{
"automationAccountName": "myaccount",
"resourceGroupName": "mygroup",
"scheduleInfo": map[string]interface{}{
"advancedSchedule": map[string]interface{}{
"weekDays": []interface{}{
"Monday",
"Thursday",
},
},
"expiryTime": "2018-11-09T11:22:57+00:00",
"frequency": "Hour",
"interval": 1,
"startTime": "2017-10-19T12:22:57+00:00",
"timeZone": "America/Los_Angeles",
},
"softwareUpdateConfigurationName": "testpatch",
"tasks": map[string]interface{}{
"postTask": map[string]interface{}{
"source": "GetCache",
},
"preTask": map[string]interface{}{
"parameters": map[string]interface{}{
"COMPUTERNAME": "Computer1",
},
"source": "HelloWorld",
},
},
"updateConfiguration": map[string]interface{}{
"azureVirtualMachines": []interface{}{
"/subscriptions/5ae68d89-69a4-454f-b5ce-e443cc4e0067/resourceGroups/myresources/providers/Microsoft.Compute/virtualMachines/vm-01",
"/subscriptions/5ae68d89-69a4-454f-b5ce-e443cc4e0067/resourceGroups/myresources/providers/Microsoft.Compute/virtualMachines/vm-02",
"/subscriptions/5ae68d89-69a4-454f-b5ce-e443cc4e0067/resourceGroups/myresources/providers/Microsoft.Compute/virtualMachines/vm-03",
},
"duration": "PT2H0M",
"nonAzureComputerNames": []interface{}{
"box1.contoso.com",
"box2.contoso.com",
},
"operatingSystem": "Windows",
"targets": map[string]interface{}{
"azureQueries": []interface{}{
map[string]interface{}{
"locations": []interface{}{
"Japan East",
"UK South",
},
"scope": []interface{}{
"/subscriptions/5ae68d89-69a4-454f-b5ce-e443cc4e0067/resourceGroups/myresources",
"/subscriptions/5ae68d89-69a4-454f-b5ce-e443cc4e0067",
}, "tagSettings": map[string]interface{}{
"filterOperator": "All",
"tags": []interface{}{
map[string]interface{}{
"tag1": []interface{}{
"tag1Value1",
"tag1Value2",
"tag1Value3",
},
},
map[string]interface{}{
"tag2": []interface{}{
"tag2Value1",
"tag2Value2",
"tag2Value3",
},
},
},
},
},
},
"nonAzureQueries": []interface{}{
map[string]interface{}{
"functionAlias": "SavedSearch1",
"workspaceId": "WorkspaceId1",
},
map[string]interface{}{
"functionAlias": "SavedSearch2",
"workspaceId": "WorkspaceId2",
},
},
}, "windows": map[string]interface{}{
"excludedKbNumbers": []interface{}{
"168934",
"168973",
},
"includedUpdateClassifications": "Critical",
"rebootSetting": "IfRequired",
},
},
},
},
{
name: "VMScaleSet",
inputFunc: serialize(vmScaleSet),
resourceName: "azure-native:compute:VirtualMachineScaleSet",
expected: map[string]interface{}{
"location": "westus",
"overprovision": true,
"resourceGroupName": "myResourceGroup",
"sku": map[string]interface{}{
"capacity": 3,
"name": "Standard_D1_v2",
"tier": "Standard",
},
"upgradePolicy": map[string]interface{}{"mode": "Manual"},
"virtualMachineProfile": map[string]interface{}{
"networkProfile": map[string]interface{}{
"networkInterfaceConfigurations": []interface{}{
map[string]interface{}{
"enableIPForwarding": true,
"ipConfigurations": []interface{}{
map[string]interface{}{
"name": "{vmss-name}",
"subnet": map[string]interface{}{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/{existing-virtual-network-name}/subnets/{existing-subnet-name}",
},
},
},
"name": "{vmss-name}",
"primary": true,
},
},
},
"osProfile": map[string]interface{}{
"adminPassword": "{your-password}",
"adminUsername": "{your-username}",
"computerNamePrefix": "{vmss-name}",
},
"storageProfile": map[string]interface{}{
"imageReference": map[string]interface{}{
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}",
},
"osDisk": map[string]interface{}{
"caching": "ReadWrite",
"createOption": "FromImage",
"managedDisk": map[string]interface{}{
"storageAccountType": "Standard_LRS",
},
},
},
},
"vmScaleSetName": "{vmss-name}",
},
},
{
name: "NoMissingFields",
input: map[string]interface{}{
"parameters": map[string]interface{}{
"appResource": map[string]interface{}{
"properties": map[string]interface{}{
"public": true,
"httpsOnly": false,
"temporaryDisk": map[string]interface{}{
"sizeInGB": 2,
"mountPath": "mytemporarydisk",
},
"persistentDisk": map[string]interface{}{
"sizeInGB": 2,
"mountPath": "mypersistentdisk",
},
},
"identity": nil,
"location": "eastus",
},
"api-version": "2020-07-01",
"subscriptionId": "00000000-0000-0000-0000-000000000000",
"resourceGroupName": "myResourceGroup",
"serviceName": "myservice",
"appName": "myapp",
},
},
resourceName: "azure-native:appplatform:App",
expected: map[string]interface{}{
"appName": "myapp",
"location": "eastus",
"properties": map[string]interface{}{
"httpsOnly": false,
"persistentDisk": map[string]interface{}{
"mountPath": "mypersistentdisk",
"sizeInGB": 2,
},
"public": true,
"temporaryDisk": map[string]interface{}{
"mountPath": "mytemporarydisk",
"sizeInGB": 2,
},
},
"resourceGroupName": "myResourceGroup",
"serviceName": "myservice",
},
},
{
name: "ACI",
inputFunc: serialize(`
{
"parameters":
{"containerGroup":
{ "properties": {
"containers": [
{
"name": "[parameters('name')]",
"properties": {
"image": "[parameters('image')]",
"ports": [
{
"port": "[parameters('port')]"
}
],
"resources": {
"requests": {
"cpu": "[parameters('cpuCores')]",
"memoryInGB": "[parameters('memoryInGb')]"
}
}
}
}
],
"osType": "Linux",
"restartPolicy": "[parameters('restartPolicy')]",
"ipAddress": {
"type": "Public",
"ports": [
{
"protocol": "Tcp",
"port": "[parameters('port')]"
}
]
}
}
}
}
}`),
resourceName: "azure-native:containerinstance:ContainerGroup",
expected: map[string]interface{}{
"containers": []interface{}{
map[string]interface{}{
"image": "[parameters('image')]",
"name": "[parameters('name')]",
"ports": []interface{}{
map[string]interface{}{
"port": "[parameters('port')]",
},
},
"resources": map[string]interface{}{
"requests": map[string]interface{}{
"cpu": "[parameters('cpuCores')]", "memoryInGB": "[parameters('memoryInGb')]",
},
},
},
},
"ipAddress": map[string]interface{}{
"ports": []interface{}{
map[string]interface{}{
"port": "[parameters('port')]",
"protocol": "Tcp",
},
},
"type": "Public",
},
"osType": "Linux",
"restartPolicy": "[parameters('restartPolicy')]",
},
},
{
name: "Site",
inputFunc: serialize(`
{
"parameters": {
"siteEnvelope": {
"properties": {
"siteConfig": "[variables('configReference')[parameters('language')]]",
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('appServicePlanPortalName'))]"
}
}
}
}`),
resourceName: "azure-native:web/v20220901:WebApp",
expected: map[string]interface{}{
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('appServicePlanPortalName'))]",
"siteConfig": "[variables('configReference')[parameters('language')]]",
},
},
{
name: "DatabaseAccount",
inputFunc: serialize(`
{
"parameters": {
"createUpdateParameters": {
"properties": {
"databaseAccountOfferType": "Standard",
"locations": [
{
"id": "[concat(parameters('name'), '-', parameters('location'))]",
"failoverPriority": 0,
"locationName": "[parameters('location')]"
}
],
"backupPolicy": {
"type": "Periodic",
"periodicModeProperties": {
"backupIntervalInMinutes": 240,
"backupRetentionIntervalInHours": 8
}
},
"capabilities": [
{
"name": "EnableServerless"
}
],
"enableFreeTier": false
}
}
}
}`),
resourceName: "azure-native:cosmosdb:DatabaseAccount",
expected: map[string]interface{}{
"backupPolicy": map[string]interface{}{
"periodicModeProperties": map[string]interface{}{
"backupIntervalInMinutes": 240,
"backupRetentionIntervalInHours": 8,
},
"type": "Periodic",
},
"capabilities": []interface{}{
map[string]interface{}{
"name": "EnableServerless",
},
},
"databaseAccountOfferType": "Standard",
"enableFreeTier": false,
"locations": []interface{}{
map[string]interface{}{
"failoverPriority": 0,
"locationName": "[parameters('location')]",
},
},
},
},
{
name: "JsonAny",
inputFunc: serialize(`{
"parameters": {
"extensionParameters": {
"properties": {
"autoUpgradeMinorVersion": true,
"publisher": "Microsoft.OSTCExtensions",
"type": "VMAccessForLinux",
"typeHandlerVersion": "1.4",
"settings": {},
"protectedSettings": {
"username": "[parameters('extensions_enablevmaccess_username')]",
"password": "[parameters('extensions_enablevmaccess_password')]",
"ssh_key": "[parameters('extensions_enablevmaccess_ssh_key')]",
"reset_ssh": "[parameters('extensions_enablevmaccess_reset_ssh')]",
"remove_user": "[parameters('extensions_enablevmaccess_remove_user')]",
"expiration": "[parameters('extensions_enablevmaccess_expiration')]"
}
}
}
}
}`),
resourceName: "azure-native:compute/v20230301:VirtualMachineExtension",
expected: map[string]interface{}{
"autoUpgradeMinorVersion": true,
"publisher": "Microsoft.OSTCExtensions",
"type": "VMAccessForLinux",
"typeHandlerVersion": "1.4",
"settings": map[string]interface{}{},
"protectedSettings": map[string]interface{}{
"username": "[parameters('extensions_enablevmaccess_username')]",
"password": "[parameters('extensions_enablevmaccess_password')]",
"ssh_key": "[parameters('extensions_enablevmaccess_ssh_key')]",
"reset_ssh": "[parameters('extensions_enablevmaccess_reset_ssh')]",
"remove_user": "[parameters('extensions_enablevmaccess_remove_user')]",
"expiration": "[parameters('extensions_enablevmaccess_expiration')]",
},
},
},
{
name: "OneOf",
input: map[string]interface{}{
"parameters": map[string]interface{}{
"subscriptionId": "subscription-id",
"resourceGroupName": "OneResourceGroupName",
"api-version": "2020-06-02",
"resourceName": "samplebotname",
"channelName": "AlexaChannel",
"parameters": map[string]interface{}{
"location": "global",
"properties": map[string]interface{}{
"channelName": "AlexaChannel",
"properties": map[string]interface{}{
"alexaSkillId": "XAlexaSkillIdX",
"isEnabled": true,
},
},
},
},
},
resourceName: "azure-native:botservice/v20220915:Channel",
expected: map[string]interface{}{
"channelName": "AlexaChannel",
"location": "global",
"properties": map[string]interface{}{
"channelName": "AlexaChannel",
"properties": map[string]interface{}{
"alexaSkillId": "XAlexaSkillIdX",
"isEnabled": true,
},
},
"resourceGroupName": "OneResourceGroupName",
"resourceName": "samplebotname",
},
},
} {
t.Run(test.name, func(t *testing.T) {
if test.input == nil {
test.input = test.inputFunc(t)
}
in := test.input["parameters"].(map[string]interface{})
params := map[string]resources.AzureAPIParameter{}
resource, resourceFound := metadata.Resources[test.resourceName]
if !resourceFound {
require.Failf(t, "resource not found", "resource %s not found", test.resourceName)
}
for _, param := range resource.PutParameters {
params[param.Name] = param
}
out, err := FlattenParams(in, params, metadata.Types)
if test.err != nil {
require.Error(t, err)
require.Empty(t, out)
} else {
require.NoError(t, err)
expected, actual := &strings.Builder{}, &strings.Builder{}
require.NoError(t, json.NewEncoder(expected).Encode(test.expected))
require.NoError(t, json.NewEncoder(actual).Encode(out))
require.JSONEq(t, expected.String(), actual.String())
}
})
}
}
func serialize(input string) func(*testing.T) map[string]interface{} {
return func(t *testing.T) map[string]interface{} {
serialized := make(map[string]interface{})
require.NoError(t, json.Unmarshal([]byte(input), &serialized))
return serialized
}
}
const (
npe = `{
"parameters": {
"subscriptionId": "51766542-3ed7-4a72-a187-0c8ab644ddab",
"resourceGroupName": "mygroup",
"automationAccountName": "myaccount",
"softwareUpdateConfigurationName": "testpatch",
"api-version": "2017-05-15-preview",
"parameters": {
"properties": {
"updateConfiguration": {
"operatingSystem": "Windows",
"duration": "PT2H0M",
"windows": {
"excludedKbNumbers": [
"168934",
"168973"
],
"includedUpdateClassifications": "Critical",
"rebootSetting": "IfRequired"
},
"azureVirtualMachines": [
"/subscriptions/5ae68d89-69a4-454f-b5ce-e443cc4e0067/resourceGroups/myresources/providers/Microsoft.Compute/virtualMachines/vm-01",
"/subscriptions/5ae68d89-69a4-454f-b5ce-e443cc4e0067/resourceGroups/myresources/providers/Microsoft.Compute/virtualMachines/vm-02",
"/subscriptions/5ae68d89-69a4-454f-b5ce-e443cc4e0067/resourceGroups/myresources/providers/Microsoft.Compute/virtualMachines/vm-03"
],
"nonAzureComputerNames": [
"box1.contoso.com",
"box2.contoso.com"
],
"targets": {
"azureQueries": [
{
"scope": [
"/subscriptions/5ae68d89-69a4-454f-b5ce-e443cc4e0067/resourceGroups/myresources",
"/subscriptions/5ae68d89-69a4-454f-b5ce-e443cc4e0067"
],
"tagSettings": {
"tags": [
{
"tag1": [
"tag1Value1",
"tag1Value2",
"tag1Value3"
]
},
{
"tag2": [
"tag2Value1",
"tag2Value2",
"tag2Value3"
]
}
],
"filterOperator": "All"
},
"locations": [
"Japan East",
"UK South"
]
}
],
"nonAzureQueries": [
{
"functionAlias": "SavedSearch1",
"workspaceId": "WorkspaceId1"
},
{
"functionAlias": "SavedSearch2",
"workspaceId": "WorkspaceId2"
}
]
}
},
"scheduleInfo": {
"frequency": "Hour",
"startTime": "2017-10-19T12:22:57+00:00",
"timeZone": "America/Los_Angeles",
"interval": 1,
"expiryTime": "2018-11-09T11:22:57+00:00",
"advancedSchedule": {
"weekDays": [
"Monday",
"Thursday"
]
}
},
"tasks": {
"preTask": {
"source": "HelloWorld",
"parameters": {
"COMPUTERNAME": "Computer1"
}
},
"postTask": {
"source": "GetCache",
"parameters": null
}
}
}
}
}
}`
vmScaleSet = `{
"parameters": {
"subscriptionId": "{subscription-id}",
"resourceGroupName": "myResourceGroup",
"vmScaleSetName": "{vmss-name}",
"api-version": "2020-06-01",
"parameters": {
"sku": {
"tier": "Standard",
"capacity": 3,
"name": "Standard_D1_v2"
},
"location": "westus",
"properties": {
"overprovision": true,
"virtualMachineProfile": {
"storageProfile": {
"imageReference": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/images/{existing-custom-image-name}"
},
"osDisk": {
"caching": "ReadWrite",
"managedDisk": {
"storageAccountType": "Standard_LRS"
},
"createOption": "FromImage"
}
},
"osProfile": {
"computerNamePrefix": "{vmss-name}",
"adminUsername": "{your-username}",
"adminPassword": "{your-password}"
},
"networkProfile": {
"networkInterfaceConfigurations": [
{
"name": "{vmss-name}",
"properties": {
"primary": true,
"enableIPForwarding": true,
"ipConfigurations": [
{
"name": "{vmss-name}",
"properties": {
"subnet": {
"id": "/subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Network/virtualNetworks/{existing-virtual-network-name}/subnets/{existing-subnet-name}"
}
}
}
]
}
}
]
}
},
"upgradePolicy": {
"mode": "Manual"
}
}
}
}
}`
)
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/replacement.go | provider/pkg/gen/replacement.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package gen
import (
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi/pkg/v3/codegen"
)
// forceNewMap is a map of Module Name -> Resource Name -> Properties that cause replacements.
// API Versions are currently ignored.
var forceNewMap = map[openapi.ModuleName]map[string]codegen.StringSet{
"Authorization": {
"RoleAssignment": codegen.NewStringSet("principalId", "scope"),
},
"Automation": {
"JobSchedule": codegen.NewStringSet("parameters"),
},
"Cdn": {
"Profile": codegen.NewStringSet(
"location",
// sku
"name",
),
},
"ContainerService": {
"ManagedCluster": codegen.NewStringSet(
// cluster
"diskEncryptionSetID",
"dnsPrefix",
"fqdnSubdomain",
"linuxProfile",
"location",
"networkProfile",
"nodeResourceGroup",
"windowsProfile",
),
"AgentPool": codegen.NewStringSet(
"gpuInstanceProfile",
"vmSize",
),
},
"DocumentDB": {
"SqlResourceSqlRoleAssignment": codegen.NewStringSet("principalId", "scope"),
},
"Insights": {
"Component": codegen.NewStringSet(), // covered by x-ms-mutability
},
"Network": {
// https://github.com/pulumi/pulumi-azure-native/issues/3883
// https://stackoverflow.com/questions/78877433/arm-template-is-it-possible-to-change-subnets-of-private-endpoint
// https://learn.microsoft.com/en-us/answers/questions/1295954/how-to-migrate-a-keyvault-private-endpoint-to-a-ne
"PrivateEndpoint": codegen.NewStringSet("subnet"),
"PublicIPAddress": codegen.NewStringSet("location", "publicIPAddressVersion", "publicIPPrefix", "sku"),
"Subnet": codegen.NewStringSet(), // no force-news
"VirtualNetwork": codegen.NewStringSet("location"),
},
"Resources": {
"ResourceGroup": codegen.NewStringSet("location"),
},
"ServiceBus": {
"Topic": codegen.NewStringSet("requiresDuplicateDetection", "requiresSession", "enablePartitioning"),
"Queue": codegen.NewStringSet("requiresDuplicateDetection", "requiresSession", "enablePartitioning"),
},
"Storage": {
"BlobContainer": codegen.NewStringSet(), // no force-news
"StorageAccount": codegen.NewStringSet("isHnsEnabled", "location"),
},
"Web": {
"AppServicePlan": codegen.NewStringSet(), // covered by x-ms-mutability
"WebApp": codegen.NewStringSet("location", "kind"),
},
}
// noForceNewMap overrides forceNewMap and x-ms-mutability to *not* force
// replacement. Appropriate when Azure previously forced replacement but no longer does.
var noForceNewMap = map[openapi.ModuleName]map[string]codegen.StringSet{
"ServiceBus": {
"Namespace": codegen.NewStringSet("zoneRedundant"), // https://github.com/pulumi/pulumi-azure-native/issues/4105
},
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/merging.go | provider/pkg/gen/merging.go | package gen
import (
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
// mergeTypes checks that two type specs are allowed to be represented as a single schema type.
// Refs are not followed, but are just checked for equality as the referred type will then be checked independently.
// If you face an error coming from this function for a new API change, consider changing the typeNameOverride map
// or adjusting the way the top-level resources are projected in versioner.go.
func mergeTypes(t1 schema.ComplexTypeSpec, t2 schema.ComplexTypeSpec, isOutput bool) (*schema.ComplexTypeSpec, error) {
if t1.Type != t2.Type {
return nil, errors.Errorf("types do not match: %s vs %s", t1.Type, t2.Type)
}
if !isOutput {
// Check that every required property of T1 and T2 exists in T1 and has the same type (for inputs only).
t1Required := codegen.NewStringSet(t1.Required...)
t2Required := codegen.NewStringSet(t2.Required...)
t1Only := t1Required.Subtract(t2Required)
t2Only := t2Required.Subtract(t1Required)
if len(t1Only) != 0 || len(t2Only) != 0 {
var requiredErrors []string
if len(t1Only) != 0 {
t1Fmt := strings.Join(t1Only.SortedValues(), ",")
requiredErrors = append(requiredErrors, fmt.Sprintf("only required in A: %s", t1Fmt))
}
if len(t2Only) != 0 {
t2Fmt := strings.Join(t2Only.SortedValues(), ",")
requiredErrors = append(requiredErrors, fmt.Sprintf("only required in B: %s", t2Fmt))
}
return nil, errors.Errorf("required properties do not match: %s", strings.Join(requiredErrors, "; ")+" (check playbooks/Resolving-api-merge-conflicts.md)")
}
}
if t1.Properties == nil && t2.Properties == nil {
return &t1, nil
}
mergedProperties := map[string]schema.PropertySpec{}
for name, p := range t1.Properties {
mergedProperties[name] = p
}
for name, p2 := range t2.Properties {
p1, found := mergedProperties[name]
if !found {
mergedProperties[name] = p2
continue
}
mergedProperty, err := mergePropertySpec(p1, p2)
if err != nil {
return nil, err
}
mergedProperties[name] = *mergedProperty
}
merged := t1
merged.Properties = mergedProperties
return &merged, nil
}
func mergePropertySpec(p1, p2 schema.PropertySpec) (*schema.PropertySpec, error) {
mergedTypeSpec, err := mergeTypeSpec(p1.TypeSpec, p2.TypeSpec)
if err != nil {
return nil, err
}
p1.TypeSpec = *mergedTypeSpec
return &p1, nil
}
func mergeTypeSpec(t1, t2 schema.TypeSpec) (*schema.TypeSpec, error) {
// Simple case: both types are the same primitive.
if isPrimitiveType(t1) && isPrimitiveType(t2) {
if t1.Type == t2.Type {
return &t1, nil
}
if t1.Type == "integer" && t2.Type == "number" || t1.Type == "number" && t2.Type == "integer" {
// If one is an integer and the other is a number, the merged type is number.
return &schema.TypeSpec{Type: "number"}, nil
}
}
if t1.Ref != "" && t2.Ref != "" {
// Simple case: both types are the same ref.
if t1.Ref == t2.Ref {
return &t1, nil
}
// Refs don't match - fail with error.
return nil, errors.Errorf("refs do not match: %s vs %s", t1.Ref, t2.Ref)
}
if t1.Type == "array" && t2.Type == "array" {
contract.Assertf(t1.Items != nil && t2.Items != nil, "Type %v is missing items (other: %v)", t1, t2)
// Both are arrays - merge the element types.
items, err := mergeTypeSpec(*t1.Items, *t2.Items)
if err != nil {
return nil, err
}
t1.Items = items
return &t1, nil
}
if t1.Type == "object" && t2.Type == "object" {
contract.Assertf(t1.AdditionalProperties != nil, "Type %v is missing additionalProperties (other: %v)", t1, t2)
contract.Assertf(t2.AdditionalProperties != nil, "Type %v is missing additionalProperties (other: %v)", t2, t1)
// Both are objects - merge the properties.
merged, err := mergeTypeSpec(*t1.AdditionalProperties, *t2.AdditionalProperties)
if err != nil {
return nil, err
}
t1.AdditionalProperties = merged
return &t1, nil
}
// One is a oneOf - combine the other into it.
if t1.OneOf != nil || t2.OneOf != nil {
oneOf, other := t1, t2
if t1.OneOf == nil {
oneOf, other = t2, t1
}
return unionOneOfTypes(oneOf, other)
}
// Fail with error
return nil, errors.Errorf("types not mergable: %v vs %v", t1, t2)
}
func isPrimitiveType(t schema.TypeSpec) bool {
return t.Type == "string" || t.Type == "integer" || t.Type == "number" || t.Type == "boolean"
}
// unionOneOfTypes checks that two oneOf types are allowed to be represented as a single schema type.
func unionOneOfTypes(oneOf, other schema.TypeSpec) (*schema.TypeSpec, error) {
contract.Assertf(oneOf.OneOf != nil, "Type %v is not a oneOf", oneOf)
if isPrimitiveType(other) {
// Check if type exists in oneOf.
for _, t := range oneOf.OneOf {
if t.Type == other.Type {
return &oneOf, nil
}
}
// Not found - add it.
oneOf.OneOf = append(oneOf.OneOf, other)
return &oneOf, nil
}
if other.Ref != "" {
// Check if ref exists in oneOf.
for _, t := range oneOf.OneOf {
if t.Ref == other.Ref {
return &oneOf, nil
}
}
// Not found - add it.
oneOf.OneOf = append(oneOf.OneOf, other)
return &oneOf, nil
}
if other.OneOf != nil {
bothHaveDiscriminators := oneOf.Discriminator != nil && other.Discriminator != nil
onlyOneHasDiscriminator := (oneOf.Discriminator == nil && other.Discriminator != nil) || (oneOf.Discriminator != nil && other.Discriminator == nil)
if onlyOneHasDiscriminator || (bothHaveDiscriminators && oneOf.Discriminator.PropertyName != other.Discriminator.PropertyName) {
return nil, errors.Errorf("cannot union oneOf with different discriminators: %v vs %v", oneOf, other)
}
if oneOf.Discriminator != nil {
// Union the discriminators.
for k, otherRef := range other.Discriminator.Mapping {
if oneOfRef, found := oneOf.Discriminator.Mapping[k]; found && oneOfRef != otherRef {
return nil, errors.Errorf("cannot union oneOf with different discriminators: %v vs %v", oneOf, other)
}
oneOf.Discriminator.Mapping[k] = otherRef
}
}
// Union each type in other oneOf with the first oneOf.
for _, t := range other.OneOf {
merged, err := unionOneOfTypes(oneOf, t)
if err != nil {
return nil, err
}
oneOf = *merged
}
return &oneOf, nil
}
return nil, errors.Errorf("cannot union oneOf with specified type %v", other)
}
// func intersectOneOfTypes(oneOf, other schema.TypeSpec) (*schema.TypeSpec, error) {
// contract.Assert(oneOf.OneOf != nil)
// if isPrimitiveType(other) {
// // Check if type exists in oneOf.
// for _, t := range oneOf.OneOf {
// if t.Type == other.Type {
// return &other, nil
// }
// }
// // Not found - return error.
// return nil, errors.Errorf("cannot intersect oneOf with specified type %v", other)
// }
// if other.Ref != "" {
// // Check if ref exists in oneOf.
// for _, t := range oneOf.OneOf {
// if t.Ref == other.Ref {
// return &other, nil
// }
// }
// // Not found - return error.
// return nil, errors.Errorf("cannot intersect oneOf with specified type %v", other)
// }
// if other.OneOf != nil {
// // Find common types in other oneOf and the first oneOf.
// common := []schema.TypeSpec{}
// otherByKey := make(map[string]schema.TypeSpec)
// for _, t := range other.OneOf {
// otherByKey[oneOfTypeKey(t)] = t
// }
// for _, t := range oneOf.OneOf {
// if _, ok := otherByKey[oneOfTypeKey(t)]; ok {
// common = append(common, t)
// }
// }
// if len(common) == 0 {
// return nil, errors.Errorf("cannot intersect oneOf with specified type %v", other)
// }
// if len(common) == 1 {
// return &common[0], nil
// }
// oneOf.OneOf = common
// return &oneOf, nil
// }
// return nil, errors.Errorf("cannot union oneOf with specified type %v", other)
// }
//
// func oneOfTypeKey(t schema.TypeSpec) string {
// // convert to json
// b, err := json.Marshal(t)
// contract.Assert(err == nil)
// return string(b)
// }
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/goModVersion_test.go | provider/pkg/gen/goModVersion_test.go | // Copyright 2016-2020, Pulumi Corporation.
package gen
import (
"testing"
"github.com/blang/semver"
"github.com/stretchr/testify/assert"
)
func testVersion(input, expected string) func(t *testing.T) {
return func(t *testing.T) {
version, err := semver.Parse(input)
if err != nil {
assert.Error(t, err)
return
}
actual := GoModVersion(&version)
assert.Equal(t, expected, actual)
}
}
func TestGoModVersion(t *testing.T) {
t.Run("Major", testVersion("1.0.0", "v1.0.0"))
t.Run("Build", testVersion("1.1.0-alpha.1662577914+9fa804e8", "v1.1.0-alpha.9fa804e8"))
t.Run("Local Dirty", testVersion("1.1.0-alpha.0+9fa804e8.dirty", "v1.1.0-alpha.9fa804e8.dirty"))
t.Run("No tags", testVersion("0.0.1-alpha.0+68804cfa", "v0.0.1-alpha.68804cfa"))
t.Run("Beta", testVersion("2.0.0-beta.3", "v2.0.0-beta.3"))
t.Run("Build with leading zero", testVersion("3.9.0-alpha.1761105334+0701526", "v3.9.0-alpha.g0701526"))
t.Run("Build with leading zero and dirty", testVersion("3.9.0-alpha.0+0701526.dirty", "v3.9.0-alpha.g0701526.dirty"))
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/utilities_test.go | provider/pkg/gen/utilities_test.go | // Copyright 2016-2020, Pulumi Corporation.
package gen
import "testing"
func TestToLowerCamel(t *testing.T) {
cases := [][]string{
{"foo-bar", "fooBar"},
{"TestCase", "testCase"},
{"", ""},
{"AnyKind of_string", "anyKindOfString"},
{"AnyKind.of-string", "anyKindOfString"},
{"ID", "id"},
{"TTL", "ttl"},
{"_ref", "ref"},
{"5qi", "fiveQi"},
{"6", "six"},
}
for _, i := range cases {
in := i[0]
out := i[1]
result := ToLowerCamel(in)
if result != out {
t.Error("'" + result + "' != '" + out + "'")
}
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/schema_test.go | provider/pkg/gen/schema_test.go | // Copyright 2016-2020, Pulumi Corporation.
package gen
import (
"fmt"
"strings"
"testing"
"github.com/go-openapi/spec"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/version"
pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Ensure our VersionMetadata type implements the gen.Versioning interface
// The compiler will raise an error here if the interface isn't implemented
var _ Versioning = (*versioningStub)(nil)
type versioningStub struct {
shouldInclude func(moduleName openapi.ModuleName, version *openapi.ApiVersion, typeName, token string) bool
getDeprecations func(token string) (ResourceDeprecation, bool)
getAllVersions func(moduleName openapi.ModuleName, resource string) []openapi.ApiVersion
previousTokenPaths map[string]string
}
func (v versioningStub) ShouldInclude(moduleName openapi.ModuleName, version *openapi.ApiVersion, typeName, token string) bool {
if v.shouldInclude != nil {
return v.shouldInclude(moduleName, version, typeName, token)
}
return true
}
func (v versioningStub) GetDeprecation(token string) (ResourceDeprecation, bool) {
if v.getDeprecations != nil {
return v.getDeprecations(token)
}
return ResourceDeprecation{}, false
}
func (v versioningStub) GetAllVersions(moduleName openapi.ModuleName, resource string) []openapi.ApiVersion {
if v.getAllVersions != nil {
return v.getAllVersions(moduleName, resource)
}
return []openapi.ApiVersion{}
}
func (v versioningStub) GetPreviousCompatibleTokensLookup() (*CompatibleTokensLookup, error) {
return NewCompatibleTokensLookup(v.previousTokenPaths)
}
func TestAliases(t *testing.T) {
// Wrap the generation of type aliases in a function to make it easier to test
generateTypeAliases := func(moduleName, typeName string, sdkVersion openapi.SdkVersion, oldTokens []string, typeNameAliases []string, versions []openapi.ApiVersion) []string {
path := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Foo/resources/{name}"
previousTokenPaths := map[string]string{}
for _, token := range oldTokens {
previousTokenPaths[token] = path
}
previousCompatibleTokensLookup, err := NewCompatibleTokensLookup(previousTokenPaths)
require.NoError(t, err, "failed to create previous compatible tokens lookup")
generator := packageGenerator{
pkg: &pschema.PackageSpec{Name: "azure-native"},
sdkVersion: sdkVersion,
versioning: versioningStub{},
moduleName: openapi.ModuleName(moduleName),
majorVersion: 2,
previousCompatibleTokensLookup: previousCompatibleTokensLookup,
}
resource := &resourceVariant{
ResourceSpec: &openapi.ResourceSpec{
Path: path,
CompatibleVersions: versions,
},
typeName: typeName,
}
resourceTok := generateTok(openapi.ModuleName(moduleName), typeName, sdkVersion)
aliasSpecs := generator.generateAliases(resourceTok, resource, typeNameAliases...)
typeAliases := []string{}
for _, alias := range aliasSpecs {
typeAliases = append(typeAliases, alias.Type)
}
return typeAliases
}
t.Run("compatible version", func(t *testing.T) {
actual := generateTypeAliases("Insights", "PrivateLinkForAzureAd", "v20220222", nil, nil, []openapi.ApiVersion{"2020-01-10", "2021-01-11"})
expected := []string{
"azure-native:insights/v20200110:PrivateLinkForAzureAd",
"azure-native:insights/v20210111:PrivateLinkForAzureAd",
}
assert.ElementsMatch(t, expected, actual)
})
t.Run("type alias", func(t *testing.T) {
actual := generateTypeAliases("Insights", "PrivateLinkForAzureAd", "v20220222", nil, []string{"privateLinkForAzureAd"}, []openapi.ApiVersion{})
expected := []string{
"azure-native:insights/v20220222:privateLinkForAzureAd",
}
assert.ElementsMatch(t, expected, actual)
})
t.Run("compatible version & type alias", func(t *testing.T) {
actual := generateTypeAliases("Insights", "PrivateLinkForAzureAd", "v20220222", nil, []string{"privateLinkForAzureAd"}, []openapi.ApiVersion{"2020-01-10", "2021-01-11"})
expected := []string{
"azure-native:insights/v20200110:privateLinkForAzureAd",
"azure-native:insights/v20200110:PrivateLinkForAzureAd",
"azure-native:insights/v20210111:privateLinkForAzureAd",
"azure-native:insights/v20210111:PrivateLinkForAzureAd",
"azure-native:insights/v20220222:privateLinkForAzureAd",
}
assert.ElementsMatch(t, expected, actual)
})
t.Run("previous module", func(t *testing.T) {
actual := generateTypeAliases("Monitor", "PrivateLinkForAzureAd", "v20220222", []string{"azure-native:insights/v20220222:PrivateLinkForAzureAd"}, nil, []openapi.ApiVersion{})
expected := []string{
"azure-native:insights/v20220222:PrivateLinkForAzureAd",
}
assert.ElementsMatch(t, expected, actual)
})
t.Run("previous module & compatible version", func(t *testing.T) {
actual := generateTypeAliases("Monitor", "PrivateLinkForAzureAd", "v20220222", []string{"azure-native:insights/v20220222:PrivateLinkForAzureAd"}, nil, []openapi.ApiVersion{"2020-01-10", "2021-01-11"})
expected := []string{
"azure-native:monitor/v20200110:PrivateLinkForAzureAd", // change version
"azure-native:insights/v20220222:PrivateLinkForAzureAd", // previous major version
"azure-native:monitor/v20210111:PrivateLinkForAzureAd", // change version
}
assert.ElementsMatch(t, expected, actual)
})
t.Run("previous module, compatible version & type alias", func(t *testing.T) {
actual := generateTypeAliases("Monitor", "PrivateLinkForAzureAd", "v20220222", []string{"azure-native:insights/v20220222:PrivateLinkForAzureAd"}, []string{"privateLinkForAzureAd"}, []openapi.ApiVersion{"2020-01-10", "2021-01-11"})
expected := []string{
"azure-native:monitor/v20200110:PrivateLinkForAzureAd", // change version
"azure-native:monitor/v20200110:privateLinkForAzureAd", // change version & case
"azure-native:monitor/v20210111:PrivateLinkForAzureAd", // change version
"azure-native:monitor/v20210111:privateLinkForAzureAd", // change version & case
"azure-native:monitor/v20220222:privateLinkForAzureAd", // change case
"azure-native:insights/v20220222:PrivateLinkForAzureAd", // previous major version
}
assert.ElementsMatch(t, expected, actual)
})
}
func TestFindNestedResources(t *testing.T) {
parent := &openapi.ResourceSpec{
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}",
}
otherResources := map[string]*openapi.ResourceSpec{
"VirtualNetwork": {
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}",
},
"VirtualNetworks": {
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks",
},
"Subnet": {
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}",
},
"SubnetPrivateEndpoint": {
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}",
},
"VirtualNetworkPeering": {
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}",
},
}
actual := findNestedResources(parent, otherResources)
expected := []*openapi.ResourceSpec{
{
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}",
},
{
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}",
},
{
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}",
},
}
assert.Equal(t, expected, actual)
}
func TestFindResourcesBodyRefs(t *testing.T) {
nestedResources := []*openapi.ResourceSpec{
{
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}",
PathItem: &spec.PathItem{
PathItemProps: spec.PathItemProps{
Put: &spec.Operation{
OperationProps: spec.OperationProps{
Parameters: []spec.Parameter{
{
ParamProps: spec.ParamProps{
In: "body",
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Ref: spec.MustCreateRef("#/definitions/Subnet"),
},
},
},
},
},
},
},
},
},
},
}
actual := findResourcesBodyRefs(nestedResources)
expected := []string{"#/definitions/Subnet"}
assert.Equal(t, expected, actual)
}
func TestNormalizePattern(t *testing.T) {
openapiParam := func(pattern string, maxLength int64) *openapi.Parameter {
return &openapi.Parameter{
Parameter: &spec.Parameter{
CommonValidations: spec.CommonValidations{
Pattern: pattern,
MaxLength: &maxLength,
},
ParamProps: spec.ParamProps{
Name: "dashboardName",
},
},
}
}
t.Run("not a dashboard name", func(t *testing.T) {
p := openapiParam("^[a-zA-Z0-9-]{3,24}$", 90)
p.Name = "foo"
assert.Equal(t, "^[a-zA-Z0-9-]{3,24}$", normalizeParamPattern(p))
})
t.Run("empty", func(t *testing.T) {
p := openapiParam("", 0)
assert.Equal(t, "", normalizeParamPattern(p))
})
t.Run("empty with length", func(t *testing.T) {
p := openapiParam("", 90)
assert.Equal(t, "", normalizeParamPattern(p))
})
t.Run("pattern without length", func(t *testing.T) {
p := openapiParam("^[a-zA-Z0-9-]{3,24}$", 0)
assert.Equal(t, "^[a-zA-Z0-9-]{3,24}$", normalizeParamPattern(p))
})
t.Run("pattern with correct length", func(t *testing.T) {
p := openapiParam("^[a-zA-Z0-9-]{3,24}$", 24)
assert.Equal(t, "^[a-zA-Z0-9-]{3,24}$", normalizeParamPattern(p))
})
t.Run("pattern with shorter length", func(t *testing.T) {
p := openapiParam("^[a-zA-Z0-9-]{3,24}$", 23)
assert.Equal(t, "^[a-zA-Z0-9-]{3,24}$", normalizeParamPattern(p))
})
t.Run("pattern with longer length", func(t *testing.T) {
p := openapiParam("^[a-zA-Z0-9-]{3,24}$", 60)
assert.Equal(t, "^[a-zA-Z0-9-]{3,60}$", normalizeParamPattern(p))
})
}
func TestPropertyDescriptions(t *testing.T) {
t.Run("no description", func(t *testing.T) {
s := &spec.Schema{}
desc, err := getPropertyDescription(s, nil, false)
require.NoError(t, err)
assert.Equal(t, "", desc)
})
t.Run("simple description", func(t *testing.T) {
s := &spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "A simple description",
},
}
desc, err := getPropertyDescription(s, nil, false)
require.NoError(t, err)
assert.Equal(t, "A simple description", desc)
})
t.Run("line breaks in description are preserved", func(t *testing.T) {
s := &spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "A simple \ndescription",
},
}
desc, err := getPropertyDescription(s, nil, false)
require.NoError(t, err)
assert.Equal(t, "A simple \ndescription", desc)
})
t.Run("description with weird whitespace", func(t *testing.T) {
s := &spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "This \u2028 is not \u2029 allowed",
},
}
desc, err := getPropertyDescription(s, nil, false)
require.NoError(t, err)
assert.Equal(t, "This is not allowed", desc)
})
}
func TestResourceIsSingleton(t *testing.T) {
t.Run("singleton", func(t *testing.T) {
res := &resourceVariant{
ResourceSpec: &openapi.ResourceSpec{
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}",
PathItem: &spec.PathItem{},
},
}
assert.True(t, isSingleton(res))
})
t.Run("implicit singleton", func(t *testing.T) {
res := &resourceVariant{
ResourceSpec: &openapi.ResourceSpec{
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Foo/bar",
PathItem: &spec.PathItem{},
},
}
assert.True(t, isSingleton(res))
})
t.Run("not a singleton", func(t *testing.T) {
res := &resourceVariant{
ResourceSpec: &openapi.ResourceSpec{
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Foo/bar",
PathItem: &spec.PathItem{
PathItemProps: spec.PathItemProps{
Delete: &spec.Operation{},
},
}},
}
assert.False(t, isSingleton(res))
})
}
func TestGoModuleName(t *testing.T) {
t.Run("explicit version", func(t *testing.T) {
assert.Equal(t, "github.com/pulumi/pulumi-azure-native-sdk/network/v3/v20220222", goModuleName("Network", "v20220222"))
})
t.Run("default version", func(t *testing.T) {
assert.Equal(t, "github.com/pulumi/pulumi-azure-native-sdk/network/v3", goModuleName("Network", ""))
})
}
func TestResourcePathTracker(t *testing.T) {
t.Run("no conflicts, one module", func(t *testing.T) {
tracker := newResourcesPathConflictsTracker()
tracker.addPathConflictsForModule("compute", map[openapi.ResourceName]map[string][]openapi.ApiVersion{
"VirtualMachine": {"/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}": {openapi.ApiVersion("2022-02-22")}},
})
assert.False(t, tracker.hasConflicts())
})
t.Run("conflicts, one module", func(t *testing.T) {
tracker := newResourcesPathConflictsTracker()
tracker.addPathConflictsForModule("compute", map[openapi.ResourceName]map[string][]openapi.ApiVersion{
"VirtualMachine": {
"/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}": {openapi.ApiVersion("2022-02-22")},
"/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachinesFoo/{}": {openapi.ApiVersion("2024-04-22")},
},
})
assert.True(t, tracker.hasConflicts())
})
t.Run("no conflicts, multiple modules", func(t *testing.T) {
tracker := newResourcesPathConflictsTracker()
tracker.addPathConflictsForModule("compute", map[openapi.ResourceName]map[string][]openapi.ApiVersion{
"VirtualMachine": {"/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}": {openapi.ApiVersion("2022-02-22")}},
})
tracker.addPathConflictsForModule("storage", map[openapi.ResourceName]map[string][]openapi.ApiVersion{
"StorageAccount": {"/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}": {openapi.ApiVersion("2022-02-22")}},
})
assert.False(t, tracker.hasConflicts())
})
t.Run("conflicts, multiple modules", func(t *testing.T) {
tracker := newResourcesPathConflictsTracker()
tracker.addPathConflictsForModule("storage", map[openapi.ResourceName]map[string][]openapi.ApiVersion{
"StorageAccount": {"/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}": {openapi.ApiVersion("2022-02-22")}},
})
tracker.addPathConflictsForModule("compute", map[openapi.ResourceName]map[string][]openapi.ApiVersion{
"VirtualMachine": {
"/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}": {openapi.ApiVersion("2022-02-22")},
"/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachinesFoo/{}": {openapi.ApiVersion("2024-04-22")},
},
})
tracker.addPathConflictsForModule("migrate", map[openapi.ResourceName]map[string][]openapi.ApiVersion{
"AssessmentProject": {"/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Migrate/assessmentProjects/{}": {openapi.ApiVersion("2022-02-22")}},
})
assert.True(t, tracker.hasConflicts())
})
}
func TestIsApiVersionQueryParam(t *testing.T) {
createParam := func(name, in string) *openapi.Parameter {
return &openapi.Parameter{
Parameter: &spec.Parameter{
ParamProps: spec.ParamProps{
Name: name,
In: in,
},
},
}
}
t.Run("not api-version param", func(t *testing.T) {
m := &moduleGenerator{
moduleName: "SomeModule",
resourceName: "SomeResource",
}
param := createParam("some-other-param", "query")
assert.False(t, m.paramIsSetByProvider(param, nil))
})
t.Run("not query param", func(t *testing.T) {
m := &moduleGenerator{
moduleName: "SomeModule",
resourceName: "SomeResource",
}
param := createParam("some-other-param", "path")
assert.False(t, m.paramIsSetByProvider(param, nil))
})
t.Run("Resources.Resource special case", func(t *testing.T) {
m := &moduleGenerator{
moduleName: "Resources",
resourceName: "Resource",
}
param := createParam("api-version", "query")
assert.False(t, m.paramIsSetByProvider(param, nil))
})
t.Run("Authorization.ManagementLockAtResourceLevel special case", func(t *testing.T) {
m := &moduleGenerator{
moduleName: "Authorization",
resourceName: "ManagementLockAtResourceLevel",
}
param := createParam("api-version", "query")
assert.False(t, m.paramIsSetByProvider(param, nil))
})
t.Run("standard api-version query param", func(t *testing.T) {
m := &moduleGenerator{
moduleName: "SomeModule",
resourceName: "SomeResource",
}
param := createParam("api-version", "query")
assert.True(t, m.paramIsSetByProvider(param, nil))
})
}
func TestFormatDescriptionV2(t *testing.T) {
t.Parallel()
g := &packageGenerator{
majorVersion: 2,
versioning: versioningStub{},
}
t.Run("no description", func(t *testing.T) {
desc := g.formatDescription("", "SomeResource", "2022-02-22", "", nil)
assert.Equal(t, "Uses Azure REST API version 2022-02-22.", strings.TrimSpace(desc))
})
t.Run("description", func(t *testing.T) {
desc := g.formatDescription("This is a wonderful resource.", "SomeResource", "2022-02-22", "", nil)
assert.Equal(t, "This is a wonderful resource.\n\nUses Azure REST API version 2022-02-22.", strings.TrimSpace(desc))
})
t.Run("additional docs", func(t *testing.T) {
desc := g.formatDescription("", "SomeResource", "2022-02-22", "", pulumi.StringRef("Additional docs."))
assert.Equal(t, "Uses Azure REST API version 2022-02-22.\n\nAdditional docs.", strings.TrimSpace(desc))
})
t.Run("previous default version", func(t *testing.T) {
desc := g.formatDescription("", "SomeResource", "2022-02-22", "2021-01-01", nil)
assert.Equal(t, "Uses Azure REST API version 2022-02-22. In version 1.x of the Azure Native provider, it used API version 2021-01-01.", strings.TrimSpace(desc))
})
t.Run("other versions", func(t *testing.T) {
g := &packageGenerator{
majorVersion: 2,
versioning: versioningStub{
getAllVersions: func(moduleName openapi.ModuleName, resource string) []openapi.ApiVersion {
return []openapi.ApiVersion{"2023-03-03", "2024-04-04"}
},
},
}
desc := g.formatDescription("", "SomeResource", "2022-02-22", "", nil)
assert.Equal(t, "Uses Azure REST API version 2022-02-22.\n\nOther available API versions: 2023-03-03, 2024-04-04.", strings.TrimSpace(desc))
})
t.Run("everything", func(t *testing.T) {
g := &packageGenerator{
majorVersion: 2,
versioning: versioningStub{
getAllVersions: func(moduleName openapi.ModuleName, resource string) []openapi.ApiVersion {
return []openapi.ApiVersion{"2023-03-03", "2024-04-04"}
},
},
}
desc := g.formatDescription("This is a wonderful resource.", "SomeResource", "2022-02-22", "2021-01-01", pulumi.StringRef("Additional docs."))
assert.Equal(t, `This is a wonderful resource.
Uses Azure REST API version 2022-02-22. In version 1.x of the Azure Native provider, it used API version 2021-01-01.
Other available API versions: 2023-03-03, 2024-04-04.
Additional docs.`, strings.TrimSpace(desc))
})
}
func TestFormatDescriptionV3(t *testing.T) {
t.Parallel()
g := &packageGenerator{
majorVersion: 3,
versioning: versioningStub{},
}
t.Run("no description", func(t *testing.T) {
desc := g.formatDescription("", "SomeResource", "2022-02-22", "", nil)
assert.Equal(t, "Uses Azure REST API version 2022-02-22.", strings.TrimSpace(desc))
})
t.Run("description", func(t *testing.T) {
desc := g.formatDescription("This is a wonderful resource.", "SomeResource", "2022-02-22", "", nil)
assert.Equal(t, "This is a wonderful resource.\n\nUses Azure REST API version 2022-02-22.", strings.TrimSpace(desc))
})
t.Run("additional docs", func(t *testing.T) {
desc := g.formatDescription("", "SomeResource", "2022-02-22", "", pulumi.StringRef("Additional docs."))
assert.Equal(t, "Uses Azure REST API version 2022-02-22.\n\nAdditional docs.", strings.TrimSpace(desc))
})
t.Run("previous default version", func(t *testing.T) {
desc := g.formatDescription("", "SomeResource", "2022-02-22", "2021-01-01", nil)
assert.Equal(t, "Uses Azure REST API version 2022-02-22. In version 2.x of the Azure Native provider, it used API version 2021-01-01.", strings.TrimSpace(desc))
})
t.Run("other versions", func(t *testing.T) {
g := &packageGenerator{
majorVersion: 3,
moduleName: "storage",
versioning: versioningStub{
getAllVersions: func(moduleName openapi.ModuleName, resource string) []openapi.ApiVersion {
return []openapi.ApiVersion{"2023-03-03", "2024-04-04"}
},
},
}
desc := g.formatDescription("", "SomeResource", "2022-02-22", "", nil)
assert.Equal(t, `Uses Azure REST API version 2022-02-22.
Other available API versions: 2023-03-03, 2024-04-04. These can be accessed by generating a local SDK package using the CLI command `+"`"+`pulumi package add azure-native storage [ApiVersion]`+"`"+`. See the [version guide](../../../version-guide/#accessing-any-api-version-via-local-packages) for details.`,
strings.TrimSpace(desc))
})
t.Run("everything", func(t *testing.T) {
g := &packageGenerator{
majorVersion: 3,
moduleName: "Authorization",
versioning: versioningStub{
getAllVersions: func(moduleName openapi.ModuleName, resource string) []openapi.ApiVersion {
return []openapi.ApiVersion{"2021-01-01", "2023-03-03", "2024-04-04"}
},
},
}
desc := g.formatDescription("This is a wonderful resource.", "SomeResource", "2022-02-22", "2021-01-01", pulumi.StringRef("Additional docs."))
assert.Equal(t, `This is a wonderful resource.
Uses Azure REST API version 2022-02-22. In version 2.x of the Azure Native provider, it used API version 2021-01-01.
Other available API versions: 2021-01-01, 2023-03-03, 2024-04-04. These can be accessed by generating a local SDK package using the CLI command `+"`"+`pulumi package add azure-native authorization [ApiVersion]`+"`"+`. See the [version guide](../../../version-guide/#accessing-any-api-version-via-local-packages) for details.
Additional docs.`, strings.TrimSpace(desc))
})
}
func TestGoModuleVersionMatches(t *testing.T) {
t.Parallel()
version := version.GetVersion().Major
expected := fmt.Sprintf("/v%d", version)
assert.Equal(t, expected, goModuleVersion)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/requiredContainers.go | provider/pkg/gen/requiredContainers.go | package gen
// Some resources which require empty containers to be present in the request body
// aren't listed as required in the specification, so we add them here manually.
func additionalRequiredContainers(resourceTok string) RequiredContainers {
switch resourceTok {
case "azure-native:app:ManagedEnvironment":
return [][]string{{"properties"}}
}
return nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/gen/schema.go | provider/pkg/gen/schema.go | // Copyright 2016-2021, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gen
import (
"context"
"fmt"
"log"
"net/url"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"github.com/segmentio/encoding/json"
"github.com/blang/semver"
"github.com/go-openapi/spec"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/collections"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi/paths"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources/customresources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"github.com/pulumi/pulumi/pkg/v3/codegen"
pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
// Note - this needs to be kept in sync with the layout in the SDK package
const goBasePath = "github.com/pulumi/pulumi-azure-native-sdk/v3"
const goModuleRepoPath = "github.com/pulumi/pulumi-azure-native-sdk"
const goModuleVersion = "/v3"
// pulumiProviderName is the name of the provider as used in all tokens.
const pulumiProviderName = "azure-native"
type ResourceDeprecation struct {
ReplacementToken string
}
type Versioning interface {
ShouldInclude(moduleName openapi.ModuleName, version *openapi.ApiVersion, typeName, token string) bool
GetDeprecation(token string) (ResourceDeprecation, bool)
GetAllVersions(openapi.ModuleName, openapi.ResourceName) []openapi.ApiVersion
GetPreviousCompatibleTokensLookup() (*CompatibleTokensLookup, error)
}
type GenerationResult struct {
Schema *pschema.PackageSpec
Metadata *resources.AzureAPIMetadata
Examples map[string][]resources.AzureAPIExample
ForceNewTypes []ForceNewType
TypeCaseConflicts CaseConflicts
FlattenedPropertyConflicts map[string]map[string]any
// A map of module -> resource -> set of paths, to record resources that have conflicts where the same resource
// maps to more than one API path.
PathConflicts map[openapi.ModuleName]map[openapi.ResourceName]map[string][]openapi.ApiVersion
TokenPaths map[string]string
}
// PulumiSchema will generate a Pulumi schema for the given Azure modules and resources map.
func PulumiSchema(rootDir string, modules openapi.AzureModules, versioning Versioning, providerVersion semver.Version, onlyExplicitVersions bool) (*GenerationResult, error) {
pkg := pschema.PackageSpec{
Name: "azure-native",
Description: "A native Pulumi package for creating and managing Azure resources.",
DisplayName: "Azure Native",
License: "Apache-2.0",
Keywords: []string{"pulumi", "azure", "azure-native", "category/cloud", "kind/native"},
Homepage: "https://pulumi.com",
Publisher: "Pulumi",
Repository: "https://github.com/pulumi/pulumi-azure-native",
Config: pschema.ConfigSpec{
Variables: map[string]pschema.PropertySpec{
"subscriptionId": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Subscription ID which should be used.",
},
"clientId": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Client ID which should be used.",
Secret: true,
},
"clientSecret": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Client Secret which should be used. For use when authenticating as a Service Principal using a Client Secret.",
Secret: true,
},
"tenantId": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Tenant ID which should be used.",
},
"auxiliaryTenantIds": {
TypeSpec: pschema.TypeSpec{Type: "array", Items: &pschema.TypeSpec{Type: "string"}},
Description: "Any additional Tenant IDs which should be used for authentication.",
},
"environment": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Cloud Environment which should be used. Possible values are public, usgovernment, and china. Defaults to public. Not used when metadataHost is specified or when ARM_METADATA_HOSTNAME is set.",
},
"location": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The location to use. ResourceGroups will consult this property for a default location, if one was not supplied explicitly when defining the resource.",
},
"clientCertificatePath": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The path to the Client Certificate associated with the Service Principal for use when authenticating as a Service Principal using a Client Certificate.",
},
"clientCertificatePassword": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The password associated with the Client Certificate. For use when authenticating as a Service Principal using a Client Certificate",
Secret: true,
},
"useMsi": {
TypeSpec: pschema.TypeSpec{Type: "boolean"},
Description: "Allow Managed Service Identity be used for Authentication.",
},
"msiEndpoint": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The path to a custom endpoint for Managed Service Identity - in most circumstances this should be detected automatically.",
},
// Custom environments
"disableInstanceDiscovery": {
TypeSpec: pschema.TypeSpec{Type: "boolean"},
Description: "Determines whether or not instance discovery is performed when attempting to authenticate. Setting this to true will completely disable both instance discovery and authority validation. This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in private clouds or Azure Stack.",
},
"metadataHost": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Hostname of the Azure Metadata Service.",
},
"useOidc": {
TypeSpec: pschema.TypeSpec{Type: "boolean"},
Description: "Allow OpenID Connect (OIDC) to be used for Authentication.",
},
"oidcToken": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The OIDC token to exchange for an Azure token.",
},
"oidcTokenFilePath": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The path to a file containing an OIDC token to exchange for an Azure token.",
},
"oidcRequestToken": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "Your cloud service or provider's bearer token to exchange for an OIDC ID token.",
},
"oidcRequestUrl": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The URL to initiate the OIDC token exchange. ",
},
"useDefaultAzureCredential": {
TypeSpec: pschema.TypeSpec{Type: "boolean"},
Description: "Use the default credential chain of the Azure SDK (see https://learn.microsoft.com/en-us/azure/developer/go/sdk/authentication/credential-chains#defaultazurecredential-overview).",
},
// Managed Tracking GUID for User-Agent.
"partnerId": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "A GUID/UUID that is registered with Microsoft to facilitate partner resource usage attribution.",
},
"disablePulumiPartnerId": {
TypeSpec: pschema.TypeSpec{Type: "boolean"},
Description: "This will disable the Pulumi Partner ID which is used if a custom `partnerId` isn't specified.",
},
},
},
Provider: pschema.ResourceSpec{
ObjectTypeSpec: pschema.ObjectTypeSpec{
Description: "The provider type for the native Azure package.",
Type: "object",
},
InputProperties: map[string]pschema.PropertySpec{
"subscriptionId": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Subscription ID which should be used.",
},
"clientId": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Client ID which should be used.",
Secret: true,
},
"clientSecret": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Client Secret which should be used. For use When authenticating as a Service Principal using a Client Secret.",
Secret: true,
},
"tenantId": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Tenant ID which should be used.",
},
"auxiliaryTenantIds": {
TypeSpec: pschema.TypeSpec{Type: "array", Items: &pschema.TypeSpec{Type: "string"}},
Description: "Any additional Tenant IDs which should be used for authentication.",
},
"environment": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Default: "public",
Description: "The Cloud Environment which should be used. Possible values are public, usgovernment, and china. Defaults to public. Not used when metadataHost is specified or when ARM_METADATA_HOSTNAME is set.",
},
"location": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The location to use. ResourceGroups will consult this property for a default location, if one was not supplied explicitly when defining the resource.",
},
"clientCertificatePath": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The path to the Client Certificate associated with the Service Principal for use when authenticating as a Service Principal using a Client Certificate.",
},
"clientCertificatePassword": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The password associated with the Client Certificate. For use when authenticating as a Service Principal using a Client Certificate",
Secret: true,
},
"useMsi": {
TypeSpec: pschema.TypeSpec{Type: "boolean"},
Description: "Allow Managed Service Identity to be used for Authentication.",
},
"msiEndpoint": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The path to a custom endpoint for Managed Service Identity - in most circumstances this should be detected automatically.",
},
// Custom environments
"disableInstanceDiscovery": {
TypeSpec: pschema.TypeSpec{Type: "boolean"},
Description: "Determines whether or not instance discovery is performed when attempting to authenticate. Setting this to true will completely disable both instance discovery and authority validation. This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in private clouds or Azure Stack.",
},
"metadataHost": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The Hostname of the Azure Metadata Service.",
},
"useOidc": {
TypeSpec: pschema.TypeSpec{Type: "boolean"},
Description: "Allow OpenID Connect (OIDC) to be used for Authentication.",
},
"oidcToken": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The OIDC token to exchange for an Azure token.",
},
"oidcRequestToken": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "Your cloud service or provider’s bearer token to exchange for an OIDC ID token.",
},
"oidcRequestUrl": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "The URL to initiate the `oidcRequestToken` OIDC token exchange.",
},
"useDefaultAzureCredential": {
TypeSpec: pschema.TypeSpec{Type: "boolean"},
Description: "Use the default credential chain of the Azure SDK (see https://learn.microsoft.com/en-us/azure/developer/go/sdk/authentication/credential-chains#defaultazurecredential-overview).",
},
// Managed Tracking GUID for User-Agent.
"partnerId": {
TypeSpec: pschema.TypeSpec{Type: "string"},
Description: "A GUID/UUID that is registered with Microsoft to facilitate partner resource usage attribution.",
},
"disablePulumiPartnerId": {
TypeSpec: pschema.TypeSpec{Type: "boolean"},
Description: "This will disable the Pulumi Partner ID which is used if a custom `partnerId` isn't specified.",
},
},
},
Types: map[string]pschema.ComplexTypeSpec{},
Resources: map[string]pschema.ResourceSpec{},
Functions: map[string]pschema.FunctionSpec{},
Language: map[string]pschema.RawMessage{},
}
metadata := resources.AzureAPIMetadata{
Types: map[string]resources.AzureAPIType{},
Resources: map[string]resources.AzureAPIResource{},
Invokes: map[string]resources.AzureAPIInvoke{},
}
csharpVersionReplacer := strings.NewReplacer("privatepreview", "PrivatePreview", "preview", "Preview", "beta", "Beta")
csharpNamespaces := map[string]string{
"azure-native": "AzureNative",
}
javaPackages := map[string]string{
"azure-native": "azurenative",
}
pythonModuleNames := map[string]string{}
golangImportAliases := map[string]string{}
// Track some global data
var forceNewTypes []ForceNewType
caseSensitiveTypes := newCaseSensitiveTokens()
flattenedPropertyConflicts := map[string]map[string]any{}
exampleMap := make(map[string][]resources.AzureAPIExample)
resourcesPathTracker := newResourcesPathConflictsTracker()
previousCompatibleTokensLookup, err := versioning.GetPreviousCompatibleTokensLookup()
if err != nil {
return nil, err
}
if !previousCompatibleTokensLookup.IsPopulated() && providerVersion.Major >= 3 {
logging.V(3).Infof("GetPreviousCompatibleTokensLookup is not populated. This is likely due to v%d-token-paths.json being missing or empty", providerVersion.Major-1)
}
for moduleName, moduleVersions := range util.MapOrdered(modules) {
resourcePaths := map[openapi.ResourceName]map[string][]openapi.ApiVersion{}
allVersions := util.SortedKeys(moduleVersions)
// The version in the parsed module is "" for the default version.
for moduleVersion, versionResources := range util.MapOrdered(moduleVersions) {
var sdkVersion openapi.SdkVersion
var apiVersion *openapi.ApiVersion
if moduleVersion.IsDefault() {
apiVersion = nil
sdkVersion = ""
} else {
apiVersion = &moduleVersion
sdkVersion = openapi.ApiToSdkVersion(moduleVersion)
}
gen := packageGenerator{
pkg: &pkg,
metadata: &metadata,
moduleName: moduleName,
apiVersion: apiVersion,
sdkVersion: sdkVersion,
allVersions: allVersions,
examples: exampleMap,
versioning: versioning,
caseSensitiveTypes: caseSensitiveTypes,
rootDir: rootDir,
flattenedPropertyConflicts: flattenedPropertyConflicts,
majorVersion: int(providerVersion.Major),
resourcePaths: map[openapi.ResourceName]map[string]openapi.ApiVersion{},
previousCompatibleTokensLookup: previousCompatibleTokensLookup,
}
// Populate C#, Java, Python and Go module mapping.
module := gen.moduleWithVersion()
csharpNamespaces[moduleName.Lowered()] = string(moduleName)
javaPackages[string(module)] = moduleName.Lowered()
if sdkVersion != "" {
csVersion := strings.Title(csharpVersionReplacer.Replace(string(sdkVersion)))
csharpNamespaces[string(module)] = fmt.Sprintf("%s.%s", moduleName, csVersion)
javaPackages[string(module)] = fmt.Sprintf("%s.%s", moduleName.Lowered(), sdkVersion)
}
pythonModuleNames[string(module)] = string(module)
golangImportAliases[goModuleName(gen.moduleName, gen.sdkVersion)] = moduleName.Lowered()
// Populate resources and get invokes.
for typeName, resource := range util.MapOrdered(versionResources.Resources) {
nestedResourceBodyRefs := findNestedResourceBodyRefs(resource, versionResources.Resources)
err := gen.genResources(typeName, resource, nestedResourceBodyRefs)
if err != nil {
return nil, err
}
}
// Populate invokes.
gen.genInvokes(versionResources.Invokes)
forceNewTypes = append(forceNewTypes, gen.forceNewTypes...)
gen.mergeResourcePathsInto(resourcePaths)
}
resourcesPathTracker.addPathConflictsForModule(moduleName, resourcePaths)
}
// When a resource maps to more than one API path, it's a conflict and we need to detect and report it. #2495
if providerVersion.Major >= 3 && resourcesPathTracker.hasConflicts() {
return nil, fmt.Errorf("path conflicts detected. You probably need to add a case to resources.go/ResourceName.\n%+v", resourcesPathTracker.pathConflicts)
}
err = genMixins(&pkg, &metadata, !onlyExplicitVersions)
if err != nil {
return nil, err
}
pkg.Language["go"] = rawMessage(map[string]interface{}{
"importBasePath": goBasePath,
"packageImportAliases": golangImportAliases,
"importPathPattern": "github.com/pulumi/pulumi-azure-native-sdk/{module}" + goModuleVersion,
"rootPackageName": "pulumiazurenativesdk",
"generateResourceContainerTypes": false,
"disableInputTypeRegistrations": true,
"internalModuleName": "utilities",
"respectSchemaVersion": true,
})
pkg.Language["nodejs"] = rawMessage(map[string]interface{}{
"readme": `The native Azure provider package offers support for all Azure Resource Manager (ARM)
resources and their properties. Resources are exposed as types from modules based on Azure Resource
Providers such as 'compute', 'network', 'storage', and 'web', among many others. Using this package
allows you to programmatically declare instances of any Azure resource and any supported resource
version using infrastructure as code, which Pulumi then uses to drive the ARM API.`,
"respectSchemaVersion": true,
})
pkg.Language["python"] = rawMessage(map[string]interface{}{
"moduleNameOverrides": pythonModuleNames,
"usesIOClasses": true,
"inputTypes": "classes-and-dicts",
"readme": `The native Azure provider package offers support for all Azure Resource Manager (ARM)
resources and their properties. Resources are exposed as types from modules based on Azure Resource
Providers such as 'compute', 'network', 'storage', and 'web', among many others. Using this package
allows you to programmatically declare instances of any Azure resource and any supported resource
version using infrastructure as code, which Pulumi then uses to drive the ARM API.`,
"pyproject": map[string]bool{
"enabled": true,
},
"respectSchemaVersion": true,
})
pkg.Language["csharp"] = rawMessage(map[string]interface{}{
"packageReferences": map[string]string{
"Pulumi": "3.*",
"System.Collections.Immutable": "5.0.0",
},
"namespaces": csharpNamespaces,
"respectSchemaVersion": true,
})
pkg.Language["java"] = rawMessage(map[string]interface{}{
"packages": javaPackages,
})
tokenPaths := map[string]string{}
for token, resource := range metadata.Resources {
tokenPaths[token] = resource.Path
}
return &GenerationResult{
Schema: &pkg,
Metadata: &metadata,
Examples: exampleMap,
ForceNewTypes: forceNewTypes,
TypeCaseConflicts: caseSensitiveTypes.findCaseConflicts(),
FlattenedPropertyConflicts: flattenedPropertyConflicts,
PathConflicts: resourcesPathTracker.pathConflicts,
TokenPaths: tokenPaths,
}, nil
}
// resourcesPathConflictsTracker tracks resource path conflicts by module. Use newResourcesPathTracker to instantiate.
type resourcesPathConflictsTracker struct {
pathConflicts map[openapi.ModuleName]map[openapi.ResourceName]map[string][]openapi.ApiVersion
}
func newResourcesPathConflictsTracker() *resourcesPathConflictsTracker {
return &resourcesPathConflictsTracker{pathConflicts: map[openapi.ModuleName]map[openapi.ResourceName]map[string][]openapi.ApiVersion{}}
}
func (rpt *resourcesPathConflictsTracker) addPathConflictsForModule(moduleName openapi.ModuleName, resourcePaths map[openapi.ResourceName]map[string][]openapi.ApiVersion) {
modulePathConflicts := map[openapi.ResourceName]map[string][]openapi.ApiVersion{}
for resource, paths := range resourcePaths {
if len(paths) > 1 {
modulePathConflicts[resource] = paths
}
}
if len(modulePathConflicts) > 0 {
rpt.pathConflicts[moduleName] = modulePathConflicts
}
}
func (rpt *resourcesPathConflictsTracker) hasConflicts() bool {
return len(rpt.pathConflicts) > 0
}
func (g *packageGenerator) genInvokes(invokes map[string]*openapi.ResourceSpec) {
var invokeNames []string
for invokeName := range invokes {
invokeNames = append(invokeNames, invokeName)
}
sort.Strings(invokeNames)
for _, invokeName := range invokeNames {
invoke := invokes[invokeName]
op := invoke.PathItem.Post
if op == nil {
op = invoke.PathItem.Get
}
if op == nil {
panic(fmt.Sprintf("Invoke %s has no POST or GET operation", invokeName))
}
g.genFunctions(invokeName, invoke.Path, invoke.PathItem.Parameters, op, invoke.Swagger)
}
}
func findNestedResourceBodyRefs(resource *openapi.ResourceSpec, resourceSpecs map[string]*openapi.ResourceSpec) []string {
nestedResources := findNestedResources(resource, resourceSpecs)
return findResourcesBodyRefs(nestedResources)
}
func findResourcesBodyRefs(nestedResources []*openapi.ResourceSpec) []string {
var nestedResourcePostBodyTypeRefs []string
for _, nestedResource := range nestedResources {
nestedResourcePostBodyTypeRef, ok := findResourcePutBodyTypeRef(nestedResource)
if ok {
nestedResourcePostBodyTypeRefs = append(nestedResourcePostBodyTypeRefs, nestedResourcePostBodyTypeRef)
}
}
return nestedResourcePostBodyTypeRefs
}
func findResourcePutBodyTypeRef(resource *openapi.ResourceSpec) (string, bool) {
if resource.PathItem != nil && resource.PathItem.Put != nil {
for _, parameter := range resource.PathItem.Put.Parameters {
if parameter.In != "body" || parameter.Schema == nil {
continue
}
return parameter.Schema.Ref.String(), true
}
}
return "", false
}
func findNestedResources(resource *openapi.ResourceSpec, resourceSpecs map[string]*openapi.ResourceSpec) []*openapi.ResourceSpec {
var nestedResourceSpecs []*openapi.ResourceSpec
for _, otherResource := range util.MapOrdered(resourceSpecs) {
// Ignore self
if otherResource.Path == resource.Path {
continue
}
if strings.HasPrefix(otherResource.Path, resource.Path) {
nestedResourceSpecs = append(nestedResourceSpecs, otherResource)
}
}
return nestedResourceSpecs
}
func genMixins(pkg *pschema.PackageSpec, metadata *resources.AzureAPIMetadata, includeCustomResources bool) error {
// Mixin 'getClientConfig' to read current configuration values.
if _, has := pkg.Functions["azure-native:authorization:getClientConfig"]; has {
return errors.New("Invoke 'azure-native:authorization:getClientConfig' is already defined")
}
pkg.Functions["azure-native:authorization:getClientConfig"] = pschema.FunctionSpec{
Description: "Use this function to access the current configuration of the native Azure provider.",
Outputs: &pschema.ObjectTypeSpec{
Description: "Configuration values returned by getClientConfig.",
Properties: map[string]pschema.PropertySpec{
"clientId": {
Description: "Azure Client ID (Application Object ID).",
TypeSpec: pschema.TypeSpec{Type: "string"},
},
"objectId": {
Description: "Azure Object ID of the current user or service principal.",
TypeSpec: pschema.TypeSpec{Type: "string"},
},
"subscriptionId": {
Description: "Azure Subscription ID",
TypeSpec: pschema.TypeSpec{Type: "string"},
},
"tenantId": {
Description: "Azure Tenant ID",
TypeSpec: pschema.TypeSpec{Type: "string"},
},
},
Type: "object",
Required: []string{"clientId", "objectId", "subscriptionId", "tenantId"},
},
}
// Mixin 'getClientToken' to obtain an Azure auth token.
if _, has := pkg.Functions["azure-native:authorization:getClientToken"]; has {
return errors.New("Invoke 'azure-native:authorization:getClientToken' is already defined")
}
pkg.Functions["azure-native:authorization:getClientToken"] = pschema.FunctionSpec{
Description: "Use this function to get an Azure authentication token for the current login context.",
Inputs: &pschema.ObjectTypeSpec{
Properties: map[string]pschema.PropertySpec{
"endpoint": {
Description: "Optional authentication endpoint. Defaults to the endpoint of Azure Resource Manager.",
TypeSpec: pschema.TypeSpec{Type: "string"},
},
},
Type: "object",
},
Outputs: &pschema.ObjectTypeSpec{
Description: "Configuration values returned by getClientToken.",
Properties: map[string]pschema.PropertySpec{
"token": {
Description: "OAuth token for Azure Management API and SDK authentication.",
TypeSpec: pschema.TypeSpec{Type: "string"},
},
},
Type: "object",
Required: []string{"token"},
},
}
if includeCustomResources {
// Mixin all the custom resources that define schema and/or metadata.
for tok, r := range customresources.SchemaMixins() {
if _, has := pkg.Resources[tok]; has {
return errors.Errorf("Resource %q is already defined", tok)
}
pkg.Resources[tok] = r
}
for tok, t := range customresources.SchemaTypeMixins() {
if _, has := pkg.Types[tok]; has {
return errors.Errorf("Type %q is already defined", tok)
}
pkg.Types[tok] = t
}
for tok, t := range customresources.SchemaTypeOverrides() {
pkg.Types[tok] = t
}
for tok, r := range customresources.MetaMixins() {
if _, has := metadata.Resources[tok]; has {
return errors.Errorf("Metadata %q is already defined", tok)
}
metadata.Resources[tok] = r
}
for tok, r := range customresources.MetaTypeMixins() {
if _, has := metadata.Types[tok]; has {
return errors.Errorf("Metadata type %q is already defined", tok)
}
metadata.Types[tok] = r
}
for tok, r := range customresources.MetaTypeOverrides() {
metadata.Types[tok] = r
}
// Apply custom resource modifications to the schema and metadata.
err := customresources.ApplySchemas(pkg, metadata)
if err != nil {
return err
}
}
// Add a note regarding WorkspaceSqlAadAdmin creation.
workspaceSqlAadAdmin := pkg.Resources["azure-native:synapse:WorkspaceSqlAadAdmin"]
workspaceSqlAadAdmin.Description += "\n\nNote: SQL AAD Admin is configured automatically during workspace creation and assigned to the current user. One can't add more admins with this resource unless you manually delete the current SQL AAD Admin."
pkg.Resources["azure-native:synapse:WorkspaceSqlAadAdmin"] = workspaceSqlAadAdmin
// Remove unused types.
normalizePackage(pkg, metadata)
return nil
}
func normalizePackage(pkg *pschema.PackageSpec, metadata *resources.AzureAPIMetadata) {
// Record all type tokens referenced from resources and functions.
usedTypes := map[string]bool{}
visitor := func(t string, _ pschema.ComplexTypeSpec) {
usedTypes[t] = true
}
resources.VisitPackageSpecTypes(pkg, visitor)
// Elide unused types.
for typeName, t := range util.MapOrdered(pkg.Types) {
if !usedTypes[typeName] {
if len(t.Enum) > 0 {
continue
}
delete(pkg.Types, typeName)
delete(metadata.Types, typeName)
}
}
}
// Microsoft-specific API extension constants.
const (
extensionClientFlatten = "x-ms-client-flatten"
extensionClientName = "x-ms-client-name"
extensionDiscriminatorValue = "x-ms-discriminator-value"
extensionEnum = "x-ms-enum"
extensionIdentifiers = "x-ms-identifiers" // ids in keyed arrays
extensionLongRunning = "x-ms-long-running-operation"
extensionLongRunningDefault = "azure-async-operation"
extensionLongRunningOpts = "x-ms-long-running-operation-options"
extensionLongRunningVia = "final-state-via"
extensionMutability = "x-ms-mutability"
extensionMutabilityCreate = "create"
extensionMutabilityRead = "read"
extensionMutabilityUpdate = "update"
extensionParameterLocation = "x-ms-parameter-location"
extensionSkipUrlEncoding = "x-ms-skip-url-encoding"
)
type packageGenerator struct {
pkg *pschema.PackageSpec
metadata *resources.AzureAPIMetadata
moduleName openapi.ModuleName
examples map[string][]resources.AzureAPIExample
apiVersion *openapi.ApiVersion
sdkVersion openapi.SdkVersion
allVersions []openapi.ApiVersion
versioning Versioning
caseSensitiveTypes caseSensitiveTokens
// rootDir is used to resolve relative paths in the examples.
rootDir string
forceNewTypes []ForceNewType
// Token -> set<property>
flattenedPropertyConflicts map[string]map[string]any
majorVersion int
// A resource -> path -> API version map to record API paths per resource and later detect conflicts.
// Each packageGenerator instance is only used for a single API version, so there won't be conflicting paths here.
resourcePaths map[openapi.ResourceName]map[string]openapi.ApiVersion
previousCompatibleTokensLookup *CompatibleTokensLookup
}
func (g *packageGenerator) genResources(typeName string, resource *openapi.ResourceSpec, nestedResourceBodyRefs []string) error {
// Resource names should consistently start with upper case.
typeNameAliases := g.genAliases(typeName)
titleCasedTypeName := strings.Title(typeName)
// A single API path can be modelled as several resources if it accepts a polymorphic payload:
// i.e., when the request body is a discriminated union type of several object types. Pulumi
// schema doesn't support polymorphic (OneOf) resources, so the provider creates a separate resource
// per each union case. We call them "variants" in the code below.
variants, err := g.findResourceVariants(resource)
if err != nil {
return errors.Wrapf(err, "resource %s.%s", g.moduleName, titleCasedTypeName)
}
for _, v := range variants {
err = g.genResourceVariant(resource, v, nestedResourceBodyRefs, typeNameAliases...)
if err != nil {
return err
}
}
// If variants are found, we don't need the main or base resource.
if len(variants) > 0 {
return nil
}
mainResource := &resourceVariant{
ResourceSpec: resource,
typeName: titleCasedTypeName,
}
if resource.DeprecationMessage != "" {
mainResource.deprecationMessage = resource.DeprecationMessage
}
return g.genResourceVariant(resource, mainResource, nestedResourceBodyRefs, typeNameAliases...)
}
func (g *packageGenerator) genAliases(typeName string) []string {
switch g.majorVersion {
case 2:
// We need to alias the previous, lowercase name so users can upgrade to v2 without replacement.
// These aliases aren't required anymore with v3.
if strings.Title(typeName) != typeName {
return []string{typeName}
}
case 3:
// TODO: Add additional aliases for v3 case changes: https://github.com/pulumi/pulumi-azure-native/issues/3848
}
return nil
}
// resourceVariant points to request body's and response's schemas of a resource which is one of the variants
// of a resource related to an API path.
type resourceVariant struct {
*openapi.ResourceSpec
typeName string
body *openapi.Schema
response *openapi.Schema
deprecationMessage string
}
// findResourceVariants searches for discriminated unions in the resource's API specs and returns
// a list of those variants. An empty list is returned for non-discriminated types.
func (g *packageGenerator) findResourceVariants(resource *openapi.ResourceSpec) ([]*resourceVariant, error) {
updateOp := resource.PathItem.Put
if resource.PathItem.Put == nil {
updateOp = resource.PathItem.Patch
}
// Check if the body schema has a discriminator, return otherwise.
bodySchema, err := getRequestBodySchema(resource.Swagger.ReferenceContext, updateOp.Parameters)
if bodySchema == nil || err != nil {
return nil, err
}
if bodySchema.Discriminator == "" {
return nil, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | true |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/squeeze/squeeze.go | provider/pkg/squeeze/squeeze.go | package squeeze
import (
"fmt"
"sort"
"strings"
"time"
mapset "github.com/deckarep/golang-set/v2"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
)
// CompareAll returns a map of resource tokens to be removed with an optional token to a resource it should be replaced with.
func CompareAll(sch *schema.PackageSpec) (map[string]string, error) {
resourceMap := map[string]mapset.Set[string]{}
for name := range sch.Resources {
if !isVersionedName(name) {
continue
}
vls := versionlessName(name)
if existing, ok := resourceMap[vls]; ok {
existing.Add(name)
} else {
resourceMap[vls] = mapset.NewSet(name)
}
}
replacements := map[string]string{}
for _, group := range util.MapOrdered(resourceMap) {
unique := calculateUniqueVersions(sch, group)
reduced := group.Difference(unique)
for k := range reduced.Iter() {
for _, a := range mapset.Sorted(unique) {
if a > k {
replacements[k] = a
break
}
}
}
}
return replacements, nil
}
func compareResources(sch *schema.PackageSpec, oldName string, newName string) ([]string, error) {
var violations []string
oldRes, ok := sch.Resources[oldName]
if !ok {
return nil, fmt.Errorf("resource %q missing", oldName)
}
newRes, ok := sch.Resources[newName]
if !ok {
return nil, fmt.Errorf("resource %q missing", newName)
}
for propName, prop := range oldRes.InputProperties {
newProp, ok := newRes.InputProperties[propName]
if !ok {
violations = append(violations, fmt.Sprintf("Resource %q missing input %q", newName, propName))
continue
}
vs := validateTypesDeep(sch, &prop.TypeSpec, &newProp.TypeSpec, fmt.Sprintf("Resource %q input %q", newName, propName), true)
violations = append(violations, vs...)
}
for propName, prop := range oldRes.Properties {
newProp, ok := newRes.Properties[propName]
if !ok {
violations = append(violations, fmt.Sprintf("Resource %q missing output %q", newName, propName))
continue
}
vs := validateTypesDeep(sch, &prop.TypeSpec, &newProp.TypeSpec, fmt.Sprintf("Resource %q output %q", newName, propName), false)
violations = append(violations, vs...)
}
oldRequiredSet := mapset.NewSet(oldRes.RequiredInputs...)
for _, propName := range newRes.RequiredInputs {
if !oldRequiredSet.Contains(propName) {
violations = append(violations, fmt.Sprintf("Resource %q has a new required input %q", newName, propName))
}
}
newRequiredSet := mapset.NewSet(newRes.Required...)
for _, propName := range oldRes.Required {
if !newRequiredSet.Contains(propName) {
violations = append(violations, fmt.Sprintf("Resource %q has output %q that is not required anymore", newName, propName))
}
}
return violations, nil
}
func calculateUniqueVersions(sch *schema.PackageSpec, resVersions mapset.Set[string]) mapset.Set[string] {
uniqueVersions := mapset.NewSet[string]()
sortedVersions := mapset.Sorted(resVersions)
sortApiVersions(sortedVersions)
outer:
for _, oldName := range sortedVersions {
for _, newName := range sortedVersions {
if oldName >= newName {
continue
}
violations, err := compareResources(sch, oldName, newName)
if err == nil && len(violations) == 0 {
continue outer
}
}
uniqueVersions.Add(oldName)
}
return uniqueVersions
}
func apiVersionToDate(apiVersion string) (time.Time, error) {
if len(apiVersion) < 9 {
return time.Time{}, fmt.Errorf("invalid API version %q", apiVersion)
}
// The API version is in the format YYYY-MM-DD - ignore suffixes like "-preview".
return time.Parse("20060102", apiVersion[1:9])
}
func compareApiVersions(a, b string) int {
timeA, err := apiVersionToDate(a)
if err != nil {
return strings.Compare(a, b)
}
timeB, err := apiVersionToDate(b)
if err != nil {
return strings.Compare(a, b)
}
timeDiff := timeA.Compare(timeB)
if timeDiff != 0 {
return timeDiff
}
// Sort private first, preview second, stable last.
aPrivate := isPrivate(a)
bPrivate := isPrivate(b)
if aPrivate != bPrivate {
if aPrivate {
return -1
}
return 1
}
aPreview := isPreview(a)
bPreview := isPreview(b)
if aPreview != bPreview {
if aPreview {
return -1
}
return 1
}
return 0
}
func isPreview(apiVersion string) bool {
lower := strings.ToLower(apiVersion)
return strings.Contains(lower, "preview") || strings.Contains(lower, "beta")
}
func isPrivate(apiVersion string) bool {
lower := strings.ToLower(apiVersion)
return strings.Contains(lower, "private")
}
func sortApiVersions(versions []string) {
sort.SliceStable(versions, func(i, j int) bool {
return compareApiVersions(versions[i], versions[j]) < 0
})
}
func validateTypesDeep(sch *schema.PackageSpec, old *schema.TypeSpec, new *schema.TypeSpec, prefix string, input bool) (violations []string) {
switch {
case old == nil && new == nil:
return
case old != nil && new == nil:
violations = append(violations, fmt.Sprintf("had %+v but now has no type", old))
return
case old == nil && new != nil:
violations = append(violations, fmt.Sprintf("had no type but now has %+v", new))
return
}
oldType := old.Type
if old.Ref != "" {
oldType = old.Ref
}
newType := new.Type
if new.Ref != "" {
newType = new.Ref
}
if oldType != newType {
if strings.HasPrefix(oldType, "#/types/azure-native") && //azure-native:resources/v20210101:MyType
strings.HasPrefix(newType, "#/types/azure-native") &&
versionlessName(oldType) == versionlessName(newType) { // resources:MyType
// Both are reference types, let's do a deep comparison
oldTypeRef := sch.Types[oldType]
newTypeRef := sch.Types[newType]
for propName, prop := range oldTypeRef.Properties {
newProp, ok := newTypeRef.Properties[propName]
if !ok {
violations = append(violations, fmt.Sprintf("Type %q missing input %q", newType, propName))
continue
}
vs := validateTypesDeep(sch, &prop.TypeSpec, &newProp.TypeSpec, fmt.Sprintf("Type %q input %q", newType, propName), input)
violations = append(violations, vs...)
}
if input {
oldRequiredSet := mapset.NewSet(oldTypeRef.Required...)
for _, propName := range newTypeRef.Required {
if !oldRequiredSet.Contains(propName) {
violations = append(violations, fmt.Sprintf("Type %q has a new required input %q", newType, propName))
}
}
} else {
newRequiredSet := mapset.NewSet(newTypeRef.Required...)
for _, propName := range oldTypeRef.Required {
if !newRequiredSet.Contains(propName) {
violations = append(violations, fmt.Sprintf("Type %q has output %q that is not required anymore", newType, propName))
}
}
}
} else {
violations = append(violations, fmt.Sprintf("%s type changed from %q to %q", prefix, oldType, newType))
}
}
violations = append(violations, validateTypesDeep(sch, old.Items, new.Items, prefix+" items", input)...)
violations = append(violations, validateTypesDeep(sch, old.AdditionalProperties, new.AdditionalProperties, prefix+" additional properties", input)...)
return
}
// Is it of the form "azure-native:appplatform/v20230101preview" or just "azure-native:appplatform"?
func isVersionedName(name string) bool {
return strings.Contains(name, "/v")
}
// "azure-native:appplatform/v20230101preview" -> "appplatform"
func versionlessName(name string) string {
parts := strings.Split(name, ":")
mod := parts[1]
modParts := strings.Split(mod, "/")
if len(modParts) == 2 {
mod = modParts[0]
}
return fmt.Sprintf("%s:%s", mod, parts[2])
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/squeeze/squeeze_test.go | provider/pkg/squeeze/squeeze_test.go | package squeeze
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestApiVersionToDate(t *testing.T) {
t.Run("simple", func(t *testing.T) {
apiVersion := "v20200101"
date, err := apiVersionToDate(apiVersion)
assert.NoError(t, err)
expected := "2020-01-01"
actual := date.Format("2006-01-02")
assert.Equal(t, expected, actual)
})
t.Run("preview", func(t *testing.T) {
apiVersion := "v20200101preview"
date, err := apiVersionToDate(apiVersion)
assert.NoError(t, err)
expected := "2020-01-01"
actual := date.Format("2006-01-02")
assert.Equal(t, expected, actual)
})
}
func TestSortApiVersions(t *testing.T) {
t.Run("already ordered", func(t *testing.T) {
versions := []string{"v20200101", "v20210202"}
sortApiVersions(versions)
expected := []string{"v20200101", "v20210202"}
assert.Equal(t, expected, versions)
})
t.Run("reversed", func(t *testing.T) {
versions := []string{"v20210202", "v20200101"}
sortApiVersions(versions)
expected := []string{"v20200101", "v20210202"}
assert.Equal(t, expected, versions)
})
t.Run("preview comes before stable", func(t *testing.T) {
versions := []string{"v20200101", "v20200101preview"}
sortApiVersions(versions)
expected := []string{"v20200101preview", "v20200101"}
assert.Equal(t, expected, versions)
})
t.Run("private comes before preview", func(t *testing.T) {
versions := []string{"v20200101preview", "v20200101privatepreview"}
sortApiVersions(versions)
expected := []string{"v20200101privatepreview", "v20200101preview"}
assert.Equal(t, expected, versions)
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/providerlist/providerlist.go | provider/pkg/providerlist/providerlist.go | package providerlist
import (
"encoding/json"
"io"
"os"
"strings"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi/pkg/v3/codegen"
)
// LoweredProviderName e.g. analysisservices
type LoweredProviderName = string
// ResourcePath is a lowered resource path e.g. locations or locations/checknameavailability
type ResourcePath = string
// ApiVersions StringSet of versions e.g. 2019-03-01-preview or 2018-05-05
type ApiVersions = codegen.StringSet
// ApiVersion e.g. 2020-01-02
type ApiVersion = string
// ProviderPathVersions is a map of lowered provider names to Api Versions e.g. `analysisservices -> "locations/checknameavailability" -> [2019-03-01-preview, 2018-05-05]`
type ProviderPathVersions = map[LoweredProviderName]map[ResourcePath]ApiVersions
// ResourceType represents a single resource type within a provider namespace of the `az provider list` output.
// This is used to indicate which versions of the API are available for a given resource type.
type ResourceType struct {
ResourceType string `json:"resourceType"`
DefaultApiVersion *string `json:"defaultApiVersion"`
ApiVersions []ApiVersion `json:"apiVersions"`
Locations []string `json:"locations"`
}
// Provider represents an Azure provider namespace of the `az provider list` output
type Provider struct {
Namespace string `json:"namespace"`
ResourceTypes []ResourceType `json:"resourceTypes"`
}
// ProviderList represents the top level element of the `az provider list` output
type ProviderList struct {
Providers []Provider `json:"providers"`
}
// ReadProviderList reads provider_list.json, normalises casing and indexes for fast lookup
func ReadProviderList(providerListPath string) (*ProviderList, error) {
jsonFile, err := os.Open(providerListPath)
if err != nil {
return nil, err
}
defer jsonFile.Close()
byteValue, err := io.ReadAll(jsonFile)
if err != nil {
return nil, err
}
var providers []Provider
err = json.Unmarshal(byteValue, &providers)
if err != nil {
return nil, err
}
return &ProviderList{Providers: providers}, nil
}
type ActiveVersionChecker interface {
HasProviderVersion(namespace string, version openapi.ApiVersion) bool
}
type providerListIndex struct {
providerResourceVersionLookup ProviderPathVersions
providerVersions map[LoweredProviderName]ApiVersions
}
func (index *providerListIndex) HasProviderVersion(namespace string, version openapi.ApiVersion) bool {
namespace = strings.ToLower(namespace)
versions, ok := index.providerVersions[namespace]
if !ok {
return false
}
return versions.Has(string(version))
}
// Ensure providerListIndex implements ProviderListActiveVersionChecker
var _ ActiveVersionChecker = &providerListIndex{}
func (providers ProviderList) Index() *providerListIndex {
providerLiveVersions := make(ProviderPathVersions)
providerVersions := make(map[LoweredProviderName]ApiVersions)
for _, provider := range providers.Providers {
namespace := strings.ToLower(provider.Namespace)
if !strings.HasPrefix(namespace, "microsoft.") {
continue
}
pathVersions := map[ResourcePath]ApiVersions{}
allVersions := codegen.NewStringSet()
for _, resourceType := range provider.ResourceTypes {
versions := codegen.NewStringSet()
for _, version := range resourceType.ApiVersions {
allVersions.Add(version)
versions.Add(version)
}
rtName := strings.ToLower(resourceType.ResourceType)
pathVersions[rtName] = versions
}
pathVersions[""] = allVersions
providerVersions[namespace] = allVersions
providerLiveVersions[namespace] = pathVersions
}
return &providerListIndex{
providerResourceVersionLookup: providerLiveVersions,
providerVersions: providerVersions,
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/collections/orderableSet.go | provider/pkg/collections/orderableSet.go | package collections
import (
"cmp"
"slices"
)
type OrderableSet[T cmp.Ordered] struct {
m map[T]struct{}
}
func NewOrderableSet[T cmp.Ordered](values ...T) *OrderableSet[T] {
newSet := &OrderableSet[T]{m: make(map[T]struct{})}
for _, value := range values {
newSet.Add(value)
}
return newSet
}
func (s *OrderableSet[T]) Add(value T) {
s.m[value] = struct{}{}
}
func (s *OrderableSet[T]) Has(value T) bool {
_, ok := s.m[value]
return ok
}
func (s *OrderableSet[T]) Remove(value T) {
delete(s.m, value)
}
func (s *OrderableSet[T]) Count() int {
return len(s.m)
}
func (s *OrderableSet[T]) SortedValues() []T {
values := make([]T, 0, len(s.m))
for value := range s.m {
values = append(values, value)
}
slices.Sort(values)
return values
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/azure_cli.go | provider/pkg/provider/azure_cli.go | // Copyright 2016-2025, Pulumi Corporation.
package provider
import (
"bytes"
"context"
"encoding/json"
"os"
"os/exec"
"strings"
"time"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
// Subscription represents a Subscription from the Azure CLI
type Subscription struct {
EnvironmentName string `json:"environmentName"`
ID string `json:"id"`
IsDefault bool `json:"isDefault"`
Name string `json:"name"`
State string `json:"state"`
TenantID string `json:"tenantId"`
User *User `json:"user"`
}
// User represents a User from the Azure CLI
type User struct {
Name string `json:"name"`
Type string `json:"type"`
}
type subscriptionUnavailableError struct {
message string
}
func (e *subscriptionUnavailableError) Error() string {
return e.message
}
func newSubscriptionUnavailableError(message string) error {
return &subscriptionUnavailableError{message}
}
type azSubscriptionProvider func(ctx context.Context, subscriptionID string) (*Subscription, error)
// defaultAzSubscriptionProvider invokes the Azure CLI to acquire a subscription. It assumes
// callers have verified that all string arguments are safe to pass to the CLI.
// this code is derived from "CLI token provider" code in the Azure SDK for Go:
// https://github.com/Azure/azure-sdk-for-go/blob/519e8ab1a0e433b755c31ebaa6b177dfc83cb838/sdk/azidentity/azure_cli_credential.go#L117-L172
var defaultAzSubscriptionProvider = func(ctx context.Context, subscriptionID string) (*Subscription, error) {
// Build command arguments as array to avoid shell quoting issues
args := []string{"account", "show", "-o", "json"}
if subscriptionID != "" {
args = append(args, "--subscription", subscriptionID)
}
logging.V(9).Infof("Running command: az %s", strings.Join(args, " "))
cliCmd := exec.CommandContext(ctx, "az", args...)
cliCmd.Env = os.Environ()
var stdout, stderr bytes.Buffer
cliCmd.Stderr = &stderr
cliCmd.Stdout = &stdout
cliCmd.WaitDelay = 100 * time.Millisecond
output, err := func() ([]byte, error) {
err := cliCmd.Run()
stdout := stdout.Bytes()
if errors.Is(err, exec.ErrWaitDelay) && len(stdout) > 0 {
// The child process wrote to stdout and exited without closing it.
// Swallow this error and return stdout because it may contain output.
return stdout, nil
}
return stdout, err
}()
if err != nil {
msg := stderr.String()
logging.Errorf("az command error %v: %s", err, msg)
var exErr *exec.ExitError
if errors.As(err, &exErr) && exErr.ExitCode() == 127 || strings.HasPrefix(msg, "'az' is not recognized") {
msg = "Azure CLI not found on path"
}
if msg == "" {
msg = err.Error()
}
return nil, newSubscriptionUnavailableError(msg)
}
logging.V(9).Infof("Command output: %s", output)
s := Subscription{}
err = json.Unmarshal(output, &s)
if err != nil {
return nil, newSubscriptionUnavailableError(err.Error())
}
return &s, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/auth_azidentity_test.go | provider/pkg/provider/auth_azidentity_test.go | // Copyright 2016-2024, Pulumi Corporation.
package provider
import (
"context"
_ "embed"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
azcloud "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
//go:embed test.pfx
var testPfxCert []byte
type testProvider struct {
config map[string]string
}
func (k *testProvider) getConfig(configName, envName string) string {
if val, ok := k.config[configName]; ok {
return val
}
return os.Getenv(envName)
}
func TestGetAuthConfig(t *testing.T) {
getMetadata := func(ctx context.Context, endpoint string) (cloud.Configuration, error) {
return cloud.Configuration{}, nil
}
setAuthEnvVariables := func(value, boolValue string) {
if value != "" {
t.Setenv("ARM_AUXILIARY_TENANT_IDS", `["`+value+`"]`)
}
t.Setenv("ARM_CLIENT_CERTIFICATE_PASSWORD", value)
t.Setenv("ARM_CLIENT_CERTIFICATE_PATH", value)
t.Setenv("ARM_CLIENT_ID", value)
t.Setenv("ARM_CLIENT_SECRET", value)
t.Setenv("ARM_OIDC_AUDIENCE", value)
t.Setenv("ARM_OIDC_TOKEN", value)
t.Setenv("ARM_OIDC_TOKEN_FILE_PATH", value)
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", value)
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", value)
t.Setenv("ARM_TENANT_ID", value)
t.Setenv("ARM_USE_MSI", boolValue)
t.Setenv("ARM_USE_OIDC", boolValue)
}
t.Run("empty", func(t *testing.T) {
setAuthEnvVariables("", "")
p := &testProvider{}
c, err := readAuthConfig(context.Background(), p.getConfig, getMetadata)
require.NoError(t, err)
require.NotNil(t, c)
require.Empty(t, c.auxTenants)
require.Empty(t, c.clientCertPassword)
require.Empty(t, c.clientCertPath)
require.Empty(t, c.clientId)
require.Empty(t, c.clientSecret)
require.Empty(t, c.oidcAudience)
require.Empty(t, c.oidcToken)
require.Empty(t, c.oidcTokenFilePath)
require.Empty(t, c.oidcTokenRequestToken)
require.Empty(t, c.oidcTokenRequestUrl)
require.Empty(t, c.tenantId)
require.False(t, c.useOidc)
require.False(t, c.useMsi)
require.Nil(t, c.cloud)
})
t.Run("values from config take precedence", func(t *testing.T) {
setAuthEnvVariables("env", "false")
t.Setenv("ARM_ENVIRONMENT", "public")
p := &testProvider{
config: map[string]string{
"auxiliaryTenantIds": `["conf"]`,
"clientCertificatePassword": "conf",
"clientCertificatePath": "conf",
"clientId": "conf",
"clientSecret": "conf",
"environment": "usgov",
"oidcAudience": "conf",
"oidcToken": "conf",
"oidcTokenFilePath": "conf",
"oidcRequestToken": "conf",
"oidcRequestUrl": "conf",
"tenantId": "conf",
"useMsi": "true",
"useOidc": "true",
},
}
c, err := readAuthConfig(context.Background(), p.getConfig, getMetadata)
require.NoError(t, err)
require.NotNil(t, c)
require.Equal(t, []string{"conf"}, c.auxTenants)
require.Equal(t, "conf", c.clientCertPassword)
require.Equal(t, "conf", c.clientCertPath)
require.Equal(t, "conf", c.clientId)
require.Equal(t, "conf", c.clientSecret)
require.Equal(t, "conf", c.oidcAudience)
require.Equal(t, "conf", c.oidcToken)
require.Equal(t, "conf", c.oidcTokenFilePath)
require.Equal(t, "conf", c.oidcTokenRequestToken)
require.Equal(t, "conf", c.oidcTokenRequestUrl)
require.Equal(t, "conf", c.tenantId)
require.NotNil(t, c.cloud)
require.Equal(t, "https://login.microsoftonline.us/", c.cloud.ActiveDirectoryAuthorityHost)
require.True(t, c.useOidc)
require.True(t, c.useMsi)
})
t.Run("values from env", func(t *testing.T) {
p := &testProvider{}
setAuthEnvVariables("env", "true")
t.Setenv("ARM_ENVIRONMENT", "usgovernment")
c, err := readAuthConfig(context.Background(), p.getConfig, getMetadata)
require.NoError(t, err)
require.NotNil(t, c)
require.Equal(t, []string{"env"}, c.auxTenants)
require.Equal(t, "env", c.clientCertPassword)
require.Equal(t, "env", c.clientCertPath)
require.Equal(t, "env", c.clientId)
require.Equal(t, "env", c.clientSecret)
require.Equal(t, "env", c.oidcAudience)
require.Equal(t, "env", c.oidcToken)
require.Equal(t, "env", c.oidcTokenFilePath)
require.Equal(t, "env", c.oidcTokenRequestToken)
require.Equal(t, "env", c.oidcTokenRequestUrl)
require.Equal(t, "env", c.tenantId)
require.NotNil(t, c.cloud)
require.Equal(t, "https://login.microsoftonline.us/", c.cloud.ActiveDirectoryAuthorityHost)
require.True(t, c.useOidc)
require.True(t, c.useMsi)
})
}
func TestNewCredential(t *testing.T) {
t.Run("SP with client secret", func(t *testing.T) {
conf := &authConfiguration{
clientId: "client-id",
clientSecret: "client-secret",
tenantId: "tenant-id",
subscriptionId: "subscription-id",
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.ClientSecretCredential{}, cred)
clientVal := reflect.ValueOf(cred).Elem().FieldByName("client")
require.Equal(t, "client-id", clientVal.Elem().FieldByName("clientID").String())
require.Equal(t, "tenant-id", clientVal.Elem().FieldByName("tenantID").String())
})
t.Run("Incomplete SP missing subscription id", func(t *testing.T) {
conf := &authConfiguration{
clientId: "client-id",
clientSecret: "client-secret",
tenantId: "tenant-id",
}
_, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.Error(t, err)
require.Contains(t, err.Error(), "Subscription")
})
t.Run("Incomplete SP with client secret conf missing tenant id", func(t *testing.T) {
conf := &authConfiguration{
clientId: "client-id",
clientSecret: "client-secret",
subscriptionId: "subscription-id",
}
_, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.Error(t, err)
require.Contains(t, err.Error(), "Tenant")
})
t.Run("SP with client cert", func(t *testing.T) {
certPath := filepath.Join(t.TempDir(), "cert.pfx")
require.NoError(t, os.WriteFile(certPath, testPfxCert, 0644))
conf := &authConfiguration{
clientId: "client-id",
clientCertPath: certPath,
clientCertPassword: "pulumi",
tenantId: "tenant-id",
subscriptionId: "subscription-id",
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.ClientCertificateCredential{}, cred)
clientVal := reflect.ValueOf(cred).Elem().FieldByName("client")
require.Equal(t, "client-id", clientVal.Elem().FieldByName("clientID").String())
require.Equal(t, "tenant-id", clientVal.Elem().FieldByName("tenantID").String())
})
t.Run("SP with invalid client cert", func(t *testing.T) {
certPath := filepath.Join(t.TempDir(), "cert.pem")
require.NoError(t, os.WriteFile(certPath, []byte("cert"), 0644))
conf := &authConfiguration{
clientId: "client-id",
clientCertPath: certPath,
tenantId: "tenant-id",
subscriptionId: "subscription-id",
}
_, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.Error(t, err)
require.Contains(t, err.Error(), "failed to parse certificate")
})
t.Run("SP with client cert and wrong password", func(t *testing.T) {
certPath := filepath.Join(t.TempDir(), "cert.pfx")
require.NoError(t, os.WriteFile(certPath, testPfxCert, 0644))
conf := &authConfiguration{
clientId: "client-id",
clientCertPath: certPath,
clientCertPassword: "wrong",
tenantId: "tenant-id",
subscriptionId: "subscription-id",
}
_, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.Error(t, err)
require.Contains(t, err.Error(), "failed to parse certificate")
require.Contains(t, err.Error(), "password incorrect")
})
t.Run("OIDC with token", func(t *testing.T) {
conf := &authConfiguration{
useOidc: true,
oidcToken: "oidc-token",
clientId: "client-id",
tenantId: "tenant-id",
subscriptionId: "subscription-id",
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.ClientAssertionCredential{}, cred)
clientVal := reflect.ValueOf(cred).Elem().FieldByName("client")
require.Equal(t, "client-id", clientVal.Elem().FieldByName("clientID").String())
require.Equal(t, "tenant-id", clientVal.Elem().FieldByName("tenantID").String())
})
t.Run("OIDC with token file", func(t *testing.T) {
tokenPath := filepath.Join(t.TempDir(), "my.token")
require.NoError(t, os.WriteFile(tokenPath, []byte("token"), 0644))
conf := &authConfiguration{
useOidc: true,
oidcTokenFilePath: tokenPath,
clientId: "client-id",
tenantId: "tenant-id",
subscriptionId: "subscription-id",
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.ClientAssertionCredential{}, cred)
})
t.Run("OIDC with wrong token file", func(t *testing.T) {
conf := &authConfiguration{
useOidc: true,
oidcTokenFilePath: filepath.Join(t.TempDir(), "foo"),
clientId: "client-id",
tenantId: "tenant-id",
subscriptionId: "subscription-id",
}
_, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.Error(t, err)
require.ErrorIs(t, err, os.ErrNotExist)
})
t.Run("OIDC with token exchange URL", func(t *testing.T) {
conf := &authConfiguration{
useOidc: true,
oidcTokenRequestToken: "oidc-token",
oidcTokenRequestUrl: "oidc-token-url",
clientId: "client-id",
tenantId: "tenant-id",
subscriptionId: "subscription-id",
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.ClientAssertionCredential{}, cred)
})
t.Run("OIDC with token exchange URL and custom audience", func(t *testing.T) {
conf := &authConfiguration{
useOidc: true,
oidcAudience: "api://oidc-audience",
oidcTokenRequestToken: "oidc-token",
oidcTokenRequestUrl: "oidc-token-url",
clientId: "client-id",
tenantId: "tenant-id",
subscriptionId: "subscription-id",
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.ClientAssertionCredential{}, cred)
})
t.Run("Incomplete OIDC conf", func(t *testing.T) {
for _, conf := range []*authConfiguration{
{ // missing tenantId
useOidc: true,
oidcToken: "oidc-token",
clientId: "client-id",
subscriptionId: "subscription-id",
},
{ // missing oidcTokenRequestToken
useOidc: true,
oidcTokenRequestUrl: "oidc-token-url",
clientId: "client-id",
tenantId: "tenant-id",
subscriptionId: "subscription-id",
},
{ // missing subscriptionId
useOidc: true,
oidcToken: "oidc-token",
clientId: "client-id",
tenantId: "tenant-id",
},
} {
_, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.Error(t, err)
}
})
t.Run("MSI", func(t *testing.T) {
conf := &authConfiguration{
useMsi: true,
subscriptionId: "subscription-id",
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.ManagedIdentityCredential{}, cred)
})
// Used for user-assigned managed identity
t.Run("MSI with client id", func(t *testing.T) {
conf := &authConfiguration{
useMsi: true,
clientId: "123",
subscriptionId: "subscription-id",
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.ManagedIdentityCredential{}, cred)
// FUTURE: assert cred.client.id = "123"
})
t.Run("CLI", func(t *testing.T) {
conf := &authConfiguration{}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.AzureCLICredential{}, cred)
})
t.Run("CLI with aux tenants", func(t *testing.T) {
conf := &authConfiguration{
auxTenants: []string{"123", "456"},
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.AzureCLICredential{}, cred)
optsVal := reflect.ValueOf(cred).Elem().FieldByName("opts")
require.Equal(t, "123", optsVal.FieldByName("AdditionallyAllowedTenants").Index(0).String())
require.Equal(t, "456", optsVal.FieldByName("AdditionallyAllowedTenants").Index(1).String())
})
t.Run("CLI with subscription id", func(t *testing.T) {
conf := &authConfiguration{
subscriptionId: "subscription-id",
// Mock showSubscription to return a non-default subscription
showSubscription: func(ctx context.Context, subscriptionID string) (*Subscription, error) {
return &Subscription{
ID: "subscription-id",
IsDefault: false, // Non-default subscription should be passed to SDK
}, nil
},
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.AzureCLICredential{}, cred)
optsVal := reflect.ValueOf(cred).Elem().FieldByName("opts")
require.Equal(t, "subscription-id", optsVal.FieldByName("Subscription").String())
})
t.Run("CLI with default subscription id", func(t *testing.T) {
conf := &authConfiguration{
subscriptionId: "subscription-id",
// Mock showSubscription to return the default subscription
showSubscription: func(ctx context.Context, subscriptionID string) (*Subscription, error) {
return &Subscription{
ID: "subscription-id",
IsDefault: true, // Default subscription should NOT be passed to SDK
}, nil
},
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.AzureCLICredential{}, cred)
optsVal := reflect.ValueOf(cred).Elem().FieldByName("opts")
// When it's the default subscription, we should NOT pass it to the SDK
require.Equal(t, "", optsVal.FieldByName("Subscription").String())
})
t.Run("Azure Default Credential", func(t *testing.T) {
conf := &authConfiguration{
useDefault: true,
subscriptionId: "subscription-id",
}
cred, err := newSingleMethodAuthCredential(context.Background(), conf, azcore.ClientOptions{})
require.NoError(t, err)
require.IsType(t, &azidentity.DefaultAzureCredential{}, cred)
})
}
func TestOidcTokenExchangeAssertion(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "GET", r.Method)
assert.Equal(t, "application/x-www-form-urlencoded", r.Header.Get("Content-Type"))
assert.Equal(t, "application/json", r.Header.Get("Accept"))
assert.Equal(t, "api://AzureADTokenExchange", r.URL.Query().Get("audience"))
assert.Equal(t, "Bearer oidc-token", r.Header.Get("Authorization"))
w.Write([]byte(`{"Value": "new-oidc-token"}`))
}))
defer ts.Close()
conf := &authConfiguration{
oidcTokenRequestToken: "oidc-token",
oidcTokenRequestUrl: ts.URL,
}
assertion := getOidcTokenExchangeAssertion(conf)
oidcToken, err := assertion(context.Background())
require.NoError(t, err)
require.Equal(t, "new-oidc-token", oidcToken)
}
var testEnvironment = cloud.Configuration{
Name: "Test",
Configuration: azcloud.Configuration{
ActiveDirectoryAuthorityHost: "https://login.test/",
Services: map[azcloud.ServiceName]azcloud.ServiceConfiguration{
azcloud.ResourceManager: {
Audience: "https://management.core.test/",
Endpoint: "https://management.test/",
},
},
},
Endpoints: cloud.ConfigurationEndpoints{
MicrosoftGraph: "https://microsoftgraph.test/",
},
Suffixes: cloud.ConfigurationSuffixes{
StorageEndpoint: "core.storage.test",
KeyVaultDNS: ".vault.test",
},
}
func TestReadCloudConfiguration(t *testing.T) {
type testCase struct {
name string
config map[string]string
env map[string]string
metadata cloud.Configuration
expectErr bool
expect *cloud.Configuration
}
tests := []testCase{
{
name: "no config, no env returns nil",
config: map[string]string{},
env: map[string]string{},
expectErr: false,
expect: nil,
},
{
name: "well-known cloud by config",
config: map[string]string{
"environment": "public",
},
env: map[string]string{},
expectErr: false,
expect: &cloud.AzurePublic,
},
{
name: "well-known cloud by ARM_ENVIRONMENT",
config: map[string]string{},
env: map[string]string{
"ARM_ENVIRONMENT": "usgovernment",
},
expectErr: false,
expect: &cloud.AzureGovernment,
},
{
name: "well-known cloud by AZURE_ENVIRONMENT",
config: map[string]string{},
env: map[string]string{
"AZURE_ENVIRONMENT": "china",
},
expectErr: false,
expect: &cloud.AzureChina,
},
{
name: "from metadata server",
env: map[string]string{
"ARM_METADATA_HOSTNAME": "metadata.test",
},
metadata: testEnvironment,
expectErr: false,
expect: &testEnvironment,
},
{
name: "from metadata server (overriding ARM_ENVIRONMENT)",
env: map[string]string{
"ARM_METADATA_HOSTNAME": "metadata.test",
"ARM_ENVIRONMENT": "usgovernment",
},
metadata: testEnvironment,
expectErr: false,
expect: &testEnvironment,
},
{
name: "unknown environment with no metadata server returns error",
config: map[string]string{
"environment": "unknowncloud",
},
env: map[string]string{},
expectErr: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
for k, v := range tc.env {
t.Setenv(k, v)
}
getMetadata := func(ctx context.Context, endpoint string) (cloud.Configuration, error) {
return tc.metadata, nil
}
getConfig := func(configName, envName string) string {
if val, ok := tc.config[configName]; ok {
return val
}
return os.Getenv(envName)
}
cloudConf, err := readCloudConfiguration(context.Background(), getConfig, getMetadata)
if tc.expectErr {
require.Error(t, err)
} else {
require.NoError(t, err)
if tc.expect == nil {
require.Nil(t, cloudConf)
} else {
require.NotNil(t, cloudConf)
require.Equal(t, tc.expect.Name, cloudConf.Name)
require.Equal(t, tc.expect.Configuration.ActiveDirectoryAuthorityHost, cloudConf.Configuration.ActiveDirectoryAuthorityHost)
require.Equal(t,
tc.expect.Configuration.Services[azcloud.ResourceManager],
cloudConf.Configuration.Services[azcloud.ResourceManager],
)
require.Equal(t, tc.expect.Endpoints.MicrosoftGraph, cloudConf.Endpoints.MicrosoftGraph)
require.Equal(t, tc.expect.Suffixes.StorageEndpoint, cloudConf.Suffixes.StorageEndpoint)
require.Equal(t, tc.expect.Suffixes.KeyVaultDNS, cloudConf.Suffixes.KeyVaultDNS)
}
}
})
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/provider_parameterize_test.go | provider/pkg/provider/provider_parameterize_test.go | // Copyright 2025, Pulumi Corporation.
package provider
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/pulumi/providertest/pulumitest"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
rpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func TestGetParameterizeArgs(t *testing.T) {
t.Parallel()
t.Run("value", func(t *testing.T) {
t.Parallel()
args := parameterizeArgs{
Module: "aad",
Version: "v20221201",
}
serialized, err := serializeParameterizeArgs(&args)
require.NoError(t, err)
req := &rpc.ParameterizeRequest{
Parameters: &rpc.ParameterizeRequest_Value{
Value: &rpc.ParameterizeRequest_ParametersValue{
Value: serialized,
},
},
}
got, err := getParameterizeArgs(req)
require.NoError(t, err)
require.Equal(t, args, *got)
})
t.Run("args", func(t *testing.T) {
t.Parallel()
req := &rpc.ParameterizeRequest{
Parameters: &rpc.ParameterizeRequest_Args{
Args: &rpc.ParameterizeRequest_ParametersArgs{
Args: []string{"aad", "v20221201"},
},
},
}
got, err := getParameterizeArgs(req)
require.NoError(t, err)
require.Equal(t, "aad", got.Module)
require.Equal(t, "v20221201", got.Version)
})
t.Run("unexpected args", func(t *testing.T) {
t.Parallel()
req := &rpc.ParameterizeRequest{
Parameters: &rpc.ParameterizeRequest_Args{
Args: &rpc.ParameterizeRequest_ParametersArgs{
Args: []string{"aad"},
},
},
}
got, err := getParameterizeArgs(req)
require.Error(t, err)
require.Nil(t, got)
})
t.Run("empty", func(t *testing.T) {
t.Parallel()
req := &rpc.ParameterizeRequest{}
_, err := getParameterizeArgs(req)
require.Error(t, err)
})
}
// A struct to get the schema version without deserializing the whole schema.
type schemaWithVersion struct {
Version string `json:"version"`
}
func TestParameterizeCreatesSchemaAndMetadata(t *testing.T) {
t.Parallel()
schemaBytes, err := os.ReadFile("../../../bin/schema-full.json")
require.NoError(t, err)
// Get the schema version from the schema. In production, it would be the same than version.GetVersion(), but in
// CI it's not - 2.0.0-alpha.0+dev vs. 2.90.0-alpha.1741284698+8268d88.
var v schemaWithVersion
err = json.Unmarshal(schemaBytes, &v)
require.NoError(t, err)
providerVersion := v.Version
provider, err := makeProviderInternal(nil, "azure-native", providerVersion, schemaBytes, &resources.APIMetadata{
Types: resources.GoMap[resources.AzureAPIType]{},
Resources: resources.GoMap[resources.AzureAPIResource]{
"azure-native:aad/v20221201:DomainService": {},
},
Invokes: resources.GoMap[resources.AzureAPIInvoke]{},
})
require.NoError(t, err)
parameterizationArgs := []string{"aad", "v20221201"}
expectedProviderName := "azure-native_aad_v20221201"
require.NoError(t, err)
resp, err := provider.Parameterize(context.Background(), &rpc.ParameterizeRequest{
Parameters: &rpc.ParameterizeRequest_Args{
Args: &rpc.ParameterizeRequest_ParametersArgs{
Args: parameterizationArgs,
},
},
})
require.NoError(t, err)
require.Equal(t, expectedProviderName, resp.Name)
// check that schema looks ok
var schema pschema.PackageSpec
err = json.Unmarshal(provider.schemaBytes, &schema)
require.NoError(t, err)
assert.NotEmpty(t, schema.Types)
for typeName := range schema.Types {
assert.True(t, strings.HasPrefix(typeName, expectedProviderName+":"))
}
assert.NotEmpty(t, schema.Resources)
for resourceName := range schema.Resources {
assert.True(t, strings.HasPrefix(resourceName, expectedProviderName+":"))
}
assert.NotEmpty(t, schema.Functions)
// check that metadata looks ok
metadata := provider.resourceMap
assert.NotNil(t, metadata)
assert.NotNil(t, metadata.Resources)
assert.NotNil(t, metadata.Types)
assert.NotNil(t, metadata.Invokes)
resource, ok, err := metadata.Resources.Get(expectedProviderName + ":aad:DomainService")
require.NoError(t, err)
assert.True(t, ok)
assert.NotNil(t, resource)
_, ok, err = metadata.Resources.Get("azure-native:aad/v20221201:DomainService")
require.NoError(t, err)
assert.False(t, ok)
// parameterization arguments a serialized as a base64-encoded JSON string
assert.NotEmpty(t, schema.Parameterization.Parameter)
args, err := deserializeParameterizeArgs(schema.Parameterization.Parameter)
require.NoError(t, err)
assert.Equal(t, "aad", args.Module)
assert.Equal(t, "v20221201", args.Version)
}
func TestParameterizeUpdatesConverterTypes(t *testing.T) {
t.Parallel()
schemaBytes, err := os.ReadFile("../../../bin/schema-full.json")
require.NoError(t, err)
var v schemaWithVersion
err = json.Unmarshal(schemaBytes, &v)
require.NoError(t, err)
providerVersion := v.Version
// Use a type that exists in the schema: DomainSecuritySettings
// This type has properties with kebab-case wire names and camelCase sdkNames
originalTypeToken := "azure-native:aad/v20221201:DomainSecuritySettings"
provider, err := makeProviderInternal(nil, "azure-native", providerVersion, schemaBytes, &resources.APIMetadata{
Types: resources.GoMap[resources.AzureAPIType]{
originalTypeToken: {
Properties: map[string]resources.AzureAPIProperty{
"ntlm-v1": {SdkName: "ntlmV1", Type: "string"},
},
},
},
Resources: resources.GoMap[resources.AzureAPIResource]{
"azure-native:aad/v20221201:DomainService": {},
},
Invokes: resources.GoMap[resources.AzureAPIInvoke]{},
})
require.NoError(t, err)
// Before parameterization, the converter should find the type by original token
typ, ok, err := provider.converter.GetType(originalTypeToken)
require.NoError(t, err)
assert.True(t, ok, "converter should find type by original token before parameterization")
assert.Equal(t, "ntlmV1", typ.Properties["ntlm-v1"].SdkName)
// Parameterize the provider
_, err = provider.Parameterize(context.Background(), &rpc.ParameterizeRequest{
Parameters: &rpc.ParameterizeRequest_Args{
Args: &rpc.ParameterizeRequest_ParametersArgs{
Args: []string{"aad", "v20221201"},
},
},
})
require.NoError(t, err)
// After parameterization, the converter should find the type by the NEW token
newTypeToken := "azure-native_aad_v20221201:aad:DomainSecuritySettings"
typ, ok, err = provider.converter.GetType(newTypeToken)
require.NoError(t, err)
assert.True(t, ok, "converter should find type by new token after parameterization")
assert.Equal(t, "ntlmV1", typ.Properties["ntlm-v1"].SdkName)
// The old token should no longer be found
_, ok, err = provider.converter.GetType(originalTypeToken)
require.NoError(t, err)
assert.False(t, ok, "converter should NOT find type by original token after parameterization")
}
func TestRoundtripParameterizeArgs(t *testing.T) {
t.Parallel()
args := parameterizeArgs{
Module: "aad",
Version: "v20221201",
}
serialized, err := serializeParameterizeArgs(&args)
require.NoError(t, err)
deserialized, err := deserializeParameterizeArgs(serialized)
require.NoError(t, err)
require.Equal(t, args, *deserialized)
}
func TestFilterTokens(t *testing.T) {
t.Parallel()
types := map[string]struct{}{
"azure-native:aad:Application": {},
"azure-native:aad/v20221201:Application": {},
"azure-native:aad/v20331201:Application": {},
"azure-native:storage/v20221201:StorageAccount": {},
}
names, err := filterTokens(types, "aad", "v20221201")
require.NoError(t, err)
require.Len(t, names, 1)
require.Equal(t, "Application", names["azure-native:aad/v20221201:Application"])
}
func TestParseApiVersion(t *testing.T) {
t.Parallel()
t.Run("Valid", func(t *testing.T) {
t.Parallel()
for _, v := range [][]string{
{"2020-01-01", "v20200101"},
{"2027-01-01", "v20270101"},
{"2020-12-31", "v20201231"},
{"v2020-12-31", "v20201231"},
{"V2020-12-31", "v20201231"},
{"v20230301", "v20230301"},
{"V20230301", "v20230301"},
{"20230301", "v20230301"},
{" 20230301 ", "v20230301"},
{"2023-03-01-preview", "v20230301preview"},
{"2023-03-01-privatepreview ", "v20230301privatepreview"},
{"v20230301preview", "v20230301preview"},
{"v20230301privatepreview ", "v20230301privatepreview"},
} {
parsed, err := parseApiVersion(v[0])
require.NoError(t, err)
assert.Equal(t, v[1], parsed)
}
})
t.Run("Invalid", func(t *testing.T) {
t.Parallel()
for _, v := range []string{
"1999-01-01",
"2027-011-01",
"2020-12-311",
"2020-12-41",
"2020-22-31",
"v2023030",
"V202303011",
"19990301",
"2023-03-01-alpha",
} {
_, err := parseApiVersion(v)
assert.Error(t, err, v)
}
})
}
func TestUpdateMetadataRefs(t *testing.T) {
t.Parallel()
t.Run("Empty metadata", func(t *testing.T) {
t.Parallel()
metadata := &resources.APIMetadata{}
updated, err := updateMetadataRefs(metadata, "azure-native_storage_v20240101", "storage", "v20240101")
require.NoError(t, err)
require.Empty(t, updated.Resources)
require.Empty(t, updated.Types)
require.Empty(t, updated.Invokes)
})
t.Run("Updates refs in types", func(t *testing.T) {
t.Parallel()
metadata := &resources.APIMetadata{
Types: resources.GoMap[resources.AzureAPIType]{
"type1": {
Properties: map[string]resources.AzureAPIProperty{
"prop1": {
Ref: "#/types/azure-native:storage/v20240101:StorageAccount",
},
},
},
},
}
updated, err := updateMetadataRefs(metadata, "azure-native_storage_v20240101", "storage", "v20240101")
require.NoError(t, err)
prop, ok, err := updated.Types.Get("type1")
require.NoError(t, err)
require.True(t, ok)
assert.Equal(t, "#/types/azure-native_storage_v20240101:storage:StorageAccount", prop.Properties["prop1"].Ref)
})
t.Run("Updates refs in resources", func(t *testing.T) {
t.Parallel()
metadata := &resources.APIMetadata{
Resources: resources.GoMap[resources.AzureAPIResource]{
"resource1": {
PutParameters: []resources.AzureAPIParameter{
{
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"prop1": {
Ref: "#/types/azure-native:storage/v20240101:StorageAccount",
},
},
},
},
},
},
},
}
updated, err := updateMetadataRefs(metadata, "azure-native_storage_v20240101", "storage", "v20240101")
require.NoError(t, err)
resource, ok, err := updated.Resources.Get("resource1")
require.NoError(t, err)
require.True(t, ok)
require.Len(t, resource.PutParameters, 1)
assert.Equal(t, "#/types/azure-native_storage_v20240101:storage:StorageAccount", resource.PutParameters[0].Body.Properties["prop1"].Ref)
})
t.Run("Updates refs in invokes", func(t *testing.T) {
t.Parallel()
metadata := &resources.APIMetadata{
Invokes: resources.GoMap[resources.AzureAPIInvoke]{
"invoke1": {
Response: map[string]resources.AzureAPIProperty{
"prop1": {
Ref: "#/types/azure-native:storage/v20240101:StorageAccount",
},
},
},
},
}
updated, err := updateMetadataRefs(metadata, "azure-native_storage_v20240101", "storage", "v20240101")
require.NoError(t, err)
invoke, ok, err := updated.Invokes.Get("invoke1")
require.NoError(t, err)
require.True(t, ok)
assert.Equal(t, "#/types/azure-native_storage_v20240101:storage:StorageAccount", invoke.Response["prop1"].Ref)
})
t.Run("Does not update refs pointing to a different module", func(t *testing.T) {
t.Parallel()
metadata := &resources.APIMetadata{
Resources: resources.GoMap[resources.AzureAPIResource]{
"resource1": {
PutParameters: []resources.AzureAPIParameter{
{
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"prop1": {
Ref: "#/types/azure-native:common:ManagedIdentity",
},
},
},
},
},
},
},
}
updated, err := updateMetadataRefs(metadata, "azure-native_storage_v20240101", "storage", "v20240101")
require.NoError(t, err)
resource, ok, err := updated.Resources.Get("resource1")
require.NoError(t, err)
require.True(t, ok)
require.Len(t, resource.PutParameters, 1)
assert.Equal(t, "#/types/azure-native:common:ManagedIdentity", resource.PutParameters[0].Body.Properties["prop1"].Ref)
})
}
// Ensure that we can run `pulumi package add` with a local provider binary and get a new SDK.
func TestParameterizePackageAdd(t *testing.T) {
t.Parallel()
pt := pulumitest.NewPulumiTest(t, filepath.Join("test-programs", "parameterize-storage"))
pulumiPackageAdd(t, pt, "../../../bin/pulumi-resource-azure-native", "storage", "v20240101")
sdkPath := filepath.Join(pt.WorkingDir(), "sdks", "azure-native_storage_v20240101")
if _, err := os.Stat(sdkPath); os.IsNotExist(err) {
t.Fatalf("generated SDK directory not found at path: %s", sdkPath)
}
}
func pulumiPackageAdd(
t *testing.T,
pt *pulumitest.PulumiTest,
localProviderBinPath string,
args ...string,
) {
if _, err := os.Stat(localProviderBinPath); os.IsNotExist(err) {
t.Fatalf("Provider binary not found at path: %s", localProviderBinPath)
}
absLocalProviderBinPath, err := filepath.Abs(localProviderBinPath)
require.NoError(t, err)
ctx := context.Background()
allArgs := append([]string{"package", "add", absLocalProviderBinPath}, args...)
stdout, stderr, exitCode, err := pt.CurrentStack().Workspace().PulumiCommand().Run(
ctx,
pt.WorkingDir(),
nil, /* reader */
nil, /* additionalOutput */
nil, /* additionalErrorOutput */
nil, /* additionalEnv */
allArgs...,
)
if err != nil || exitCode != 0 {
t.Fatalf("Failed to run pulumi package add\nExit code: %d\nError: %v\n%s\n%s",
exitCode, err, stdout, stderr)
}
}
func TestCreateSchemaErrorChecking(t *testing.T) {
t.Parallel()
schema := pschema.PackageSpec{
Resources: map[string]pschema.ResourceSpec{
"azure-native:storage:StorageAccount": {},
"azure-native:storage/v20230303:StorageAccount": {},
"azure-native:storage/v20220202:StorageAccount": {},
},
}
t.Run("No such API version", func(t *testing.T) {
_, _, err := createSchema(nil, schema, "storage", "v20240101")
require.Error(t, err)
assert.Equal(t, codes.InvalidArgument, status.Code(err))
assert.Contains(t, err.Error(), "no resources found for module storage at API version v20240101. Available API versions: v20220202, v20230303")
})
t.Run("No such module", func(t *testing.T) {
_, _, err := createSchema(nil, schema, "compute", "v20240101")
require.Error(t, err)
assert.Equal(t, codes.InvalidArgument, status.Code(err))
assert.Contains(t, err.Error(), "module compute not found. Some modules were renamed in v3 of the provider")
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/serve.go | provider/pkg/provider/serve.go | // Copyright 2016-2020, Pulumi Corporation.
package provider
import (
"github.com/pulumi/pulumi/pkg/v3/resource/provider"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
rpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
)
// Serve launches the gRPC server for the resource provider.
func Serve(providerName, version string, schemaBytes []byte, azureAPIResourcesBytes []byte) {
// Start gRPC service.
err := provider.Main(providerName, func(host *provider.HostClient) (rpc.ResourceProviderServer, error) {
return makeProvider(host, providerName, version, schemaBytes, azureAPIResourcesBytes)
})
if err != nil {
cmdutil.ExitError(err.Error())
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/log.go | provider/pkg/provider/log.go | // Copyright 2016-2020, Pulumi Corporation.
package provider
import (
"bufio"
"context"
"strings"
"github.com/pulumi/pulumi/pkg/v3/resource/provider"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
// LogRedirector creates a new redirection writer that takes as input plugin stderr output, and routes it to the
// correct Pulumi stream based on the standard Terraform logging output prefixes.
type LogRedirector struct {
enabled bool // true if standard logging is on; false for debug-only.
writers map[string]func(string) error // the writers for certain labels.
buffer []byte // a buffer that holds up to a line of output.
}
// NewLogRedirector returns a new LogRedirector with the (unexported) writers field
// set to the given map.
func NewTerraformLogRedirector(ctx context.Context, hostClient *provider.HostClient) *LogRedirector {
return &LogRedirector{
writers: map[string]func(string) error{
tfTracePrefix: func(msg string) error { return hostClient.Log(ctx, diag.Debug, "", msg) },
tfDebugPrefix: func(msg string) error { return hostClient.Log(ctx, diag.Debug, "", msg) },
tfInfoPrefix: func(msg string) error { return hostClient.Log(ctx, diag.Info, "", msg) },
tfWarnPrefix: func(msg string) error { return hostClient.Log(ctx, diag.Warning, "", msg) },
tfErrorPrefix: func(msg string) error { return hostClient.Log(ctx, diag.Error, "", msg) },
},
}
}
const (
tfTracePrefix = "[TRACE]"
tfDebugPrefix = "[DEBUG]"
tfInfoPrefix = "[INFO]"
tfWarnPrefix = "[WARN]"
tfErrorPrefix = "[ERROR]"
)
// Enable turns on full featured logging. This is the default.
func (lr *LogRedirector) Enable() {
lr.enabled = true
}
// Disable disables most of the specific logging levels, but it retains debug logging.
func (lr *LogRedirector) Disable() {
lr.enabled = false
}
func (lr *LogRedirector) Write(p []byte) (n int, err error) {
written := 0
// If a line starts with [TRACE], [DEBUG], or [INFO], then we emit to a debug log entry. If a line starts with
// [WARN], we emit a warning. If a line starts with [ERROR], on the other hand, we emit a normal stderr line.
// All others simply get redirected to stdout as normal output.
for len(p) > 0 {
adv, tok, err := bufio.ScanLines(p, false)
if err != nil {
return written, err
}
// If adv == 0, there was no newline; buffer it all and move on.
if adv == 0 {
lr.buffer = append(lr.buffer, p...)
written += len(p)
break
}
// Otherwise, there was a newline; emit the buffer plus payload to the right place, and keep going if
// there is more.
lr.buffer = append(lr.buffer, tok...) // append the buffer.
s := string(lr.buffer)
// To do this we need to parse the label if there is one (e.g., [TRACE], et al).
var label string
if start := strings.IndexRune(s, '['); start != -1 {
if end := strings.Index(s[start:], "] "); end != -1 {
label = s[start : start+end+1]
s = s[start+end+2:] // skip past the "] " (notice the space)
}
}
w, has := lr.writers[label]
if !has || !lr.enabled {
// If there was no writer for this label, or logging is disabled, use the debug label.
w = lr.writers[tfDebugPrefix]
contract.Assert(w != nil)
}
if err := w(s); err != nil {
return written, err
}
// Now keep moving on provided there is more left in the buffer.
lr.buffer = lr.buffer[:0] // clear out the buffer.
p = p[adv:] // advance beyond the extracted region.
written += adv
}
return written, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/properties_diff_test.go | provider/pkg/provider/properties_diff_test.go | // Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package provider
// NOTE: this file was copied from pulumi/pulumi/sdk/go/common/resource as part of #2968 which
// required customizing the diffing logic.
import (
"testing"
"github.com/stretchr/testify/assert"
. "github.com/pulumi/pulumi/sdk/v3/go/common/resource"
)
func assertDeepEqualsIffEmptyDiff(t *testing.T, val1, val2 PropertyValue) {
diff := val1.Diff(val2)
equals := val1.DeepEquals(val2)
assert.Equal(t, diff == nil, equals, "DeepEquals <--> empty diff")
}
func TestNullPropertyValueDiffs(t *testing.T) {
t.Parallel()
d1 := NewNullProperty().Diff(NewNullProperty())
assert.Nil(t, d1)
d2 := NewNullProperty().Diff(NewProperty(true))
assert.NotNil(t, d2)
assert.Nil(t, d2.Array)
assert.Nil(t, d2.Object)
assert.True(t, d2.Old.IsNull())
assert.True(t, d2.New.IsBool())
assert.Equal(t, true, d2.New.BoolValue())
}
func TestBoolPropertyValueDiffs(t *testing.T) {
t.Parallel()
d1 := NewProperty(true).Diff(NewProperty(true))
assert.Nil(t, d1)
d2 := NewProperty(true).Diff(NewProperty(false))
assert.NotNil(t, d2)
assert.Nil(t, d2.Array)
assert.Nil(t, d2.Object)
assert.True(t, d2.Old.IsBool())
assert.Equal(t, true, d2.Old.BoolValue())
assert.True(t, d2.New.IsBool())
assert.Equal(t, false, d2.New.BoolValue())
d3 := NewProperty(true).Diff(NewNullProperty())
assert.NotNil(t, d3)
assert.Nil(t, d3.Array)
assert.Nil(t, d3.Object)
assert.True(t, d3.Old.IsBool())
assert.Equal(t, true, d3.Old.BoolValue())
assert.True(t, d3.New.IsNull())
}
func TestNumberPropertyValueDiffs(t *testing.T) {
t.Parallel()
d1 := NewProperty(42.0).Diff(NewProperty(42.0))
assert.Nil(t, d1)
d2 := NewProperty(42.0).Diff(NewProperty(66.0))
assert.NotNil(t, d2)
assert.Nil(t, d2.Array)
assert.Nil(t, d2.Object)
assert.True(t, d2.Old.IsNumber())
assert.Equal(t, float64(42), d2.Old.NumberValue())
assert.True(t, d2.New.IsNumber())
assert.Equal(t, float64(66), d2.New.NumberValue())
d3 := NewProperty(88.0).Diff(NewProperty(true))
assert.NotNil(t, d3)
assert.Nil(t, d3.Array)
assert.Nil(t, d3.Object)
assert.True(t, d3.Old.IsNumber())
assert.Equal(t, float64(88), d3.Old.NumberValue())
assert.True(t, d3.New.IsBool())
assert.Equal(t, true, d3.New.BoolValue())
}
func TestStringPropertyValueDiffs(t *testing.T) {
t.Parallel()
d1 := NewProperty("a string").Diff(NewProperty("a string"))
assert.Nil(t, d1)
d2 := NewProperty("a string").Diff(NewProperty("some other string"))
assert.NotNil(t, d2)
assert.True(t, d2.Old.IsString())
assert.Equal(t, "a string", d2.Old.StringValue())
assert.True(t, d2.New.IsString())
assert.Equal(t, "some other string", d2.New.StringValue())
d3 := NewProperty("what a string").Diff(NewProperty(973.0))
assert.NotNil(t, d3)
assert.Nil(t, d3.Array)
assert.Nil(t, d3.Object)
assert.True(t, d3.Old.IsString())
assert.Equal(t, "what a string", d3.Old.StringValue(), "what a string")
assert.True(t, d3.New.IsNumber())
assert.Equal(t, float64(973), d3.New.NumberValue())
}
func TestArrayPropertyValueDiffs(t *testing.T) {
t.Parallel()
// no diffs:
d1 := NewProperty([]PropertyValue{}).Diff(NewProperty([]PropertyValue{}))
assert.Nil(t, d1)
d2 := NewProperty([]PropertyValue{
NewProperty("element one"), NewProperty(2.0), NewNullProperty(),
}).Diff(NewProperty([]PropertyValue{
NewProperty("element one"), NewProperty(2.0), NewNullProperty(),
}))
assert.Nil(t, d2)
// all updates:
d3a1 := NewProperty([]PropertyValue{
NewProperty("element one"), NewProperty(2.0), NewNullProperty(),
})
d3a2 := NewProperty([]PropertyValue{
NewProperty(1.0), NewNullProperty(), NewProperty("element three"),
})
assertDeepEqualsIffEmptyDiff(t, NewPropertyValue(d3a1), NewPropertyValue(d3a2))
d3 := d3a1.Diff(d3a2)
assert.NotNil(t, d3)
assert.NotNil(t, d3.Array)
assert.Nil(t, d3.Object)
assert.Equal(t, 0, len(d3.Array.Adds))
assert.Equal(t, 0, len(d3.Array.Deletes))
assert.Equal(t, 0, len(d3.Array.Sames))
assert.Equal(t, 3, len(d3.Array.Updates))
for i, update := range d3.Array.Updates {
assert.Equal(t, d3a1.ArrayValue()[i], update.Old)
assert.Equal(t, d3a2.ArrayValue()[i], update.New)
}
// update one, keep one, delete one:
d4a1 := NewProperty([]PropertyValue{
NewProperty("element one"), NewProperty(2.0), NewProperty(true),
})
d4a2 := NewProperty([]PropertyValue{
NewProperty("element 1"), NewProperty(2.0),
})
assertDeepEqualsIffEmptyDiff(t, NewPropertyValue(d4a1), NewPropertyValue(d4a2))
d4 := d4a1.Diff(d4a2)
assert.NotNil(t, d4)
assert.NotNil(t, d4.Array)
assert.Nil(t, d4.Object)
assert.Equal(t, 0, len(d4.Array.Adds))
assert.Equal(t, 1, len(d4.Array.Deletes))
for i, delete := range d4.Array.Deletes {
assert.Equal(t, 2, i)
assert.Equal(t, d4a1.ArrayValue()[i], delete)
}
assert.Equal(t, 1, len(d4.Array.Sames))
for i, same := range d4.Array.Sames {
assert.Equal(t, 1, i)
assert.Equal(t, d4a1.ArrayValue()[i], same)
assert.Equal(t, d4a2.ArrayValue()[i], same)
}
assert.Equal(t, 1, len(d4.Array.Updates))
for i, update := range d4.Array.Updates {
assert.Equal(t, 0, i)
assert.Equal(t, d4a1.ArrayValue()[i], update.Old)
assert.Equal(t, d4a2.ArrayValue()[i], update.New)
}
// keep one, update one, add one:
d5a1 := NewProperty([]PropertyValue{
NewProperty("element one"), NewProperty(2.0),
})
d5a2 := NewProperty([]PropertyValue{
NewProperty("element 1"), NewProperty(2.0), NewProperty(true),
})
assertDeepEqualsIffEmptyDiff(t, NewPropertyValue(d5a1), NewPropertyValue(d5a2))
d5 := d5a1.Diff(d5a2)
assert.NotNil(t, d5)
assert.NotNil(t, d5.Array)
assert.Nil(t, d5.Object)
assert.Equal(t, 1, len(d5.Array.Adds))
for i, add := range d5.Array.Adds {
assert.Equal(t, 2, i)
assert.Equal(t, d5a2.ArrayValue()[i], add)
}
assert.Equal(t, 0, len(d5.Array.Deletes))
assert.Equal(t, 1, len(d5.Array.Sames))
for i, same := range d5.Array.Sames {
assert.Equal(t, 1, i)
assert.Equal(t, d5a1.ArrayValue()[i], same)
assert.Equal(t, d5a2.ArrayValue()[i], same)
}
assert.Equal(t, 1, len(d5.Array.Updates))
for i, update := range d5.Array.Updates {
assert.Equal(t, 0, i)
assert.Equal(t, d5a1.ArrayValue()[i], update.Old)
assert.Equal(t, d5a2.ArrayValue()[i], update.New)
}
// from nil to empty array:
d6 := NewNullProperty().Diff(NewProperty([]PropertyValue{}))
assert.NotNil(t, d6)
}
func TestObjectPropertyValueDiffs(t *testing.T) {
t.Parallel()
// no diffs:
d1 := PropertyMap{}.Diff(PropertyMap{})
assert.Nil(t, d1)
d2 := PropertyMap{
PropertyKey("a"): NewProperty(true),
}.Diff(PropertyMap{
PropertyKey("a"): NewProperty(true),
})
assert.Nil(t, d2)
// all updates:
{
obj1 := PropertyMap{
PropertyKey("prop-a"): NewProperty(true),
PropertyKey("prop-b"): NewProperty("bbb"),
PropertyKey("prop-c"): NewProperty(PropertyMap{
PropertyKey("inner-prop-a"): NewProperty(673.0),
}),
}
obj2 := PropertyMap{
PropertyKey("prop-a"): NewProperty(false),
PropertyKey("prop-b"): NewProperty(89.0),
PropertyKey("prop-c"): NewProperty(PropertyMap{
PropertyKey("inner-prop-a"): NewProperty(672.0),
}),
}
assertDeepEqualsIffEmptyDiff(t, NewPropertyValue(obj1), NewPropertyValue(obj2))
d3 := obj1.Diff(obj2)
assert.NotNil(t, d3)
assert.Equal(t, 0, len(d3.Adds))
assert.Equal(t, 0, len(d3.Deletes))
assert.Equal(t, 0, len(d3.Sames))
assert.Equal(t, 3, len(d3.Updates))
d3pa := d3.Updates[PropertyKey("prop-a")]
assert.Nil(t, d3pa.Array)
assert.Nil(t, d3pa.Object)
assert.True(t, d3pa.Old.IsBool())
assert.Equal(t, true, d3pa.Old.BoolValue())
assert.True(t, d3pa.Old.IsBool())
assert.Equal(t, false, d3pa.New.BoolValue())
d3pb := d3.Updates[PropertyKey("prop-b")]
assert.Nil(t, d3pb.Array)
assert.Nil(t, d3pb.Object)
assert.True(t, d3pb.Old.IsString())
assert.Equal(t, "bbb", d3pb.Old.StringValue())
assert.True(t, d3pb.New.IsNumber())
assert.Equal(t, float64(89), d3pb.New.NumberValue())
d3pc := d3.Updates[PropertyKey("prop-c")]
assert.Nil(t, d3pc.Array)
assert.NotNil(t, d3pc.Object)
assert.Equal(t, 0, len(d3pc.Object.Adds))
assert.Equal(t, 0, len(d3pc.Object.Deletes))
assert.Equal(t, 0, len(d3pc.Object.Sames))
assert.Equal(t, 1, len(d3pc.Object.Updates))
d3pcu := d3pc.Object.Updates[PropertyKey("inner-prop-a")]
assert.True(t, d3pcu.Old.IsNumber())
assert.Equal(t, float64(673), d3pcu.Old.NumberValue())
assert.True(t, d3pcu.New.IsNumber())
assert.Equal(t, float64(672), d3pcu.New.NumberValue())
}
// add two (1 missing key, 1 null), update one, keep two, delete two (1 missing key, 1 null).
{
obj1 := PropertyMap{
PropertyKey("prop-a-2"): NewNullProperty(),
PropertyKey("prop-b"): NewProperty("bbb"),
PropertyKey("prop-c-1"): NewProperty(6767.0),
PropertyKey("prop-c-2"): NewNullProperty(),
PropertyKey("prop-d-1"): NewProperty(true),
PropertyKey("prop-d-2"): NewProperty(false),
}
obj2 := PropertyMap{
PropertyKey("prop-a-1"): NewProperty("a fresh value"),
PropertyKey("prop-a-2"): NewProperty("a non-nil value"),
PropertyKey("prop-b"): NewProperty(89.0),
PropertyKey("prop-c-1"): NewProperty(6767.0),
PropertyKey("prop-c-2"): NewNullProperty(),
PropertyKey("prop-d-2"): NewNullProperty(),
}
assertDeepEqualsIffEmptyDiff(t, NewPropertyValue(obj1), NewPropertyValue(obj2))
d4 := obj1.Diff(obj2)
assert.NotNil(t, d4)
assert.Equal(t, 2, len(d4.Adds))
assert.Equal(t, obj2[PropertyKey("prop-a-1")], d4.Adds[PropertyKey("prop-a-1")])
assert.Equal(t, obj2[PropertyKey("prop-a-2")], d4.Adds[PropertyKey("prop-a-2")])
assert.Equal(t, 2, len(d4.Deletes))
assert.Equal(t, obj1[PropertyKey("prop-d-1")], d4.Deletes[PropertyKey("prop-d-1")])
assert.Equal(t, obj1[PropertyKey("prop-d-2")], d4.Deletes[PropertyKey("prop-d-2")])
assert.Equal(t, 2, len(d4.Sames))
assert.Equal(t, obj1[PropertyKey("prop-c-1")], d4.Sames[PropertyKey("prop-c-1")])
assert.Equal(t, obj1[PropertyKey("prop-c-2")], d4.Sames[PropertyKey("prop-c-2")])
assert.Equal(t, obj2[PropertyKey("prop-c-1")], d4.Sames[PropertyKey("prop-c-1")])
assert.Equal(t, obj2[PropertyKey("prop-c-2")], d4.Sames[PropertyKey("prop-c-2")])
assert.Equal(t, 1, len(d4.Updates))
assert.Equal(t, obj1[PropertyKey("prop-b")], d4.Updates[PropertyKey("prop-b")].Old)
assert.Equal(t, obj2[PropertyKey("prop-b")], d4.Updates[PropertyKey("prop-b")].New)
}
}
func TestAssetPropertyValueDiffs(t *testing.T) {
t.Parallel()
a1, err := NewTextAsset("test")
assert.NoError(t, err)
d1 := NewProperty(a1).Diff(NewProperty(a1))
assert.Nil(t, d1)
a2, err := NewTextAsset("test2")
assert.NoError(t, err)
d2 := NewProperty(a1).Diff(NewProperty(a2))
assert.NotNil(t, d2)
assert.Nil(t, d2.Array)
assert.Nil(t, d2.Object)
assert.True(t, d2.Old.IsAsset())
assert.Equal(t, "test", d2.Old.AssetValue().Text)
assert.True(t, d2.New.IsAsset())
assert.Equal(t, "test2", d2.New.AssetValue().Text)
d3 := NewProperty(a1).Diff(NewNullProperty())
assert.NotNil(t, d3)
assert.Nil(t, d3.Array)
assert.Nil(t, d3.Object)
assert.True(t, d3.Old.IsAsset())
assert.Equal(t, "test", d3.Old.AssetValue().Text)
assert.True(t, d3.New.IsNull())
}
func TestMismatchedPropertyValueDiff(t *testing.T) {
t.Parallel()
a1 := NewPropertyValue([]string{"a", "b", "c"})
a2 := NewPropertyValue([]string{"a", "b", "c"})
s1 := MakeSecret(a1)
s2 := MakeSecret(a2)
assert.True(t, s2.DeepEquals(s1))
assert.True(t, s1.DeepEquals(s2))
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/provider_parameterize.go | provider/pkg/provider/provider_parameterize.go | // Copyright 2025, Pulumi Corporation.
package provider
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
rpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// parameterizeArgs is the data that is embedded in the SDK when the provider is parameterized. It will be sent to the
// provider on subsequent invocations of Parameterize to be deserialized.
type parameterizeArgs struct {
Module string `json:"module"`
Version string `json:"version"`
}
func serializeParameterizeArgs(args *parameterizeArgs) ([]byte, error) {
serialized, err := json.Marshal(args)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to serialize parameterize args: %v", err)
}
return []byte(base64.StdEncoding.EncodeToString(serialized)), nil
}
func deserializeParameterizeArgs(in []byte) (*parameterizeArgs, error) {
decoded, err := base64.StdEncoding.DecodeString(string(in))
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to deserialize parameterize args: %v", err)
}
var args parameterizeArgs
if err := json.Unmarshal(decoded, &args); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to deserialize parameterize args: %v", err)
}
return &args, nil
}
// parseApiVersion parses an Azure API version from the given string. Since the input comes from users (via `package
// add`), it tries to be lenient and accept several formats. The returned result, if successful, is an "SDL version" of
// the form v20200101.
func parseApiVersion(version string) (string, error) {
v := strings.TrimSpace(version)
v = strings.TrimLeft(v, "vV")
isApiVersion, err := regexp.MatchString(`^20\d{2}-[01]\d-[0-3]\d(-preview|-privatepreview)?$`, v)
if err != nil {
return "", status.Errorf(codes.InvalidArgument, "unexpected error parsing version %s: %v", version, err)
}
if isApiVersion {
apiVersion := openapi.ApiVersion(v)
return string(apiVersion.ToSdkVersion()), nil
}
isDigits, err := regexp.MatchString(`^20\d{6}(preview|privatepreview)?$`, v)
if err != nil {
return "", status.Errorf(codes.InvalidArgument, "unexpected error parsing version %s: %v", version, err)
}
if isDigits {
return "v" + v, nil
}
return "", status.Errorf(codes.InvalidArgument, "invalid API version: %s", version)
}
// "When generating an SDK (e.g. using a pulumi package add command), we need to boot up a provider and parameterize it
// using only information from the command-line invocation. In this case, the parameter is a string array representing
// the command-line arguments (args)."
// https://pulumi-developer-docs.readthedocs.io/latest/docs/architecture/providers/parameterized.html#parameterized-providers
func getParameterizeArgs(req *rpc.ParameterizeRequest) (*parameterizeArgs, error) {
switch {
// initial parameterization
case req.GetArgs() != nil:
args := req.GetArgs().Args
// "aad" "v20221201"
if len(args) != 2 {
return nil, status.Errorf(codes.InvalidArgument, "expected 2 arguments (module and API version), got %d", len(args))
}
targetApiVersion, err := parseApiVersion(args[1])
if err != nil {
return nil, err
}
return ¶meterizeArgs{
Module: args[0],
Version: targetApiVersion,
}, nil
// provider has already been parameterized and the arguments were serialized into the SDK
case req.GetValue() != nil:
return deserializeParameterizeArgs(req.GetValue().Value)
default:
return nil, status.Errorf(codes.InvalidArgument, "cannot handle ParameterizeRequest with parameters of type %T", req.Parameters)
}
}
func (p *azureNativeProvider) Parameterize(ctx context.Context, req *rpc.ParameterizeRequest) (*rpc.ParameterizeResponse, error) {
logging.V(9).Info("Parameterizing Azure Native provider")
args, err := getParameterizeArgs(req)
if err != nil {
return nil, err
}
logging.V(9).Infof("Creating parameterized Azure Native for %s %s", args.Module, args.Version)
var schema pschema.PackageSpec
err = json.Unmarshal(p.schemaBytes, &schema)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to unmarshal schema: %v", err)
}
newSchema, newMetadata, err := createSchema(p, schema, args.Module, args.Version)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to create parameterized schema: %v", err)
}
newPackageName := newSchema.Name
serializedArgs, err := serializeParameterizeArgs(args)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to serialize args %v: %v", args, err)
}
newSchema.Parameterization = &pschema.ParameterizationSpec{
BaseProvider: pschema.BaseProviderSpec{
Name: p.name,
Version: newSchema.Version,
},
Parameter: serializedArgs,
}
s, err := json.Marshal(newSchema)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to marshal schema: %v", err)
}
s = updateRefs(s, newPackageName, args.Module, args.Version)
newMetadata, err = updateMetadataRefs(newMetadata, newPackageName, args.Module, args.Version)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to update metadata $refs: %v", err)
}
p.schemaBytes = s
p.resourceMap = newMetadata
p.name = newPackageName
p.converter.Types = newMetadata.Types
if _, found := os.LookupEnv("PULUMI_DEBUG_PARAMETERIZE"); found {
tmpPath := filepath.Join(os.TempDir(), newPackageName+".json")
err = os.WriteFile(tmpPath, s, 0644)
if err != nil {
logging.Infof("failed to write PULUMI_DEBUG_PARAMETERIZE schema to %s: %v", tmpPath, err)
} else {
logging.Infof("wrote PULUMI_DEBUG_PARAMETERIZE schema to %s", tmpPath)
}
}
resp := &rpc.ParameterizeResponse{
Name: newPackageName,
Version: newSchema.Version,
}
return resp, nil
}
const parameterizedNameSeparator = "_"
func generateNewPackageName(unparameterizedPackageName, targetModule, targetApiVersion string) string {
return strings.Join([]string{unparameterizedPackageName, targetModule, targetApiVersion}, parameterizedNameSeparator)
}
// updateRefs updates all `$ref` pointers in the serialized schema to use the new package name, e.g., from `"$ref":
// "#/types/azure-native:..."` to `"$ref": "#/types/azure-native_resources_20240101:..."`.
func updateRefs(serialized []byte, newPackageName, module, apiVersion string) []byte {
oldRefPrefix := fmt.Sprintf(`"$ref":"#/types/azure-native:%s/%s`, module, apiVersion)
newRefPrefix := fmt.Sprintf(`"$ref": "#/types/%s:%s`, newPackageName, module)
return bytes.ReplaceAll(serialized, []byte(oldRefPrefix), []byte(newRefPrefix))
}
// updateMetadataRefs updates all `$ref` pointers in the metadata to use the new package name.
// This implementation uses a JSON round-trip to update the `$ref`'s via a global string-replacement. Not elegant, but effective.
func updateMetadataRefs(metadata *resources.APIMetadata, newPackageName, module, apiVersion string) (*resources.APIMetadata, error) {
m, err := json.Marshal(metadata)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to marshal metadata: %v", err)
}
updated := updateRefs(m, newPackageName, module, apiVersion)
newMetadata := &resources.APIMetadata{}
err = json.Unmarshal(updated, newMetadata)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to unmarshal metadata: %v", err)
}
return newMetadata, nil
}
func getAvailableApiVersions(schema pschema.PackageSpec, targetModule string) []string {
versions := map[string]struct{}{}
for resourceName := range schema.Resources {
moduleName, version, _, err := resources.ParseToken(resourceName)
if err != nil {
continue
}
if moduleName == targetModule && version != "" {
versions[version] = struct{}{}
}
}
return util.SortedKeys(versions)
}
// createParameterizedSchemaForApiVersion creates a new schema for the given module and API version by picking the
// required resources, types, and functions from the providers existing schema and metadata. This assumes that the given
// provider has a full schema with all API versions.
//
// There are other ways of obtaining such a schema, for instance, generating it directly from the Azure spec. This way
// was the most pragmatic approach since we already have the full schema in the provider.
//
// All names change because their "module" part needs to match the new schema, and the new package name can't be just
// "azure-native" which already exists.
//
// To separate concerns, the `Parameterization` of the new schema is NOT populated yet, the caller is responsible for
// doing that.
func createSchema(p *azureNativeProvider, schema pschema.PackageSpec, targetModule, targetApiVersion string) (*pschema.PackageSpec, *resources.APIMetadata, error) {
newPackageName := generateNewPackageName(schema.Name, targetModule, targetApiVersion)
newSchema := pschema.PackageSpec{
Name: newPackageName,
Version: schema.Version,
Description: fmt.Sprintf("A specialized Pulumi Azure Native package for %s %s", targetModule, targetApiVersion),
DisplayName: schema.DisplayName,
License: schema.License,
Keywords: schema.Keywords,
Homepage: schema.Homepage,
Publisher: schema.Publisher,
Repository: schema.Repository,
Config: schema.Config,
Provider: schema.Provider,
Language: schema.Language,
Types: map[string]pschema.ComplexTypeSpec{},
Resources: map[string]pschema.ResourceSpec{},
Functions: map[string]pschema.FunctionSpec{},
}
makeToken := func(name string) string {
return fmt.Sprintf("%s:%s:%s", newPackageName, targetModule, name)
}
typeNames, err := filterTokens(schema.Types, targetModule, targetApiVersion)
if err != nil {
return nil, nil, status.Errorf(codes.InvalidArgument, "failed to parse type token: %v", err)
}
resourceNames, err := filterTokens(schema.Resources, targetModule, targetApiVersion)
if err != nil {
return nil, nil, status.Errorf(codes.InvalidArgument, "failed to parse resource token: %v", err)
}
functionNames, err := filterTokens(schema.Functions, targetModule, targetApiVersion)
if err != nil {
return nil, nil, status.Errorf(codes.InvalidArgument, "failed to parse function token: %v", err)
}
logging.V(9).Infof("Creating parameterized Azure Native for %s %s: found %d types, %d resources, %d functions",
targetModule, targetApiVersion, len(typeNames), len(resourceNames), len(functionNames))
if len(resourceNames) == 0 {
availableVersions := getAvailableApiVersions(schema, targetModule)
if len(availableVersions) == 0 {
return nil, nil, status.Errorf(codes.InvalidArgument, "module %s not found. Some modules were renamed in v3 of the provider; "+
"please see https://www.pulumi.com/registry/packages/azure-native/from-v2-to-v3/#new-module-structure-and-naming-aligned-closer-to-azure-sdks.",
targetModule)
}
return nil, nil, status.Errorf(codes.InvalidArgument, "no resources found for module %s at API version %s. Available API versions: %s",
targetModule, targetApiVersion, strings.Join(availableVersions, ", "))
}
metadataTypes := map[string]resources.AzureAPIType{}
metadataResources := map[string]resources.AzureAPIResource{}
metadataInvokes := map[string]resources.AzureAPIInvoke{}
for typeTok, typeName := range typeNames {
newTok := makeToken(typeName)
newSchema.Types[newTok] = schema.Types[typeTok]
apiType, ok, err := p.lookupType(typeTok)
if err != nil {
return nil, nil, status.Errorf(codes.InvalidArgument, "failed to get type %s: %v", typeName, err)
}
if !ok {
logging.Warningf("type %s not found in metadata", typeName)
} else {
metadataTypes[newTok] = *apiType
}
}
for resourceTok, resourceName := range resourceNames {
newTok := makeToken(resourceName)
schemaResource := schema.Resources[resourceTok]
newSchema.Resources[newTok] = schemaResource
resource, ok, err := p.resourceMap.Resources.Get(resourceTok)
if err != nil {
return nil, nil, status.Errorf(codes.InvalidArgument, "failed to get type %s: %v", resourceName, err)
}
if !ok {
logging.Warningf("resource %s not found in metadata", resourceName)
} else {
metadataResources[newTok] = resource
}
}
for functionTok, functionName := range functionNames {
newTok := makeToken(functionName)
newSchema.Functions[newTok] = schema.Functions[functionTok]
invoke, ok, err := p.resourceMap.Invokes.Get(functionTok)
if err != nil {
return nil, nil, status.Errorf(codes.InvalidArgument, "failed to get type %s: %v", functionName, err)
}
if !ok {
logging.Warningf("function %s not found in metadata", functionName)
} else {
metadataInvokes[newTok] = invoke
}
}
metadata := &resources.APIMetadata{
Types: resources.GoMap[resources.AzureAPIType](metadataTypes),
Resources: resources.GoMap[resources.AzureAPIResource](metadataResources),
Invokes: resources.GoMap[resources.AzureAPIInvoke](metadataInvokes),
}
return &newSchema, metadata, nil
}
// filterTokens returns a map of tokens that match the target module and API version.
func filterTokens[T any](tokens map[string]T, targetModule, targetApiVersion string) (map[string]string, error) {
typeNames := map[string]string{}
for token := range tokens {
moduleName, version, name, err := resources.ParseToken(token)
if err != nil {
return nil, err
}
if !strings.EqualFold(moduleName, targetModule) || version != targetApiVersion {
continue
}
typeNames[token] = name
}
return typeNames, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/auth_getclientconfig.go | provider/pkg/provider/auth_getclientconfig.go | // Copyright 2016-2025, Pulumi Corporation.
package provider
import (
"context"
"fmt"
"net/url"
"strings"
azpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
auth "github.com/microsoftgraph/msgraph-sdk-go-core/authentication"
"github.com/microsoftgraph/msgraph-sdk-go/serviceprincipals"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
// ClientConfig represents the provider's Azure client configuration, including the Azure environment,
// client identity, and target subscription.
type ClientConfig struct {
Cloud cloud.Configuration
ClientID string
ObjectID string
SubscriptionID string
TenantID string
AuthenticatedAsAServicePrincipal bool
}
// GetClientConfig resolves the provider's identity given the auth configuration and a TokenCredential.
// It returns a ClientConfig which contains the client ID, object ID, subscription ID, tenant.
func GetClientConfig(ctx context.Context, config *authConfiguration, cred *azAccount) (*ClientConfig, error) {
// The original specification for what constitutes the "client configuration" is from here:
// https://github.com/hashicorp/terraform-provider-azurerm/blob/572bb4f37d73f4f0d914737eaca4e5a1fd084c86/internal/clients/auth.go#L33
endpoint := cred.Cloud.Endpoints.MicrosoftGraph
if endpoint == "" {
return nil, errors.New("The provider configuration must include a value for microsoftGraphEndpoint")
}
endpointUrl, err := url.Parse(endpoint)
if err != nil {
return nil, fmt.Errorf("could not parse microsoftGraphEndpoint: %w", err)
}
logging.V(9).Infof("MSGraph endpoint: %s", endpointUrl)
// Acquire an access token so we can inspect the claims.
// note on scopes: https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#trailing-slash-and-default
scope := fmt.Sprintf("%s/.default", endpoint)
token, err := cred.GetToken(ctx, azpolicy.TokenRequestOptions{
Scopes: []string{scope},
})
if err != nil {
return nil, fmt.Errorf("could not acquire access token to parse claims: %+v", err)
}
tokenClaims, err := azure.ParseClaims(token)
if err != nil {
return nil, fmt.Errorf("parsing claims from access token: %+v", err)
}
authenticatedAsServicePrincipal := true
if strings.Contains(strings.ToLower(tokenClaims.Scopes), "openid") {
authenticatedAsServicePrincipal = false
}
clientId := tokenClaims.AppId
if clientId == "" {
logging.V(9).Infof("Using user-supplied ClientID because the `appid` claim was missing from the access token")
clientId = config.clientId
}
objectId := tokenClaims.ObjectId
if objectId == "" {
// Initialize an MS Graph client for the target cloud
authProvider, err := auth.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{scope})
if err != nil {
return nil, err
}
adapter, err := msgraphsdk.NewGraphRequestAdapter(authProvider)
if err != nil {
return nil, err
}
adapter.SetBaseUrl(endpointUrl.JoinPath("/v1.0").String())
client := msgraphsdk.NewGraphServiceClient(adapter)
// Lookup the object ID
if authenticatedAsServicePrincipal {
logging.V(9).Infof("Querying Microsoft Graph to discover authenticated service principal object ID because the `oid` claim was missing from the access token")
id, err := servicePrincipalObjectID(ctx, client, clientId)
if err != nil {
return nil, fmt.Errorf("attempting to discover object ID for authenticated service principal with client ID %q: %w", clientId, err)
}
objectId = *id
} else {
logging.V(9).Infof("Querying Microsoft Graph to discover authenticated user principal object ID because the `oid` claim was missing from the access token")
id, err := userPrincipalObjectID(ctx, client)
if err != nil {
return nil, fmt.Errorf("attempting to discover object ID for authenticated user principal: %w", err)
}
objectId = *id
}
}
tenantId := tokenClaims.TenantId
if tenantId == "" {
logging.V(9).Infof("Using user-supplied TenantID because the `tid` claim was missing from the access token")
tenantId = config.tenantId
}
account := &ClientConfig{
Cloud: cred.Cloud,
ClientID: clientId,
ObjectID: objectId,
SubscriptionID: cred.SubscriptionId,
TenantID: tenantId,
AuthenticatedAsAServicePrincipal: authenticatedAsServicePrincipal,
}
return account, nil
}
func servicePrincipalObjectID(ctx context.Context, client *msgraphsdk.GraphServiceClient, clientId string) (*string, error) {
filter := fmt.Sprintf("appId eq '%s'", clientId)
response, err := client.ServicePrincipals().Get(ctx, &serviceprincipals.ServicePrincipalsRequestBuilderGetRequestConfiguration{
QueryParameters: &serviceprincipals.ServicePrincipalsRequestBuilderGetQueryParameters{
Filter: &filter,
},
})
if err != nil {
return nil, fmt.Errorf("executing request: %w", err)
}
principals := response.GetValue()
if len(principals) != 1 {
return nil, fmt.Errorf("unexpected number of results, expected 1, received %d", len(principals))
}
id := principals[0].GetId()
if id == nil {
return nil, errors.New("returned object ID was nil")
}
return id, nil
}
func userPrincipalObjectID(ctx context.Context, client *msgraphsdk.GraphServiceClient) (*string, error) {
me, err := client.Me().Get(ctx, nil)
if err != nil {
return nil, fmt.Errorf("executing request: %w", err)
}
if me.GetId() == nil {
return nil, fmt.Errorf("returned object ID was nil")
}
return me.GetId(), nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/diff.go | provider/pkg/provider/diff.go | // Copyright 2016-2020, Pulumi Corporation.
package provider
import (
"fmt"
"log"
"os"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"github.com/davegardnerisme/deephash"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/version"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
rpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
)
const body = "body"
func ignoreKey(key resource.PropertyKey) bool {
return strings.HasPrefix(string(key), "__")
}
// mapProperties traverses the given APIResource and creates a map from all properties, including
// in referenced types, to their property spec. The map key is a JSONPath to the property.
func mapProperties(res resources.AzureAPIResource, lookupType resources.TypeLookupFunc) map[string]resources.AzureAPIProperty {
properties := map[string]resources.AzureAPIProperty{}
for _, p := range res.PutParameters {
if p.Location == body && p.Body != nil {
resources.TraverseProperties(p.Body.Properties, lookupType,
false, // don't include flattened containers, we're comparing the SDK shape
func(name string, prop resources.AzureAPIProperty, path []string) {
path = append(path, name)
jsonPath := strings.Join(path, ".")
properties[jsonPath] = prop
})
}
}
return properties
}
// diff is the provider's main entry point to diffing resources.
func diff(lookupType resources.TypeLookupFunc,
res resources.AzureAPIResource,
oldInputs, newInputs resource.PropertyMap) map[string]*rpc.PropertyDiff {
properties := mapProperties(res, lookupType)
// This JSONPath will be updated as we traverse the inputs, to look up properties in the above
// `properties` map.
path := ""
diff := objectDiff(properties, oldInputs, newInputs, path)
if diff == nil {
return nil
}
// Calculate the detailed diff object containing information about replacements.
return calculateDetailedDiff(&res, lookupType, diff)
}
func objectDiff(properties map[string]resources.AzureAPIProperty,
oldInputs, newInputs resource.PropertyMap,
path string) *resource.ObjectDiff {
adds := make(resource.PropertyMap)
deletes := make(resource.PropertyMap)
sames := make(resource.PropertyMap)
updates := make(map[resource.PropertyKey]resource.ValueDiff)
addToPath := func(p string, key resource.PropertyKey) string {
if p == "" {
return string(key)
}
return p + "." + string(key)
}
// First find any updates or deletes.
for k, old := range oldInputs {
if ignoreKey(k) {
continue
}
if new, has := newInputs[k]; has {
// If a new exists, use it; for output properties, however, ignore differences.
if new.IsOutput() {
sames[k] = old
} else if diff := valueDiff(properties, old, new, addToPath(path, k)); diff != nil {
if !old.HasValue() {
adds[k] = new
} else if !new.HasValue() {
deletes[k] = old
} else {
updates[k] = *diff
}
} else {
sames[k] = old
}
} else if old.HasValue() {
// If there was no new property, it has been deleted.
deletes[k] = old
}
}
// Next find any additions not in the old map.
for k, new := range newInputs {
if ignoreKey(k) {
continue
}
if _, has := oldInputs[k]; !has && new.HasValue() {
adds[k] = new
}
}
// If no diffs were found, return nil; else return a diff structure.
if len(adds) == 0 && len(deletes) == 0 && len(updates) == 0 {
return nil
}
return &resource.ObjectDiff{
Adds: adds,
Deletes: deletes,
Sames: sames,
Updates: updates,
}
}
func valueDiff(properties map[string]resources.AzureAPIProperty,
old, new resource.PropertyValue,
path string) *resource.ValueDiff {
if old.IsArray() && new.IsArray() {
oldArr := old.ArrayValue()
newArr := new.ArrayValue()
prop, ok := properties[path]
if ok && len(prop.ArrayIdentifiers) > 0 {
result, ok := diffKeyedArrays(properties, prop.ArrayIdentifiers, oldArr, newArr, path)
if ok {
return result
}
log.Printf("WARNING: arrays at %s have identifiers specified but could not be parsed as keyed arrays", path)
}
// If any elements exist in the new array but not the old, track them as adds.
adds := make(map[int]resource.PropertyValue)
for i := len(oldArr); i < len(newArr); i++ {
adds[i] = newArr[i]
}
// If any elements exist in the old array but not the new, track them as adds.
deletes := make(map[int]resource.PropertyValue)
for i := len(newArr); i < len(oldArr); i++ {
deletes[i] = oldArr[i]
}
// Now if elements exist in both, track them as sames or updates.
sames := make(map[int]resource.PropertyValue)
updates := make(map[int]resource.ValueDiff)
for i := 0; i < len(oldArr) && i < len(newArr); i++ {
if diff := valueDiff(properties, oldArr[i], newArr[i], path); diff != nil {
updates[i] = *diff
} else {
sames[i] = oldArr[i]
}
}
if len(adds) == 0 && len(deletes) == 0 && len(updates) == 0 {
return nil
}
return &resource.ValueDiff{
Old: old,
New: new,
Array: &resource.ArrayDiff{
Adds: adds,
Deletes: deletes,
Sames: sames,
Updates: updates,
},
}
}
if old.IsObject() && new.IsObject() {
oldObj := old.ObjectValue()
newObj := new.ObjectValue()
if diff := objectDiff(properties, oldObj, newObj, path); diff != nil {
return &resource.ValueDiff{
Old: old,
New: new,
Object: diff,
}
}
return nil
}
if old.IsString() && new.IsString() {
if stringsEqualCaseInsensitiveAzureIds(old.StringValue(), new.StringValue()) {
return nil
}
}
// If we got here, either the values are primitives, or they weren't the same type; do a simple diff.
if old.DeepEquals(new) {
return nil
}
return &resource.ValueDiff{Old: old, New: new}
}
// azureIdRegex is a regular expression that matches Azure resource IDs.
var azureIdRegex = regexp.MustCompile(`(?i)(/subscriptions/.+?/resourcegroups/.+?/providers/microsoft.+?/)(.*)`)
// stringsEqualCaseInsensitiveAzureIds compares two strings for equality. If they look like Azure
// resource IDs, the common prefix `/subscriptions/.+?/resourcegroups/.+?/providers/microsoft.+?/`
// is compared case-insensitively. The rest is compared case-sensitively since we cannot know if
// names of various resource providers are case-insensitive. If the strings don't look like Azure
// resource IDs, they are compared using regular `==` string comparison.
func stringsEqualCaseInsensitiveAzureIds(a, b string) bool {
// Compare plain strings first to save the regex matching cost
if a == b {
return true
}
matchesA := azureIdRegex.FindStringSubmatch(a)
if len(matchesA) > 0 {
matchesB := azureIdRegex.FindStringSubmatch(b)
if len(matchesB) > 0 {
return strings.EqualFold(matchesA[1], matchesB[1]) && matchesA[2] == matchesB[2]
}
}
return false
}
// normalizeAzureId normalizes an Azure resource ID by lowercasing the common prefix
// `/subscriptions/.+?/resourcegroups/.+?/providers/microsoft.+?/`. If the string doesn't look like
// an Azure resource ID, it is returned unchanged.
func normalizeAzureId(id string) string {
match := azureIdRegex.FindStringSubmatch(id)
if len(match) > 0 {
return strings.ToLower(match[1]) + match[2]
}
return id
}
// calculateDetailedDiff produced a property diff for a given object diff and a resource definition. It inspects
// the schema of the resource to find out if the requested diff can be performed in-place or requires a replacement.
func calculateDetailedDiff(resource *resources.AzureAPIResource, lookupType resources.TypeLookupFunc,
diff *resource.ObjectDiff) map[string]*rpc.PropertyDiff {
replaceKeys := codegen.NewStringSet()
for _, p := range resource.PutParameters {
// All the parameters that are part of the resource path cause a replacement.
if p.Location == "path" {
name := p.Name
if p.Value != nil && p.Value.SdkName != "" {
name = p.Value.SdkName
}
replaceKeys.Add(name)
}
// Force New on resource properties also cause a replacement.
if p.Location == body && p.Body != nil {
// Top-level properties.
findForceNew("", p.Body.Properties, replaceKeys)
for propName, prop := range p.Body.Properties {
// Object types.
if prop.Ref != "" {
if typ, has, err := lookupType(prop.Ref); has && err == nil {
findForceNew(propName+".", typ.Properties, replaceKeys)
}
}
// Arrays of objects.
if prop.Items != nil && prop.Items.Ref != "" {
if typ, has, err := lookupType(prop.Items.Ref); has && err == nil {
findForceNew(propName+"[].", typ.Properties, replaceKeys)
}
}
}
}
}
applyAzureSpecificDiff(diff)
d := differ{replaceKeys: replaceKeys}
return d.calculateObjectDiff(diff, "", "")
}
func findForceNew(base string, props map[string]resources.AzureAPIProperty, replaceKeys codegen.StringSet) {
var forceNewFromSubtypes bool
if v, ok := os.LookupEnv("PULUMI_FORCE_NEW_FROM_SUBTYPES"); ok {
forceNewFromSubtypes, _ = strconv.ParseBool(v)
} else {
// https://github.com/pulumi/pulumi-azure-native/issues/3006
forceNewFromSubtypes = version.GetVersion().Major >= 3
}
for propName, prop := range props {
if prop.ForceNew || (prop.ForceNewInferredFromReferencedTypes && forceNewFromSubtypes) {
name := propName
if prop.SdkName != "" {
name = prop.SdkName
}
replaceKeys.Add(base + name)
}
}
}
type differ struct {
replaceKeys codegen.StringSet
}
func quotePropertyKeyForDetailedDiff(key resource.PropertyKey) string {
str := string(key)
if strings.Contains(str, ".") {
return "[\"" + str + "\"]"
}
return str
}
func (d *differ) calculateObjectDiff(diff *resource.ObjectDiff, diffBase, replaceBase string) map[string]*rpc.PropertyDiff {
detailedDiff := map[string]*rpc.PropertyDiff{}
for k, v := range diff.Updates {
key := diffBase + quotePropertyKeyForDetailedDiff(k)
subDiff := d.calculateValueDiff(&v, key, replaceBase+string(k))
for sk, sv := range subDiff {
detailedDiff[sk] = sv
}
}
for k := range diff.Adds {
diffKey := diffBase + quotePropertyKeyForDetailedDiff(k)
replaceKey := replaceBase + string(k)
kind := rpc.PropertyDiff_ADD
if d.replaceKeys.Has(replaceKey) {
kind = rpc.PropertyDiff_ADD_REPLACE
}
detailedDiff[diffKey] = &rpc.PropertyDiff{Kind: kind}
}
for k := range diff.Deletes {
diffKey := diffBase + quotePropertyKeyForDetailedDiff(k)
replaceKey := replaceBase + string(k)
kind := rpc.PropertyDiff_DELETE
if d.replaceKeys.Has(replaceKey) {
kind = rpc.PropertyDiff_DELETE_REPLACE
}
detailedDiff[diffKey] = &rpc.PropertyDiff{Kind: kind}
}
return detailedDiff
}
func (d *differ) calculateValueDiff(v *resource.ValueDiff, diffBase, replaceBase string) map[string]*rpc.PropertyDiff {
detailedDiff := map[string]*rpc.PropertyDiff{}
switch {
case v.Object != nil:
objectNeedsReplace := d.replaceKeys.Has(replaceBase)
subDiff := d.calculateObjectDiff(v.Object, diffBase+".", replaceBase+".")
for sk, sv := range subDiff {
if sv.Kind == rpc.PropertyDiff_UPDATE && objectNeedsReplace {
// If the parent property causes a replacement, all child properties cause a replacement.
sv.Kind = rpc.PropertyDiff_UPDATE_REPLACE
}
detailedDiff[sk] = sv
}
// Any addition or removal of properties to an object marked as ForceNew causes its replacement.
for _, sv := range subDiff {
if (sv.Kind == rpc.PropertyDiff_ADD || sv.Kind == rpc.PropertyDiff_DELETE) && objectNeedsReplace {
detailedDiff[diffBase] = &rpc.PropertyDiff{Kind: rpc.PropertyDiff_UPDATE_REPLACE}
break
}
}
case v.Array != nil:
for idx, item := range v.Array.Updates {
key := fmt.Sprintf("%s[%d]", diffBase, idx)
subDiff := d.calculateValueDiff(&item, key, replaceBase+"[]")
for sk, sv := range subDiff {
detailedDiff[sk] = sv
}
}
for idx := range v.Array.Adds {
key := fmt.Sprintf("%s[%d]", diffBase, idx)
detailedDiff[key] = &rpc.PropertyDiff{Kind: rpc.PropertyDiff_ADD}
}
for idx := range v.Array.Deletes {
key := fmt.Sprintf("%s[%d]", diffBase, idx)
detailedDiff[key] = &rpc.PropertyDiff{Kind: rpc.PropertyDiff_DELETE}
}
default:
kind := rpc.PropertyDiff_UPDATE
if d.replaceKeys.Has(replaceBase) {
kind = rpc.PropertyDiff_UPDATE_REPLACE
}
detailedDiff[diffBase] = &rpc.PropertyDiff{Kind: kind}
}
return detailedDiff
}
// applyDiff produces a new map as a merge of a calculated diff into an existing map of values.
// Note that the use case for it is rather specific to the particular Read implementation:
// - values are inputs currently stored in state before Read was called
// - diff is a calculated difference between old and new _outputs_
// So, diff values are independent of the values map. Practically, diff values may contain
// more properties in object maps, and that doesn't necessarily mean we need to copy all of
// them. Instead, we want to copy only the changed properties, and do so recursively.
func applyDiff(values resource.PropertyMap, diff *resource.ObjectDiff) resource.PropertyMap {
if diff == nil {
return values
}
result := resource.PropertyMap{}
for name, value := range values {
if !diff.Deleted(name) {
result[name] = value
}
}
for key, value := range diff.Adds {
result[key] = value
}
for key, update := range diff.Updates {
if value, has := values[key]; has {
result[key] = applyValueDiff(value, update.Old, update.New)
} else {
result[key] = update.New
}
}
return result
}
func applyValueDiff(baseValue resource.PropertyValue, oldValue resource.PropertyValue,
newValue resource.PropertyValue) resource.PropertyValue {
// Objects are compared property-by-property recursively and we only copy the changed sub-properties back.
if baseValue.IsObject() && oldValue.IsObject() && newValue.IsObject() {
subDiff := oldValue.ObjectValue().Diff(newValue.ObjectValue())
result := applyDiff(baseValue.ObjectValue(), subDiff)
return resource.NewObjectProperty(result)
}
// Arrays are compared element-by-element recursively.
if baseValue.IsArray() && oldValue.IsArray() && newValue.IsArray() {
baseValueArray := baseValue.ArrayValue()
oldValueArray := oldValue.ArrayValue()
newValueArray := newValue.ArrayValue()
length := len(newValueArray)
result := make([]resource.PropertyValue, length)
for i, el := range newValueArray {
if i >= len(baseValueArray) || i >= len(oldValueArray) {
// A new element was added, copy as-is.
result[i] = el
continue
}
// Calculate the diff recursively for each element.
result[i] = applyValueDiff(baseValueArray[i], oldValueArray[i], newValueArray[i])
}
return resource.NewArrayProperty(result)
}
// For plain values, just use the new baseValue.
return newValue
}
// applyAzureSpecificDiff modifies a generic diff calculated by the Platform with any
// Azure-specific diffing adjustments.
func applyAzureSpecificDiff(diff *resource.ObjectDiff) {
updates := map[resource.PropertyKey]resource.ValueDiff{}
for k, v := range diff.Updates {
// Apply special diffing logic to some well-known top-level properties.
switch string(k) {
case "resourceGroupName":
// "resourceGroupName" is case-insensitive.
if v.Old.IsString() && v.New.IsString() {
if strings.EqualFold(strings.ToLower(v.Old.StringValue()), v.New.StringValue()) {
continue
}
}
case "location":
// "location" is case- and spaces-insensitive.
if v.Old.IsString() && v.New.IsString() {
if normalizedLocation(v.Old.StringValue()) == normalizedLocation(v.New.StringValue()) {
continue
}
}
case "sku":
// Another special case is "sku" in AKS clusters.
if v.Old.IsObject() && v.New.IsObject() {
if sameManagedClusterSku(v.Old.ObjectValue(), v.New.ObjectValue()) {
continue
}
}
}
updates[k] = v
}
diff.Updates = updates
}
// normalizedLocation converts Azure location values of a format like "West US 2" and
// "WestUS2" to the lowercase and no-space format of "westus2".
func normalizedLocation(location string) string {
return strings.ToLower(strings.ReplaceAll(location, " ", ""))
}
// sameManagedClusterSku checks whether two property maps representing a SKU are
// equivalent in terms of AKS nomenclature.
// See https://github.com/pulumi/pulumi-azure-native/issues/2600
func sameManagedClusterSku(oldMap resource.PropertyMap, newMap resource.PropertyMap) bool {
// Expect exactly two keys: name and tier - in both maps.
if len(oldMap) != 2 || len(newMap) != 2 {
return false
}
// Check that 'name' exists in both.
oldName, hasOld := oldMap["name"]
newName, hasNew := newMap["name"]
if !hasOld || !hasNew || !oldName.IsString() || !newName.IsString() {
return false
}
// Check that 'tier' exists in both.
oldTier, hasOld := oldMap["tier"]
newTier, hasNew := newMap["tier"]
if !hasOld || !hasNew || !oldTier.IsString() || !newTier.IsString() {
return false
}
// Check that name is exactly the same or both are Basic or Base.
sameName := oldName.StringValue() == newName.StringValue() ||
(oldName.StringValue() == "Basic" && newName.StringValue() == "Base") ||
(oldName.StringValue() == "Base" && newName.StringValue() == "Basic")
// Check that tier is exactly the same or both are Paid or Standard.
sameTier := oldTier.StringValue() == newTier.StringValue() ||
(oldTier.StringValue() == "Paid" && newTier.StringValue() == "Standard") ||
(oldTier.StringValue() == "Standard" && newTier.StringValue() == "Paid")
// Return true if both of the above hold.
return sameName && sameTier
}
// calculateChangesAndReplacements compares a property diff with the old and new inputs and the
// previous state. It returns a list of properties that will change, and a list of properties
// that will be replaced. In some cases, entries of the diff may not lead to any change or
// replacement, e.g., new properties set to their default value are not considered changes.
func calculateChangesAndReplacements(
detailedDiff map[string]*rpc.PropertyDiff,
oldInputs, newInputs, oldState resource.PropertyMap,
res resources.AzureAPIResource) ([]string, []string) {
var changes, replaces []string
for k, v := range detailedDiff {
switch v.Kind {
case rpc.PropertyDiff_ADD_REPLACE:
// Special case: previously, the property input had no value but is now set to X.
// If the output contains this property and it's X, that's not a replacement.
// Workaround for https://github.com/pulumi/pulumi-azure-nextgen/issues/238
// TODO: remove this block before GA.
key := resource.PropertyKey(k)
_, hasOldInput := oldInputs[key]
newInputValue, hasNewInput := newInputs[key]
outputValue, hasOutput := oldState[key]
if !hasOldInput && hasNewInput && hasOutput && reflect.DeepEqual(newInputValue, outputValue) {
v.Kind = rpc.PropertyDiff_ADD
} else {
replaces = append(replaces, k)
}
case rpc.PropertyDiff_ADD:
key := resource.PropertyKey(k)
_, hasOldInput := oldInputs[key]
newInputValue, hasNewInput := newInputs[key]
if !hasOldInput && hasNewInput {
// If this is a new property that is merely being initialized with its default
// value, we don't need to show a noisy diff.
prop, found := res.LookupProperty(k)
if found && prop.Default != nil && reflect.DeepEqual(newInputValue.V, prop.Default) {
logging.V(9).Infof("Skipping diff for %s, property with default value %v is added", k, newInputValue)
continue
}
}
case rpc.PropertyDiff_DELETE_REPLACE, rpc.PropertyDiff_UPDATE_REPLACE:
replaces = append(replaces, k)
}
changes = append(changes, reducePropertyPathToTopLevelKey(k))
v.InputDiff = true
}
return changes, replaces
}
// agentPoolProfiles.count -> agentPoolProfiles
// agentPoolProfiles[0] -> agentPoolProfiles
// agentPoolProfiles[0].count -> agentPoolProfiles
func reducePropertyPathToTopLevelKey(path string) string {
topLevelChange := strings.Split(path, ".")[0]
return strings.Split(topLevelChange, "[")[0]
}
// arrayElement is a helper struct to track the index of a property value in an array.
type arrayElement struct {
element resource.PropertyValue
index int
}
// diffKeyedArrays compares two arrays that are annotated in the API spec with the extension
// "x-ms-identifiers" and behave more like sets. The combined `keys` form a unique identifier for
// the array elements, so order doesn't matter.
func diffKeyedArrays(properties map[string]resources.AzureAPIProperty,
keys []string,
old, new []resource.PropertyValue,
path string) (*resource.ValueDiff, bool) {
adds := make(map[int]resource.PropertyValue)
deletes := make(map[int]resource.PropertyValue)
sames := make(map[int]resource.PropertyValue)
updates := make(map[int]resource.ValueDiff)
sortedKeys := sort.StringSlice(keys) // for stable map keys
oldIdValues := map[string]arrayElement{}
for i, oldItem := range old {
hash, ok := checkAndHashObject(oldItem, sortedKeys)
if !ok {
return nil, false
}
oldIdValues[hash] = arrayElement{element: oldItem, index: i}
}
newSeen := map[string]struct{}{}
for i, newItem := range new {
hash, ok := checkAndHashObject(newItem, sortedKeys)
if !ok {
return nil, false
}
if _, ok := newSeen[hash]; ok {
logging.V(9).Infof("WARNING: diffKeyedArray: duplicate key values, treating as normal array\n")
return nil, false
}
newSeen[hash] = struct{}{}
oldItem, ok := oldIdValues[hash]
if !ok {
adds[i] = newItem
} else {
diff := valueDiff(properties, oldItem.element, newItem, path)
if diff == nil {
sames[i] = newItem
} else if diff.Object != nil || diff.Array != nil {
updates[i] = *diff
}
}
}
// Check for olds that are gone
for oldHash, oldEntry := range oldIdValues {
if _, ok := newSeen[oldHash]; !ok {
deletes[oldEntry.index] = oldEntry.element
}
}
if len(adds) == 0 && len(deletes) == 0 && len(updates) == 0 {
return nil, true
}
return &resource.ValueDiff{
Old: resource.NewPropertyValue(old),
New: resource.NewPropertyValue(new),
Array: &resource.ArrayDiff{
Adds: adds,
Deletes: deletes,
Sames: sames,
Updates: updates,
},
}, true
}
// hashObject computes a deep hash of an object value using the object's property values indexed by
// the given keys. The second "ok" return value is false if the value is not actually an object or
// doesn't have any of the keys. In that case, the keyed array diff cannot be applied.
func checkAndHashObject(val resource.PropertyValue, sortedKeys []string) (string, bool) {
if !val.IsObject() {
logging.V(9).Infof("WARNING: diffKeyedArray: item %v is not an object\n", val)
return "", false
}
obj := val.ObjectValue()
idValues := make([]any, 0, len(sortedKeys))
for _, key := range sortedKeys {
if val, ok := obj[resource.PropertyKey(key)]; ok {
if val.IsString() {
val = resource.NewPropertyValue(normalizeAzureId(val.StringValue()))
}
idValues = append(idValues, val)
}
}
if len(idValues) == 0 {
logging.V(9).Infof("WARNING: diffKeyedArray: item %v has none of the keys\n", obj)
return "", false
}
return string(deephash.Hash(idValues)[:]), true
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/autonaming_test.go | provider/pkg/provider/autonaming_test.go | // Copyright 2016-2024, Pulumi Corporation.
package provider
import (
"context"
"testing"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"github.com/stretchr/testify/assert"
)
func TestGetDefaultName(t *testing.T) {
t.Parallel()
p := &azureNativeProvider{}
const testUrn = "urn:pulumi:stack::project::azure-native:storage:StorageAccount::test"
testSeed := []byte("seed")
t.Run("returns old name if exists", func(t *testing.T) {
oldName := resource.NewStringProperty("existing-name")
olds := resource.PropertyMap{
"name": oldName,
}
result, randomlyNamed, ok := p.getDefaultName(
testUrn,
testSeed,
nil,
resources.AutoNameRandom,
"name",
olds,
)
assert.True(t, ok)
assert.False(t, randomlyNamed)
assert.Equal(t, &oldName, result)
})
t.Run("returns old name and createBeforeDelete if flag exists", func(t *testing.T) {
oldName := resource.NewStringProperty("existing-name")
olds := resource.PropertyMap{
"name": oldName,
createBeforeDeleteFlag: resource.NewBoolProperty(true),
}
result, randomlyNamed, ok := p.getDefaultName(
testUrn,
testSeed,
nil,
resources.AutoNameRandom,
"name",
olds,
)
assert.True(t, ok)
assert.True(t, randomlyNamed)
assert.Equal(t, &oldName, result)
})
t.Run("fails if auto-naming is disabled", func(t *testing.T) {
result, _, ok := p.getDefaultName(
testUrn,
testSeed,
&pulumirpc.CheckRequest_AutonamingOptions{
Mode: pulumirpc.CheckRequest_AutonamingOptions_DISABLE,
},
resources.AutoNameRandom,
"name",
resource.PropertyMap{},
)
assert.False(t, ok)
assert.Nil(t, result)
})
t.Run("returns proposed name for enforce mode", func(t *testing.T) {
result, randomlyNamed, ok := p.getDefaultName(
testUrn,
testSeed,
&pulumirpc.CheckRequest_AutonamingOptions{
Mode: pulumirpc.CheckRequest_AutonamingOptions_ENFORCE,
ProposedName: "proposed-uuid-name",
},
resources.AutoNameUuid, // UUID would otherwise take priority over proposed name
"name",
resource.PropertyMap{},
)
assert.True(t, ok)
assert.True(t, randomlyNamed)
assert.Equal(t, "proposed-uuid-name", result.StringValue())
})
t.Run("returns URN name for copy strategy without auto-naming options", func(t *testing.T) {
result, randomlyNamed, ok := p.getDefaultName(
testUrn,
testSeed,
nil,
resources.AutoNameCopy,
"name",
resource.PropertyMap{},
)
assert.True(t, ok)
assert.False(t, randomlyNamed)
assert.Equal(t, "test", result.StringValue())
})
t.Run("returns random name for random strategy without auto-naming options", func(t *testing.T) {
result, randomlyNamed, ok := p.getDefaultName(
testUrn,
testSeed,
nil,
resources.AutoNameRandom,
"name",
resource.PropertyMap{},
)
assert.True(t, ok)
assert.True(t, randomlyNamed)
assert.Equal(t, "test614742c2", result.StringValue())
})
t.Run("returns proposed name for random strategy with propose mode", func(t *testing.T) {
result, randomlyNamed, ok := p.getDefaultName(
testUrn,
testSeed,
&pulumirpc.CheckRequest_AutonamingOptions{
Mode: pulumirpc.CheckRequest_AutonamingOptions_PROPOSE,
ProposedName: "proposed-random-name",
},
resources.AutoNameRandom,
"name",
resource.PropertyMap{},
)
assert.True(t, ok)
assert.True(t, randomlyNamed)
assert.Equal(t, "proposed-random-name", result.StringValue())
})
t.Run("returns proposed name for copy strategy with propose mode", func(t *testing.T) {
result, randomlyNamed, ok := p.getDefaultName(
testUrn,
testSeed,
&pulumirpc.CheckRequest_AutonamingOptions{
Mode: pulumirpc.CheckRequest_AutonamingOptions_PROPOSE,
ProposedName: "proposed-copy-name",
},
resources.AutoNameCopy,
"name",
resource.PropertyMap{},
)
assert.True(t, ok)
assert.True(t, randomlyNamed)
assert.Equal(t, "proposed-copy-name", result.StringValue())
})
t.Run("returns UUID for UUID strategy with propose mode", func(t *testing.T) {
result, randomlyNamed, ok := p.getDefaultName(
testUrn,
testSeed,
&pulumirpc.CheckRequest_AutonamingOptions{
Mode: pulumirpc.CheckRequest_AutonamingOptions_PROPOSE,
ProposedName: "proposed-uuid-name",
},
resources.AutoNameUuid,
"name",
resource.PropertyMap{},
)
assert.True(t, ok)
assert.True(t, randomlyNamed)
assert.Equal(t, "614742c2-d31f-db71-69aa-0171258e619a", result.StringValue())
})
}
func TestCheck_AutoNaming(t *testing.T) {
t.Parallel()
p := &azureNativeProvider{}
const testUrn = "urn:pulumi:stack::project::azure-native:storage:StorageAccount::test"
t.Run("applies auto-naming when enabled", func(t *testing.T) {
// Setup resource metadata
p.resourceMap = &resources.APIMetadata{
Resources: func() *resources.PartialMap[resources.AzureAPIResource] {
m := resources.NewPartialMap[resources.AzureAPIResource]()
m.UnmarshalJSON([]byte(`{
"azure-native:storage:StorageAccount": {
"apiVersion": "2021-01-01",
"PUT": [{
"name": "name",
"value": {
"autoName": "random"
}
}]
}
}`))
return &m
}(),
}
// Call Check with auto-naming options
resp, err := p.Check(context.Background(), &pulumirpc.CheckRequest{
Urn: testUrn,
News: &structpb.Struct{}, // Empty inputs
Olds: &structpb.Struct{}, // Empty old state
RandomSeed: []byte("seed"),
Autonaming: &pulumirpc.CheckRequest_AutonamingOptions{
Mode: pulumirpc.CheckRequest_AutonamingOptions_ENFORCE,
ProposedName: "proposed-name",
},
})
// Verify the response
assert.NoError(t, err)
inputs, err := plugin.UnmarshalProperties(resp.Inputs, plugin.MarshalOptions{})
assert.NoError(t, err)
assert.Equal(t, "proposed-name", inputs["name"].StringValue())
assert.True(t, inputs[createBeforeDeleteFlag].BoolValue())
})
t.Run("returns error when auto-naming is disabled", func(t *testing.T) {
// Setup resource metadata
p.resourceMap = &resources.APIMetadata{
Resources: func() *resources.PartialMap[resources.AzureAPIResource] {
m := resources.NewPartialMap[resources.AzureAPIResource]()
m.UnmarshalJSON([]byte(`{
"azure-native:storage:StorageAccount": {
"apiVersion": "2021-01-01",
"PUT": [{
"name": "name",
"required": true,
"value": {
"autoName": "random"
}
}]
}
}`))
return &m
}(),
}
// Call Check with auto-naming disabled
resp, err := p.Check(context.Background(), &pulumirpc.CheckRequest{
Urn: testUrn,
News: &structpb.Struct{}, // Empty inputs
Olds: &structpb.Struct{}, // Empty old state
RandomSeed: []byte("seed"),
Autonaming: &pulumirpc.CheckRequest_AutonamingOptions{
Mode: pulumirpc.CheckRequest_AutonamingOptions_DISABLE,
},
})
// Verify the error
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.Len(t, resp.Failures, 1)
assert.Contains(t, resp.Failures[0].Reason, "missing required property 'name'")
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/auth.go | provider/pkg/provider/auth.go | // Copyright 2016-2022, Pulumi Corporation.
package provider
import (
"bytes"
"encoding/json"
"fmt"
"os/exec"
"strings"
goversion "github.com/hashicorp/go-version"
)
func getAzVersion() (*goversion.Version, error) {
_, err := exec.LookPath("az")
if err != nil {
return nil, fmt.Errorf("could not find `az`: %w", err)
}
var azVersion struct {
Cli string `json:"azure-cli"`
}
err = runAzCmd(&azVersion, "version")
if err != nil {
return nil, fmt.Errorf("could not determine az version: %w", err)
}
actual, err := goversion.NewVersion(azVersion.Cli)
if err != nil {
return nil, fmt.Errorf("could not parse az version \"%q\": %w", azVersion.Cli, err)
}
return actual, nil
}
func assertAzVersion(version *goversion.Version) error {
const versionHint = `Please make sure that the Azure CLI is installed in a version of at least 2.37 but less than
3.x; or configure another authentication method. See
https://www.pulumi.com/registry/packages/azure-native/installation-configuration/#credentials
for more information.`
// We need this version because it doesn't print the error of #1565
versionRange := goversion.MustConstraints(goversion.NewConstraint(">=2.37.0, <3"))
if !versionRange.Check(version) {
return fmt.Errorf("found incompatible az version %s. %s", version, versionHint)
}
return nil
}
// Run `az` with the given args and unmarshal the output into the given target struct.
// The `az` output is always in JSON, requested via `--output json`.
func runAzCmd(target interface{}, arg ...string) error {
var stderr bytes.Buffer
var stdout bytes.Buffer
arg = append(arg, "--output", "json")
cmd := exec.Command("az", arg...)
cmd.Stderr = &stderr
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
err := fmt.Errorf("running az: %w", err)
if stdErrStr := stderr.String(); stdErrStr != "" {
err = fmt.Errorf("%s: %s", err, strings.TrimSpace(stdErrStr))
}
return err
}
if err := json.Unmarshal(stdout.Bytes(), target); err != nil {
return fmt.Errorf("unmarshaling the result of Azure CLI: %w", err)
}
return nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/provider_e2e_test.go | provider/pkg/provider/provider_e2e_test.go | // Copyright 2023, Pulumi Corporation. All rights reserved.
// Disable running if we've specifically selected unit tests to run as this is an integration test.
// This is easier than having to remember to explicitly tag every unit test with `//go:build unit || all`.
//go:build !unit
package provider
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/golang-jwt/jwt"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/version"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pulumi/providertest"
"github.com/pulumi/providertest/optproviderupgrade"
"github.com/pulumi/providertest/providers"
"github.com/pulumi/providertest/pulumitest"
"github.com/pulumi/providertest/pulumitest/assertpreview"
"github.com/pulumi/providertest/pulumitest/assertrefresh"
"github.com/pulumi/providertest/pulumitest/changesummary"
"github.com/pulumi/providertest/pulumitest/opttest"
"github.com/pulumi/pulumi/sdk/v3/go/auto"
"github.com/pulumi/pulumi/sdk/v3/go/auto/debug"
"github.com/pulumi/pulumi/sdk/v3/go/auto/optup"
"github.com/pulumi/pulumi/sdk/v3/go/common/apitype"
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
)
var schemaBytes []byte
var azureAPIResourcesBytes []byte
func init() {
var err error
schemaBytes, err = os.ReadFile(filepath.Join("..", "..", "..", "bin", "schema-full.json"))
if err != nil {
fmt.Printf("failed to read schema file, run `make schema` before running tests: %v", err)
}
azureAPIResourcesBytes, err = os.ReadFile(filepath.Join("..", "..", "..", "bin", "metadata-compact.json"))
if err != nil {
fmt.Printf("failed to read metadata file, run `make schema` before running tests: %v", err)
}
}
func TestStorageBlob(t *testing.T) {
t.Parallel()
pt := newPulumiTest(t, "storage-blob")
pt.Preview(t)
pt.Up(t)
assertrefresh.HasNoChanges(t, pt.Refresh(t))
}
func TestApi(t *testing.T) {
t.Parallel()
pt := newPulumiTest(t, "api")
pt.Preview(t)
pt.Up(t)
assertrefresh.HasNoChanges(t, pt.Refresh(t))
}
func TestRequiredContainers(t *testing.T) {
t.Parallel()
pt := newPulumiTest(t, "required-containers")
pt.Preview(t)
pt.Up(t)
assertrefresh.HasNoChanges(t, pt.Refresh(t))
}
func TestSubResources(t *testing.T) {
t.Parallel()
pt := newPulumiTest(t, "subresources")
// deploy an NSG with an "external" security rule, and an NSG with an inline security rule.
up := pt.Up(t)
assert.Len(t, up.Outputs["external-nsg-security-rules"].Value, 0)
assert.Len(t, up.Outputs["inline-nsg-security-rules"].Value, 1)
inlineRule := up.Outputs["inline-nsg-security-rules"].Value.([]any)[0].(map[string]any)
assert.Equal(t, "inline", inlineRule["name"])
// update a tag on the NSGs, and then check that the external security rules are now available as outputs.
pt.SetConfig(t, "subresources:revision", "2")
up = pt.Up(t)
upSummary := changesummary.FromStringIntMap(*up.Summary.ResourceChanges)
assert.Equal(t, 2, upSummary[apitype.OpUpdate])
assert.Len(t, up.Outputs["inline-nsg-security-rules"].Value, 1)
assert.Len(t, up.Outputs["external-nsg-security-rules"].Value, 1)
externalRule := up.Outputs["external-nsg-security-rules"].Value.([]any)[0].(map[string]any)
assert.Equal(t, "external", externalRule["name"])
// check that the state is stable after a refresh.
assertrefresh.HasNoChanges(t, pt.Refresh(t))
}
func TestParallelSubnetCreation(t *testing.T) {
t.Parallel()
pt := newPulumiTest(t, "parallel-subnet-creation")
pt.Preview(t)
pt.Up(t)
assertrefresh.HasNoChanges(t, pt.Refresh(t))
}
func TestAutonaming(t *testing.T) {
t.Parallel()
pt := newPulumiTest(t, "autonaming", opttest.Env("PULUMI_EXPERIMENTAL", "1"))
pt.Preview(t)
up := pt.Up(t)
rgname, ok := up.Outputs["rgname"].Value.(string)
assert.True(t, ok)
assert.Contains(t, rgname, "autonaming-rg-") // project + name + random suffix
saname, ok := up.Outputs["saname"].Value.(string)
assert.True(t, ok)
assert.Contains(t, saname, "autonamingsa") // project + name + random suffix, no dashes
}
func TestTagging(t *testing.T) {
t.Parallel()
pt := newPulumiTest(t, "tagging")
pt.Preview(t)
up := pt.Up(t)
// Verify that the tags were truly applied to the resource groups.
// One must first refresh the state to see the tags applied by the TagAtScope resource.
up = pt.Up(t, optup.Refresh())
rg1Tags, _ := up.Outputs["rg_1_tags"].Value.(map[string]any)
assert.Equal(t, map[string]any{"owner": "tag_1"}, rg1Tags)
rg2Tags, _ := up.Outputs["rg_2_tags"].Value.(map[string]any)
assert.Equal(t, map[string]any{"owner": "tag_2"}, rg2Tags)
}
func TestDefaultAzSubscriptionProvider(t *testing.T) {
if testing.Short() {
t.Skipf("Skipping in testing.Short() mode")
return
}
// AZURE_CONFIG_DIR_FOR_TEST is set by the GH workflow build-test.yml
// to provide an isolated configuration directory for the Azure CLI.
configDir := os.Getenv("AZURE_CONFIG_DIR_FOR_TEST")
if configDir == "" {
if os.Getenv("CI") != "" {
t.Error("CLI test without AZURE_CONFIG_DIR_FOR_TEST")
}
t.Skip("Skipping CLI test without AZURE_CONFIG_DIR_FOR_TEST")
}
t.Setenv("AZURE_CONFIG_DIR", configDir)
ctx := context.Background()
subscription, err := defaultAzSubscriptionProvider(ctx, os.Getenv("ARM_SUBSCRIPTION_ID"))
assert.NoError(t, err)
assert.NotNil(t, subscription)
}
func TestAzidentity(t *testing.T) {
if testing.Short() {
t.Skipf("Skipping in testing.Short() mode")
return
}
validate := func(t *testing.T, up auto.UpResult) (map[string]interface{}, jwt.MapClaims) {
// validate clientConfig
require.Contains(t, up.Outputs, "clientConfig", "expected clientConfig output")
clientConfig, _ := up.Outputs["clientConfig"].Value.(map[string]interface{})
clientConfigJSON, _ := json.Marshal(clientConfig)
t.Logf("clientConfig: %s", clientConfigJSON)
assert.Contains(t, clientConfig, "clientId")
assert.Contains(t, clientConfig, "objectId")
assert.Contains(t, clientConfig, "subscriptionId")
assert.Contains(t, clientConfig, "tenantId")
// validate clientToken
require.Contains(t, up.Outputs, "clientToken", "expected clientToken output")
clientToken, _ := up.Outputs["clientToken"].Value.(map[string]interface{})
claims, err := parseJwtUnverified(clientToken["token"].(string))
require.NoError(t, err)
claimsJSON, _ := json.Marshal(claims)
t.Logf("clientToken: %s", claimsJSON)
return clientConfig, claims
}
t.Run("OIDC", func(t *testing.T) {
oidcClientId := os.Getenv("OIDC_ARM_CLIENT_ID")
if oidcClientId == "" {
t.Skip("Skipping OIDC test without OIDC_ARM_CLIENT_ID")
}
t.Setenv("ARM_USE_OIDC", "true")
t.Setenv("ARM_CLIENT_ID", oidcClientId)
// Make sure we test the OIDC method
t.Setenv("ARM_CLIENT_SECRET", "")
t.Setenv("ARM_CLIENT_CERTIFICATE_PATH", "")
t.Setenv("ARM_CLIENT_CERTIFICATE_PASSWORD", "")
pt := newPulumiTest(t, "azidentity")
up := pt.Up(t)
clientConfig, clientToken := validate(t, up)
assert.Equal(t, os.Getenv("ARM_CLIENT_ID"), clientConfig["clientId"])
assert.Equal(t, os.Getenv("ARM_CLIENT_ID"), clientToken["appid"])
assert.Equal(t, "app", clientToken["idtyp"])
})
t.Run("SP_clientsecret", func(t *testing.T) {
clientSecret := os.Getenv("ARM_CLIENT_SECRET")
if clientSecret == "" {
if os.Getenv("CI") != "" {
t.Error("SP test without ARM_CLIENT_SECRET")
}
t.Skip("Skipping SP test without ARM_CLIENT_SECRET")
}
t.Setenv("ARM_CLIENT_ID", os.Getenv("ARM_CLIENT_ID"))
t.Setenv("ARM_CLIENT_SECRET", clientSecret)
// Make sure we test the client secret method
t.Setenv("ARM_CLIENT_CERTIFICATE_PASSWORD", "")
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "")
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "")
pt := newPulumiTest(t, "azidentity")
up := pt.Up(t)
clientConfig, clientToken := validate(t, up)
assert.Equal(t, os.Getenv("ARM_CLIENT_ID"), clientConfig["clientId"])
assert.Equal(t, os.Getenv("ARM_CLIENT_ID"), clientToken["appid"])
assert.Equal(t, "app", clientToken["idtyp"])
})
t.Run("SP_clientcert", func(t *testing.T) {
certPath := os.Getenv("ARM_CLIENT_CERTIFICATE_PATH_FOR_TEST")
if certPath == "" {
if os.Getenv("CI") != "" {
t.Error("SP test without ARM_CLIENT_CERTIFICATE_PATH_FOR_TEST")
}
t.Skip("Skipping SP test without ARM_CLIENT_CERTIFICATE_PATH_FOR_TEST")
}
t.Setenv("ARM_CLIENT_ID", os.Getenv("ARM_CLIENT_ID"))
t.Setenv("ARM_CLIENT_CERTIFICATE_PATH", certPath)
t.Setenv("ARM_CLIENT_CERTIFICATE_PASSWORD", os.Getenv("ARM_CLIENT_CERTIFICATE_PASSWORD_FOR_TEST"))
// Make sure we test the client certificate method
t.Setenv("ARM_CLIENT_SECRET", "")
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "")
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "")
pt := newPulumiTest(t, "azidentity")
up := pt.Up(t)
clientConfig, clientToken := validate(t, up)
assert.Equal(t, os.Getenv("ARM_CLIENT_ID"), clientConfig["clientId"])
assert.Equal(t, os.Getenv("ARM_CLIENT_ID"), clientToken["appid"])
assert.Equal(t, "app", clientToken["idtyp"])
})
t.Run("CLI", func(t *testing.T) {
// AZURE_CONFIG_DIR_FOR_TEST is set by the GH workflow build-test.yml
// to provide an isolated configuration directory for the Azure CLI.
configDir := os.Getenv("AZURE_CONFIG_DIR_FOR_TEST")
if configDir == "" {
if os.Getenv("CI") != "" {
t.Error("CLI test without AZURE_CONFIG_DIR_FOR_TEST")
}
t.Skip("Skipping CLI test without AZURE_CONFIG_DIR_FOR_TEST")
}
t.Setenv("AZURE_CONFIG_DIR", configDir)
// Make sure we test the CLI method
t.Setenv("ARM_USE_MSI", "false")
t.Setenv("ARM_USE_OIDC", "false")
t.Setenv("ARM_TENANT_ID", "")
t.Setenv("ARM_CLIENT_ID", "")
t.Setenv("ARM_CLIENT_SECRET", "")
t.Setenv("ARM_CLIENT_CERTIFICATE_PATH", "")
t.Setenv("ARM_CLIENT_CERTIFICATE_PASSWORD", "")
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "")
t.Setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "")
pt := newPulumiTest(t, "azidentity")
up := pt.Up(t)
clientConfig, clientToken := validate(t, up)
// When using service principal authentication, verify we got valid credentials
assert.NotEmpty(t, clientConfig["clientId"], "clientId should be present")
assert.NotEmpty(t, clientToken["appid"], "appid should be present")
// Service principal tokens have idtyp "app" (not "user")
assert.Equal(t, "app", clientToken["idtyp"])
})
t.Run("Default Azure Credential", func(t *testing.T) {
t.Setenv("ARM_USE_DEFAULT_AZURE_CREDENTIAL", "true")
if _, ok := os.LookupEnv("CI"); ok {
// Configure the default credential chain to use variables provided in build-test.yml, per:
// https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#readme-environment-variables
t.Setenv("AZURE_TOKEN_CREDENTIALS", "EnvironmentCredential")
t.Setenv("AZURE_CLIENT_ID", os.Getenv("ARM_CLIENT_ID"))
t.Setenv("AZURE_TENANT_ID", os.Getenv("ARM_TENANT_ID"))
t.Setenv("AZURE_CLIENT_SECRET", os.Getenv("ARM_CLIENT_SECRET"))
// Ensure that a subscription ID was provided, because ADC doesn't provide one.
require.NotEmpty(t, os.Getenv("ARM_SUBSCRIPTION_ID"))
}
pt := newPulumiTest(t, "azidentity")
up := pt.Up(t)
clientConfig, clientToken := validate(t, up)
if _, ok := os.LookupEnv("CI"); ok {
assert.Equal(t, os.Getenv("ARM_CLIENT_ID"), clientConfig["clientId"])
assert.Equal(t, os.Getenv("ARM_CLIENT_ID"), clientToken["appid"])
assert.Equal(t, "app", clientToken["idtyp"])
}
})
}
func TestUpgradeKeyVault_2_76_0(t *testing.T) {
upgradeTest(t, "upgrade-keyvault", "2.76.0")
}
func TestUpgradeNetworkedVm_2_76_0(t *testing.T) {
upgradeTest(t, "upgrade-networked-vm", "2.76.0")
}
func TestUpgradeStorageBlob_2_76_0(t *testing.T) {
upgradeTest(t, "upgrade-storage-blob", "2.76.0")
}
func TestUpgradeSqlDatabase_2_76_0(t *testing.T) {
upgradeTest(t, "upgrade-sql-database", "2.76.0")
}
func TestUpgradeServiceBusMessaging_2_76_0(t *testing.T) {
upgradeTest(t, "upgrade-servicebus-messaging", "2.76.0")
}
func TestUpgradeAppServicesWebApp_2_76_0(t *testing.T) {
upgradeTest(t, "upgrade-appservices-webapp", "2.76.0")
}
func TestUpgradeCosmosdbNosql_2_90_0(t *testing.T) {
upgradeTest(t, "upgrade-cosmosdb-nosql", "2.90.0",
// DocumentDB was renamed to CosmosDB in v3
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "upgrade-cosmosdb-nosql", "v3-cosmosdb")))
}
func TestUpgradeContainerServiceAgentPool_2_90_0(t *testing.T) {
upgradeTest(t, "upgrade-containerservice-agentpool", "2.90.0")
}
func TestUpgradeAksApiVersion_2_90_0(t *testing.T) {
upgradeTest(t, "upgrade-aks-api-version", "2.90.0",
// v2 uses versioned type (containerservice/v20240102preview), v3 uses unversioned with alias
optproviderupgrade.NewSourcePath(filepath.Join("test-programs", "upgrade-aks-api-version", "v3")))
}
func upgradeTest(t *testing.T, testProgramDir string, upgradeFromVersion string, opts ...optproviderupgrade.PreviewProviderUpgradeOpt) {
t.Helper()
if testing.Short() {
t.Skipf("Skipping in testing.Short() mode, assuming this is a CI run without cloud credentials")
return
}
dir := filepath.Join("test-programs", testProgramDir)
azureLocation := getLocation()
rpFactory := providers.ResourceProviderFactory(providerServer)
cacheDir := providertest.GetUpgradeCacheDir(filepath.Base(dir), upgradeFromVersion)
pt := pulumitest.NewPulumiTest(t, dir,
opttest.AttachProvider("azure-native",
rpFactory.ReplayInvokes(filepath.Join(cacheDir, "grpc.json"), false /* allowLiveFallback */)))
pt.SetConfig(t, "azure-native:location", azureLocation)
previewResult := providertest.PreviewProviderUpgrade(t, pt, "azure-native", upgradeFromVersion, opts...)
assertpreview.HasNoReplacements(t, previewResult)
assertpreview.HasNoDeletes(t, previewResult)
}
func newPulumiTest(t *testing.T, testProgramDir string, opts ...opttest.Option) *pulumitest.PulumiTest {
t.Helper()
if testing.Short() {
t.Skipf("Skipping in testing.Short() mode, assuming this is a CI run without cloud credentials")
return nil
}
dir := filepath.Join("test-programs", testProgramDir)
azureLocation := getLocation()
rpFactory := providers.ResourceProviderFactory(providerServer)
attachOpt := opttest.AttachProvider("azure-native", rpFactory)
pt := pulumitest.NewPulumiTest(t, dir, append(opts, attachOpt)...)
pt.SetConfig(t, "azure-native:location", azureLocation)
return pt
}
func providerServer(_ providers.PulumiTest) (pulumirpc.ResourceProviderServer, error) {
version.Version = os.Getenv("PROVIDER_VERSION")
if version.Version == "" {
version.Version = "3.0.0"
}
if len(schemaBytes) == 0 {
return nil, fmt.Errorf("schema not loaded")
}
if len(azureAPIResourcesBytes) == 0 {
return nil, fmt.Errorf("azure API resources not loaded")
}
return makeProvider(nil, "azure-native", version.GetVersion().String(), schemaBytes, azureAPIResourcesBytes)
}
func getLocation() string {
azureLocation := os.Getenv("ARM_LOCATION")
if azureLocation == "" {
azureLocation = "westus2"
fmt.Println("Defaulting location to 'westus2'. You can override using the ARM_LOCATION variable.")
}
return azureLocation
}
func parseJwtUnverified(tokenString string) (jwt.MapClaims, error) {
token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
return nil, err
}
claims, _ := token.Claims.(jwt.MapClaims)
return claims, nil
}
func debugLogging() debug.LoggingOptions {
var level uint = 11
return debug.LoggingOptions{
LogLevel: &level,
Debug: true,
FlowToPlugins: true,
LogToStdErr: true,
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/auth_azidentity.go | provider/pkg/provider/auth_azidentity.go | // Copyright 2016-2022, Pulumi Corporation.
package provider
import (
"context"
"crypto"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
_ "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" // initialize the well-known cloud configurations
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
const (
cliCloudMismatchMessage = `
The configured Azure environment '%s' does not match the active environment '%s'.
When authenticating using the Azure CLI, the configured environment needs to match the one shown by 'az account show'.
You can change environments using 'az cloud set --name <cloud>'.`
cliCloudUnsupportedMessage = `
The active Azure environment '%s' is not supported directly by the provider, and an Azure Metadata Server was not available.
`
)
// azAccount is the provider's resolved Azure account for authentication and for resource management.
type azAccount struct {
azcore.TokenCredential
// The Azure cloud configuration to use for resource management operations.
Cloud cloud.Configuration
// The subscription ID to use for resource management operations; empty if not configured or auto-detected.
SubscriptionId string
}
// NewAzCoreIdentity is the main entry to the new azcore/azidentity-based authentication stack.
// It determines the provider's Azure account such as the cloud and subscription ID, and a
// TokenCredential which can be passed into various Azure Go SDKs.
func NewAzCoreIdentity(ctx context.Context, authConf *authConfiguration, baseClientOpts policy.ClientOptions) (*azAccount, error) {
account := &azAccount{}
if authConf.cloud != nil {
baseClientOpts.Cloud = authConf.cloud.Configuration
}
// Create the azcore.TokenCredential implementation based on the auth configuration.
// This routine evaluates the auth configuration and other environment variables,
// and ultimately resolves the Azure cloud and subscription ID.
cred, err := newSingleMethodAuthCredential(ctx, authConf, baseClientOpts)
if err != nil {
return nil, err
}
account.TokenCredential = cred
// Based on the credential type, we may be able to resolve the Azure cloud and subscription ID.
if _, ok := cred.(*azidentity.AzureCLICredential); ok {
// get the given (or default) account from the Azure CLI
activeSubscription, err := authConf.showSubscription(ctx, authConf.subscriptionId)
if err != nil {
return nil, err
}
logging.V(6).Infof("Using Az account %q in environment %q", activeSubscription.Name, activeSubscription.EnvironmentName)
// automatically configure the environment and subscription ID based on the Azure CLI account
// and guard against an accidental mismatch between the CLI and the provider configuration.
if authConf.cloud != nil && activeSubscription.EnvironmentName != authConf.cloud.Name {
return nil, fmt.Errorf(cliCloudMismatchMessage, authConf.cloud.Name, activeSubscription.EnvironmentName)
}
if authConf.cloud == nil {
// Automatically use the Azure CLI's current environment.
wellknown, ok := cloud.FromName(activeSubscription.EnvironmentName)
if !ok {
// The CLI is configured with a custom environment.
// FUTURE: use `az cloud show` to automatically obtain the environment configuration.
return nil, fmt.Errorf(cliCloudUnsupportedMessage, activeSubscription.EnvironmentName)
}
account.Cloud = wellknown
} else {
account.Cloud = *authConf.cloud
}
account.SubscriptionId = activeSubscription.ID
} else {
// use the configured values and/or defaults
if authConf.cloud == nil {
// if the cloud is not set, use the default Azure cloud as does newSingleMethodAuthCredential.
account.Cloud = cloud.AzurePublic
} else {
account.Cloud = *authConf.cloud
}
account.SubscriptionId = authConf.subscriptionId
}
logging.V(6).Infof("Using Az cloud %q with subscription ID %q", account.Cloud.Name, account.SubscriptionId)
return account, nil
}
// newSingleMethodAuthCredential creates an azcore.TokenCredential. Depending on the given authConfiguration, it is
// backed by one of several authentication methods such as Service Principal, OIDC, Managed Identity, or Azure CLI.
//
// Note: this function's behavior is written to match the behavior of
// "github.com/hashicorp/go-azure-helpers/authentication".Builder.Build() in some ways, to minimize changes in provider
// behavior when upgrading authentication dependencies from go-azure-helpers to azidentity. Namely:
// - The order in which the the different authentication methods are attempted is the same:
// 1. Default Credential
// 2. Service Principal with client certificate
// 3. Service Principal with client secret
// 4. OIDC
// 5. Managed Identity
// 6. Azure CLI
// - When a method is configured but instantiating the credential fails, we return an error and do not fall through to
// the next method.
// - Auxiliary or additional tenants are supported for SP with client secret and CLI authentication, not for others.
func newSingleMethodAuthCredential(ctx context.Context, authConf *authConfiguration, baseClientOpts azcore.ClientOptions) (azcore.TokenCredential, error) {
if authConf.useDefault {
logging.V(9).Infof("[auth] Using default Azure credential")
fmtErrorMessage := "A %s must be configured when authenticating using the Default Azure Credential."
if authConf.subscriptionId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Subscription ID")
}
options := &azidentity.DefaultAzureCredentialOptions{
ClientOptions: baseClientOpts,
AdditionallyAllowedTenants: authConf.auxTenants, // usually empty which is fine
DisableInstanceDiscovery: authConf.disableInstanceDiscovery,
}
return azidentity.NewDefaultAzureCredential(options)
} else {
logging.V(11).Infof("Default Azure Credential is not enabled, skipping")
}
if authConf.clientCertPath != "" {
logging.V(9).Infof("[auth] Using SP with client certificate credential")
fmtErrorMessage := "A %s must be configured when authenticating as a Service Principal using a Client Certificate."
if authConf.subscriptionId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Subscription ID")
}
if authConf.tenantId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Tenant ID")
}
if authConf.clientId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Client ID")
}
certs, key, err := readCertificate(authConf.clientCertPath, authConf.clientCertPassword)
if err != nil {
return nil, fmt.Errorf("the Client Certificate Path is not a valid pfx file: %w", err)
}
options := &azidentity.ClientCertificateCredentialOptions{
AdditionallyAllowedTenants: authConf.auxTenants, // usually empty which is fine
ClientOptions: baseClientOpts,
DisableInstanceDiscovery: authConf.disableInstanceDiscovery,
}
return azidentity.NewClientCertificateCredential(authConf.tenantId, authConf.clientId, certs, key, options)
} else {
logging.V(11).Infof("SP with client certificate credential is not enabled, skipping")
}
if authConf.clientSecret != "" {
logging.V(9).Infof("[auth] Using SP with client secret credential")
fmtErrorMessage := "A %s must be configured when authenticating as a Service Principal using a Client Secret."
if authConf.subscriptionId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Subscription ID")
}
if authConf.tenantId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Tenant ID")
}
if authConf.clientId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Client ID")
}
options := &azidentity.ClientSecretCredentialOptions{
AdditionallyAllowedTenants: authConf.auxTenants, // usually empty which is fine
ClientOptions: baseClientOpts,
DisableInstanceDiscovery: authConf.disableInstanceDiscovery,
}
return azidentity.NewClientSecretCredential(authConf.tenantId, authConf.clientId, authConf.clientSecret, options)
} else {
logging.V(11).Infof("SP with client secret credential is not enabled, skipping")
}
if authConf.useOidc {
logging.V(9).Infof("[auth] Using OIDC credential")
return newOidcCredential(authConf, baseClientOpts)
} else {
logging.V(11).Infof("OIDC credential is not enabled, skipping")
}
if authConf.useMsi {
logging.V(9).Infof("[auth] Using Managed Identity (MSI) credential")
fmtErrorMessage := "A %s must be configured when authenticating as a Managed Identity using MSI."
if authConf.subscriptionId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Subscription ID")
}
msiOpts := azidentity.ManagedIdentityCredentialOptions{
ClientOptions: baseClientOpts,
}
if authConf.clientId != "" {
msiOpts.ID = azidentity.ClientID(authConf.clientId)
}
return azidentity.NewManagedIdentityCredential(&msiOpts)
} else {
logging.V(11).Infof("Managed Identity (MSI) credential is not enabled, skipping")
}
logging.V(9).Infof("[auth] Using Azure CLI credential")
options := &azidentity.AzureCLICredentialOptions{
AdditionallyAllowedTenants: authConf.auxTenants, // usually empty which is fine
}
// note that the subscription ID is discoverable when using the Azure CLI credential and hence optional.
if authConf.subscriptionId != "" {
// Query the subscription to check if it's the default.
// This avoids triggering a shell quoting bug in the Azure SDK when using the default subscription.
activeSubscription, err := authConf.showSubscription(ctx, authConf.subscriptionId)
if err != nil {
return nil, err
}
// Only pass subscription to SDK if it's not the default subscription.
// When using the default, the SDK will auto-detect it without needing the parameter.
if !activeSubscription.IsDefault {
options.Subscription = authConf.subscriptionId
}
}
return azidentity.NewAzureCLICredential(options)
}
// newOidcCredential creates a TokenCredential for OpenID Connect (OIDC) authentication.
// An OIDC credential is an azidentity.ClientAssertionCredential that authenticates with a token
// obtained from a callback function. The token itself can be provided in various ways:
// - directly via config/environment variable
// - from a file
// - through a token exchange by making a request to a configured endpoint
// This function configures the client assertion callback according to the above cases.
func newOidcCredential(authConf *authConfiguration, clientOpts azcore.ClientOptions) (azcore.TokenCredential, error) {
fmtErrorMessage := "A %s must be configured when authenticating with OIDC."
if authConf.subscriptionId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Subscription ID")
}
if authConf.tenantId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Tenant ID")
}
if authConf.clientId == "" {
return nil, fmt.Errorf(fmtErrorMessage, "Client ID")
}
// The generic client assertion that simply returns the token it was created with.
oidcTokenCredentialCallback := func(token string) (azcore.TokenCredential, error) {
return azidentity.NewClientAssertionCredential(
authConf.tenantId,
authConf.clientId,
func(ctx context.Context) (string, error) {
return token, nil
},
&azidentity.ClientAssertionCredentialOptions{
ClientOptions: clientOpts,
DisableInstanceDiscovery: authConf.disableInstanceDiscovery,
})
}
if authConf.oidcToken != "" {
return oidcTokenCredentialCallback(authConf.oidcToken)
}
if authConf.oidcTokenFilePath != "" {
token, err := os.ReadFile(authConf.oidcTokenFilePath)
if err != nil {
return nil, fmt.Errorf("failed to read OIDC token from %s: %w", authConf.oidcTokenFilePath, err)
}
return oidcTokenCredentialCallback(string(token))
}
// In this case, we need to obtain the OIDC token first from the configured endpoint.
if authConf.oidcTokenRequestUrl != "" && authConf.oidcTokenRequestToken != "" {
return azidentity.NewClientAssertionCredential(
authConf.tenantId,
authConf.clientId,
getOidcTokenExchangeAssertion(authConf),
&azidentity.ClientAssertionCredentialOptions{
ClientOptions: clientOpts,
DisableInstanceDiscovery: authConf.disableInstanceDiscovery,
})
}
return nil, fmt.Errorf(fmtErrorMessage, "OIDC token or request URL and token")
}
// getOidcTokenExchangeAssertion returns a callback function that implements the OIDC token
// exchange flow on GitHub. The function makes a request to the configured endpoint with the
// configured bearer token and returns the OIDC token from the response. It's intended to be used
// in an azidentity.ClientAssertionCredential.
func getOidcTokenExchangeAssertion(authConf *authConfiguration) func(ctx context.Context) (string, error) {
return func(ctx context.Context) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, authConf.oidcTokenRequestUrl, http.NoBody)
if err != nil {
return "", fmt.Errorf("GitHub OIDC: failed to build request to %s: %w", authConf.oidcTokenRequestUrl, err)
}
query, err := url.ParseQuery(req.URL.RawQuery)
if err != nil {
return "", fmt.Errorf("githubAssertion: cannot parse URL query")
}
// see https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-azure#adding-the-federated-credentials-to-azure
audience := "api://AzureADTokenExchange"
if authConf.oidcAudience != "" {
audience = authConf.oidcAudience
}
query.Set("audience", audience)
req.URL.RawQuery = query.Encode()
req.Header.Set("Accept", "application/json")
// see https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/about-security-hardening-with-openid-connect#updating-your-actions-for-oidc
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authConf.oidcTokenRequestToken))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("GitHub OIDC: couldn't request token: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("GitHub OIDC: cannot read response: %w", err)
}
if c := resp.StatusCode; c < 200 || c > 299 {
return "", fmt.Errorf("GitHub OIDC: %d with response: %s", resp.StatusCode, body)
}
var tokenResponse struct {
Value string `json:"value"`
}
if err := json.Unmarshal(body, &tokenResponse); err != nil {
return "", fmt.Errorf("GitHub OIDC: cannot unmarshal response: %w", err)
}
return tokenResponse.Value, nil
}
}
func readCertificate(certPath, certPassword string) ([]*x509.Certificate, crypto.PrivateKey, error) {
cert, err := os.ReadFile(certPath)
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to read certificate from %s", certPath)
}
var pwBytes []byte
if certPassword != "" {
pwBytes = []byte(certPassword)
}
certs, key, err := azidentity.ParseCertificates(cert, pwBytes)
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to parse certificate from %s", certPath)
}
if len(certs) == 0 {
return nil, nil, errors.Errorf("no certificates found in %s", certPath)
}
return certs, key, nil
}
type authConfiguration struct {
cloud *cloud.Configuration
subscriptionId string
clientId string
tenantId string
auxTenants []string
useOidc bool
oidcAudience string
oidcToken string
oidcTokenFilePath string
oidcTokenRequestToken string
oidcTokenRequestUrl string
clientSecret string
clientCertPath string
clientCertPassword string
// Note: for MSI, there used to be a msiEndpoint/ARM_MSI_ENDPOINT and a metadataHost/
// ARM_METADATA_HOSTNAME configuration. The newer azidentity package handles the MSI endpoint
// automatically:
// https://github.com/Azure/azure-sdk-for-go/blob/sdk/azidentity/v1.8.0/sdk/azidentity/managed_identity_client.go#L143
useMsi bool
// Enables the use of azcore's DefaultAzureCredential strategy.
// DefaultAzureCredential simplifies authentication while developing applications that deploy to Azure by
// combining credentials used in Azure hosting environments and credentials used in local development.
useDefault bool
// When true, disables instance discovery for credentials that support it.
disableInstanceDiscovery bool
// showSubscription invokes `az account show` and is overridable by tests to fake invoking the az CLI.
showSubscription azSubscriptionProvider
}
type configGetter func(configName, envName string) string
type metadataGetter func(ctx context.Context, endpoint string) (cloud.Configuration, error)
// readAuthConfig collects auth-related configuration from Pulumi config and environment variables
func readAuthConfig(ctx context.Context, getConfig configGetter, getMetadata metadataGetter) (*authConfiguration, error) {
cloud, err := readCloudConfiguration(ctx, getConfig, getMetadata)
if err != nil {
return nil, err
}
auxTenantsString := getConfig("auxiliaryTenantIds", "ARM_AUXILIARY_TENANT_IDS")
var auxTenants []string
if auxTenantsString != "" {
err := json.Unmarshal([]byte(auxTenantsString), &auxTenants)
if err != nil {
return nil, errors.Wrapf(err, "failed to unmarshal '%s' as Auxiliary Tenants", auxTenantsString)
}
}
authConf := &authConfiguration{
clientId: getConfig("clientId", "ARM_CLIENT_ID"),
tenantId: getConfig("tenantId", "ARM_TENANT_ID"),
auxTenants: auxTenants,
cloud: cloud,
subscriptionId: getConfig("subscriptionId", "ARM_SUBSCRIPTION_ID"),
clientSecret: getConfig("clientSecret", "ARM_CLIENT_SECRET"),
clientCertPath: getConfig("clientCertificatePath", "ARM_CLIENT_CERTIFICATE_PATH"),
clientCertPassword: getConfig("clientCertificatePassword", "ARM_CLIENT_CERTIFICATE_PASSWORD"),
useMsi: getConfig("useMsi", "ARM_USE_MSI") == "true",
useOidc: getConfig("useOidc", "ARM_USE_OIDC") == "true",
oidcAudience: getConfig("oidcAudience", "ARM_OIDC_AUDIENCE"),
oidcToken: getConfig("oidcToken", "ARM_OIDC_TOKEN"),
oidcTokenFilePath: getConfig("oidcTokenFilePath", "ARM_OIDC_TOKEN_FILE_PATH"),
oidcTokenRequestToken: getConfig("oidcRequestToken", "ACTIONS_ID_TOKEN_REQUEST_TOKEN"),
oidcTokenRequestUrl: getConfig("oidcRequestUrl", "ACTIONS_ID_TOKEN_REQUEST_URL"),
useDefault: getConfig("useDefaultAzureCredential", "ARM_USE_DEFAULT_AZURE_CREDENTIAL") == "true",
disableInstanceDiscovery: getConfig("disableInstanceDiscovery", "ARM_DISABLE_INSTANCE_DISCOVERY") == "true",
showSubscription: defaultAzSubscriptionProvider,
}
return authConf, nil
}
// readCloudConfiguration returns the configured Azure cloud (environment).
// Returns nil if not configured, to allow for other detection methods before defaulting to the public cloud.
func readCloudConfiguration(ctx context.Context, getConfig configGetter, getMetadata metadataGetter) (*cloud.Configuration, error) {
// Start by looking for an Azure metadata endpoint, to dynamically configure the cloud environment.
metadataHost := getConfig("metadataHost", "ARM_METADATA_HOSTNAME")
if metadataHost != "" {
logging.V(6).Infof("Using Azure metadata endpoint: %s", metadataHost)
active, err := getMetadata(ctx, metadataHost)
if err != nil {
return nil, fmt.Errorf("failed to get Azure environment metadata from %s: %w", metadataHost, err)
}
return &active, nil
}
// Fall back to the well-known environments
envName := getConfig("environment", "ARM_ENVIRONMENT")
if envName == "" {
envName = getConfig("environment", "AZURE_ENVIRONMENT")
}
if envName != "" {
logging.V(6).Infof("Using Azure environment: %s", envName)
// Look up the cloud configuration by name; if not found, it might be a custom configuration,
// but no metadata server was available to provide the necessary details.
wellknown, ok := cloud.FromName(envName)
if !ok {
return nil, fmt.Errorf("configuration data is not available for Azure environment '%s' and ARM_METADATA_HOSTNAME is not set", envName)
}
return &wellknown, nil
}
// don't default to public cloud just yet; allow for CLI-based detection later.
return nil, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/provider.go | provider/pkg/provider/provider.go | // Copyright 2016-2024, Pulumi Corporation.
package provider
import (
"context"
"fmt"
"log"
"math"
"os"
"reflect"
"regexp"
"strings"
"time"
"github.com/blang/semver"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/deepcopy"
"github.com/segmentio/encoding/json"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
azcloud "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
pbempty "github.com/golang/protobuf/ptypes/empty"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/convert"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi/defaults"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/provider/crud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources/customresources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/version"
"github.com/pulumi/pulumi/pkg/v3/resource/provider"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
rpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
// Microsoft's Pulumi Partner ID.
PulumiPartnerID = "a90539d8-a7a6-5826-95c4-1fbef22d4b22"
apiVersionResources = "2020-10-01"
createBeforeDeleteFlag = "__createBeforeDelete"
)
type azureNativeProvider struct {
rpc.UnimplementedResourceProviderServer
authConfig authConfiguration
credential *azAccount
azureClient azure.AzureClient
host *provider.HostClient
name string
version string
subscriptionID string
cloud cloud.Configuration
config map[string]string
// also known as "metadata"
resourceMap *resources.APIMetadata
schemaBytes []byte
converter *convert.SdkShapeConverter
customResources map[string]*customresources.CustomResource
rgLocationMap map[string]string
lookupType resources.TypeLookupFunc
skipReadOnUpdate bool
context context.Context
shutdown context.CancelFunc
}
func makeProvider(host *provider.HostClient, name, version string, schemaBytes []byte,
azureAPIResourcesBytes []byte) (rpc.ResourceProviderServer, error) {
resourceMap, err := LoadMetadataPartial(azureAPIResourcesBytes)
if err != nil {
return nil, err
}
return makeProviderInternal(host, name, version, schemaBytes, resourceMap)
}
func makeProviderInternal(host *provider.HostClient, name, version string, schemaBytes []byte,
resourceMap *resources.APIMetadata) (*azureNativeProvider, error) {
converter := convert.NewSdkShapeConverterPartial(resourceMap.Types)
ctx, shutdown := context.WithCancel(context.Background())
// Return the new provider
p := &azureNativeProvider{
// Note: azureClient and subscriptionId will be initialized in Configure.
host: host,
name: name,
version: version,
resourceMap: resourceMap,
config: map[string]string{},
schemaBytes: schemaBytes,
converter: &converter,
rgLocationMap: map[string]string{},
context: ctx,
shutdown: shutdown,
}
p.lookupType = p.lookupTypeDefault
return p, nil
}
func (k *azureNativeProvider) getVersion() semver.Version {
if k.version == "" {
return version.GetVersion()
}
return semver.MustParse(k.version)
}
// LoadMetadataPartial partially deserializes the provided json byte array into an AzureAPIMetadata
// in memory
func LoadMetadataPartial(azureAPIResourcesBytes []byte) (*resources.APIMetadata, error) {
var resourceMap resources.PartialAzureAPIMetadata
if _, err := json.Parse(azureAPIResourcesBytes, &resourceMap, json.ZeroCopy); err != nil {
return nil, errors.Wrap(err, "unmarshalling resource map")
}
apiMetadata := resources.APIMetadata{
Types: &resourceMap.Types,
Resources: &resourceMap.Resources,
Invokes: &resourceMap.Invokes,
}
return &apiMetadata, nil
}
// LoadMetadata deserializes the provided json byte array into an AzureAPIMetadata in memory
func LoadMetadata(azureAPIResourcesBytes []byte) (*resources.AzureAPIMetadata, error) {
var resourceMap resources.AzureAPIMetadata
if _, err := json.Parse(azureAPIResourcesBytes, &resourceMap, json.ZeroCopy); err != nil {
return nil, errors.Wrap(err, "unmarshalling resource map")
}
return &resourceMap, nil
}
// Looks up a type reference, with or without the #/types/ prefix, in the resource map.
// Typically used via lookupType so it can be overridden for tests.
func (k *azureNativeProvider) lookupTypeDefault(ref string) (*resources.AzureAPIType, bool, error) {
typeName := strings.TrimPrefix(ref, "#/types/")
t, ok, err := k.resourceMap.Types.Get(typeName)
return &t, ok, err
}
func (k *azureNativeProvider) LookupResource(resourceType string) (resources.AzureAPIResource, bool, error) {
return k.resourceMap.Resources.Get(resourceType)
}
func (k *azureNativeProvider) lookupResourceFromURN(urn resource.URN) (*resources.AzureAPIResource, error) {
resourceKey := string(urn.Type())
res, ok, err := k.LookupResource(resourceKey)
if err != nil {
return nil, errors.Errorf("Decoding resource spec %s", resourceKey)
}
if !ok {
return nil, errors.Errorf("Resource type %s not found", resourceKey)
}
return &res, nil
}
// lookupResourceWithAPIVersion attempts to look up resource metadata for a specific API version.
// It finds a resource with the same ARM path as the current resource but with the requested API version.
// This works because the ARM path is stable across API versions for the same resource type.
func (k *azureNativeProvider) lookupResourceWithAPIVersion(urn resource.URN, apiVersion string) (*resources.AzureAPIResource, error) {
// Get current resource to extract its ARM path for verification
currentRes, err := k.lookupResourceFromURN(urn)
if err != nil {
return nil, err
}
// Parse the current type token to extract module and resource name
currentType := string(urn.Type())
module, _, resourceName, err := resources.ParseToken(currentType)
if err != nil {
return nil, errors.Wrapf(err, "parsing resource type %s", currentType)
}
// Convert API version from ISO format (2024-01-02) to SDK version format (v20240102)
sdkVersion := openapi.ApiToSdkVersion(openapi.ApiVersion(apiVersion))
// Construct candidate type token with the target API version
candidateType := resources.BuildToken(module, string(sdkVersion), resourceName)
// Look up the resource with this type token
res, ok, err := k.LookupResource(candidateType)
if err != nil {
return nil, errors.Wrapf(err, "looking up resource type %s", candidateType)
}
if !ok {
return nil, errors.Errorf("Resource type %s not found (API version %s not available in this provider version)",
candidateType, apiVersion)
}
// Verify this resource has the same path and correct API version
if res.Path != currentRes.Path {
return nil, errors.Errorf("Resource path mismatch: expected %s, found %s", currentRes.Path, res.Path)
}
if res.APIVersion != apiVersion {
return nil, errors.Errorf("API version mismatch: expected %s, found %s", apiVersion, res.APIVersion)
}
return &res, nil
}
// newCrudClient implements crud.ResourceCrudClientFactory
func (p *azureNativeProvider) newCrudClient(res *resources.AzureAPIResource) crud.ResourceCrudClient {
return crud.NewResourceCrudClient(p.azureClient, p.lookupType, p.converter, p.subscriptionID, res)
}
func (p *azureNativeProvider) Attach(context context.Context, req *rpc.PluginAttach) (*emptypb.Empty, error) {
host, err := provider.NewHostClient(req.GetAddress())
if err != nil {
return nil, err
}
p.host = host
return &pbempty.Empty{}, nil
}
// Configure configures the resource provider with "globals" that control its behavior.
func (k *azureNativeProvider) Configure(ctx context.Context,
req *rpc.ConfigureRequest) (*rpc.ConfigureResponse, error) {
if k.getVersion().Major >= 3 && (!req.GetSendsOldInputs() || !req.GetSendsOldInputsToDelete()) {
// https://github.com/pulumi/pulumi-azure-native/issues/2686
return nil, errors.New("Azure Native provider requires Pulumi CLI v3.74.0 or later")
}
// Check if legacy backend was explicitly disabled - error since it's no longer supported
// https://github.com/pulumi/pulumi-azure-native/issues/4047
if enable, ok := os.LookupEnv("PULUMI_ENABLE_AZCORE_BACKEND"); ok && enable != "true" {
return nil, errors.New("PULUMI_ENABLE_AZCORE_BACKEND=false is no longer supported. " +
"The legacy autorest authentication backend has been removed. " +
"Please remove this environment variable or set it to 'true'.")
}
for key, val := range req.GetVariables() {
k.config[strings.TrimPrefix(key, "azure-native:config:")] = val
}
k.setLoggingContext(ctx)
k.skipReadOnUpdate = k.getConfig("skipReadOnUpdate", "ARM_SKIP_READ_ON_UPDATE") == "true"
logging.V(9).Infof("Using azcore authentication")
userAgent := k.getUserAgent()
logging.V(9).Infof("User agent: %s", userAgent)
authConfig, err := readAuthConfig(ctx, k.getConfig, cloud.FromMetadataEndpoint)
if err != nil {
return nil, err
}
k.authConfig = *authConfig
logging.V(9).Infof("Provider auth configuration: %+v", k.authConfig)
clientOpts := azcore.ClientOptions{}
credential, err := NewAzCoreIdentity(ctx, authConfig, clientOpts)
if err != nil {
return nil, err
}
k.credential = credential
k.cloud = credential.Cloud
k.subscriptionID = credential.SubscriptionId
logging.V(9).Infof("Azure cloud: %+v", k.cloud)
logging.V(9).Infof("Azure subscription ID: %s", k.subscriptionID)
k.azureClient, err = azure.NewAzCoreClient(credential, userAgent, k.cloud.Configuration, nil)
if err != nil {
return nil, err
}
// When the provider is parameterized, resources and types that custom resources are built on will probably not be available.
if !k.isParameterized() {
var err error
k.customResources, err = customresources.BuildCustomResources(
k.azureClient, k.LookupResource, k.newCrudClient,
k.subscriptionID, k.cloud, credential)
if err != nil {
return nil, fmt.Errorf("initializing custom resources: %w", err)
}
}
return &rpc.ConfigureResponse{
SupportsPreview: true,
SupportsAutonamingConfiguration: true,
}, nil
}
func (k *azureNativeProvider) isParameterized() bool {
return strings.HasPrefix(k.name, "azure-native"+parameterizedNameSeparator)
}
// Invoke dynamically executes a built-in function in the provider.
func (k *azureNativeProvider) Invoke(ctx context.Context, req *rpc.InvokeRequest) (*rpc.InvokeResponse, error) {
label := fmt.Sprintf("%s.Invoke(%s)", k.name, req.Tok)
logging.V(9).Infof("%s executing", label)
args, err := plugin.UnmarshalProperties(req.GetArgs(), plugin.MarshalOptions{
Label: fmt.Sprintf("%s.args", label), KeepUnknowns: true, SkipNulls: true, KeepSecrets: true,
})
if err != nil {
return nil, err
}
var outputs map[string]interface{}
switch req.Tok {
case "azure-native:authorization:getClientConfig":
auth, err := k.getClientConfig(ctx)
if err != nil {
return nil, fmt.Errorf("getting client config: %w", err)
}
outputs = map[string]interface{}{
"clientId": auth.ClientID,
"objectId": auth.ObjectID,
"subscriptionId": auth.SubscriptionID,
"tenantId": auth.TenantID,
}
case "azure-native:authorization:getClientToken":
token, err := k.getClientToken(ctx, args["endpoint"])
if err != nil {
return nil, err
}
outputs = map[string]interface{}{"token": token}
default:
res, ok, err := k.resourceMap.Invokes.Get(req.Tok)
if err != nil {
return nil, errors.Errorf("Decoding invoke spec %s", req.Tok)
}
if !ok {
return nil, errors.Errorf("Invoke type %s not found", req.Tok)
}
parameters := res.GetParameters
if parameters == nil {
parameters = res.PostParameters
}
// Construct ARM REST API path from args.
id, query, err := crud.PrepareAzureRESTIdAndQuery(
res.Path,
parameters,
args.Mappable(),
map[string]interface{}{
"subscriptionId": k.subscriptionID,
"api-version": res.APIVersion,
},
)
if err != nil {
return nil, err
}
body, err := crud.PrepareAzureRESTBody(id, parameters, nil, args.Mappable(), k.converter)
if err != nil {
if body == nil {
return nil, fmt.Errorf("error preparing body for %s: %v", label, err)
}
// Ignore the error if we've got a body as it's just a warning
}
var response any
if res.GetParameters != nil {
response, err = k.azureClient.Get(ctx, id, res.APIVersion, nil)
} else if res.PostParameters != nil {
if body == nil {
body = map[string]interface{}{}
}
response, err = k.azureClient.Post(ctx, id, body, query)
} else {
return nil, errors.Errorf("neither GET nor POST is defined for %s", label)
}
if err != nil {
return nil, errors.Wrapf(err, "request failed %v", id)
}
outputs = k.invokeResponseToOutputs(response, res)
}
// Serialize and return RPC outputs.
result, err := plugin.MarshalProperties(
resource.NewPropertyMapFromMap(outputs),
plugin.MarshalOptions{Label: fmt.Sprintf("%s.response", label), KeepUnknowns: true, SkipNulls: true},
)
if err != nil {
return nil, err
}
return &rpc.InvokeResponse{Return: result}, nil
}
func (k *azureNativeProvider) getClientConfig(ctx context.Context) (config *ClientConfig, err error) {
return GetClientConfig(ctx, &k.authConfig, k.credential)
}
func (k *azureNativeProvider) getClientToken(ctx context.Context, endpointArg resource.PropertyValue) (token string, err error) {
endpoint := k.tokenEndpoint(endpointArg)
logging.V(9).Infof("getting a token credential for %s", endpoint)
t, err := k.credential.GetToken(ctx, tokenRequestOpts(endpoint))
if err != nil {
return "", err
}
return t.Token, nil
}
// Returns the endpoint to be used as the resource (scope) of the token request.
// If the argument is not null or empty, it will be used verbatim.
func (k *azureNativeProvider) tokenEndpoint(endpointArg resource.PropertyValue) string {
if endpointArg.HasValue() && endpointArg.IsString() && endpointArg.StringValue() != "" {
return endpointArg.StringValue()
}
// see: https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#trailing-slash-and-default
endpoint := k.cloud.Services[azcloud.ResourceManager].Endpoint
if !strings.HasSuffix(endpoint, "/") {
endpoint += "/"
}
return endpoint
}
func tokenRequestOpts(endpoint string) policy.TokenRequestOptions {
return policy.TokenRequestOptions{
// "".default" is the well-defined scope for all resources accessible to the user or
// application. Despite the URL, it doesn't apply only to OIDC.
// https://learn.microsoft.com/en-us/entra/identity-platform/scopes-oidc#the-default-scope
Scopes: []string{endpoint + "/.default"},
}
}
func (k *azureNativeProvider) invokeResponseToOutputs(response any, res resources.AzureAPIInvoke) map[string]any {
var outputs map[string]any
if responseMap, ok := response.(map[string]any); ok {
// Map the raw response to the shape of outputs that the SDKs expect.
outputs = k.converter.ResponseBodyToSdkOutputs(res.Response, responseMap)
} else {
outputs = map[string]any{resources.SingleValueProperty: response}
}
if res.IsResourceGetter {
// resource getters have an azureApiVersion output property.
if k.getVersion().Major >= 3 {
if res.APIVersion != "" {
outputs["azureApiVersion"] = resource.NewStringProperty(res.APIVersion)
}
}
}
return outputs
}
// Check validates that the given property bag is valid for a resource of the given type and returns
// the inputs that should be passed to successive calls to Diff, Create, or Update for this
// resource. As a rule, the provider inputs returned by a call to Check should preserve the original
// representation of the properties as present in the program inputs. Though this rule is not
// required for correctness, violations thereof can negatively impact the end-user experience, as
// the provider inputs are using for detecting and rendering diffs.
func (k *azureNativeProvider) Check(ctx context.Context, req *rpc.CheckRequest) (*rpc.CheckResponse, error) {
urn := resource.URN(req.GetUrn())
label := fmt.Sprintf("%s.Check(%s)", k.name, urn)
logging.V(9).Infof("%s executing", label)
var failures []*rpc.CheckFailure
// Deserialize RPC inputs.
oldResInputs := req.GetOlds()
olds, err := plugin.UnmarshalProperties(oldResInputs, plugin.MarshalOptions{
Label: fmt.Sprintf("%s.olds", label), SkipNulls: true,
})
if err != nil {
return nil, err
}
newResInputs := req.GetNews()
news, err := plugin.UnmarshalProperties(newResInputs, plugin.MarshalOptions{
Label: fmt.Sprintf("%s.news", label), KeepUnknowns: true, SkipNulls: true,
})
if err != nil {
return nil, err
}
res, err := k.lookupResourceFromURN(urn)
if err != nil {
return nil, err
}
k.applyDefaults(ctx, req.Urn, req.RandomSeed, req.Autonaming, *res, olds, news)
inputMap := news.Mappable()
// Validate inputs against PUT parameters.
for _, param := range res.PutParameters {
if param.Name == "subscriptionId" || param.Name == "api-version" {
// These parameters are supplied by the provider, not user's code.
continue
}
if param.Location == "body" {
// Body parameter is a collection of properties, so validate all properties in its type.
failures = append(failures, k.validateType("", param.Body, inputMap)...)
continue
}
name := param.Name
if param.Value.SdkName != "" {
name = param.Value.SdkName
}
if value, has := inputMap[name]; has {
// Check if the value matches the parameter constraints (recursively).
failures = append(failures, k.validateProperty(name, param.Value, value)...)
} else if param.IsRequired {
// Report a missing required parameter.
failures = append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("missing required property '%s'", name),
})
}
}
resInputs, err := plugin.MarshalProperties(news, plugin.MarshalOptions{
Label: fmt.Sprintf("%s.resInputs", label), KeepUnknowns: true})
if err != nil {
return nil, err
}
return &rpc.CheckResponse{Inputs: resInputs, Failures: failures}, nil
}
// Get a default location property for the given inputs.
func (k *azureNativeProvider) getDefaultLocation(ctx context.Context, olds, news resource.PropertyMap) *resource.PropertyValue {
result := func(s string) *resource.PropertyValue {
p := resource.NewStringProperty(s)
return &p
}
// 1. Check if old inputs define a location.
if v, ok := olds["location"]; ok {
return &v
}
// 2. Check if the config has a fixed location.
if v, ok := k.config["location"]; ok {
return result(v)
}
// 3. If there is a link to a resource group, try to use its location.
rg, ok := news["resourceGroupName"]
if !ok {
return nil
}
// 3a. Resource group is unknown yet - make location unknown too.
if rg.ContainsUnknowns() {
computed := resource.MakeComputed(resource.NewStringProperty(""))
return &computed
}
// 3b. Resource group name is known and its location is already in the cache: use the cached value.
rgName := rg.StringValue()
if v, ok := k.rgLocationMap[rgName]; ok {
return result(v)
}
// 3c. Retrieve the resource group's properties from ARM API.
id := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s", k.subscriptionID, rgName)
response, err := k.azureClient.Get(ctx, id, apiVersionResources, nil)
if err != nil {
logging.V(9).Infof("failed to lookup the location of resource group %q: %v", rgName, err)
return nil
}
v, ok := response["location"].(string)
if !ok {
logging.V(9).Infof("no location for resource group %q", rgName)
return nil
}
// Save the location to the cache and return the value.
k.rgLocationMap[rgName] = v
return result(v)
}
func (k *azureNativeProvider) getDefaultName(urn string, randomSeed []byte,
autonaming *rpc.CheckRequest_AutonamingOptions, strategy resources.AutoNameKind, key resource.PropertyKey,
olds resource.PropertyMap) (nameValue *resource.PropertyValue, randomlyNamed bool, ok bool) {
if v, ok := olds[key]; ok {
if vf, ok := olds[createBeforeDeleteFlag]; ok && vf.IsBool() {
return &v, vf.BoolValue(), true
}
return &v, false, true
}
result := func(s string) *resource.PropertyValue {
p := resource.NewStringProperty(s)
return &p
}
if autonaming != nil {
switch autonaming.Mode {
case rpc.CheckRequest_AutonamingOptions_DISABLE:
// Do not return any value. If the property is required, Check will fail
// with a missing required property error.
return nil, false, false
case rpc.CheckRequest_AutonamingOptions_ENFORCE:
return result(autonaming.ProposedName), true, true
case rpc.CheckRequest_AutonamingOptions_PROPOSE:
switch strategy {
case resources.AutoNameRandom, resources.AutoNameCopy:
return result(autonaming.ProposedName), true, true
case resources.AutoNameUuid:
// Do nothing for UUIDs in proposed mode, fall back to the normal logic below.
}
}
}
urnParts := strings.Split(urn, "::")
name := urnParts[len(urnParts)-1]
switch strategy {
case resources.AutoNameRandom:
// Resource name is URN name + random suffix.
random, err := resource.NewUniqueName(randomSeed, name, 8, 0, nil)
contract.AssertNoError(err)
return result(random), true, true
case resources.AutoNameUuid:
// Resource name is a random UUID. We need to do a similar trick as NewUniqueName so that this is
// deterministic by randomSeed. We simply ask NewUniqueName for a 32 byte random hex name.
hexID, err := resource.NewUniqueName(randomSeed, "", 32, 0, nil)
contract.AssertNoError(err)
return result(uuid.MustParse(hexID).String()), true, true
case resources.AutoNameCopy:
// Resource name is just a copy of the URN name.
return result(name), false, true
default:
panic(fmt.Sprintf("unknown auto-naming strategy %q", strategy))
}
}
// Apply default values (e.g., location) to user's inputs.
func (k *azureNativeProvider) applyDefaults(ctx context.Context, urn string, randomSeed []byte,
autonaming *rpc.CheckRequest_AutonamingOptions, res resources.AzureAPIResource, olds, news resource.PropertyMap) {
for _, par := range res.PutParameters {
sdkName := par.Name
if par.Value != nil && par.Value.SdkName != "" {
sdkName = par.Value.SdkName
}
// Auto-naming.
key := resource.PropertyKey(sdkName)
if !news.HasValue(key) && par.Value != nil && par.Value.AutoName != "" {
name, randomlyNamed, ok := k.getDefaultName(urn, randomSeed, autonaming, par.Value.AutoName, key, olds)
if ok {
news[key] = *name
if randomlyNamed {
news[createBeforeDeleteFlag] = resource.NewBoolProperty(true)
}
}
}
// Auto-location.
if !news.HasValue("location") && par.Body != nil && !res.AutoLocationDisabled {
if _, ok := par.Body.Properties["location"]; ok {
v := k.getDefaultLocation(ctx, olds, news)
if v != nil {
news["location"] = *v
}
}
}
}
// Set the default value of azureApiVersion to the APIVersion of the inputs.
// Note that some Azure resource types do not have an APIVersion (e.g. storage:Blob).
if k.getVersion().Major >= 3 {
if !news.HasValue("azureApiVersion") && res.APIVersion != "" {
news["azureApiVersion"] = resource.NewStringProperty(res.APIVersion)
}
}
}
// validateType checks the all properties and required properties of the given type and value map.
func (k *azureNativeProvider) validateType(ctx string, typ *resources.AzureAPIType,
values map[string]interface{}) []*rpc.CheckFailure {
var failures []*rpc.CheckFailure
for _, name := range typ.RequiredProperties {
prop := typ.Properties[name]
if prop.SdkName != "" {
name = prop.SdkName
}
if _, has := values[name]; !has {
propCtx := name
if ctx != "" {
propCtx = fmt.Sprintf("%s.%s", ctx, name)
}
reason := fmt.Sprintf("missing required property '%s'", propCtx)
if propCtx == "location" {
reason += ". Either set it explicitly or configure it with 'pulumi config set azure-native:location <value>'."
}
failures = append(failures, &rpc.CheckFailure{
Reason: reason,
})
}
}
for name, prop := range typ.Properties {
p := prop // https://go.dev/wiki/CommonMistakes#using-reference-to-loop-iterator-variable
if prop.SdkName != "" {
name = prop.SdkName
}
value, ok := values[name]
if !ok {
continue
}
propCtx := name
if ctx != "" {
propCtx = fmt.Sprintf("%s.%s", ctx, name)
}
failures = append(failures, k.validateProperty(propCtx, &p, value)...)
}
return failures
}
// validateProperty checks the property value against its metadata.
func (k *azureNativeProvider) validateProperty(ctx string, prop *resources.AzureAPIProperty,
value interface{}) []*rpc.CheckFailure {
var failures []*rpc.CheckFailure
if _, ok := value.(resource.Computed); ok {
return failures
}
if prop == nil || prop.Ref == convert.TypeAny {
return failures
}
switch value := value.(type) {
case resource.Computed:
// Skip an unresolved value.
return failures
case map[string]interface{}:
if prop.Ref == "" {
return failures
}
// Typed object: validate all properties by looking up its type definition.
typeName := strings.TrimPrefix(prop.Ref, "#/types/")
typ, ok, err := k.lookupType(prop.Ref)
if err != nil {
return append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("error decoding type spec '%s': %v", typeName, err),
})
}
if !ok {
return append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("schema type '%s' not found", typeName),
})
}
failures = append(failures, k.validateType(ctx, typ, value)...)
case []interface{}:
if prop.Type != "array" && !prop.IsStringSet {
return append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("'%s' should be of type '%s' but got an array", ctx, prop.Type),
})
}
// Array: validate each item.
for index, item := range value {
itemCtx := fmt.Sprintf("%s[%d]", ctx, index)
failures = append(failures, k.validateProperty(itemCtx, prop.Items, item)...)
}
case string:
if prop.Type != "string" {
return append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("'%s' should be of type '%s' but got a string", ctx, prop.Type),
})
}
// Validate a string according to https://swagger.io/docs/specification/data-models/data-types/#string
// Validate min/max length and RegEx pattern (apply to empty strings too).
length := int64(len(value))
if prop.MinLength != nil && length < *prop.MinLength {
failures = append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("'%s' is too short (%d): at least %d characters required",
ctx, length, *prop.MinLength),
})
}
if prop.MaxLength != nil && length > *prop.MaxLength {
failures = append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("'%s' is too long (%d): at most %d characters allowed",
ctx, length, *prop.MaxLength),
})
}
if prop.Pattern != "" {
pattern, err := regexp.Compile(prop.Pattern)
// TODO: Support ECMA-262 regexp https://github.com/pulumi/pulumi-azure-native/issues/164
if err == nil && !pattern.MatchString(value) {
failures = append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("'%s' does not match expression '%s'", ctx, prop.Pattern),
})
}
}
case float64:
if prop.Type != "number" && prop.Type != "integer" {
return append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("'%s' should be of type '%s' but got a number", ctx, prop.Type),
})
}
if prop.Type == "integer" {
if _, frac := math.Modf(math.Abs(value)); frac > 1e-9 && frac < 1.0-1e-9 {
failures = append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("'%s' must be an integer but got %f", ctx, value),
})
}
}
// Validate min/max inclusive ranges per https://swagger.io/docs/specification/data-models/data-types/#numbers
if prop.Minimum != nil && value < *prop.Minimum {
failures = append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("'%s' is too low (%f < %f)", ctx, value, *prop.Minimum),
})
}
if prop.Maximum != nil && value > *prop.Maximum {
failures = append(failures, &rpc.CheckFailure{
Reason: fmt.Sprintf("'%s' is too high (%f > %f)", ctx, value, *prop.Maximum),
})
}
}
return failures
}
func (k *azureNativeProvider) GetSchema(_ context.Context, req *rpc.GetSchemaRequest) (*rpc.GetSchemaResponse, error) {
if v := req.GetVersion(); v != 0 {
return nil, fmt.Errorf("unsupported schema version %d", v)
}
return &rpc.GetSchemaResponse{Schema: string(k.schemaBytes)}, nil
}
// CheckConfig validates the configuration for this provider.
func (k *azureNativeProvider) CheckConfig(_ context.Context, req *rpc.CheckRequest) (*rpc.CheckResponse, error) {
return &rpc.CheckResponse{Inputs: req.GetNews()}, nil
}
// DiffConfig diffs the configuration for this provider.
func (k *azureNativeProvider) DiffConfig(context.Context, *rpc.DiffRequest) (*rpc.DiffResponse, error) {
return &rpc.DiffResponse{
Changes: 0,
Replaces: []string{},
Stables: []string{},
DeleteBeforeReplace: false,
}, nil
}
// Diff checks what impacts a hypothetical update will have on the resource's properties.
func (k *azureNativeProvider) Diff(ctx context.Context, req *rpc.DiffRequest) (*rpc.DiffResponse, error) {
urn := resource.URN(req.GetUrn())
label := fmt.Sprintf("%s.Diff(%s)", k.name, urn)
// Retrieve the old state.
oldState, err := plugin.UnmarshalProperties(req.GetOlds(), plugin.MarshalOptions{
Label: fmt.Sprintf("%s.olds", label), KeepUnknowns: true, SkipNulls: true, KeepSecrets: true,
})
if err != nil {
return nil, err
}
// Extract old inputs from the OldInputs, if available, or the `__inputs` field of the old state as a fallback.
oldInputs, err := parseCheckpointObject(req.OldInputs, oldState, label)
if err != nil {
return nil, err
}
if oldInputs == nil {
// Protect against a crash for the transition from pre-__inputs state files.
// This shouldn't happen in any real user's stack.
oldInputs = resource.PropertyMap{}
logging.V(9).Infof("no __inputs found for '%s'", urn)
}
// v2-to-v3 migration: apiVersion might be available in the old state and we use it to suppress spurious diffs
// that would otherwise be produced by mere input-input diffing.
migratedApiVersion := false
if k.getVersion().Major >= 3 {
if _, ok := oldInputs["azureApiVersion"]; !ok {
if v, ok := oldState["azureApiVersion"]; ok {
oldInputs["azureApiVersion"] = v
migratedApiVersion = true
}
}
}
// Get new resource inputs. The user is submitting these as an update.
newResInputs, err := plugin.UnmarshalProperties(req.GetNews(), plugin.MarshalOptions{
Label: fmt.Sprintf("%s.news", label),
KeepUnknowns: true,
SkipNulls: true,
KeepSecrets: true,
})
if err != nil {
return nil, errors.Wrapf(err, "diff failed because malformed resource inputs %v %v",
oldState, newResInputs)
}
// Get the resource definition for looking up additional metadata.
res, err := k.lookupResourceFromURN(urn)
if err != nil {
return nil, err
}
// Check if API version has changed between state and current provider metadata.
// If so, warn the user to run `pulumi refresh` for proper schema alignment.
var oldApiVersion string
if azureApiVersion, ok := oldState["azureApiVersion"]; ok && azureApiVersion.IsString() {
oldApiVersion = azureApiVersion.StringValue()
if oldApiVersion != res.APIVersion {
logging.V(5).Infof("%s: API version in state (%s) differs from provider metadata (%s)",
label, oldApiVersion, res.APIVersion)
k.host.Log(ctx, diag.Warning, urn, fmt.Sprintf(
"Resource API version has changed from %s to %s. "+
"Run 'pulumi refresh' to update the resource state with the new API version schema.",
oldApiVersion, res.APIVersion))
}
}
detailedDiff := diff(k.lookupType, *res, oldInputs, newResInputs)
if detailedDiff == nil {
return &rpc.DiffResponse{
Changes: rpc.DiffResponse_DIFF_NONE,
Replaces: []string{},
Stables: []string{},
DeleteBeforeReplace: false,
}, nil
}
// Based on the detailed diff above, calculate the list of changes and replacements.
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | true |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/diff_test.go | provider/pkg/provider/diff_test.go | // Copyright 2016-2020, Pulumi Corporation.
package provider
import (
"encoding/json"
"fmt"
"testing"
"unicode"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/deepcopy"
rpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"pgregory.net/rapid"
)
func TestCalculateDiffBodyProperties(t *testing.T) {
res := resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Name: "bodyProperties",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"p1": {Type: "string"},
"p2": {Type: "number"},
"p3": {Type: "boolean"},
"p4": {Ref: "#/types/azure-native:foobar/v20200101:SomeType"},
"p5": {Type: "array", Items: &resources.AzureAPIProperty{
Type: "string",
}},
"p6": {Type: "array", Items: &resources.AzureAPIProperty{
Ref: "#/types/azure-native:foobar/v20200101:SomeType",
}},
"has.period": {Type: "string"},
"location": {Type: "string"},
},
},
},
},
}
diff := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"p1": {
Old: resource.PropertyValue{V: "oldvalue"},
New: resource.PropertyValue{V: "newvalue"},
},
"p4": {
Object: &resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"p41": {
Old: resource.PropertyValue{V: "oldvalue"},
New: resource.PropertyValue{V: "newvalue"},
},
"p44": {
Object: &resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"p441": {
Old: resource.PropertyValue{V: "oldvalue"},
New: resource.PropertyValue{V: "newvalue"},
},
},
},
},
},
Adds: map[resource.PropertyKey]resource.PropertyValue{
"p42": {V: 123},
"p45.period": {V: "yes"},
},
Deletes: map[resource.PropertyKey]resource.PropertyValue{
"p43": {V: true},
},
},
},
"p5": {
Array: &resource.ArrayDiff{
Updates: map[int]resource.ValueDiff{
0: {
Old: resource.PropertyValue{V: "old0value"},
New: resource.PropertyValue{V: "new0value"},
},
},
Adds: map[int]resource.PropertyValue{
1: {V: "new1value"},
},
Deletes: map[int]resource.PropertyValue{
2: {V: "old2value"},
},
},
},
"p6": {
Array: &resource.ArrayDiff{
Updates: map[int]resource.ValueDiff{
0: {
Object: &resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"p61": {
Old: resource.PropertyValue{V: "oldvalue"},
New: resource.PropertyValue{V: "newvalue"},
},
},
Adds: map[resource.PropertyKey]resource.PropertyValue{
"p62": {V: 123},
},
},
},
},
},
},
"has.period": {},
"location": {
Old: resource.PropertyValue{V: "East US"},
New: resource.PropertyValue{V: "East US 2"},
},
},
Adds: map[resource.PropertyKey]resource.PropertyValue{
"p2": {V: 123},
"has.period": {V: "yes"},
},
Deletes: map[resource.PropertyKey]resource.PropertyValue{
"p3": {V: true},
},
}
actual := calculateDetailedDiff(&res, emptyTypes, &diff)
expected := map[string]*rpc.PropertyDiff{
"p1": {Kind: rpc.PropertyDiff_UPDATE},
"p2": {Kind: rpc.PropertyDiff_ADD},
"p3": {Kind: rpc.PropertyDiff_DELETE},
"p4.p41": {Kind: rpc.PropertyDiff_UPDATE},
"p4.p42": {Kind: rpc.PropertyDiff_ADD},
"p4.p43": {Kind: rpc.PropertyDiff_DELETE},
"p4.[\"p45.period\"]": {Kind: rpc.PropertyDiff_ADD},
"p4.p44.p441": {Kind: rpc.PropertyDiff_UPDATE},
"p5[0]": {Kind: rpc.PropertyDiff_UPDATE},
"p5[1]": {Kind: rpc.PropertyDiff_ADD},
"p5[2]": {Kind: rpc.PropertyDiff_DELETE},
"p6[0].p61": {Kind: rpc.PropertyDiff_UPDATE},
"p6[0].p62": {Kind: rpc.PropertyDiff_ADD},
"[\"has.period\"]": {Kind: rpc.PropertyDiff_ADD},
"location": {Kind: rpc.PropertyDiff_UPDATE},
}
assert.Equal(t, expected, actual)
}
func TestCalculateDiffReplacesPathParameters(t *testing.T) {
res := resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Location: "path",
Name: "p1",
},
{
Location: "path",
Name: "p2",
Value: &resources.AzureAPIProperty{
SdkName: "Prop2",
},
},
{
Location: "query",
Name: "q1",
},
{
Location: "body",
Name: "b1",
},
},
}
diff := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"p1": {
Old: resource.PropertyValue{V: "oldpath"},
New: resource.PropertyValue{V: "newpath"},
},
"Prop2": {
Old: resource.PropertyValue{V: "oldpath"},
New: resource.PropertyValue{V: "newpath"},
},
"q1": {
Old: resource.PropertyValue{V: "oldquery"},
New: resource.PropertyValue{V: "newquery"},
},
"b1": {
Old: resource.PropertyValue{V: "oldbody"},
New: resource.PropertyValue{V: "newbody"},
},
},
}
actual := calculateDetailedDiff(&res, emptyTypes, &diff)
expected := map[string]*rpc.PropertyDiff{
"p1": {Kind: rpc.PropertyDiff_UPDATE_REPLACE},
"Prop2": {Kind: rpc.PropertyDiff_UPDATE_REPLACE},
"q1": {Kind: rpc.PropertyDiff_UPDATE},
"b1": {Kind: rpc.PropertyDiff_UPDATE},
}
assert.Equal(t, expected, actual)
}
func TestCalculateDiffReplacesBodyProperties(t *testing.T) {
const topLevelProperty = "p1"
oldToNew := resource.ValueDiff{
Old: resource.PropertyValue{V: "oldvalue"},
New: resource.PropertyValue{V: "newvalue"},
}
test := func(t *testing.T, property resources.AzureAPIProperty, refProperties map[string]resources.AzureAPIProperty, diff resource.ObjectDiff, expected map[string]*rpc.PropertyDiff) {
res := resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Name: "bodyProperties",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
topLevelProperty: property,
},
},
},
},
}
lookupType := func(t string) (*resources.AzureAPIType, bool, error) {
return &resources.AzureAPIType{
Properties: refProperties,
}, true, nil
}
actual := calculateDetailedDiff(&res, lookupType, &diff)
assert.Equal(t, expected, actual)
}
t.Run("primitive property", func(t *testing.T) {
property := resources.AzureAPIProperty{Type: "string"}
diff := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
topLevelProperty: oldToNew,
},
}
expected := map[string]*rpc.PropertyDiff{
topLevelProperty: {Kind: rpc.PropertyDiff_UPDATE},
}
test(t, property, nil, diff, expected)
})
t.Run("primitive property with forceNew", func(t *testing.T) {
property := resources.AzureAPIProperty{Type: "string", ForceNew: true}
diff := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
topLevelProperty: oldToNew,
},
}
expected := map[string]*rpc.PropertyDiff{
topLevelProperty: {Kind: rpc.PropertyDiff_UPDATE_REPLACE},
}
test(t, property, nil, diff, expected)
})
t.Run("object with updates", func(t *testing.T) {
property := resources.AzureAPIProperty{Ref: "#/types/foo"}
refProperties := map[string]resources.AzureAPIProperty{
"inner1": {},
"inner2": {ForceNew: true},
}
diff := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
topLevelProperty: {
Object: &resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"inner1": oldToNew,
"inner2": oldToNew,
},
},
},
},
}
expected := map[string]*rpc.PropertyDiff{
topLevelProperty + ".inner1": {Kind: rpc.PropertyDiff_UPDATE},
topLevelProperty + ".inner2": {Kind: rpc.PropertyDiff_UPDATE_REPLACE},
}
test(t, property, refProperties, diff, expected)
})
t.Run("object with updates and forceNew", func(t *testing.T) {
property := resources.AzureAPIProperty{Ref: "#/types/foo", ForceNew: true}
refProperties := map[string]resources.AzureAPIProperty{
"inner1": {},
}
diff := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
topLevelProperty: {
Object: &resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"inner1": oldToNew,
},
},
},
},
}
expected := map[string]*rpc.PropertyDiff{
topLevelProperty + ".inner1": {Kind: rpc.PropertyDiff_UPDATE_REPLACE},
}
test(t, property, refProperties, diff, expected)
})
diffObjectHasPropertyAddedAndDeleted := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
topLevelProperty: {
Object: &resource.ObjectDiff{
Deletes: map[resource.PropertyKey]resource.PropertyValue{
"inner1": {V: "removed"},
},
Adds: map[resource.PropertyKey]resource.PropertyValue{
"inner3": {V: "added"},
},
},
},
},
}
t.Run("object with additions and deletions only", func(t *testing.T) {
property := resources.AzureAPIProperty{Ref: "#/types/foo"}
refProperties := map[string]resources.AzureAPIProperty{
"inner1": {},
}
expected := map[string]*rpc.PropertyDiff{
topLevelProperty + ".inner1": {Kind: rpc.PropertyDiff_DELETE},
topLevelProperty + ".inner3": {Kind: rpc.PropertyDiff_ADD},
}
test(t, property, refProperties, diffObjectHasPropertyAddedAndDeleted, expected)
})
t.Run("object with additions and deletions only and forceNew", func(t *testing.T) {
property := resources.AzureAPIProperty{Ref: "#/types/foo", ForceNew: true}
refProperties := map[string]resources.AzureAPIProperty{
"inner1": {},
}
expected := map[string]*rpc.PropertyDiff{
topLevelProperty: {Kind: rpc.PropertyDiff_UPDATE_REPLACE},
topLevelProperty + ".inner1": {Kind: rpc.PropertyDiff_DELETE},
topLevelProperty + ".inner3": {Kind: rpc.PropertyDiff_ADD},
}
test(t, property, refProperties, diffObjectHasPropertyAddedAndDeleted, expected)
})
t.Run("array of object with updates", func(t *testing.T) {
property := resources.AzureAPIProperty{
Items: &resources.AzureAPIProperty{Ref: "#/types/foo"},
}
refProperties := map[string]resources.AzureAPIProperty{
"inner1": {},
"inner2": {ForceNew: true},
}
diff := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
topLevelProperty: {
Array: &resource.ArrayDiff{
Updates: map[int]resource.ValueDiff{
0: {
Object: &resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"inner1": oldToNew,
"inner2": oldToNew,
},
},
},
},
},
},
},
}
expected := map[string]*rpc.PropertyDiff{
topLevelProperty + "[0].inner1": {Kind: rpc.PropertyDiff_UPDATE},
topLevelProperty + "[0].inner2": {Kind: rpc.PropertyDiff_UPDATE_REPLACE},
}
test(t, property, refProperties, diff, expected)
})
}
func TestApplyDiff(t *testing.T) {
// Inputs are the base to apply to.
inputs := resource.PropertyMap{
"p1": {V: "oldvalue"},
"p2": {V: "iamdeleted"},
"p4": {
V: resource.PropertyMap{
"p4.1": {V: "oldervalue"},
"p4.3": {V: "willbedeleted"},
},
},
"p5": {
V: []resource.PropertyValue{
{
V: resource.PropertyMap{
"p5.1": {V: "nochange1"},
"p5.2": {
V: resource.PropertyMap{
"p5.2.1": {V: "oldestvalue"},
"p5.2.2": {V: "nochange2"},
},
},
},
},
},
},
}
// Diff represents a difference between old outputs and new outputs.
diff := resource.ObjectDiff{
Adds: resource.PropertyMap{
"p3": {V: "newkey"},
},
Deletes: resource.PropertyMap{
"p2": {V: "iamdeleted"},
},
Updates: map[resource.PropertyKey]resource.ValueDiff{
"p1": {
Old: resource.PropertyValue{V: "oldvalue"},
New: resource.PropertyValue{V: "newvalue"},
},
"p4": {
Old: resource.PropertyValue{
V: resource.PropertyMap{
"p4.1": {V: "oldervalue"},
"p4.2": {V: "same"},
"p4.3": {V: "willbedeleted"},
},
},
New: resource.PropertyValue{
V: resource.PropertyMap{
"p4.1": {V: "newervalue"},
"p4.2": {V: "same"},
"p4.4": {V: "thiswasadded"},
},
},
},
"p5": {
Old: resource.PropertyValue{
V: []resource.PropertyValue{
{
V: resource.PropertyMap{
"p5.1": {V: "nochange1"},
"p5.2": {
V: resource.PropertyMap{
"p5.2.1": {V: "oldestvalue"},
"p5.2.2": {V: "nochange2"},
"p5.2.3": {V: "nochange3"},
},
},
"p5.3": {V: "nochange4"},
},
},
},
},
New: resource.PropertyValue{
V: []resource.PropertyValue{
{
V: resource.PropertyMap{
"p5.1": {V: "nochange1"},
"p5.2": {
V: resource.PropertyMap{
"p5.2.1": {V: "newestvalue"},
"p5.2.2": {V: "nochange2"},
"p5.2.3": {V: "nochange3"},
},
},
"p5.3": {V: "nochange4"},
},
},
{
V: resource.PropertyMap{
"p6.1": {V: "new1"},
"p6.2": {
V: resource.PropertyMap{
"p6.2.1": {V: "new2"},
},
},
"p6.3": {V: "new3"},
},
},
},
},
},
},
}
actual := applyDiff(inputs, &diff)
expected := resource.PropertyMap{
"p1": {V: "newvalue"},
"p3": {V: "newkey"},
"p4": {V: resource.PropertyMap{
"p4.1": {V: "newervalue"},
"p4.4": {V: "thiswasadded"},
}},
"p5": {
V: []resource.PropertyValue{
{
V: resource.PropertyMap{
"p5.1": {V: "nochange1"},
"p5.2": {
V: resource.PropertyMap{
"p5.2.1": {V: "newestvalue"},
"p5.2.2": {V: "nochange2"},
},
},
},
},
{
V: resource.PropertyMap{
"p6.1": {V: "new1"},
"p6.2": {
V: resource.PropertyMap{
"p6.2.1": {V: "new2"},
},
},
"p6.3": {V: "new3"},
},
},
},
},
}
assert.Equal(t, expected, actual)
}
func TestResourceGroupNameDiffingIsCaseInsensitive(t *testing.T) {
res := resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Location: "path",
Name: "resourceGroupName",
},
{
Location: "body",
Name: "bodyProperties",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"something": {Type: "string"},
},
},
},
},
}
variantsSame := []string{"MyRG", "myrg", "MYRG", "MyRg"}
for _, oldValue := range variantsSame {
for _, newValue := range variantsSame {
diff := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"resourceGroupName": {
Old: resource.PropertyValue{V: oldValue},
New: resource.PropertyValue{V: newValue},
},
},
}
actual := calculateDetailedDiff(&res, emptyTypes, &diff)
expected := map[string]*rpc.PropertyDiff{}
assert.Equal(t, expected, actual)
}
}
}
func TestLocationDiffingIsInsensitiveToSpacesAndCasing(t *testing.T) {
res := resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Name: "bodyProperties",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"location": {Type: "string"},
},
},
},
},
}
variantsSame := []string{"West US 2", "WestUS2", "west us 2", "westus2"}
for _, oldValue := range variantsSame {
for _, newValue := range variantsSame {
diff := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"location": {
Old: resource.PropertyValue{V: oldValue},
New: resource.PropertyValue{V: newValue},
},
},
}
actual := calculateDetailedDiff(&res, emptyTypes, &diff)
expected := map[string]*rpc.PropertyDiff{}
assert.Equal(t, expected, actual)
}
}
}
func TestSkuDiffingIsInsensitiveToAksPermutations(t *testing.T) {
res := resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Name: "bodyProperties",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"sku": {Type: "object"},
},
},
},
},
}
testCases := [][]string{
[]string{"Basic", "Paid", "Base", "Standard", "equal"},
[]string{"Base", "Standard", "Basic", "Paid", "equal"},
[]string{"Base", "Free", "Basic", "Free", "equal"},
[]string{"Basic", "Paid", "Basic", "Standard", "equal"},
[]string{"Basic", "Paid", "Basic", "Paid", "equal"},
[]string{"Base", "Standard", "Basic", "Free", "not equal"},
[]string{"Premium", "Standard", "Basic", "Free", "not equal"},
}
for _, testCase := range testCases {
diff := resource.ObjectDiff{
Updates: map[resource.PropertyKey]resource.ValueDiff{
"sku": {
Old: resource.PropertyValue{V: resource.PropertyMap{
"name": {V: testCase[0]},
"tier": {V: testCase[1]}},
},
New: resource.PropertyValue{V: resource.PropertyMap{
"name": {V: testCase[2]},
"tier": {V: testCase[3]}},
},
},
},
}
actual := calculateDetailedDiff(&res, emptyTypes, &diff)
if testCase[4] == "equal" {
expected := map[string]*rpc.PropertyDiff{}
assert.Equal(t, expected, actual)
} else {
assert.Equal(t, 1, len(actual))
}
}
}
var emptyTypes resources.TypeLookupFunc = func(t string) (*resources.AzureAPIType, bool, error) {
return nil, false, nil
}
func TestChangesAndReplacements_AddedPropertyCausesDiff(t *testing.T) {
changes, replacements := calculateChangesAndReplacementsForOneAddedProperty(t, "newvalue", nil)
assert.Len(t, changes, 1)
assert.Len(t, replacements, 0)
}
func TestChangesAndReplacements_AddedPropertyWithDefaultCausesNoDiff(t *testing.T) {
changes, replacements := calculateChangesAndReplacementsForOneAddedProperty(t, "defaultvalue", "defaultvalue")
assert.Len(t, changes, 0)
assert.Len(t, replacements, 0)
}
func TestChangesAndReplacements_AddedPropertyWithDefaultButDifferentValueCausesDiff(t *testing.T) {
changes, replacements := calculateChangesAndReplacementsForOneAddedProperty(t, "newvalue", "defaultvalue")
assert.Len(t, changes, 1)
assert.Len(t, replacements, 0)
}
func TestChangesAndReplacements_ReduceNestedPropertiesToTopLevel(t *testing.T) {
detailedDiff := map[string]*rpc.PropertyDiff{
"agentPoolProfiles[0].count": &rpc.PropertyDiff{
Kind: rpc.PropertyDiff_ADD,
},
}
oldState := resource.PropertyMap{}
oldInputs := resource.PropertyMap{
resource.PropertyKey("agentPoolProfiles[0].count"): {V: 3},
}
newInputs := resource.PropertyMap{
resource.PropertyKey("agentPoolProfiles[0].count"): {V: 4},
}
res := resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Name: "bodyProperties",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"agentPoolProfiles": {Type: "array", Items: &resources.AzureAPIProperty{
Type: "object",
}},
},
},
},
},
}
changes, replacements := calculateChangesAndReplacements(detailedDiff, oldInputs, newInputs, oldState, res)
assert.Len(t, changes, 1)
assert.Equal(t, "agentPoolProfiles", changes[0])
assert.Empty(t, replacements)
}
func calculateChangesAndReplacementsForOneAddedProperty(t *testing.T, value string, defaultValue interface{}) ([]string, []string) {
propertyName := "p1"
var detailedDiff map[string]*rpc.PropertyDiff = map[string]*rpc.PropertyDiff{
propertyName: &rpc.PropertyDiff{
Kind: rpc.PropertyDiff_ADD,
},
}
oldInputs := resource.PropertyMap{}
oldState := resource.PropertyMap{}
newInputs := resource.PropertyMap{
resource.PropertyKey(propertyName): {V: value},
}
res := resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Name: "bodyProperties",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
propertyName: {
Type: "string",
Default: defaultValue,
},
},
},
},
},
}
return calculateChangesAndReplacements(detailedDiff, oldInputs, newInputs, oldState, res)
}
func TestNormalizeAzureId(t *testing.T) {
testCases := []struct {
input string
output string
}{
{
input: "",
output: "",
},
{
input: "foo/bar",
output: "foo/bar",
},
{
input: "/subscriptions/foo/bar",
output: "/subscriptions/foo/bar",
},
{
input: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
output: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
},
{
input: "/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/something",
output: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
},
{
input: "/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/something/with/a/path",
output: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something/with/a/path",
},
}
for _, testCase := range testCases {
assert.Equal(t, testCase.output, normalizeAzureId(testCase.input))
}
}
func TestStringsEqualCaseInsensitiveAzureIds(t *testing.T) {
for _, equalCase := range []struct {
id1 string
id2 string
}{
{
id1: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
id2: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
},
{
id1: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
id2: "/subscriptions/123/resourcegroups/rg/providers/Microsoft.compute/something",
},
{
id1: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
id2: "/subscriptions/123/resourcegroups/rg/providers/microsoft.COMPUTE/something",
},
{
id1: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
id2: "/subscriptions/123/resourceGroups/rg/Providers/microsoft.Compute/something",
},
{
id1: "/subscriptions/123/resourcegroups/rg",
id2: "/subscriptions/123/resourcegroups/rg",
},
} {
assert.True(t, stringsEqualCaseInsensitiveAzureIds(equalCase.id1, equalCase.id2))
}
for _, notEqualCase := range []struct {
id1 string
id2 string
}{
{
id1: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
id2: "/subscriptions/456/resourcegroups/rg/providers/microsoft.compute/something",
},
{
id1: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
id2: "/subscriptions/123/resourcegroups/rg2/providers/microsoft.COMPUTE/something",
},
{
id1: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
id2: "/subscriptions/123/resourcegroups/rg/providers/Microsoft.compute/somethingElse",
},
{
id1: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something",
id2: "/subscriptions/123/resourceGroups/rg/providers/microsoft.ComputeBetter/something",
},
{
id1: "/subscriptions/123/resourcegroups/rg",
id2: "/subscriptions/123/resourceGroups/rg",
},
} {
assert.False(t, stringsEqualCaseInsensitiveAzureIds(notEqualCase.id1, notEqualCase.id2))
}
}
func TestDiffKeyedArrays(t *testing.T) {
t.Run("basic example", func(t *testing.T) {
// The unique identifier for each object is the "p1" property.
keys := []string{"p1"}
// The first object will be unchanged, the second updated, the third removed and replaced
// with a different one. The unchanged one has case differences that shouldn't matter.
old := []resource.PropertyValue{
{V: resource.PropertyMap{
"p1": {V: "/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/something"},
"p2": {V: "v2"},
"p3": {V: "v3"},
}},
{V: resource.PropertyMap{
"p1": {V: "updated"},
"p2": {V: "v2"},
"p3": {V: "v3"},
}},
{V: resource.PropertyMap{
"p1": {V: "will be deleted"},
"p2": {V: "v2"},
"p3": {V: "v3"},
}},
}
// Change the order compared to `old` to prove that objects are identified by their key properties.
new := []resource.PropertyValue{
{V: resource.PropertyMap{
"p1": {V: "updated"},
"p2": {V: "v2222"},
// "p3" is deleted
"p4": {V: "v4444"}, // added property
}},
{V: resource.PropertyMap{
"p1": {V: "new"},
"p2": {V: "v222"},
}},
{V: resource.PropertyMap{
"p1": {V: "/subscriptions/123/resourcegroups/rg/providers/microsoft.compute/something"},
"p2": {V: "v2"},
"p3": {V: "v3"},
}},
}
properties := map[string]resources.AzureAPIProperty{}
diff, validKeyedArray := diffKeyedArrays(properties, keys, old, new, "")
assert.True(t, validKeyedArray)
assert.NotNil(t, diff)
assert.NotNil(t, diff.Old)
assert.NotNil(t, diff.New)
assert.Equal(t, 1, len(diff.Array.Adds))
assert.Equal(t, new[1], diff.Array.Adds[1])
require.Equal(t, 1, len(diff.Array.Sames))
require.Contains(t, diff.Array.Sames, 2)
sameOld := old[0].ObjectValue()
sameNew := diff.Array.Sames[2].ObjectValue()
assert.Equal(t, normalizeAzureId(sameOld["p1"].StringValue()), normalizeAzureId(sameNew["p1"].StringValue()))
assert.Equal(t, sameOld["p2"], sameNew["p2"])
assert.Equal(t, 1, len(diff.Array.Deletes))
assert.Equal(t, old[2], diff.Array.Deletes[2])
assert.Equal(t, 1, len(diff.Array.Updates))
assert.Contains(t, diff.Array.Updates, 0)
update := diff.Array.Updates[0]
assert.NotNil(t, update.Object)
assert.Contains(t, update.Object.Sames, resource.PropertyKey("p1"))
assert.Contains(t, update.Object.Updates, resource.PropertyKey("p2"))
assert.Contains(t, update.Object.Deletes, resource.PropertyKey("p3"))
assert.Contains(t, update.Object.Adds, resource.PropertyKey("p4"))
})
t.Run("recognizes invalid keyed array", func(t *testing.T) {
olds := map[string][]resource.PropertyValue{
"not an object": {
{V: resource.PropertyMap{"p1": {V: "oldvalue"}}},
{V: "oldvalue"},
},
"missing keys": {
{V: resource.PropertyMap{"p1": {V: "oldvalue"}}},
{V: resource.PropertyMap{"foo": {V: "bar"}}},
},
"duplicate key value": {
{V: resource.PropertyMap{"p1": {V: "oldvalue"}}},
{V: resource.PropertyMap{"p1": {V: "oldvalue"}}},
},
}
for name, old := range olds {
diff, ok := diffKeyedArrays(map[string]resources.AzureAPIProperty{}, []string{"p1"}, old, old, "")
require.False(t, ok, name)
require.Nil(t, diff, name)
}
})
}
// A series of property-based tests that use rapid to generate random inputs and random mutations
// of these inputs, then verify that the diffing algorithm produces the expected results.
func TestDiffKeyedArraysRapid(tt *testing.T) {
runRapidTest := func(t *rapid.T,
keyProperties []string,
objectGenerator *rapid.Generator[resource.PropertyValue],
mutator mutator) {
array := makeArrayGenerator(objectGenerator)
old := array.Draw(t, "old").ArrayValue()
changes, new := mutator(t, old, keyProperties)
diff, ok := diffKeyedArrays(map[string]resources.AzureAPIProperty{}, keyProperties, old, new, "")
assert.True(t, ok)
compareDiffWithRecordedChanges(t, diff, changes, old, new)
}
tt.Run("no change, single key", rapid.MakeCheck(func(t *rapid.T) {
keyProperty := []string{"p1"}
runRapidTest(t, keyProperty, makeNestedObjectGenerator(keyProperty...), noopMutator)
}))
tt.Run("no change, multiple keys", rapid.MakeCheck(func(t *rapid.T) {
keyProperties := []string{"p1", "p2", "p3"}
runRapidTest(t, keyProperties, makeNestedObjectGenerator(keyProperties...), noopMutator)
}))
tt.Run("single key, single level", rapid.MakeCheck(func(t *rapid.T) {
keyProperty := []string{"p1"}
runRapidTest(t, keyProperty, makeObjectGenerator(allStringValues, keyProperty...), keyedArrayMutator)
}))
tt.Run("single key, nested", rapid.MakeCheck(func(t *rapid.T) {
keyProperty := []string{"p1"}
runRapidTest(t, keyProperty, makeNestedObjectGenerator(keyProperty...), keyedArrayMutator)
}))
tt.Run("multiple keys, nested", rapid.MakeCheck(func(t *rapid.T) {
keyProperties := []string{"p1", "p2", "p3"}
runRapidTest(t, keyProperties, makeNestedObjectGenerator(keyProperties...), keyedArrayMutator)
}))
}
//// Rapid book-keeping
type changeKind string
const (
add changeKind = "add"
update changeKind = "update"
same changeKind = "same"
del changeKind = "delete"
)
type objectChanges map[resource.PropertyKey]changeKind
// allSames returns true if all changes are "same", i.e., the object as a whole is unchanged.
func (o objectChanges) allSames() bool {
for _, operation := range o {
if operation != same {
return false
}
}
return true
}
type arrayElementChanges struct {
update objectChanges
add, delete bool
index int
}
//// Rapid generators
var allStringValues = rapid.Custom[resource.PropertyValue](func(t *rapid.T) resource.PropertyValue {
return resource.PropertyValue{V: rapid.String().Draw(t, "any string")}
})
// Since the key properties of keyed arrays have unique id semantics, they must be unique.
// While random strings are unlikely to collide, when there's a test failure rapid minimizes the
// input which produces short repeating strings.
var seen = map[string]struct{}{}
var uniqueStrings = rapid.Custom[string](func(t *rapid.T) string {
hexValues := rapid.StringOfN(rapid.RuneFrom(nil, unicode.ASCII_Hex_Digit), 8, 8, -1)
uniqueStrings := hexValues.Filter(func(v string) bool {
_, ok := seen[v]
if ok {
return false
}
seen[v] = struct{}{}
return true
})
return uniqueStrings.Draw(t, "S")
})
var uniqueStringValues = rapid.Custom[resource.PropertyValue](func(t *rapid.T) resource.PropertyValue {
return resource.PropertyValue{V: uniqueStrings.Draw(t, "V")}
})
// makeArrayGenerator generates an array whose values are generated via the given `valueGenerator`.
// Note: if the result is used as a keyed array, valueGenerator must generate objects.
func makeArrayGenerator(valueGenerator *rapid.Generator[resource.PropertyValue]) *rapid.Generator[resource.PropertyValue] {
return rapid.Custom[resource.PropertyValue](func(t *rapid.T) resource.PropertyValue {
result := []resource.PropertyValue{}
len := rapid.IntRange(0, 8).Draw(t, "len")
for i := 0; i < len; i++ {
result = append(result, valueGenerator.Draw(t, "array value"))
}
return resource.NewArrayProperty(result)
})
}
func makeObjectGenerator(valueGenerator *rapid.Generator[resource.PropertyValue], keys ...string) *rapid.Generator[resource.PropertyValue] {
return rapid.Custom[resource.PropertyValue](func(t *rapid.T) resource.PropertyValue {
result := resource.PropertyMap{}
numOtherProperties := rapid.IntRange(0, 4).Draw(t, "numProperties")
otherProperties := make([]string, numOtherProperties)
for i := 0; i < numOtherProperties; i++ {
otherProperties[i] = uniqueStrings.Draw(t, "other property")
}
for _, key := range keys {
result[resource.PropertyKey(key)] = uniqueStringValues.Draw(t, "val")
}
for _, prop := range otherProperties {
result[resource.PropertyKey(prop)] = valueGenerator.Draw(t, "val")
}
// add some divergent properties as well, objects don't need to be totally homogenous
for i := 0; i < rapid.IntRange(0, 4).Draw(t, "numProperties"); i++ {
prop := uniqueStrings.Draw(t, "key")
result[resource.PropertyKey(prop)] = valueGenerator.Draw(t, "val")
}
return resource.PropertyValue{V: result}
})
}
func makeNestedObjectGenerator(keys ...string) *rapid.Generator[resource.PropertyValue] {
objects := makeObjectGenerator(allStringValues, keys...)
return makeObjectGenerator(objects, keys...)
}
//// Rapid mutators of PropertyValues to create changes between old and new
// mutateObject makes changes to `new` and records them in the return value.
// For each property of the object, it draws from the four operations
// [update, add, delete, same] and applies the operation.
// Key (identifier) properties in `keysToPreserve` are not mutated.
func mutateObject(t *rapid.T, old, new resource.PropertyMap, keysToPreserve []string) objectChanges {
record := objectChanges{}
operations := rapid.SampledFrom([]changeKind{add, update, same, del})
isKey := func(s string) bool {
for _, key := range keysToPreserve {
if key == s {
return true
}
}
return false
}
for k := range old {
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | true |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/provider_test.go | provider/pkg/provider/provider_test.go | package provider
import (
"context"
"fmt"
"reflect"
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/fake"
"github.com/blang/semver"
structpb "github.com/golang/protobuf/ptypes/struct"
az "github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/convert"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/provider/crud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources/customresources"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
rpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRestoreDefaultInputs(t *testing.T) {
inputs := resource.PropertyMap{
"unrelated": resource.NewStringProperty("foo"),
}
olds := resource.PropertyMap{
"unrelated": resource.NewStringProperty("foo"),
"networkRuleSet": resource.NewObjectProperty(resource.PropertyMap{}),
}
res := resources.AzureAPIResource{
DefaultProperties: map[string]interface{}{
"networkRuleSet": map[string]interface{}{
"defaultAction": "Allow",
},
},
}
err := restoreDefaultInputsForRemovedProperties(inputs, res, olds)
assert.NoError(t, err)
// Was not in inputs but was added to reset it back to default.
assert.Contains(t, inputs, resource.PropertyKey("networkRuleSet"))
}
func TestDoNotRestoreDefaultInputsIfInputPresent(t *testing.T) {
inputs := resource.PropertyMap{
"unrelated": resource.NewStringProperty("bar"),
"networkRuleSet": resource.NewObjectProperty(resource.PropertyMap{
"defaultAction": resource.NewStringProperty("Deny"),
}),
}
olds := resource.PropertyMap{
"unrelated": resource.NewStringProperty("foo"),
"networkRuleSet": resource.NewObjectProperty(resource.PropertyMap{}),
}
res := resources.AzureAPIResource{
DefaultProperties: map[string]interface{}{
"networkRuleSet": map[string]interface{}{
"defaultAction": "Allow",
},
},
}
err := restoreDefaultInputsForRemovedProperties(inputs, res, olds)
assert.NoError(t, err)
assert.Contains(t, inputs, resource.PropertyKey("networkRuleSet"))
// Input "deny" was not overwritten with default "allow"
assert.Equal(t, "Deny", inputs["networkRuleSet"].ObjectValue()["defaultAction"].StringValue())
}
func TestRestoreDefaultInputsIsNoopWithoutDefaultProperties(t *testing.T) {
inputs := resource.PropertyMap{}
olds := resource.PropertyMap{
"networkRuleSet": resource.NewObjectProperty(resource.PropertyMap{}),
}
res := resources.AzureAPIResource{} // no defaults
err := restoreDefaultInputsForRemovedProperties(inputs, res, olds)
assert.NoError(t, err)
assert.Empty(t, inputs)
// same with empty defaults
res.DefaultProperties = map[string]interface{}{}
err = restoreDefaultInputsForRemovedProperties(inputs, res, olds)
assert.NoError(t, err)
assert.Empty(t, inputs)
}
func TestMappableOldStateIsNoopWithoutDefaults(t *testing.T) {
res := resources.AzureAPIResource{} // no defaults
m := map[string]interface{}{"foo": "bar"}
removeDefaults(res, m, nil)
assert.Equal(t, map[string]interface{}{"foo": "bar"}, m)
}
func TestMappableOldStatePreservesNonDefaults(t *testing.T) {
res := resources.AzureAPIResource{
DefaultProperties: map[string]interface{}{
"networkRuleSet": map[string]interface{}{
"defaultAction": "Allow",
},
},
}
m := map[string]any{
"networkRuleSet": map[string]any{
"defaultAction": "Deny",
},
}
removeDefaults(res, m, nil)
assert.Equal(t, "Deny", m["networkRuleSet"].(map[string]interface{})["defaultAction"])
}
func TestMappableOldStateRemovesDefaultsThatWereInputs(t *testing.T) {
res := resources.AzureAPIResource{
DefaultProperties: map[string]interface{}{
"networkRuleSet": map[string]interface{}{
"defaultAction": "Allow",
},
},
}
m := map[string]any{
"networkRuleSet": map[string]any{
"defaultAction": "Allow",
},
}
removeDefaults(res, m, map[string]any{
"networkRuleSet": map[string]any{
"defaultAction": "Allow",
},
})
assert.NotContains(t, m, "networkRuleSet")
}
func TestMappableOldStatePreservesDefaultsThatWereNotInputs(t *testing.T) {
res := resources.AzureAPIResource{
DefaultProperties: map[string]interface{}{
"networkRuleSet": map[string]interface{}{
"defaultAction": "Allow",
},
},
}
m := map[string]any{
"networkRuleSet": map[string]any{
"defaultAction": "Allow",
},
}
removeDefaults(res, m, nil)
assert.Contains(t, m, "networkRuleSet")
}
func TestRemoveUnsetSubResourceProperties(t *testing.T) {
ctx := context.Background()
res, provider := setUpResourceWithRefAndProviderWithTypeLookup("")
t.Run("empty", func(t *testing.T) {
empty := &resources.AzureAPIResource{}
oldInputs := resource.PropertyMap{}
sdkResponse := map[string]any{}
actual := provider.removeUnsetSubResourceProperties(ctx, "urn", sdkResponse, oldInputs, empty)
expected := map[string]any{}
assert.Equal(t, expected, actual)
})
t.Run("remove", func(t *testing.T) {
oldInputs := resource.PropertyMap{}
sdkResponse := map[string]any{
"properties": map[string]any{
"accessPolicies": []any{
"a policy",
},
},
}
actual := provider.removeUnsetSubResourceProperties(ctx, "urn", sdkResponse, oldInputs, res)
expected := map[string]any{
"properties": map[string]any{},
}
assert.Equal(t, expected, actual)
})
t.Run("preserve", func(t *testing.T) {
oldInputs := resource.PropertyMap{
resource.PropertyKey("properties"): resource.NewObjectProperty(resource.PropertyMap{
resource.PropertyKey("accessPolicies"): resource.NewArrayProperty([]resource.PropertyValue{}),
}),
}
sdkResponse := map[string]any{
"properties": map[string]any{
"accessPolicies": []any{},
},
}
actual := provider.removeUnsetSubResourceProperties(ctx, "urn", sdkResponse, oldInputs, res)
expected := sdkResponse
assert.Equal(t, expected, actual)
})
}
func TestDeleteFromMap(t *testing.T) {
m := map[string]any{
"a": "scalar",
"b": map[string]any{
"b.a": "scalar",
"b.b": map[string]any{
"b.b.a": map[string]any{},
},
},
}
deleted := deleteFromMap(m, []string{"a"})
assert.True(t, deleted)
assert.NotContains(t, m, "a")
assert.Contains(t, m, "b")
deleted = deleteFromMap(m, []string{"b", "b.b", "b.b.a"})
assert.True(t, deleted)
assert.Contains(t, m, "b")
b := m["b"].(map[string]any)
assert.Contains(t, b, "b.a")
assert.Contains(t, b, "b.b")
bb := b["b.b"].(map[string]any)
assert.NotContains(t, bb, "b.b.a")
assert.False(t, deleteFromMap(m, []string{"b", "notfound"}))
}
// Helper to avoid repeating the same setup code in multiple tests. Returns a resource with a
// "properties" property of type azure-native:keyvault:VaultProperties, which the returned provider
// will return when asked to look up that type.
func setUpResourceWithRefAndProviderWithTypeLookup(version string) (*resources.AzureAPIResource, *azureNativeProvider) {
res := resources.AzureAPIResource{
APIVersion: "v20241101",
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"properties": {
Type: "object",
Ref: "#/types/azure-native:keyvault:VaultProperties",
Containers: []string{"container"},
},
},
},
},
},
}
metadata := map[string]resources.AzureAPIResource{
"azure-native:keyvault:Vault": res,
}
// Setup resource metadata
provider := azureNativeProvider{
version: version,
resourceMap: &resources.APIMetadata{
Resources: resources.GoMap[resources.AzureAPIResource](metadata),
},
// Mock the type lookup to only return the type referenced in the resource above
lookupType: func(ref string) (*resources.AzureAPIType, bool, error) {
if ref == "#/types/azure-native:keyvault:VaultProperties" {
return &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"accessPolicies": {
Type: "array",
Items: &resources.AzureAPIProperty{
Type: "object",
Ref: "#/types/azure-native:keyvault:AccessPolicyEntry",
},
MaintainSubResourceIfUnset: true,
},
},
}, true, nil
}
if ref == "#/types/azure-native:keyvault:AccessPolicyEntry" {
return &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"permissions": {
Type: "array",
Items: &resources.AzureAPIProperty{
Type: "string",
},
Containers: []string{"container2", "container3"},
}},
}, true, nil
}
return nil, false, nil
},
}
return &res, &provider
}
func TestInvokeResponseToOutputs(t *testing.T) {
invoke := resources.AzureAPIInvoke{
APIVersion: "v20241101",
}
conv := convert.NewSdkShapeConverterFull(map[string]resources.AzureAPIType{})
for _, val := range []any{
"string",
42,
[]string{"a", "b"},
} {
t.Run(fmt.Sprintf("single value of type %T", val), func(t *testing.T) {
p := azureNativeProvider{converter: &conv}
outputs := p.invokeResponseToOutputs(val, invoke)
require.Len(t, outputs, 1)
require.Contains(t, outputs, resources.SingleValueProperty)
assert.Equal(t, val, outputs[resources.SingleValueProperty])
})
}
t.Run("object", func(t *testing.T) {
p := azureNativeProvider{converter: &conv}
outputs := p.invokeResponseToOutputs(map[string]any{"key": "value"}, invoke)
assert.Empty(t, outputs) // the empty converter doesn't know any properties
})
t.Run("special case: IsResourceGetter", func(t *testing.T) {
invoke := resources.AzureAPIInvoke{
APIVersion: "v20241101",
IsResourceGetter: true,
}
t.Run("azureApiVersion", func(t *testing.T) {
p := azureNativeProvider{converter: &conv, version: "2.0.0"}
outputs := p.invokeResponseToOutputs(map[string]any{}, invoke)
require.NotContains(t, outputs, "azureApiVersion")
p = azureNativeProvider{converter: &conv, version: "3.0.0"}
outputs = p.invokeResponseToOutputs(map[string]any{}, invoke)
require.Contains(t, outputs, "azureApiVersion")
assert.Equal(t, "v20241101", outputs["azureApiVersion"].(resource.PropertyValue).StringValue())
})
})
}
func TestReader(t *testing.T) {
t.Run("custom Read", func(t *testing.T) {
var customReads []string
customRes := &customresources.CustomResource{
Read: func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, bool, error) {
customReads = append(customReads, id)
return map[string]any{}, true, nil
},
}
azureClient := &az.MockAzureClient{}
crudClient := crud.NewResourceCrudClient(azureClient, nil, nil, "123", nil)
r := reader(customRes, crudClient, nil)
_, err := r(context.Background(), "id1", nil)
require.NoError(t, err)
assert.Equal(t, []string{"id1"}, customReads)
assert.Empty(t, azureClient.GetIds)
})
t.Run("no custom Read", func(t *testing.T) {
resource := &resources.AzureAPIResource{
Response: map[string]resources.AzureAPIProperty{},
}
for _, otherCustomRes := range []*customresources.CustomResource{nil, {} /* custom resource that doesn't implement Read */} {
azureClient := &az.MockAzureClient{}
crudClient := crud.NewResourceCrudClient(azureClient, nil, nil, "123", resource)
r := reader(otherCustomRes, crudClient, nil)
_, err := r(context.Background(), "id2", nil)
require.NoError(t, err)
assert.Contains(t, azureClient.GetIds, "id2")
}
})
t.Run("standard resource, default API version", func(t *testing.T) {
res := &resources.AzureAPIResource{
ApiVersionIsUserInput: false,
APIVersion: "v20241101",
}
azureClient := &az.MockAzureClient{}
crudClient := crud.NewResourceCrudClient(azureClient, nil, nil, "sub123", res)
r := reader(nil, crudClient, nil)
_, err := r(context.Background(), "id3", resource.PropertyMap{
"apiVersion": resource.NewStringProperty("v20220202"), // won't be used
})
require.NoError(t, err)
assert.Contains(t, azureClient.GetIds, "id3")
assert.Equal(t, []string{"v20241101"}, azureClient.GetApiVersions)
})
t.Run("standard resource, user-provided API version", func(t *testing.T) {
res := &resources.AzureAPIResource{
ApiVersionIsUserInput: true,
APIVersion: "v20241101",
}
azureClient := &az.MockAzureClient{}
crudClient := crud.NewResourceCrudClient(azureClient, nil, nil, "sub123", res)
r := reader(nil, crudClient, resource.PropertyMap{
"apiVersion": resource.NewStringProperty("v20220202"),
})
_, err := r(context.Background(), "id3", nil)
require.NoError(t, err)
assert.Contains(t, azureClient.GetIds, "id3")
assert.Equal(t, []string{"v20220202"}, azureClient.GetApiVersions)
})
}
// TestReadWithApiVersionMismatch tests the fix for issue #4400:
// When API version changes during provider upgrade, Read() should use the OLD schema
// from state's azureApiVersion, not the NEW default API version from metadata.
func TestReadWithApiVersionMismatch(t *testing.T) {
const (
oldApiVersion = "2024-01-02-preview"
newApiVersion = "2024-10-02-preview"
resourcePath = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{clusterName}"
)
// Create resource definitions for old and new API versions
oldResource := resources.AzureAPIResource{
Path: resourcePath,
APIVersion: oldApiVersion,
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Name: "properties",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"location": {Type: "string"},
"properties": {
Type: "object",
Ref: "#/types/azure-native:containerservice/v20240102preview:ManagedClusterProperties",
},
},
},
},
},
Response: map[string]resources.AzureAPIProperty{
"id": {Type: "string"},
"location": {Type: "string"},
"azureApiVersion": {Type: "string"},
"properties": {
Type: "object",
Ref: "#/types/azure-native:containerservice/v20240102preview:ManagedClusterProperties",
},
},
}
newResource := resources.AzureAPIResource{
Path: resourcePath,
APIVersion: newApiVersion,
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Name: "properties",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"location": {Type: "string"},
"properties": {
Type: "object",
Ref: "#/types/azure-native:containerservice/v20241002preview:ManagedClusterProperties",
},
},
},
},
},
Response: map[string]resources.AzureAPIProperty{
"id": {Type: "string"},
"location": {Type: "string"},
"azureApiVersion": {Type: "string"},
"properties": {
Type: "object",
Ref: "#/types/azure-native:containerservice/v20241002preview:ManagedClusterProperties",
},
},
}
// Create mock resource map
mockResourceMap := resources.GoMap[resources.AzureAPIResource]{
"azure-native:containerservice/v20240102preview:ManagedCluster": oldResource,
"azure-native:containerservice/v20241002preview:ManagedCluster": newResource,
"azure-native:containerservice:ManagedCluster": newResource,
}
// Create provider with mock resource map
provider := &azureNativeProvider{
resourceMap: &resources.APIMetadata{
Resources: mockResourceMap,
},
azureClient: &az.MockAzureClient{},
converter: &convert.SdkShapeConverter{},
subscriptionID: "test-subscription",
customResources: make(map[string]*customresources.CustomResource),
}
// Old state with azureApiVersion from old API
oldState := resource.PropertyMap{
"id": resource.NewStringProperty("/subscriptions/test-subscription/resourceGroups/test-rg/providers/Microsoft.ContainerService/managedClusters/test-cluster"),
"location": resource.NewStringProperty("eastus"),
"azureApiVersion": resource.NewStringProperty(oldApiVersion), // Key: old API version
"properties": resource.NewObjectProperty(resource.PropertyMap{
"dnsPrefix": resource.NewStringProperty("test-aks"),
}),
}
// Call Read with current resource type (uses new API by default)
oldStateStruct, err := plugin.MarshalProperties(oldState, plugin.MarshalOptions{})
require.NoError(t, err, "Failed to marshal properties")
req := &rpc.ReadRequest{
Id: "/subscriptions/test-subscription/resourceGroups/test-rg/providers/Microsoft.ContainerService/managedClusters/test-cluster",
Urn: "urn:pulumi:test::test-project::azure-native:containerservice:ManagedCluster::test-cluster",
Properties: oldStateStruct,
}
resp, err := provider.Read(context.Background(), req)
// Assertions
require.NoError(t, err, "Read should succeed with API version mismatch")
require.NotNil(t, resp, "Response should not be nil")
require.NotNil(t, resp.Properties, "Properties should be returned")
// Verify outputs contain azureApiVersion
azureApiVer, ok := resp.Properties.Fields["azureApiVersion"]
assert.True(t, ok, "azureApiVersion should be present in outputs")
if ok {
// After Read, azureApiVersion should be UPDATED to the NEW version
// The fix for #4400 is to use the old schema for diff calculation,
// not to preserve the old API version in outputs
assert.Equal(t, newApiVersion, azureApiVer.GetStringValue(),
"azureApiVersion should be updated to the new version after Read")
}
// The key validation: Read should have succeeded without errors
// The fix ensures old schema is used for normalizing old state during diff calculation,
// preventing spurious property diffs that would cause replacement
}
func TestGetPreviousInputs(t *testing.T) {
t.Run("v2", func(t *testing.T) {
inputs := resource.PropertyMap{
"__inputs": resource.NewObjectProperty(resource.PropertyMap{
"fromState": resource.PropertyValue{},
}),
}
req := &rpc.ReadRequest{
Id: "/subscriptions/123",
Inputs: nil,
}
oldInputs, err := getPreviousInputs(inputs, req.GetInputs(), "test")
require.NoError(t, err)
assert.Contains(t, oldInputs.Mappable(), "fromState")
})
t.Run("v3", func(t *testing.T) {
inputs := resource.PropertyMap{
"__inputs": resource.NewObjectProperty(resource.PropertyMap{
"fromState": resource.PropertyValue{},
}),
}
req := &rpc.ReadRequest{
Id: "/subscriptions/123",
Inputs: &structpb.Struct{
Fields: map[string]*structpb.Value{
"fromReq": {
Kind: &structpb.Value_BoolValue{
BoolValue: true,
},
},
},
},
}
oldInputs, err := getPreviousInputs(inputs, req.GetInputs(), "test")
require.NoError(t, err)
assert.Contains(t, oldInputs.Mappable(), "fromReq")
})
}
func TestReadAfterWrite(t *testing.T) {
read := false
var reader readFunc = func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, error) {
read = true
return nil, nil
}
for _, skipReadOnUpdate := range []bool{true, false} {
p := azureNativeProvider{
skipReadOnUpdate: skipReadOnUpdate,
}
p.readAfterWrite(context.Background(), "id", "urn", "create", resource.PropertyMap{}, reader)
assert.Equal(t, !skipReadOnUpdate, read)
}
}
func TestAzcoreAzureClientUsesCorrectCloud(t *testing.T) {
for expectedHost, cloudInstance := range map[string]cloud.Configuration{
"https://management.azure.com": cloud.AzurePublic,
"https://management.chinacloudapi.cn": cloud.AzureChina,
"https://management.usgovcloudapi.net": cloud.AzureGovernment,
} {
client, err := az.NewAzCoreClient(&fake.TokenCredential{}, "", cloudInstance.Configuration, nil)
require.NoError(t, err)
require.NotNil(t, client)
// Use reflection to get the value of the private 'host' field
clientValue := reflect.ValueOf(client).Elem()
hostField := clientValue.FieldByName("host")
require.True(t, hostField.IsValid(), "host field should be valid (%s)", expectedHost)
assert.Equal(t, expectedHost, hostField.String())
}
}
func TestGetTokenEndpoint(t *testing.T) {
t.Parallel()
t.Run("explicit", func(t *testing.T) {
t.Parallel()
p := azureNativeProvider{}
endpoint := p.tokenEndpoint(resource.NewStringProperty("https://management.azure.com/"))
assert.Equal(t, "https://management.azure.com/", endpoint)
})
t.Run("implicit public", func(t *testing.T) {
t.Parallel()
p := azureNativeProvider{
cloud: cloud.AzurePublic,
}
endpoint := p.tokenEndpoint(resource.NewNullProperty())
assert.Equal(t, "https://management.azure.com/", endpoint)
})
t.Run("implicit usgov", func(t *testing.T) {
t.Parallel()
p := azureNativeProvider{
cloud: cloud.AzureGovernment,
}
endpoint := p.tokenEndpoint(resource.NewNullProperty())
assert.Equal(t, "https://management.usgovcloudapi.net/", endpoint)
})
t.Run("implicit with empty string, public", func(t *testing.T) {
t.Parallel()
p := azureNativeProvider{
cloud: cloud.AzurePublic,
}
endpoint := p.tokenEndpoint(resource.NewStringProperty(""))
assert.Equal(t, "https://management.azure.com/", endpoint)
})
}
func TestGetTokenRequestOpts(t *testing.T) {
t.Parallel()
opts := tokenRequestOpts("http://endpoint")
assert.Empty(t, opts.Claims)
assert.Empty(t, opts.TenantID)
assert.Equal(t, []string{"http://endpoint/.default"}, opts.Scopes)
}
func TestCustomCreate(t *testing.T) {
t.Parallel()
t.Run("resource doesn't exist, uses the custom resource's CanCreate", func(t *testing.T) {
t.Parallel()
calledCreate := false
customRes := &customresources.CustomResource{
CanCreate: func(ctx context.Context, id string) error {
return nil
},
Create: func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, error) {
calledCreate = true
return map[string]any{}, nil
},
}
_, err := customCreate(context.Background(), resource.PropertyMap{}, "id", nil, customRes)
require.NoError(t, err)
assert.True(t, calledCreate)
})
t.Run("resource does exist, uses the custom resource's CanCreate", func(t *testing.T) {
t.Parallel()
calledCanCreate := false
calledCreate := false
calledRead := false
customRes := &customresources.CustomResource{
CanCreate: func(ctx context.Context, id string) error {
calledCanCreate = true
return fmt.Errorf("resource already exists")
},
Read: func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, bool, error) {
calledRead = true
return map[string]any{}, true, nil
},
Create: func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, error) {
calledCreate = true
return map[string]any{}, nil
},
}
_, err := customCreate(context.Background(), resource.PropertyMap{}, "id", nil, customRes)
require.Error(t, err)
assert.True(t, calledCanCreate)
assert.False(t, calledRead)
assert.False(t, calledCreate)
})
t.Run("resource doesn't exist, uses the custom resource's Read", func(t *testing.T) {
t.Parallel()
azureClient := &az.MockAzureClient{}
crudClient := crud.NewResourceCrudClient(azureClient, nil, nil, "123", nil)
calledCreate := false
customRes := &customresources.CustomResource{
Read: func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, bool, error) {
return map[string]any{}, false, nil
},
Create: func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, error) {
calledCreate = true
return map[string]any{}, nil
},
}
_, err := customCreate(context.Background(), resource.PropertyMap{}, "id", crudClient, customRes)
require.NoError(t, err)
assert.True(t, calledCreate)
})
t.Run("resource does exist, uses the custom resource's Read", func(t *testing.T) {
t.Parallel()
azureClient := &az.MockAzureClient{}
crudClient := crud.NewResourceCrudClient(azureClient, nil, nil, "123", nil)
calledCreate := false
customRes := &customresources.CustomResource{
Read: func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, bool, error) {
return map[string]any{}, true, nil
},
Create: func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, error) {
calledCreate = true
return map[string]any{}, nil
},
}
_, err := customCreate(context.Background(), resource.PropertyMap{}, "id", crudClient, customRes)
require.Error(t, err)
require.Contains(t, err.Error(), "cannot create already existing resource")
assert.False(t, calledCreate)
})
t.Run("resource doesn't exist, uses the regular CrudClient if custom resource has neither Read nor CanCreate", func(t *testing.T) {
t.Parallel()
azureClient := &az.MockAzureClient{}
crudClient := crud.NewResourceCrudClient(azureClient, nil, nil, "123", &resources.AzureAPIResource{})
calledCreate := false
customRes := &customresources.CustomResource{
Create: func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, error) {
calledCreate = true
return map[string]any{}, nil
},
}
_, err := customCreate(context.Background(), resource.PropertyMap{}, "id", crudClient, customRes)
require.NoError(t, err)
assert.True(t, calledCreate)
})
}
func TestCheckpointObject(t *testing.T) {
t.Parallel()
res, _ := setUpResourceWithRefAndProviderWithTypeLookup("")
t.Run("stores inputs in v2", func(t *testing.T) {
t.Parallel()
inputs := resource.PropertyMap{
"name": resource.NewStringProperty("test"),
}
outputs := map[string]any{}
checkpoint := checkpointObjectVersioned(res, inputs, outputs, semver.MustParse("2.0.0"))
assert.Contains(t, checkpoint, resource.PropertyKey("__inputs"))
})
t.Run("does not store inputs in v3", func(t *testing.T) {
t.Parallel()
inputs := resource.PropertyMap{
"name": resource.NewStringProperty("test"),
}
outputs := map[string]any{}
checkpoint := checkpointObjectVersioned(res, inputs, outputs, semver.MustParse("3.0.0"))
assert.NotContains(t, checkpoint, resource.PropertyKey("__inputs"))
})
t.Run("preserves original state", func(t *testing.T) {
t.Parallel()
inputs := resource.PropertyMap{
"name": resource.NewStringProperty("test"),
}
outputs := map[string]any{
customresources.OriginalStateKey: resource.NewStringProperty("original state"),
}
checkpoint := checkpointObjectVersioned(res, inputs, outputs, semver.MustParse("2.0.0"))
assert.Contains(t, checkpoint, resource.PropertyKey(customresources.OriginalStateKey))
assert.True(t, checkpoint.ContainsSecrets())
checkpoint = checkpointObjectVersioned(res, inputs, outputs, semver.MustParse("3.0.0"))
assert.Contains(t, checkpoint, resource.PropertyKey(customresources.OriginalStateKey))
assert.True(t, checkpoint.ContainsSecrets())
})
t.Run("produces azureApiVersion", func(t *testing.T) {
inputs := resource.PropertyMap{}
outputs := map[string]interface{}{}
checkpoint := checkpointObjectVersioned(res, inputs, outputs, semver.MustParse("2.0.0"))
assert.Contains(t, checkpoint, resource.PropertyKey("azureApiVersion"))
assert.Equal(t, "v20241101", checkpoint["azureApiVersion"].StringValue())
})
}
func TestApplyDefaults(t *testing.T) {
ctx := context.Background()
t.Run("azureApiVersion", func(t *testing.T) {
olds := resource.PropertyMap{}
news := resource.PropertyMap{}
res, provider := setUpResourceWithRefAndProviderWithTypeLookup("2.0.0")
provider.applyDefaults(ctx, "urn", []byte{}, nil, *res, olds, news)
assert.NotContains(t, news, resource.PropertyKey("azureApiVersion"))
res, provider = setUpResourceWithRefAndProviderWithTypeLookup("3.0.0")
provider.applyDefaults(ctx, "urn", []byte{}, nil, *res, olds, news)
assert.Contains(t, news, resource.PropertyKey("azureApiVersion"))
assert.Equal(t, "v20241101", news["azureApiVersion"].StringValue())
})
}
func TestProviderDiff(t *testing.T) {
ctx := context.Background()
type args struct {
olds resource.PropertyMap
oldInputs resource.PropertyMap
news resource.PropertyMap
}
type want struct {
changes rpc.DiffResponse_DiffChanges
detailedDiff map[string]*rpc.PropertyDiff
}
tests := []struct {
name string
version string
args args
want want
wantErr bool
}{
{
name: "azureApiVersion_v2_olds",
version: "2.0.0",
args: args{
olds: resource.PropertyMap{
// v2.90+: output property
"azureApiVersion": resource.NewStringProperty("v20241101"),
},
oldInputs: resource.PropertyMap{},
news: resource.PropertyMap{},
},
want: want{
changes: rpc.DiffResponse_DIFF_NONE,
},
},
{
name: "azureApiVersion_v2-to-v3_same",
version: "3.0.0",
args: args{
olds: resource.PropertyMap{
// v2.90+: output property
"azureApiVersion": resource.NewStringProperty("v20241101"),
},
oldInputs: resource.PropertyMap{},
news: resource.PropertyMap{
// v3: input property
"azureApiVersion": resource.NewStringProperty("v20241101"),
},
},
want: want{
changes: rpc.DiffResponse_DIFF_NONE,
},
},
{
name: "azureApiVersion_v2-to-v3_add",
version: "3.0.0",
args: args{
olds: resource.PropertyMap{},
oldInputs: resource.PropertyMap{},
news: resource.PropertyMap{
// v3: input property
"azureApiVersion": resource.NewStringProperty("v20241101"),
},
},
want: want{
changes: rpc.DiffResponse_DIFF_SOME,
detailedDiff: map[string]*rpc.PropertyDiff{
"azureApiVersion": {
Kind: rpc.PropertyDiff_ADD,
InputDiff: true,
},
},
},
},
{
name: "azureApiVersion_v2-to-v3_update",
version: "3.0.0",
args: args{
olds: resource.PropertyMap{
// v2.90+: output property
"azureApiVersion": resource.NewStringProperty("v20241101"),
},
oldInputs: resource.PropertyMap{},
news: resource.PropertyMap{
// v3: input property
"azureApiVersion": resource.NewStringProperty("v20251101-preview"),
},
},
want: want{
changes: rpc.DiffResponse_DIFF_SOME,
detailedDiff: map[string]*rpc.PropertyDiff{
"azureApiVersion": {
Kind: rpc.PropertyDiff_UPDATE,
InputDiff: false,
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, provider := setUpResourceWithRefAndProviderWithTypeLookup(tt.version)
olds, _ := plugin.MarshalProperties(tt.args.olds, plugin.MarshalOptions{})
oldInputs, _ := plugin.MarshalProperties(tt.args.oldInputs, plugin.MarshalOptions{})
news, _ := plugin.MarshalProperties(tt.args.news, plugin.MarshalOptions{})
req := &rpc.DiffRequest{
Id: "id",
Urn: "urn:pulumi:stack::project::azure-native:keyvault:Vault::id",
Olds: olds,
OldInputs: oldInputs,
News: news,
}
resp, err := provider.Diff(ctx, req)
require.NoError(t, err)
assert.Equal(t, tt.want.changes, resp.Changes, "expected no changes")
if tt.want.detailedDiff != nil {
assert.True(t, resp.HasDetailedDiff)
assert.EqualExportedValues(t, tt.want.detailedDiff, resp.DetailedDiff, "unexpected detailed diff")
}
})
}
}
func TestIsParameterized(t *testing.T) {
t.Run("parameterized", func(t *testing.T) {
provider := &azureNativeProvider{
name: generateNewPackageName("azure-native", "aad", "v20221201"),
}
assert.True(t, provider.isParameterized())
})
t.Run("not parameterized", func(t *testing.T) {
provider := &azureNativeProvider{
name: "azure-native",
}
assert.False(t, provider.isParameterized())
})
t.Run("unexpected format", func(t *testing.T) {
provider := &azureNativeProvider{
name: "azure-native-aad-parameterized",
}
assert.False(t, provider.isParameterized())
})
}
func TestGetApiVersion(t *testing.T) {
t.Run("no override", func(t *testing.T) {
res := &resources.AzureAPIResource{
APIVersion: "v20241101",
}
inputs := resource.PropertyMap{
"apiVersion": resource.NewStringProperty("v20220202"),
}
assert.Equal(t, "v20241101", getApiVersion(res, inputs))
})
t.Run("override", func(t *testing.T) {
res := &resources.AzureAPIResource{
APIVersion: "v20241101",
ApiVersionIsUserInput: true,
}
inputs := resource.PropertyMap{
"apiVersion": resource.NewStringProperty("v20220202"),
}
assert.Equal(t, "v20220202", getApiVersion(res, inputs))
})
}
func TestConfigureRejectsDisabledAzcoreBackend(t *testing.T) {
provider := &azureNativeProvider{
name: "azure-native",
version: "3.0.0",
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | true |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/crud/crud.go | provider/pkg/provider/crud/crud.go | package crud
import (
"context"
"fmt"
"net/url"
"strings"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/convert"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/version"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/rpcutil/rpcerror"
rpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"google.golang.org/grpc/codes"
)
// AzureRESTConverter is an interface for preparing Azure inputs from Pulumi data and for converting from Azure outputs to Pulumi SDK shape.
// It operates in the context of a specific kind of Azure resource of type resources.AzureAPIResource.
type AzureRESTConverter interface {
// PrepareAzureRESTIdAndQuery prepares the ID and query parameters for an Azure REST API request.
PrepareAzureRESTIdAndQuery(inputs resource.PropertyMap) (string, map[string]any, error)
// PrepareAzureRESTBody prepares the body of an Azure REST API request.
// It returns the body as a map of strings to any, which can be marshaled to JSON.
// An error might be returned instead of or as well as the body. If the body is not nil, the error can be treated as a warning.
PrepareAzureRESTBody(id string, inputs resource.PropertyMap) (map[string]any, error)
// ResponseBodyToSdkOutputs converts an Azure REST API response to Pulumi SDK outputs.
ResponseBodyToSdkOutputs(response map[string]any) map[string]any
ResponseToSdkInputs(pathValues map[string]string, responseBody map[string]any) map[string]any
SdkInputsToRequestBody(values map[string]any, id string) (map[string]any, error)
}
// ResourceCrudOperations is an interface for performing CRUD operations on Azure resources of a certain kind.
// See AzureRESTConverter for creating proper inputs and converting outputs.
// It operates in the context of a specific kind of Azure resource of type resources.AzureAPIResource.
type ResourceCrudOperations interface {
CanCreate(ctx context.Context, id string) error
CreateOrUpdate(ctx context.Context, id string, bodyParams, queryParams map[string]any) (map[string]any, bool, error)
// `overrideApiVersion` is (rarely) used for generic resources like resources:Resource where the API version is
// specified by the user and passed on to another Azure service. Leaving it empty means use the API version from
// resource metadata, which is the standard case.
Read(ctx context.Context, id string, overrideApiVersion string) (map[string]any, error)
HandleErrorWithCheckpoint(ctx context.Context, err error, id string, inputs resource.PropertyMap, properties *structpb.Struct) error
}
// SubresourceMaintainer is an interface for handling sub-resource properties.
// It operates in the context of a specific kind of Azure resource of type resources.AzureAPIResource.
type SubresourceMaintainer interface {
MaintainSubResourcePropertiesIfNotSet(ctx context.Context, id string, bodyParams map[string]any) error
// Properties pointing to sub-resources that can be maintained as separate resources might not be
// present in the inputs because the user wants to manage them as standalone resources. However,
// such a property might be required by Azure even if it's not annotated as such in the spec, e.g.,
// Key Vault's accessPolicies. Therefore, we set these properties to their default value here,
// an empty array. For more details, see section "Sub-resources" in CONTRIBUTING.md.
//
// During create, no sub-resources can exist yet so there's no danger of overwriting existing values.
//
// The `input` param is used to determine the unset sub-resource properties. They are then reset in
// the `output` parameter which is modified in-place.
//
// Implementation note: we should make it possible to write custom resources that call code from
// the default implementation as needed. This would allow us to cleanly implement special logic
// like for Key Vault into custom resources without duplicating much code. In the Key Vault case,
// the custom Read() would look like
//
// provider.azureCanCreate(ctx, id, &res)
// setUnsetSubresourcePropertiesToDefaults(res, bodyParams) // custom
// k.azureCreateOrUpdate
// ...
SetUnsetSubresourcePropertiesToDefaults(input, output map[string]any, outputIsInApiShape bool)
}
// ResourceCrudClient is a client for performing CRUD operations on Azure resources.
// It encapsulates both common logic and instances of helpers such as azure.AzureClient and convert.SdkShapeConverter.
// It operates in the context of a specific kind of Azure resource of type resources.AzureAPIResource.
type ResourceCrudClient interface {
ResourceCrudOperations
AzureRESTConverter
SubresourceMaintainer
// ApiVersion returns the API version for the resource.
ApiVersion() string
// see `ApiVersionIsUserInput` on resources.AzureAPIResource
ApiVersionIsUserInput() bool
}
type resourceCrudClient struct {
azureClient azure.AzureClient
lookupType resources.TypeLookupFunc
converter *convert.SdkShapeConverter
subscriptionID string
res *resources.AzureAPIResource
}
type ResourceCrudClientFactory func(
res *resources.AzureAPIResource,
) ResourceCrudClient
func NewResourceCrudClient(
azureClient azure.AzureClient,
lookupType resources.TypeLookupFunc,
converter *convert.SdkShapeConverter,
subscriptionID string,
res *resources.AzureAPIResource,
) ResourceCrudClient {
return &resourceCrudClient{
azureClient: azureClient,
lookupType: lookupType,
converter: converter,
subscriptionID: subscriptionID,
res: res,
}
}
func (r *resourceCrudClient) ApiVersion() string {
return r.res.APIVersion
}
func (r *resourceCrudClient) ApiVersionIsUserInput() bool {
return r.res.ApiVersionIsUserInput
}
func (r *resourceCrudClient) PrepareAzureRESTIdAndQuery(inputs resource.PropertyMap) (string, map[string]any, error) {
return PrepareAzureRESTIdAndQuery(r.res.Path, r.res.PutParameters, inputs.Mappable(), map[string]any{
"subscriptionId": r.subscriptionID,
"api-version": r.res.APIVersion,
})
}
func (r *resourceCrudClient) PrepareAzureRESTBody(id string, inputs resource.PropertyMap) (map[string]any, error) {
return PrepareAzureRESTBody(id, r.res.PutParameters, r.res.RequiredContainers, inputs.Mappable(), r.converter)
}
func PrepareAzureRESTIdAndQuery(path string, parameters []resources.AzureAPIParameter, methodInputs, clientInputs map[string]any) (string, map[string]any, error) {
params := map[string]map[string]interface{}{
"query": {
"api-version": clientInputs["api-version"],
},
"path": {},
}
// Build maps of path and query parameters.
for _, param := range parameters {
if param.Location == "body" {
continue
}
var val interface{}
var has bool
sdkName := param.Name
if param.Value.SdkName != "" {
sdkName = param.Value.SdkName
}
// Look in both `method` and `client` inputs with `method` first
// Navigate into each level of the path to find the value.
val, has = findInContainer(methodInputs, strings.Split(sdkName, "."))
if !has {
val, has = clientInputs[sdkName]
}
if !has {
continue
}
if param.Location == "path" {
encodedVal, isString := val.(string)
if !isString {
return "", nil, errors.Errorf("expected string value for path parameter '%s', got %T", sdkName, val)
}
// Most path parameters correspond to a path component, and must be path-encoded.
// Parameters that are marked as SkipUrlEncoding represent sub-paths (containing slashes) and need not be encoded.
if !param.SkipUrlEncoding {
encodedVal = url.PathEscape(encodedVal)
} else {
// Trim leading and trailing slashes, to fit well into paths like "/{scope}/" or "/{resourceUri}/".
// This allows the caller to pass a resource ID (likely containing a leading slash) as the scope.
encodedVal = strings.Trim(encodedVal, "/")
}
val = encodedVal
}
if has {
params[param.Location][param.Name] = val
}
}
// Calculate resource ID based on path parameter values.
id := path
for key, value := range params["path"] {
strVal, _ := value.(string)
id = strings.ReplaceAll(id, "{"+key+"}", strVal)
}
return id, params["query"], nil
}
func findInContainer(container map[string]any, path []string) (interface{}, bool) {
currentContainer := container
for i, pathPart := range path {
if currentContainer == nil {
return nil, false
}
inner, has := currentContainer[pathPart]
if !has {
return nil, false
}
if i == len(path)-1 {
return inner, true
}
currentContainer, _ = inner.(map[string]any)
}
return nil, false
}
func PrepareAzureRESTBody(id string, parameters []resources.AzureAPIParameter, requiredContainers [][]string,
methodInputs map[string]any, converter *convert.SdkShapeConverter) (map[string]any, error) {
// Build the body JSON.
var body map[string]interface{}
var err error
for _, param := range parameters {
if param.Location != "body" {
continue
}
body, err = converter.SdkInputsToRequestBody(param.Body.Properties, methodInputs, id)
break
}
// Ensure all required containers are created.
for _, containers := range requiredContainers {
currentContainer := body
for _, containerName := range containers {
innerContainer, ok := currentContainer[containerName]
if !ok {
innerContainer = map[string]interface{}{}
currentContainer[containerName] = innerContainer
}
currentContainer, ok = innerContainer.(map[string]interface{})
if !ok {
break
}
}
}
return body, err
}
// partialError creates an error for resources that did not complete an operation in progress.
// The last known state of the object is included in the error so that it can be checkpointed.
func partialError(id string, err error, state *structpb.Struct, inputs *structpb.Struct) error {
detail := rpc.ErrorResourceInitFailed{
Id: id,
Properties: state,
Reasons: []string{err.Error()},
Inputs: inputs,
}
return rpcerror.WithDetails(rpcerror.New(codes.Unknown, err.Error()), &detail)
}
func (r *resourceCrudClient) HandleErrorWithCheckpoint(ctx context.Context, err error, id string, inputs resource.PropertyMap, properties *structpb.Struct) error {
// Resource was partially updated but the operation failed to complete.
// Try reading its state by ID and return a partial error if succeeded.
checkpoint, getErr := r.currentResourceStateCheckpoint(ctx, id, inputs)
if getErr != nil {
// If reading the state failed, combine the errors but still return the partial state.
err = azure.AzureError(errors.Wrapf(err, "resource created but read failed %s", getErr))
}
return partialError(id, err, checkpoint, properties)
}
// currentResourceStateCheckpoint reads the resource state by ID, converts it to outputs map, and
// produces a checkpoint with these outputs and given inputs.
func (r *resourceCrudClient) currentResourceStateCheckpoint(ctx context.Context, id string, inputs resource.PropertyMap) (*structpb.Struct, error) {
getResponse, getErr := r.azureClient.Get(ctx, id, r.res.APIVersion, r.res.ReadQueryParams)
if getErr != nil {
return nil, getErr
}
outputs := r.converter.ResponseBodyToSdkOutputs(r.res.Response, getResponse)
obj := checkpointObject(inputs, outputs)
return plugin.MarshalProperties(
obj,
plugin.MarshalOptions{
Label: "currentResourceStateCheckpoint.checkpoint",
KeepSecrets: true,
KeepUnknowns: true,
SkipNulls: true,
},
)
}
// checkpointObject produces the checkpointed state for the given inputs and outputs.
// In v2, we stored the inputs in an `__inputs` field of the state; removed in v3.
func checkpointObject(inputs resource.PropertyMap, outputs map[string]interface{}) resource.PropertyMap {
object := resource.NewPropertyMapFromMap(outputs)
if version.GetVersion().Major < 3 {
object["__inputs"] = resource.MakeSecret(resource.NewObjectProperty(inputs))
}
return object
}
func (r *resourceCrudClient) MaintainSubResourcePropertiesIfNotSet(ctx context.Context, id string, bodyParams map[string]interface{}) error {
// Identify the properties we need to read
missingProperties := findUnsetPropertiesToMaintain(r.res, bodyParams, true /* returnApiShapePaths */, r.lookupType)
if len(missingProperties) == 0 {
// Everything's already specified explicitly by the user, no need to do read.
return nil
}
// Read the current resource state.
state, err := r.azureClient.Get(ctx, id+r.res.ReadPath, r.res.APIVersion, r.res.ReadQueryParams)
if err != nil {
return fmt.Errorf("reading cloud state: %w", err)
}
writtenProperties, err := writePropertiesToBody(missingProperties, bodyParams, state)
if err != nil {
return fmt.Errorf("failed to copy remote value(s): %w", err)
}
for writtenProperty, writtenValue := range writtenProperties {
logging.V(9).Infof("Maintaining remote value for property: %s.%s = %v", id, writtenProperty, writtenValue)
}
return nil
}
// SetUnsetSubresourcePropertiesToDefaults is the standard implementation of SubresourceMaintainer.SetUnsetSubresourcePropertiesToDefaults.
func (r *resourceCrudClient) SetUnsetSubresourcePropertiesToDefaults(input, output map[string]interface{}, outputIsInApiShape bool) {
unset := findUnsetPropertiesToMaintain(r.res, input, outputIsInApiShape, r.lookupType)
for _, p := range unset {
cur := output
for _, pathEl := range p[:len(p)-1] {
curObj, ok := cur[pathEl]
if !ok {
newContainer := map[string]any{}
cur[pathEl] = newContainer
cur = newContainer
continue
}
cur, ok = curObj.(map[string]any)
if !ok {
break
}
}
cur[p[len(p)-1]] = []any{}
}
}
func findUnsetPropertiesToMaintain(res *resources.AzureAPIResource, bodyParams map[string]interface{}, returnApiShapePaths bool, lookupType resources.TypeLookupFunc) []propertyPath {
missingProperties := []propertyPath{}
for _, path := range res.PathsToSubResourcePropertiesToMaintain(returnApiShapePaths, lookupType) {
curBody := bodyParams
for i, pathEl := range path {
v, ok := curBody[pathEl]
if !ok {
missingProperties = append(missingProperties, propertyPath(path))
break
}
// At the end of the path we don't need to go deeper via references and map lookups.
if i == len(path)-1 {
break
}
curBody, ok = v.(map[string]interface{})
if !ok {
missingProperties = append(missingProperties, propertyPath(path))
break
}
}
}
return missingProperties
}
func (r *resourceCrudClient) ResponseBodyToSdkOutputs(response map[string]any) map[string]any {
return r.converter.ResponseBodyToSdkOutputs(r.res.Response, response)
}
func (r *resourceCrudClient) ResponseToSdkInputs(pathValues map[string]string, responseBody map[string]any) map[string]any {
return r.converter.ResponseToSdkInputs(r.res.PutParameters, pathValues, responseBody)
}
func (r *resourceCrudClient) SdkInputsToRequestBody(properties map[string]any, id string) (map[string]any, error) {
if bodyParam, ok := r.res.BodyParameter(); ok {
return r.converter.SdkInputsToRequestBody(bodyParam.Body.Properties, properties, id)
}
return nil, nil
}
func (r *resourceCrudClient) CanCreate(ctx context.Context, id string) error {
return r.azureClient.CanCreate(ctx, id, r.res.ReadPath, r.res.APIVersion, r.res.ReadMethod, r.res.Singleton, r.res.DefaultBody != nil, func(outputs map[string]any) bool {
return r.converter.IsDefaultResponse(r.res.PutParameters, outputs, r.res.DefaultBody)
})
}
func (r *resourceCrudClient) CreateOrUpdate(ctx context.Context, id string, bodyParams, queryParams map[string]any) (map[string]any, bool, error) {
// Submit the `PUT` or `PATCH` against the ARM endpoint
op := r.azureClient.Put
if r.res.UpdateMethod == "PATCH" {
op = r.azureClient.Patch
}
return op(ctx, id, bodyParams, queryParams, r.res.PutAsyncStyle)
}
func (r *resourceCrudClient) Read(ctx context.Context, id string, overrideApiVersion string) (map[string]any, error) {
url := id + r.res.ReadPath
apiVersion := r.res.APIVersion
if overrideApiVersion != "" {
apiVersion = overrideApiVersion
}
var resp any
var err error
switch r.res.ReadMethod {
case "HEAD":
err = r.azureClient.Head(ctx, url, apiVersion)
return nil, err
case "POST":
bodyParams := map[string]interface{}{}
queryParams := map[string]interface{}{
"api-version": apiVersion,
}
resp, err = r.azureClient.Post(ctx, url, bodyParams, queryParams)
default:
resp, err = r.azureClient.Get(ctx, url, apiVersion, r.res.ReadQueryParams)
}
if err != nil {
return nil, err
}
// Cast should be safe because we're reading a resource, only invokes return non-objects.
if respMap, ok := resp.(map[string]any); ok {
return respMap, nil
}
return nil, errors.Errorf("expected object from Read of '%s', got %T", url, resp)
}
// propertyPath represents a path to a property in a nested structure, e.g. propertyPath{"properties", "privateEndpointConnections"}.
type propertyPath = []string
func writePropertiesToBody(missingProperties []propertyPath, bodyParams map[string]interface{}, remoteState map[string]interface{}) (map[string]interface{}, error) {
writtenProperties := map[string]interface{}{}
for _, prop := range missingProperties {
stateValue, ok, err := nestedFieldNoCopy(remoteState, prop...)
if err != nil {
// the remoteState has an unexpected structure
return nil, fmt.Errorf("error reading remote state: %w", err)
}
if ok {
setNestedFieldNoCopy(bodyParams, stateValue, prop...)
writtenProperties[strings.Join(prop, ".")] = stateValue
}
}
return writtenProperties, nil
}
// nestedFieldNoCopy returns a reference to a nested field.
// Returns false if value is not found and an error if unable
// to traverse obj.
//
// Note: fields passed to this function are treated as keys within the passed
// object; no array/slice syntax is supported.
func nestedFieldNoCopy(obj map[string]any, fields ...string) (any, bool, error) {
var val any = obj
for i, field := range fields {
if val == nil {
return nil, false, nil
}
if m, ok := val.(map[string]any); ok {
val, ok = m[field]
if !ok {
return nil, false, nil
}
} else {
return nil, false, fmt.Errorf("%v accessor error: %v is of the type %T, expected map[string]any", strings.Join(fields[:i+1], "."), val, val)
}
}
return val, true, nil
}
// setNestedFieldNoCopy sets the value of a nested field to the value provided (not copied).
// Returns an error if value cannot be set because one of the nesting levels is not a map[string]any.
func setNestedFieldNoCopy(obj map[string]any, value any, fields ...string) error {
m := obj
for i, field := range fields[:len(fields)-1] {
if val, ok := m[field]; ok {
if valMap, ok := val.(map[string]any); ok {
m = valMap
} else {
return fmt.Errorf("value cannot be set because %v is not a map[string]any", strings.Join(fields[:i+1], "."))
}
} else {
newVal := make(map[string]any)
m[field] = newVal
m = newVal
}
}
m[fields[len(fields)-1]] = value
return nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/crud/crud_test.go | provider/pkg/provider/crud/crud_test.go | package crud
import (
"context"
"net/http"
"testing"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPathParamsErrorHandling(t *testing.T) {
t.Run("No params, no error", func(t *testing.T) {
_, _, err := PrepareAzureRESTIdAndQuery("/path", []resources.AzureAPIParameter{}, nil, nil)
assert.NoError(t, err)
})
t.Run("String params, no error", func(t *testing.T) {
_, _, err := PrepareAzureRESTIdAndQuery("/path",
[]resources.AzureAPIParameter{
{
Name: "p1",
Location: "path",
Value: &resources.AzureAPIProperty{Type: "string"},
},
}, map[string]any{
"p1": "yay",
}, nil)
assert.NoError(t, err)
})
t.Run("Non-string params, error", func(t *testing.T) {
_, _, err := PrepareAzureRESTIdAndQuery("/path",
[]resources.AzureAPIParameter{
{
Name: "p1",
Location: "path",
Value: &resources.AzureAPIProperty{Type: "string"}, // correct, but value is not
},
}, map[string]any{
"p1": 42,
}, nil)
if assert.Error(t, err) {
assert.Equal(t, "expected string value for path parameter 'p1', got int", err.Error())
}
})
t.Run("Path param from props", func(t *testing.T) {
id, _, err := PrepareAzureRESTIdAndQuery("/path/{p1}",
[]resources.AzureAPIParameter{
{
Name: "p1",
Location: "path",
Value: &resources.AzureAPIProperty{Type: "string"},
},
}, map[string]any{
"p1": "val",
}, nil)
require.NoError(t, err)
assert.Equal(t, "/path/val", id)
})
t.Run("Nested path param lookup from props", func(t *testing.T) {
id, _, err := PrepareAzureRESTIdAndQuery("/path/{container.p1}",
[]resources.AzureAPIParameter{
{
Name: "container.p1",
Location: "path",
Value: &resources.AzureAPIProperty{Type: "string"}, // correct, but value is not
},
}, map[string]any{
"container": map[string]any{
"p1": "innerVal",
},
}, nil)
require.NoError(t, err)
assert.Equal(t, "/path/innerVal", id)
})
t.Run("Deeply nested path param", func(t *testing.T) {
id, _, err := PrepareAzureRESTIdAndQuery("/path/{container.inner.p1}",
[]resources.AzureAPIParameter{
{
Name: "container.inner.p1",
Location: "path",
Value: &resources.AzureAPIProperty{Type: "string"}, // correct, but value is not
},
}, map[string]any{
"container": map[string]any{
"inner": map[string]any{
"p1": "deepVal",
},
},
}, nil)
require.NoError(t, err)
assert.Equal(t, "/path/deepVal", id)
})
}
func TestPathParamEncoding(t *testing.T) {
t.Run("path encoding", func(t *testing.T) {
tests := []struct {
p1 string
expected string
}{
{
p1: "my-value",
expected: "/path/my-value",
},
{
p1: "my-value with space and /",
expected: "/path/my-value%20with%20space%20and%20%2F",
},
}
for _, tt := range tests {
t.Run(tt.p1, func(t *testing.T) {
id, _, err := PrepareAzureRESTIdAndQuery("/path/{p1}",
[]resources.AzureAPIParameter{
{
Name: "p1",
Location: "path",
Value: &resources.AzureAPIProperty{Type: "string"},
SkipUrlEncoding: false,
},
}, map[string]any{
"p1": tt.p1,
}, nil)
require.NoError(t, err)
assert.Equal(t, tt.expected, id)
})
}
})
t.Run("skip url encoding", func(t *testing.T) {
tests := []struct {
scope string
expected string
}{
{
scope: "subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/my-resource-group",
expected: "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/my-resource-group/path",
},
{
scope: "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/my-resource-group",
expected: "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/my-resource-group/path",
},
}
for _, tt := range tests {
t.Run(tt.scope, func(t *testing.T) {
id, _, err := PrepareAzureRESTIdAndQuery("/{scope}/path",
[]resources.AzureAPIParameter{
{
Name: "scope",
Location: "path",
Value: &resources.AzureAPIProperty{Type: "string"},
SkipUrlEncoding: true,
},
}, map[string]any{
"scope": tt.scope,
}, nil)
require.NoError(t, err)
assert.Equal(t, tt.expected, id)
})
}
})
}
func TestCanCreate_RequestUrls(t *testing.T) {
const resourceId = "/subscriptions/123/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm"
runTest := func(t *testing.T, res *resources.AzureAPIResource, assertions func(t *testing.T, req *http.Request)) {
client, err := azure.CreateTestClient(t, assertions)
require.NoError(t, err)
crudClient := NewResourceCrudClient(client, nil, nil, "123", res)
// Runs the assertions as part of HTTP transport
crudClient.Read(context.Background(), resourceId, "")
}
t.Run("explicit GET, no read path", func(t *testing.T) {
res := resources.AzureAPIResource{
ReadMethod: "GET",
}
assertions := func(t *testing.T, req *http.Request) {
assert.Equal(t, "GET", req.Method)
assert.Equal(t, resourceId, req.URL.Path)
}
runTest(t, &res, assertions)
})
t.Run("explicit GET, read path", func(t *testing.T) {
res := resources.AzureAPIResource{
ReadMethod: "GET",
ReadPath: "/read/me",
}
assertions := func(t *testing.T, req *http.Request) {
assert.Equal(t, "GET", req.Method)
assert.Equal(t, resourceId+"/read/me", req.URL.Path)
}
runTest(t, &res, assertions)
})
t.Run("explicit GET, additional query params", func(t *testing.T) {
res := resources.AzureAPIResource{
ReadMethod: "GET",
ReadQueryParams: map[string]any{"$expand": "*"},
}
assertions := func(t *testing.T, req *http.Request) {
assert.Equal(t, "GET", req.Method)
assert.Equal(t, resourceId, req.URL.Path)
assert.Equal(t, "*", req.URL.Query().Get("$expand"))
}
runTest(t, &res, assertions)
})
t.Run("implicit GET, no read path", func(t *testing.T) {
res := resources.AzureAPIResource{}
assertions := func(t *testing.T, req *http.Request) {
assert.Equal(t, "GET", req.Method)
assert.Equal(t, resourceId, req.URL.Path)
}
runTest(t, &res, assertions)
})
t.Run("implicit GET, read path", func(t *testing.T) {
res := resources.AzureAPIResource{
ReadPath: "/read/me",
}
assertions := func(t *testing.T, req *http.Request) {
assert.Equal(t, "GET", req.Method)
assert.Equal(t, resourceId+"/read/me", req.URL.Path)
}
runTest(t, &res, assertions)
})
t.Run("POST, no read path", func(t *testing.T) {
res := resources.AzureAPIResource{
ReadMethod: "POST",
ReadPath: "/read/me",
}
assertions := func(t *testing.T, req *http.Request) {
assert.Equal(t, "POST", req.Method)
assert.Equal(t, resourceId+"/read/me", req.URL.Path)
}
runTest(t, &res, assertions)
})
t.Run("POST, read path", func(t *testing.T) {
res := resources.AzureAPIResource{
ReadMethod: "POST",
}
assertions := func(t *testing.T, req *http.Request) {
assert.Equal(t, "POST", req.Method)
assert.Equal(t, resourceId, req.URL.Path)
}
runTest(t, &res, assertions)
})
}
func TestSqlVirtualMachineUsesReadQueryParams(t *testing.T) {
sqlVmResource := resources.AzureAPIResource{
Path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/{sqlVirtualMachineName}",
ReadQueryParams: map[string]any{"$expand": "*"},
}
sqlVmId := "/subscriptions/123/resourceGroups/rg/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/vm"
runTest := func(t *testing.T, res *resources.AzureAPIResource, assertions func(t *testing.T, req *http.Request)) {
client, err := azure.CreateTestClient(t, assertions)
require.NoError(t, err)
crudClient := NewResourceCrudClient(client, nil, nil, "123", res)
// Runs the assertions as part of HTTP transport
crudClient.Read(context.Background(), sqlVmId, "")
}
runTest(t, &sqlVmResource, func(t *testing.T, req *http.Request) {
assert.Equal(t, "GET", req.Method)
assert.Equal(t, sqlVmId, req.URL.Path)
assert.Equal(t, "*", req.URL.Query().Get("$expand"))
})
// Sanity check
sqlVmResource.ReadQueryParams = nil
runTest(t, &sqlVmResource, func(t *testing.T, req *http.Request) {
assert.Equal(t, "GET", req.Method)
assert.Equal(t, sqlVmId, req.URL.Path)
assert.Empty(t, req.URL.Query().Get("$expand"))
})
}
func TestNestedFieldNoCopy(t *testing.T) {
target := map[string]any{"foo": "bar"}
obj := map[string]any{
"a": map[string]any{
"b": target,
"c": nil,
"d": []any{"foo"},
"e": []any{
map[string]any{
"f": "bar",
},
},
},
}
// case 1: field exists and is non-nil
res, exists, err := nestedFieldNoCopy(obj, "a", "b")
assert.True(t, exists)
assert.NoError(t, err)
assert.Equal(t, target, res)
target["foo"] = "baz"
assert.Equal(t, target["foo"], res.(map[string]any)["foo"], "result should be a reference to the expected item")
// case 2: field exists and is nil
res, exists, err = nestedFieldNoCopy(obj, "a", "c")
assert.True(t, exists)
assert.NoError(t, err)
assert.Nil(t, res)
// case 3: error traversing obj
res, exists, err = nestedFieldNoCopy(obj, "a", "d", "foo")
assert.False(t, exists)
assert.Error(t, err)
assert.Nil(t, res)
// case 4: field does not exist
res, exists, err = nestedFieldNoCopy(obj, "a", "g")
assert.False(t, exists)
assert.NoError(t, err)
assert.Nil(t, res)
// case 5: intermediate field does not exist
res, exists, err = nestedFieldNoCopy(obj, "a", "g", "f")
assert.False(t, exists)
assert.NoError(t, err)
assert.Nil(t, res)
// case 6: intermediate field is null
// (background: happens easily in YAML)
res, exists, err = nestedFieldNoCopy(obj, "a", "c", "f")
assert.False(t, exists)
assert.NoError(t, err)
assert.Nil(t, res)
// case 7: array/slice syntax is not supported
// (background: users may expect this to be supported)
res, exists, err = nestedFieldNoCopy(obj, "a", "e[0]")
assert.False(t, exists)
assert.NoError(t, err)
assert.Nil(t, res)
}
func TestSetNestedFieldNoCopy(t *testing.T) {
obj := map[string]any{
"x": map[string]any{
"y": 1,
"a": "foo",
},
}
// setting into a new container
err := setNestedFieldNoCopy(obj, []any{"bar"}, "z")
assert.NoError(t, err)
assert.Len(t, obj, 2)
assert.Equal(t, "bar", obj["z"].([]interface{})[0])
// setting into an existing container
err = setNestedFieldNoCopy(obj, []any{"bar"}, "x", "z")
assert.NoError(t, err)
assert.Len(t, obj["x"], 3)
assert.Len(t, obj["x"].(map[string]interface{})["z"], 1)
assert.Equal(t, "bar", obj["x"].(map[string]interface{})["z"].([]interface{})[0])
// error traversing a non-container
err = setNestedFieldNoCopy(obj, []any{}, "x", "y", "z")
assert.Error(t, err, `value cannot be set because x.y is not a map[string]interface{}`)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/provider/crud/subresources_test.go | provider/pkg/provider/crud/subresources_test.go | package crud
import (
"testing"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestWritePropertiesToBody(t *testing.T) {
t.Run("empty", func(t *testing.T) {
missingProperties := []propertyPath{}
bodyParams := map[string]interface{}{}
response := map[string]interface{}{}
writePropertiesToBody(missingProperties, bodyParams, response)
assert.Equal(t, map[string]interface{}{}, bodyParams)
})
t.Run("top-level", func(t *testing.T) {
missingProperties := []propertyPath{
{"remote"},
}
bodyParams := map[string]interface{}{
"existing": "value",
}
response := map[string]interface{}{
"remote": "foo",
}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{
"remote": "foo",
"existing": "value",
}
assert.Equal(t, expected, bodyParams)
})
t.Run("extra property", func(t *testing.T) {
missingProperties := []propertyPath{
{"properties", "remote"},
}
bodyParams := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "value",
},
}
response := map[string]interface{}{
"properties": map[string]interface{}{
"remote": "foo",
},
}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{
"properties": map[string]interface{}{
"remote": "foo",
"existing": "value",
},
}
assert.Equal(t, expected, bodyParams)
})
t.Run("existing properties are maintained", func(t *testing.T) {
missingProperties := []propertyPath{
{"properties", "remote"},
}
bodyParams := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "value",
},
}
response := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "bar",
"remote": "foo",
},
}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "value",
"remote": "foo",
},
}
assert.Equal(t, expected, bodyParams)
})
t.Run("properties missed from remote", func(t *testing.T) {
missingProperties := []propertyPath{
{"properties", "remote"},
}
bodyParams := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "value",
},
}
response := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "new-value",
},
}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "value",
},
}
assert.Equal(t, expected, bodyParams)
})
t.Run("properties container missing from remote", func(t *testing.T) {
missingProperties := []propertyPath{
{"properties", "remote"},
}
bodyParams := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "value",
},
}
response := map[string]interface{}{}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "value",
},
}
assert.Equal(t, expected, bodyParams)
})
// Regression test for #3036 - do not add empty containers to the body that will not be filled
t.Run("issue-3036", func(t *testing.T) {
missingProperties := []propertyPath{
{"properties", "privateNetworks"},
}
bodyParams := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "value",
},
}
response := map[string]interface{}{}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{
"properties": map[string]interface{}{
"existing": "value",
},
}
assert.Equal(t, expected, bodyParams)
})
// Regression test for #4094 - do not add empty container in update case
t.Run("issue-4094", func(t *testing.T) {
missingProperties := []propertyPath{
{"properties", "securityRules"},
}
bodyParams := map[string]interface{}{}
response := map[string]interface{}{
"properties": map[string]interface{}{
"securityRules": []interface{}{},
},
}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{
"properties": map[string]interface{}{
"securityRules": []interface{}{},
},
}
assert.Equal(t, expected, bodyParams)
})
t.Run("properties container missing in body", func(t *testing.T) {
missingProperties := []propertyPath{
{"properties", "remote"},
}
bodyParams := map[string]interface{}{}
response := map[string]interface{}{
"properties": map[string]interface{}{
"remote": "value",
},
}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{
"properties": map[string]interface{}{
"remote": "value",
},
}
assert.Equal(t, expected, bodyParams)
})
t.Run("empty with container", func(t *testing.T) {
missingProperties := []propertyPath{
{"properties", "remote"},
}
bodyParams := map[string]interface{}{}
response := map[string]interface{}{}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{}
assert.Equal(t, expected, bodyParams)
})
t.Run("intermediate containers", func(t *testing.T) {
missingProperties := []propertyPath{
{"properties", "remote"},
}
bodyParams := map[string]interface{}{}
response := map[string]interface{}{
"properties": map[string]interface{}{},
}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{}
assert.Equal(t, expected, bodyParams)
})
t.Run("Nested array missing from body", func(t *testing.T) {
missingProperties := []propertyPath{
{"properties", "accessPolicies"},
}
bodyParams := map[string]interface{}{
"properties": map[string]interface{}{},
}
response := map[string]interface{}{
"properties": map[string]interface{}{
"accessPolicies": []interface{}{},
},
}
writePropertiesToBody(missingProperties, bodyParams, response)
expected := map[string]interface{}{
// Container is auto-created
"properties": map[string]interface{}{
"accessPolicies": []interface{}{},
},
}
assert.Equal(t, expected, bodyParams)
})
}
func TestFindUnsetSubResourceProperties(t *testing.T) {
resWithSubResource := &resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"subResource": {
Type: "string",
MaintainSubResourceIfUnset: true,
},
},
},
},
},
}
var dummyLookupType resources.TypeLookupFunc = func(ref string) (*resources.AzureAPIType, bool, error) {
return nil, false, nil
}
t.Run("empty", func(t *testing.T) {
res := &resources.AzureAPIResource{}
oldInputs := map[string]any{}
actual := findUnsetPropertiesToMaintain(res, oldInputs, true, dummyLookupType)
expected := []propertyPath{}
assert.Equal(t, expected, actual)
})
t.Run("sub-resource not set", func(t *testing.T) {
oldInputs := map[string]any{
"existing": "value",
}
actual := findUnsetPropertiesToMaintain(resWithSubResource, oldInputs, true, dummyLookupType)
expected := []propertyPath{
{"subResource"},
}
assert.Equal(t, expected, actual)
})
t.Run("sub-resource set", func(t *testing.T) {
oldInputs := map[string]any{
"existing": "value",
"subResource": "value",
}
actual := findUnsetPropertiesToMaintain(resWithSubResource, oldInputs, true, dummyLookupType)
expected := []propertyPath{}
assert.Equal(t, expected, actual)
})
}
func TestFindUnsetSubResourcePropertiesFollowingTypeRefs(t *testing.T) {
res, lookupType := setUpResourceWithRefAndProviderWithTypeLookup()
t.Run("properties is not set", func(t *testing.T) {
bodyParams := map[string]interface{}{}
unset := findUnsetPropertiesToMaintain(res, bodyParams, false, lookupType)
require.Equal(t, 1, len(unset))
assert.Equal(t, []string{"properties", "accessPolicies"}, unset[0])
})
t.Run("KV accessPolicies is not set", func(t *testing.T) {
bodyParams := map[string]interface{}{
"properties": map[string]interface{}{},
}
unset := findUnsetPropertiesToMaintain(res, bodyParams, false, lookupType)
require.Equal(t, 1, len(unset))
assert.Equal(t, []string{"properties", "accessPolicies"}, unset[0])
})
t.Run("KV accessPolicies is set", func(t *testing.T) {
bodyParams := map[string]interface{}{
"properties": map[string]interface{}{
"accessPolicies": []interface{}{},
},
}
unset := findUnsetPropertiesToMaintain(res, bodyParams, false, lookupType)
assert.Empty(t, unset)
})
}
// Helper to avoid repeating the same setup code in multiple tests. Returns a resource with a
// "properties" property of type azure-native:keyvault:VaultProperties, which the returned provider
// will return when asked to look up that type.
func setUpResourceWithRefAndProviderWithTypeLookup() (*resources.AzureAPIResource, resources.TypeLookupFunc) {
res := resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Location: "body",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"properties": {
Type: "object",
Ref: "#/types/azure-native:keyvault:VaultProperties",
Containers: []string{"container"},
},
},
},
},
},
}
// Mock the type lookup to only return the type referenced in the resource above
lookupType := func(ref string) (*resources.AzureAPIType, bool, error) {
if ref == "#/types/azure-native:keyvault:VaultProperties" {
return &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"accessPolicies": {
Type: "array",
Items: &resources.AzureAPIProperty{
Type: "object",
Ref: "#/types/azure-native:keyvault:AccessPolicyEntry",
},
MaintainSubResourceIfUnset: true,
},
},
}, true, nil
}
if ref == "#/types/azure-native:keyvault:AccessPolicyEntry" {
return &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"permissions": {
Type: "array",
Items: &resources.AzureAPIProperty{
Type: "string",
},
Containers: []string{"container2", "container3"},
}},
}, true, nil
}
return nil, false, nil
}
return &res, lookupType
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versionLookup/query_test.go | provider/pkg/versionLookup/query_test.go | package versionLookup_test
import (
"testing"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/openapi"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/versionLookup"
"github.com/stretchr/testify/assert"
)
func TestLookup(t *testing.T) {
result, ok := versionLookup.GetDefaultApiVersionForResource("Web", "WebApp")
assert.True(t, ok, "expected to find default API version for Web/WebApp")
// Verify we can convert it back to a date to prove it's in a valid format
_, err := openapi.ApiVersionToDate(openapi.ApiVersion(result))
assert.NoError(t, err, "expected to parse API version as date")
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/versionLookup/query.go | provider/pkg/versionLookup/query.go | package versionLookup
import (
_ "embed"
"gopkg.in/yaml.v3"
)
//go:embed default-versions.yaml
var rawVersionLock []byte
// versionLock is a map from Azure provider name to resource name to API version.
// This is actually the openapi.DefaultVersionLock type but we don't want to import openapi here
// to avoid cycles.
var versionLock map[string]map[string]struct {
ApiVersion string `yaml:"ApiVersion"`
}
func init() {
err := yaml.Unmarshal(rawVersionLock, &versionLock)
if err != nil {
panic(err)
}
}
func GetDefaultApiVersionForResource(providerName, resourceName string) (string, bool) {
if resources, ok := versionLock[providerName]; ok {
if resource, ok := resources[resourceName]; ok {
return resource.ApiVersion, true
}
}
return "", false
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/raw_map.go | provider/pkg/resources/raw_map.go | package resources
import (
"fmt"
"unsafe"
"github.com/segmentio/encoding/json"
)
type MapLike[T any] interface {
Get(key string) (T, bool, error)
}
type GoMap[T any] map[string]T
func (m GoMap[T]) Get(key string) (T, bool, error) {
value, ok := m[key]
return value, ok, nil
}
type PartialMap[T any] struct {
partialMap map[string]json.RawMessage
}
func NewPartialMap[T any]() PartialMap[T] {
return PartialMap[T]{
partialMap: make(map[string]json.RawMessage),
}
}
func (m *PartialMap[T]) UnmarshalJSON(b []byte) error {
if err := unmarshal(b, &m.partialMap); err != nil {
return err
}
return nil
}
func (m PartialMap[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(m.partialMap)
}
func (m *PartialMap[T]) Get(key string) (T, bool, error) {
rawMessage, ok := m.partialMap[key]
if !ok {
return *new(T), false, nil
}
var value T
if _, err := json.Parse([]byte(rawMessage), &value, json.ZeroCopy); err != nil {
return *new(T), false, err
}
return value, true, nil
}
//// via github.com/segmentio, MIT licensed:
func unmarshal(b []byte, x interface{}) error {
r, err := json.Parse(b, x, json.ZeroCopy)
if len(r) != 0 {
if _, ok := err.(*json.SyntaxError); !ok {
// The encoding/json package prioritizes reporting errors caused by
// unexpected trailing bytes over other issues; here we emulate this
// behavior by overriding the error.
err = syntaxError(r, "invalid character '%c' after top-level value", r[0])
}
}
return err
}
func prefix(b []byte) string {
if len(b) < 32 {
return string(b)
}
return string(b[:32]) + "..."
}
var syntaxErrorMsgOffset = ^uintptr(0)
func syntaxError(b []byte, msg string, args ...interface{}) error {
e := new(json.SyntaxError)
i := syntaxErrorMsgOffset
if i != ^uintptr(0) {
s := "json: " + fmt.Sprintf(msg, args...) + ": " + prefix(b)
p := unsafe.Pointer(e)
// Hack to set the unexported `msg` field.
*(*string)(unsafe.Pointer(uintptr(p) + i)) = s
}
return e
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/resources.go | provider/pkg/resources/resources.go | // Copyright 2016-2020, Pulumi Corporation.
package resources
import (
"encoding/json"
"fmt"
"regexp"
"sort"
"strings"
"unicode"
"github.com/gedex/inflector"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/version"
)
// SingleValueProperty is the name of the property that we insert into the schema for non-object type responses of invokes.
const SingleValueProperty = "value"
// AzureAPIParameter represents a parameter of a Azure REST API endpoint.
type AzureAPIParameter struct {
Name string `json:"name"`
// Location defines the parameter's place the HTTP request: "path", "query", or "body".
Location string `json:"location"`
// IsRequired is true for mandatory parameters.
IsRequired bool `json:"required,omitempty"`
// Value contains metadata for path/query parameters.
Value *AzureAPIProperty `json:"value"`
// Body contains metadata for the body parameter.
Body *AzureAPIType `json:"body,omitempty"`
// SkipUrlEncoding indicates that the parameter should not be URL-encoded.
SkipUrlEncoding bool `json:"skipUrlEncoding,omitempty"`
}
type AutoNameKind string
const (
AutoNameRandom AutoNameKind = "random"
AutoNameCopy AutoNameKind = "copy"
AutoNameUuid AutoNameKind = "uuid"
)
// ModuleName as used within the Pulumi provider e.g. aad
// This is often derived from the "Azure Resource Provider" (namespace) in the Azure spec.
// But sometimes is related to the top-level directory in the specs.
type ModuleName string
func (m ModuleName) Lowered() string {
return strings.ToLower(string(m))
}
// AzureAPIProperty represents validation constraints for a single parameter or body property.
type AzureAPIProperty struct {
Type string `json:"type,omitempty"`
Items *AzureAPIProperty `json:"items,omitempty"`
AdditionalProperties *AzureAPIProperty `json:"additionalProperties,omitempty"`
OneOf []string `json:"oneOf,omitempty"`
Ref string `json:"$ref,omitempty"`
Const interface{} `json:"const,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
MinLength *int64 `json:"minLength,omitempty"`
MaxLength *int64 `json:"maxLength,omitempty"`
Pattern string `json:"pattern,omitempty"`
// The name in the SDK if different from the wire-serialized name, empty otherwise.
SdkName string `json:"sdkName,omitempty"`
// The names of container properties that were "flattened" during SDK generation, i.e. extra layers that exist
// in the API payload but do not exist in the SDK. The order is from the top-most to bottom-most.
Containers []string `json:"containers,omitempty"`
// Whether a change in the value of the property requires a replacement of the whole resource
// (i.e., no in-place updates allowed).
ForceNew bool `json:"forceNew,omitempty"`
ForceNewInferredFromReferencedTypes bool `json:"forceNewInferredFromReferencedTypes,omitempty"`
// If the property is a resource name where we should apply auto-naming, this will contain the kind of
// auto-naming strategy. Possible values are:
// - "copy" for 1-to-1 copy of the resource's logical name.
// - "random" for adding a random suffix to resource's logical name.
AutoName AutoNameKind `json:"autoname,omitempty"`
// If the property is represented as a map of string to nothing, the SDK represents it as a list of strings.
IsStringSet bool `json:"isStringSet,omitempty"`
// Default is the default value for the parameter, if any
Default interface{} `json:"default,omitempty"`
// Some resources are nested beneath other resources, but are also made available as a property on the parent.
// When updating the parent, if the list of nested resources is not specified as a property on the parent, the child resources will be deleted.
// When refreshing the parent, the list of nested resources will be populated from the current state - resulting in an unwanted diff.
// We work around this by setting MaintainSubResourceIfUnset to true for the properties containing a list of nested resources.
// When updating or refreshing the parent, if the list of nested resources was not originally specified inline, we'll maintain the existing sub-resources transparently.
MaintainSubResourceIfUnset bool `json:"maintainSubResourceIfUnset,omitempty"`
// Optional. Properties that combined form a unique identifier for elements in this array.
// Corresponds to the x-ms-identifiers extension in the Azure spec.
ArrayIdentifiers []string `json:"arrayIdentifiers,omitempty"`
}
// AzureAPIType represents the shape of an object property.
type AzureAPIType struct {
Properties map[string]AzureAPIProperty `json:"properties,omitempty"`
RequiredProperties []string `json:"required,omitempty"`
}
// AzureAPIResource is a resource in Azure REST API.
type AzureAPIResource struct {
// API version in "2020-10-01" format.
APIVersion string `json:"apiVersion"`
// True if the "apiVersion" parameter is set by the user, not the provider.
ApiVersionIsUserInput bool `json:"apiVersionIsUserInput,omitempty"`
Path string `json:"path"`
// HTTP method to create/update the resource. Defaults to PUT if empty.
UpdateMethod string `json:"updateMethod,omitempty"`
PutParameters []AzureAPIParameter `json:"PUT"`
Response map[string]AzureAPIProperty `json:"response"`
// A singleton resource is created by Azure with its parent.
// It can't be created or deleted explicitly on its own.
Singleton bool `json:"singleton,omitempty"`
// DefaultBody is the default state of a resource for resources that are
// created automatically by Azure. Note:
// - omitempty is not set to distinct between nil (no default) and empty maps (empty default)
// - DefaultBody applies to all singletons but also some non-singleton resources that can be
// deleted despite being created automatically.
DefaultBody map[string]interface{} `json:"defaultBody"`
// For long-running operations, defines the style of the Asynchronous Operation, see
// https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#asynchronous-operations
// Possible values: nil (not async), "azure-async-operation", "location", "original-uri", see
// https://github.com/Azure/autorest/blob/master/docs/extensions/readme.md#x-ms-long-running-operation
PutAsyncStyle string `json:"putAsyncStyle,omitempty"`
DeleteAsyncStyle string `json:"deleteAsyncStyle,omitempty"`
// HTTP method to read resource state. Defaults to GET if empty.
ReadMethod string `json:"readMethod,omitempty"`
// Path to append to the resource ID to produce the URL for to read resource state.
ReadPath string `json:"readPath,omitempty"`
// Extra query parameters and their values to include in read (GET, HEAD) requests.
ReadQueryParams map[string]any `json:"readUrlParams,omitempty"`
// By default, we populate the `location` property of every resource to the location of its resource
// group or the configured value. AutoLocationDisabled can override this default behavior.
AutoLocationDisabled bool `json:"autoLocationDisabled,omitempty"`
// Containers within the request body that are required even if no properties are set within it.
RequiredContainers [][]string `json:"requiredContainers,omitempty"`
// Default values to be used when the property is removed or in importing. Must be top-level properties.
DefaultProperties map[string]interface{} `json:"defaultProperties,omitempty"`
}
type ResourceLookupFunc func(resourceType string) (AzureAPIResource, bool, error)
type TypeLookupFunc func(ref string) (*AzureAPIType, bool, error)
func TraverseProperties(props map[string]AzureAPIProperty, lookupType TypeLookupFunc, includeContainers bool, f func(propName string, prop AzureAPIProperty, path []string)) {
// Start the traversal with an empty path and an empty set of seen types for cycle detection.
traverseProperties(props, lookupType, includeContainers, []string{}, map[string]struct{}{}, f)
}
func traverseProperties(props map[string]AzureAPIProperty,
lookupType TypeLookupFunc,
includeContainers bool,
path []string,
seen map[string]struct{},
f func(propName string, prop AzureAPIProperty, path []string)) {
// Sort the properties to ensure stable output
propNames := make([]string, 0, len(props))
for propName := range props {
propNames = append(propNames, propName)
}
sort.StringSlice(propNames).Sort()
for _, propName := range propNames {
prop := props[propName]
pathCopy := append([]string{}, path...)
if includeContainers {
pathCopy = append(pathCopy, prop.Containers...)
}
ref := prop.Ref
if ref == "" && prop.Items != nil {
ref = prop.Items.Ref
}
if ref != "" && strings.HasPrefix(ref, "#/types/azure-native") {
refType, ok, err := lookupType(ref)
if !ok || err != nil {
fmt.Printf("Cannot traverse properties of %s: failed to find ref %s: %v\n", propName, ref, err)
continue
}
if _, visited := seen[ref]; !visited {
seen[ref] = struct{}{}
nextPath := append(pathCopy, propName)
traverseProperties(refType.Properties, lookupType, includeContainers, nextPath, seen, f)
}
}
f(propName, prop, pathCopy)
}
}
func (res *AzureAPIResource) PathsToSubResourcePropertiesToMaintain(includeContainers bool, typeLookup TypeLookupFunc) [][]string {
result := [][]string{}
body, hasBody := res.BodyParameter()
if !hasBody {
return result
}
TraverseProperties(
body.Body.Properties,
typeLookup,
includeContainers,
func(propName string, prop AzureAPIProperty, path []string) {
if prop.MaintainSubResourceIfUnset {
// make a copy of path since the original might be passed to other callbacks
pathToProperty := append([]string{}, path...)
pathToProperty = append(pathToProperty, propName)
result = append(result, pathToProperty)
}
})
return result
}
func (res *AzureAPIResource) LookupProperty(key string) (AzureAPIProperty, bool) {
if body, ok := res.BodyParameter(); ok {
if prop, ok := body.Body.Properties[key]; ok {
return prop, true
}
}
return AzureAPIProperty{}, false
}
// BodyParameter returns the body parameter of a resource's PUT parameters, if any.
func (res *AzureAPIResource) BodyParameter() (*AzureAPIParameter, bool) {
for _, param := range res.PutParameters {
if param.Location == "body" || param.Body != nil {
return ¶m, true
}
}
return nil, false
}
// AzureAPIExample provides a pointer to examples relevant to a resource from the Azure REST API spec.
type AzureAPIExample struct {
Description string `json:"description"`
Location string `json:"location"`
}
// AzureAPIInvoke is an invocation target (a function) in Azure REST API.
type AzureAPIInvoke struct {
APIVersion string `json:"apiVersion"`
Path string `json:"path"`
// IsResourceGetter is true if the invoke returns a resource type.
IsResourceGetter bool `json:"isResourceGetter"`
GetParameters []AzureAPIParameter `json:"GET"`
PostParameters []AzureAPIParameter `json:"POST"`
Response map[string]AzureAPIProperty `json:"response"`
}
// PartialAzureAPIMetadata is a collection of resources and functions in the Azure REST API surface, supplementing the
// Pulumi schema. It saves memory by using PartialMap internally and unmarshaling only the parts of the spec that are
// needed. Since PartialMap implements MapLike, PartialAzureAPIMetadata can trivially be converted to APIMetadata.
type PartialAzureAPIMetadata struct {
Types PartialMap[AzureAPIType] `json:"types"`
Resources PartialMap[AzureAPIResource] `json:"resources"`
Invokes PartialMap[AzureAPIInvoke] `json:"invokes"`
}
// APIMetadata is a collection of resources and functions in the Azure REST API surface, supplementing the Pulumi schema.
type APIMetadata struct {
Types MapLike[AzureAPIType] `json:"types"`
Resources MapLike[AzureAPIResource] `json:"resources"`
Invokes MapLike[AzureAPIInvoke] `json:"invokes"`
}
// UnmarshalJSON implements custom unmarshaling for APIMetadata
func (m *APIMetadata) UnmarshalJSON(data []byte) error {
p := PartialAzureAPIMetadata{}
if err := json.Unmarshal(data, &p); err != nil {
return err
}
m.Invokes = &p.Invokes
m.Resources = &p.Resources
m.Types = &p.Types
return nil
}
// AzureAPIMetadata is a collection of resources and functions in the Azure REST API surface, supplementing the Pulumi schema.
type AzureAPIMetadata struct {
Types map[string]AzureAPIType `json:"types"`
Resources map[string]AzureAPIResource `json:"resources"`
Invokes map[string]AzureAPIInvoke `json:"invokes"`
}
// Some resource providers changed capitalization between API versions, but we should map them to the
// same spelling so that folder names and namespaces are consistent. The map below provides such
// canonical names based on which names seems to be used prominently as of 2020.
var wellKnownModuleNames = map[string]string{
"aad": "Aad",
"aadiam": "AadIam",
"dbformariadb": "DBforMariaDB",
"dbformysql": "DBforMySQL",
"dbforpostgresql": "DBforPostgreSQL",
"powerbidedicated": "PowerBIDedicated",
"servicefabricmanagedclusters": "ServiceFabric", // https://github.com/Azure/azure-rest-api-specs/issues/15867
"visualstudio": "VisualStudio",
}
type ModuleNaming struct {
ResolvedName ModuleName
SpecFolderName string
NamespaceWithoutPrefix string
RpNamespace string
}
// GetModuleName returns a module name given Open API spec file and resource's API URI.
// Returns the module name, optional old module name, or error.
func GetModuleName(majorVersion uint64, filePath, apiUri string) (ModuleNaming, error) {
// We extract the module name from two sources:
// - from the folder name of the Open API spec
// - from the URI of the API endpoint (we take the last namespace in the URI)
specFolderName, specFilePath := getSpecFolderNameAndFilePath(filePath)
namespaceWithoutPrefixFromSpecFilePath := findNamespaceWithoutPrefixFromPath(filePath, "")
namespace, err := findSpecNamespace(specFilePath)
if err != nil {
return ModuleNaming{}, err
}
// Sanity check the new and old methods return consistent results for now.
if namespaceWithoutPrefix := removeNamespacePrefixAndNormalise(namespace); namespaceWithoutPrefix != namespaceWithoutPrefixFromSpecFilePath {
return ModuleNaming{}, fmt.Errorf("resolved namespace mismatch: old: %s, new: %s", namespaceWithoutPrefixFromSpecFilePath, namespaceWithoutPrefix)
}
// Start with extracting the namespace from the folder path. If the folder name is explicitly listed,
// use it as the module name. This is the new style we use for newer resources after 1.0. Older
// resources to be migrated as part of https://github.com/pulumi/pulumi-azure-native/issues/690.
if override, hasOverride := getNameOverride(majorVersion, specFolderName); hasOverride {
return ModuleNaming{
ResolvedName: override,
SpecFolderName: specFolderName,
NamespaceWithoutPrefix: namespaceWithoutPrefixFromSpecFilePath,
RpNamespace: namespace,
}, nil
}
// We proceed with the endpoint if both module values match. This way, we avoid flukes and
// declarations outside of the current API provider.
namespaceWithoutPrefixFromResourceUrl := findNamespaceWithoutPrefixFromPath(apiUri, "Resources")
if !strings.EqualFold(namespaceWithoutPrefixFromSpecFilePath, namespaceWithoutPrefixFromResourceUrl) {
return ModuleNaming{}, fmt.Errorf("resolved module name mismatch: file: %s, uri: %s", namespaceWithoutPrefixFromSpecFilePath, namespaceWithoutPrefixFromResourceUrl)
}
// Ultimately we use the module name from the spec file path.
return ModuleNaming{
ResolvedName: ModuleName(namespaceWithoutPrefixFromSpecFilePath),
SpecFolderName: specFolderName,
NamespaceWithoutPrefix: namespaceWithoutPrefixFromSpecFilePath,
RpNamespace: namespace,
}, nil
}
var v2ModulesNamedByFolder = map[string]ModuleName{
"videoanalyzer": "VideoAnalyzer",
"webpubsub": "WebPubSub",
}
var v3ModulesNamedByFolder = map[string]ModuleName{
// "Network":
"dns": "Dns",
"dnsresolver": "DnsResolver",
"frontdoor": "FrontDoor",
"privatedns": "PrivateDns",
"trafficmanager": "TrafficManager",
// Cache:
"redis": "Redis",
"redisenterprise": "RedisEnterprise",
// Devices:
"iothub": "IoTHub",
"deviceprovisioningservices": "DeviceProvisioningServices",
// "DocumentDB":
"cosmos-db": "CosmosDB",
"mongocluster": "MongoCluster",
// Insights:
"monitor": "Monitor",
"applicationinsights": "ApplicationInsights",
}
// getNameOverride returns a name override for a given folder name, and non-prefixed namespace.
// The second return value is true if an override is found.
func getNameOverride(majorVersion uint64, specFolderName string) (ModuleName, bool) {
// For the cases below, we use folder (SDK) moduleName for module names instead of the ARM moduleName.
if moduleName, ok := v2ModulesNamedByFolder[specFolderName]; ok {
return moduleName, true
}
// Disable additional rules for v2 and below.
// TODO: Remove after v3 release.
if majorVersion < 3 {
return "", false
}
// New rules for v3 and above which include aliases back to the original namespace.
if moduleName, ok := v3ModulesNamedByFolder[specFolderName]; ok {
return moduleName, true
}
return "", false
}
// Identify the first segment of the path that contains a namespace.
func findSpecNamespace(path string) (string, error) {
parts := strings.Split(path, "/")
if len(parts) < 3 {
return "", fmt.Errorf("path did not contain at least 3 parts: %s", path)
}
for _, part := range parts {
// It must contain a dot to indicate it's a namespace,
// but not contain any curly braces which would indicate it's a parameter (used in Microsoft.EventGrid).
if strings.Contains(part, ".") && !strings.ContainsAny(part, "{}") {
return part, nil
}
}
return "", fmt.Errorf("no namespace found in path: %s", path)
}
// Remove the namespace prefix, normalise the casing and account for renames.
func removeNamespacePrefixAndNormalise(namespace string) string {
// Some namespaces can be nested such as Microsoft.Web.Admin, though it's rare.
_, after, found := strings.Cut(namespace, ".")
if !found {
return namespace
}
if knownName, ok := wellKnownModuleNames[strings.ToLower(after)]; ok {
return knownName
}
return strings.Title(after)
}
// Locate namespaces based on well known prefixes (Microsoft., microsoft., PaloAltoNetworks.)
// and return the namespace without the prefix.
// If the path is long enough, but no prefix is found, return the default value.
func findNamespaceWithoutPrefixFromPath(path, defaultValue string) string {
parts := strings.Split(path, "/")
if len(parts) < 3 {
return ""
}
for i := len(parts) - 2; i >= 0; i-- {
part := parts[i]
for _, prefix := range []string{"Microsoft.", "microsoft.", "PaloAltoNetworks."} {
if strings.HasPrefix(part, prefix) {
name := strings.Title(strings.TrimPrefix(part, prefix))
if knownName, ok := wellKnownModuleNames[strings.ToLower(name)]; ok {
return knownName
}
return name
}
}
}
return defaultValue
}
var folderModulePattern = regexp.MustCompile(`.*/specification/([a-zA-Z0-9-]+)/resource-manager/(.*)`)
func getSpecFolderNameAndFilePath(path string) (string, string) {
// Note that this returns last match, e.g. the following path matches `C`, `D`:
// specification/A/resource-manager/B/specification/C/resource-manager/D
subMatches := folderModulePattern.FindStringSubmatch(path)
if len(subMatches) > 2 {
moduleAlias := subMatches[1]
filePath := subMatches[2]
return moduleAlias, filePath
}
return "", ""
}
var verbReplacer = strings.NewReplacer(
"GetProperties", "",
"Get", "",
"getByName", "",
"get", "",
"ListByResourceName", "",
"List", "",
"list", "",
"CheckEntityExists", "",
// Specifically for DesktopVirtualization getHostPoolRegistrationToken.
// In v3 we should replace all instances of "retrieve" #3329.
"RetrieveRegistration", "Registration",
)
var wellKnownNames = map[string]string{
"AssessmentsMetadata": "AssessmentMetadata",
"Caches": "Cache",
"Metadata": "Metadata",
"Mediaservices": "MediaService",
"Redis": "Redis",
}
type NameDisambiguation struct {
// The path to the OpenAPI spec file that generates the ambiguous name.
FileLocation string
// The operation ID that is ambiguous.
OperationID string
// The path of the resource or invoke that is ambiguous.
Path string
// The name of the resource or invoke that is ambiguous.
GeneratedName string
// The API versions that the name is ambiguous between.
DisambiguatedName string
}
// ResourceName constructs a name of a resource based on Get or List operation ID,
// e.g. "Managers_GetActivationKey" -> "ManagerActivationKey".
func ResourceName(operationID, path string) (string, *NameDisambiguation) {
return createResourceName(operationID, path, version.GetVersion().Major)
}
func createResourceName(operationID, path string, majorVersion uint64) (string, *NameDisambiguation) {
if majorVersion >= 3 {
// Uppercase the first character of operationID
r := []rune(operationID)
r[0] = unicode.ToUpper(r[0])
operationID = string(r)
}
normalizedID := strings.ReplaceAll(operationID, "-", "_")
parts := strings.Split(normalizedID, "_")
var name, verb string
if len(parts) == 1 {
verb = parts[0]
} else {
if v, ok := wellKnownNames[parts[0]]; ok {
name = v
} else {
name = inflector.Singularize(parts[0])
}
verb = parts[1]
}
subName := verbReplacer.Replace(verb)
// Sometimes, name or its part is included in the operation name. We want to eliminate obvious duplication
// in the resulting resource name.
nameParts := splitCamelCase(name)
subNameParts := splitCamelCase(inflector.Singularize(subName))
for i := 0; i < len(nameParts); i++ {
if sliceHasPrefix(subNameParts, nameParts[i:]) {
namePrefix := strings.Join(nameParts[:i], "")
name = namePrefix
break
}
}
resourceName := name + subName
return handleResourceNameSpecialCases(resourceName, operationID, path, majorVersion)
}
// handleResourceNameSpecialCases returns a modified resource name if the resource is mapped to multiple API paths. For
// instance, the deprecated "single server" resources in `dbformysql` and `dbforpostgresql` are renamed to `SingleServer`.
func handleResourceNameSpecialCases(resourceName, operationID, path string, majorVersion uint64) (string, *NameDisambiguation) {
newName := func(prefix, newName string) (string, *NameDisambiguation) {
// Don't generate "RedisRedis"
if prefix != "" && !strings.HasPrefix(resourceName, prefix) {
newName = prefix + newName
}
var nameDisambiguation *NameDisambiguation
if newName != resourceName {
nameDisambiguation = &NameDisambiguation{
OperationID: operationID,
Path: path,
GeneratedName: resourceName,
DisambiguatedName: newName,
}
}
return newName, nameDisambiguation
}
var nameDisambiguation *NameDisambiguation
lowerPath := strings.ToLower(path)
// Microsoft.CognitiveServices has global and per-account commitment plans with the same name.
// The global ones are new, introduced in 2022-12-01, so we rename them.
// The global plan still has the description "Cognitive Services account commitment plan." - upstream issue?
if resourceName == "CommitmentPlan" && strings.Contains(path, "/providers/Microsoft.CognitiveServices/commitmentPlans/") {
resourceName, nameDisambiguation = newName("", "SharedCommitmentPlan")
}
// Microsoft.NetApp
if strings.Contains(lowerPath, "/providers/microsoft.netapp/backupvaults/") {
resourceName, nameDisambiguation = newName("BackupVault", resourceName)
}
// Microsoft.Network
// Manual override to resolve ambiguity between public and private RecordSet.
// See https://github.com/pulumi/pulumi-azure-native/issues/583.
// To be removed with https://github.com/pulumi/pulumi-azure-native/issues/690.
if resourceName == "RecordSet" && strings.Contains(path, "/providers/Microsoft.Network/privateDnsZones/") {
resourceName, nameDisambiguation = newName("", "PrivateRecordSet")
}
// Microsoft.Network
// Both are virtual network links, but the other side of the link is a different resource and
// the links have different properties.
// https://learn.microsoft.com/en-us/azure/dns/dns-private-resolver-overview#virtual-network-links
// https://learn.microsoft.com/en-us/azure/dns/private-dns-virtual-network-links
if resourceName == "VirtualNetworkLink" && strings.Contains(path, "/providers/Microsoft.Network/dnsForwardingRulesets/") {
resourceName, nameDisambiguation = newName("", "PrivateResolverVirtualNetworkLink")
}
// ServiceFabric introduced managed clusters in a new folder 'servicefabricmanagedclusters' but
// in the same Microsoft.ServiceFabric namespace. We need to disambiguate some resource names.
if strings.Contains(path, "ServiceFabric/managedclusters") &&
(resourceName == "Application" ||
resourceName == "ApplicationType" ||
resourceName == "ApplicationTypeVersion" ||
resourceName == "Service") {
resourceName, nameDisambiguation = newName("ManagedCluster", resourceName)
}
if majorVersion < 3 {
if resourceName == "PrivateEndpointConnection" && strings.Contains(path, "/providers/Microsoft.Cache/redisEnterprise/") {
resourceName, nameDisambiguation = newName("", "EnterprisePrivateEndpointConnection")
}
}
if majorVersion >= 3 {
// Microsoft.DBforMySQL
if strings.Contains(lowerPath, "/providers/microsoft.dbformysql/servers/") {
if resourceName == "Server" {
resourceName, nameDisambiguation = newName("", "SingleServer")
} else {
resourceName, nameDisambiguation = newName("SingleServer", resourceName)
}
}
// Microsoft.DBforPostgreSQL
if strings.Contains(lowerPath, "/providers/microsoft.dbforpostgresql/servers/") {
if resourceName == "Server" {
resourceName, nameDisambiguation = newName("", "SingleServer")
} else {
resourceName, nameDisambiguation = newName("SingleServer", resourceName)
}
} else if strings.Contains(lowerPath, "/providers/microsoft.dbforpostgresql/servergroupsv2/") {
resourceName, nameDisambiguation = newName("ServerGroup", resourceName)
}
// Microsoft.HDInsight
if strings.Contains(lowerPath, "/providers/microsoft.hdinsight/clusterpools/") {
resourceName, nameDisambiguation = newName("ClusterPool", resourceName)
}
// Microsoft.HybridContainerService
if strings.Contains(lowerPath, "/providers/microsoft.hybridcontainerservice/provisionedclusterinstances/") {
if !strings.Contains(resourceName, "ClusterInstance") {
resourceName, nameDisambiguation = newName("ClusterInstance", resourceName)
}
}
// Microsoft.NetApp
if strings.Contains(lowerPath, "/providers/microsoft.netapp/netappaccounts/") && strings.Contains(lowerPath, "/capacitypools/") {
if resourceName == "Pool" {
resourceName, nameDisambiguation = newName("", "CapacityPool")
} else {
resourceName, nameDisambiguation = newName("CapacityPool", resourceName)
}
}
}
return resourceName, nameDisambiguation
}
var referenceNameReplacer = strings.NewReplacer("CreateOrUpdateParameters", "", "Create", "", "Request", "")
// DiscriminatedResourceName returns the name of a resource variant based on the variant's schema name.
func DiscriminatedResourceName(referenceName string) string {
return referenceNameReplacer.Replace(referenceName)
}
// AutoNamer decides on the per-property auto-naming property for a given API path.
type AutoNamer struct {
path string
}
// NewAutoNamer creates a new AutoNamer for a given API path.
func NewAutoNamer(path string) AutoNamer {
return AutoNamer{path}
}
// AutoName returns auto-naming strategy ("random", "copy") for a given property name and a resource path.
// The second value is true if auto-naming should be applied.
func (a *AutoNamer) AutoName(name, format string) (AutoNameKind, bool) {
suffix := fmt.Sprintf("{%s}", name)
if !strings.HasSuffix(a.path, suffix) {
return "", false
}
if format == "uuid" {
return AutoNameUuid, true
}
switch name {
// Endpoints and custom domains both produce URIs, so they are globally unique.
case "endpointName", "customDomainName":
return AutoNameRandom, true
// Work around https://github.com/Azure/azure-rest-api-specs/issues/1684.
case "roleAssignmentName", "roleDefinitionId":
return AutoNameUuid, true
}
parts := strings.Split(strings.ToLower(a.path), "microsoft.")
resourcePath := parts[len(parts)-1]
if len(parts) == 1 || strings.Count(resourcePath, "{") == 1 {
return AutoNameRandom, true
}
return AutoNameCopy, true
}
// AutoLocationDisabled returns true auto-location should not be applied for a given resource path.
func AutoLocationDisabled(path string) bool {
switch strings.ToLower(path) {
case "/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.resources/deployments/{deploymentname}":
// Template deployment.
return true
case "/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.network/loadbalancers/{loadbalancername}/backendaddresspools/{backendaddresspoolname}":
// Load balancer backend address pool, see https://github.com/pulumi/pulumi-azure-native/issues/819.
return true
case "/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.documentdb/databaseaccounts/{accountname}/cassandrakeyspaces/{keyspacename}",
"/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.documentdb/databaseaccounts/{accountname}/cassandrakeyspaces/{keyspacename}/tables/{tablename}",
"/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.documentdb/databaseaccounts/{accountname}/gremlindatabases/{databasename}",
"/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.documentdb/databaseaccounts/{accountname}/gremlindatabases/{databasename}/graphs/{graphname}",
"/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.documentdb/databaseaccounts/{accountname}/mongodbdatabases/{databasename}",
"/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.documentdb/databaseaccounts/{accountname}/mongodbdatabases/{databasename}/collections/{collectionname}",
"/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.documentdb/databaseaccounts/{accountname}/sqldatabases/{databasename}",
"/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.documentdb/databaseaccounts/{accountname}/sqldatabases/{databasename}/containers/{containername}",
"/subscriptions/{subscriptionid}/resourcegroups/{resourcegroupname}/providers/microsoft.documentdb/databaseaccounts/{accountname}/tables/{tablename}":
// Child resources of Cosmos DB accounts.
return true
default:
return false
}
}
func sliceHasPrefix(slice, subSlice []string) bool {
if len(subSlice) > len(slice) {
return false
}
for i := range subSlice {
if slice[i] != subSlice[i] {
return false
}
}
return true
}
func splitCamelCase(s string) (entries []string) {
current := ""
for _, v := range s {
if v >= 'A' && v <= 'Z' {
if current != "" {
entries = append(entries, current)
}
current = string(v)
} else {
current += string(v)
}
}
entries = append(entries, current)
return
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/ids_test.go | provider/pkg/resources/ids_test.go | // Copyright 2024, Pulumi Corporation.
package resources
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
type resourceIDCase struct {
id string
path string
}
func TestParseResourceID(t *testing.T) {
t.Run("invalid", func(t *testing.T) {
cases := []resourceIDCase{
// ID shorter than Path
{"/resourceGroup/myrg", "/resourceGroup/{resourceGroup}/subResource"},
// ID longer than Path
{"/resourceGroup/myrg/cdn/mycdn", "/resourceGroup/{resourceGroup}/cdn"},
// Segment names don't match
{"/resourceGroup/myrg/foo/mycdn", "/resourceGroup/{resourceGroup}/bar/{cdn}"},
}
for _, testCase := range cases {
_, err := ParseResourceID(testCase.id, testCase.path)
assert.Error(t, err)
}
})
t.Run("full", func(t *testing.T) {
id := "/subscriptions/0282681f-7a9e-123b-40b2-96babd57a8a1/resourcegroups/pulumi-name/providers/Microsoft.Network/networkInterfaces/pulumi-nic/ipConfigurations/ipconfig1"
path := "/subscriptions/{subscriptionID}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/ipConfigurations/{ipConfigurationName}"
actual, err := ParseResourceID(id, path)
assert.NoError(t, err)
expected := map[string]string{
"subscriptionID": "0282681f-7a9e-123b-40b2-96babd57a8a1",
"resourceGroupName": "pulumi-name",
"networkInterfaceName": "pulumi-nic",
"ipConfigurationName": "ipconfig1",
}
assert.Equal(t, expected, actual)
})
t.Run("scoped", func(t *testing.T) {
id := "/subscriptions/1200b1c8-3c58-42db-b33a-304a75913333/resourceGroups/devops-dev/providers/Microsoft.Authorization/roleAssignments/2a88abc7-f599-0eba-a21f-a1817e597115"
path := "/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}"
actual, err := ParseResourceID(id, path)
assert.NoError(t, err)
expected := map[string]string{
"scope": "subscriptions/1200b1c8-3c58-42db-b33a-304a75913333/resourceGroups/devops-dev",
"roleAssignmentName": "2a88abc7-f599-0eba-a21f-a1817e597115",
}
assert.Equal(t, expected, actual)
})
t.Run("nested identifier", func(t *testing.T) {
id := "/subscriptions/1200b1c8-3c58-42db-b33a-304a75913333/resourceGroups/resource-group/providers/Microsoft.KeyVault/vaults/vault-name/accessPolicy/policy-object-id"
path := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/accessPolicy/{policy.objectId}"
actual, err := ParseResourceID(id, path)
assert.NoError(t, err)
expected := map[string]string{
"subscriptionId": "1200b1c8-3c58-42db-b33a-304a75913333",
"resourceGroupName": "resource-group",
"vaultName": "vault-name",
"policy.objectId": "policy-object-id",
}
assert.Equal(t, expected, actual)
})
}
func TestParseToken(t *testing.T) {
type testCase struct {
mod string
apiVersion string
resourceName string
err string
}
tests := []struct {
name string
token string
expected testCase
}{
{
name: "ValidTokenDefaultVersion",
token: "azure-native:messaging:ServiceBus",
expected: testCase{
mod: "messaging",
apiVersion: "",
resourceName: "ServiceBus",
},
},
{
name: "ValidTokenExplicitVersion",
token: "azure-native:messaging/v20240101preview:ServiceBus",
expected: testCase{
mod: "messaging",
apiVersion: "v20240101preview",
resourceName: "ServiceBus",
},
},
{
name: "MalformedTokenTooFewParts",
token: "messaging/v20240101preview:ServiceBus",
expected: testCase{
err: "malformed token 'messaging/v20240101preview:ServiceBus'",
},
},
{
name: "MalformedTokenTooManyParts",
token: "azure-native:messaging:ServiceBus:eventhub:EventHub",
expected: testCase{
err: "malformed token 'azure-native:messaging:ServiceBus:eventhub:EventHub'",
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
mod, apiVersion, resourceName, err := ParseToken(test.token)
assert.Equal(t, test.expected.mod, mod)
assert.Equal(t, test.expected.apiVersion, apiVersion)
assert.Equal(t, test.expected.resourceName, resourceName)
if err != nil {
assert.Equal(t, test.expected.err, err.Error())
} else {
assert.Equal(t, test.expected.err, "")
}
})
}
}
func TestBuildToken(t *testing.T) {
tests := []struct {
mod string
apiVersion string
name string
expected string
}{
{
mod: "messaging",
apiVersion: "",
name: "ServiceBus",
expected: "azure-native:messaging:ServiceBus",
},
{
mod: "messaging",
apiVersion: "v20240101preview",
name: "ServiceBus",
expected: "azure-native:messaging/v20240101preview:ServiceBus",
},
}
for _, test := range tests {
t.Run(fmt.Sprintf("mod=%s, apiVersion=%s, name=%s", test.mod, test.apiVersion, test.name), func(t *testing.T) {
actual := BuildToken(test.mod, test.apiVersion, test.name)
assert.Equal(t, test.expected, actual)
})
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/typeVisitor_test.go | provider/pkg/resources/typeVisitor_test.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package resources
import (
"testing"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/stretchr/testify/assert"
)
func TestVisitPackageSpecTypes(t *testing.T) {
pkg := &schema.PackageSpec{
Resources: map[string]schema.ResourceSpec{
"azure-native:test:MyResource": {
InputProperties: map[string]schema.PropertySpec{
"input1": {
TypeSpec: schema.TypeSpec{
Ref: "#/types/azure-native:test:MyType1",
},
},
},
ObjectTypeSpec: schema.ObjectTypeSpec{
Properties: map[string]schema.PropertySpec{
"output1": {
TypeSpec: schema.TypeSpec{
Type: "array",
Items: &schema.TypeSpec{
Ref: "#/types/azure-native:test:MyType2",
},
},
},
},
},
},
},
Functions: map[string]schema.FunctionSpec{
"azure-native:test:MyFunction": {
Inputs: &schema.ObjectTypeSpec{
Properties: map[string]schema.PropertySpec{
"input1": {
TypeSpec: schema.TypeSpec{
Type: "object",
AdditionalProperties: &schema.TypeSpec{
Ref: "#/types/azure-native:test:MyType3",
},
},
},
},
},
Outputs: &schema.ObjectTypeSpec{
Properties: map[string]schema.PropertySpec{
"output1": {
TypeSpec: schema.TypeSpec{
OneOf: []schema.TypeSpec{
{
Ref: "#/types/azure-native:test:MyType4",
},
{
Ref: "#/types/azure-native:test:MyType5",
},
},
},
},
},
},
},
},
Types: map[string]schema.ComplexTypeSpec{
"azure-native:test:MyType1": {},
"azure-native:test:MyType2": {},
"azure-native:test:MyType3": {},
"azure-native:test:MyType4": {},
"azure-native:test:MyType5": {},
"azure-native:test:MyTypeNotReferenced": {},
},
}
visitedTypes := make(map[string]bool)
visitor := func(tok string, t schema.ComplexTypeSpec) {
visitedTypes[tok] = true
}
VisitPackageSpecTypes(pkg, visitor)
assert.Len(t, visitedTypes, 5)
for tok := range visitedTypes {
assert.Contains(t, pkg.Types, tok)
}
assert.NotContains(t, visitedTypes, "azure-native:test:MyTypeNotReferenced")
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/typeVisitor.go | provider/pkg/resources/typeVisitor.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package resources
import (
"strings"
"github.com/pulumi/pulumi/pkg/v3/codegen"
pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
)
// VisitPackageSpecTypes navigates all resources and functions, searching for all schema types that they reference.
// It then calls the visitor callback for each type found.
func VisitPackageSpecTypes(pkg *pschema.PackageSpec, visitor func(tok string, t pschema.ComplexTypeSpec)) {
seen := codegen.Set{}
for _, r := range pkg.Resources {
for _, p := range r.InputProperties {
visitComplexTypes(pkg.Types, p.TypeSpec, visitor, seen)
}
for _, p := range r.Properties {
visitComplexTypes(pkg.Types, p.TypeSpec, visitor, seen)
}
}
for _, f := range pkg.Functions {
if f.Inputs != nil {
for _, p := range f.Inputs.Properties {
visitComplexTypes(pkg.Types, p.TypeSpec, visitor, seen)
}
}
if f.Outputs != nil {
for _, p := range f.Outputs.Properties {
visitComplexTypes(pkg.Types, p.TypeSpec, visitor, seen)
}
if f.ReturnType != nil && f.ReturnType.TypeSpec != nil {
if f.ReturnType.TypeSpec != nil {
visitComplexTypes(pkg.Types, *f.ReturnType.TypeSpec, visitor, seen)
} else if f.ReturnType.ObjectTypeSpec != nil {
for _, p := range f.ReturnType.ObjectTypeSpec.Properties {
visitComplexTypes(pkg.Types, p.TypeSpec, visitor, seen)
}
}
}
}
}
}
func VisitResourceTypes(pkg *pschema.PackageSpec, resourceToken string, visitor func(tok string, t pschema.ComplexTypeSpec)) {
seen := codegen.Set{}
resource, ok := pkg.Resources[resourceToken]
if !ok {
return
}
for _, p := range resource.InputProperties {
visitComplexTypes(pkg.Types, p.TypeSpec, visitor, seen)
}
for _, p := range resource.Properties {
visitComplexTypes(pkg.Types, p.TypeSpec, visitor, seen)
}
}
func visitComplexTypes(types map[string]pschema.ComplexTypeSpec, t pschema.TypeSpec, visitor func(tok string, t pschema.ComplexTypeSpec), seen codegen.Set) {
if strings.HasPrefix(t.Ref, "#/types/azure-native:") {
typeName := strings.TrimPrefix(t.Ref, "#/types/")
other, ok := types[typeName]
if ok {
visitor(typeName, other)
if !seen.Has(typeName) {
seen.Add(typeName)
for _, p := range other.ObjectTypeSpec.Properties {
visitComplexTypes(types, p.TypeSpec, visitor, seen)
}
}
}
}
if t.AdditionalProperties != nil {
visitComplexTypes(types, *t.AdditionalProperties, visitor, seen)
}
if t.Items != nil {
visitComplexTypes(types, *t.Items, visitor, seen)
}
for _, other := range t.OneOf {
visitComplexTypes(types, other, visitor, seen)
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/resources_test.go | provider/pkg/resources/resources_test.go | // Copyright 2016-2020, Pulumi Corporation.
package resources
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type resourceNameTestCase struct {
operationID string
path string
expected string
}
func TestStandardResourceNames(t *testing.T) {
// Empty path means "doesn't matter", not that these resources don't have a path.
testCases := []resourceNameTestCase{
{"GetUserSettings", "", "UserSettings"},
{"Mediaservices_Get", "", "MediaService"},
{"Redis_Get", "", "Redis"},
{"AssessmentsMetadata_GetInSubscription", "", "AssessmentMetadataInSubscription"},
{"Caches_Get", "", "Cache"},
{"CognitiveServicesAccounts_GetProperties", "", "CognitiveServicesAccount"},
{"WorkspaceCollections_getByName", "", "WorkspaceCollection"},
{"getUserSettingsWithLocation", "", "UserSettingsWithLocation"},
{"SupportPlanTypes_ListInfo", "", "SupportPlanTypeInfo"},
{"WebSite_GetWebSite", "", "WebSite"},
{"ManagedCluster_ClusterUserGet", "", "ManagedClusterUser"},
{"BlobService_ServicePropertiesGet", "", "BlobServiceProperties"},
{"SaasResource-listAccessToken", "", "SaasResourceAccessToken"},
{"WebApps_ListApplicationSettings", "", "WebAppApplicationSettings"},
{"Products_GetProducts", "", "Products"},
{"PowerBIResources_ListByResourceName", "", "PowerBIResource"},
}
for _, tc := range testCases {
require.NotEmpty(t, tc.expected) // test invariant
for _, majorVersion := range []uint64{2, 3} {
actual, _ := createResourceName(tc.operationID, tc.path, majorVersion)
assert.Equal(t, tc.expected, actual)
}
}
}
func TestSpecialResourceNames(t *testing.T) {
testCases := []resourceNameTestCase{
{
"Servers_Get",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}",
"Server",
},
// An exception for https://github.com/pulumi/pulumi-azure-native/issues/583, disambiguated by path.
{
"RecordSets_Get",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateDnsZones/{privateZoneName}/{recordType}/{relativeRecordSetName}",
"PrivateRecordSet",
},
{
"RecordSets_Get",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}",
"RecordSet",
},
}
for _, tc := range testCases {
require.NotEmpty(t, tc.expected) // test invariant
for _, majorVersion := range []uint64{2, 3} {
actual, _ := createResourceName(tc.operationID, tc.path, majorVersion)
assert.Equal(t, tc.expected, actual)
}
}
}
func TestSpecialResourceNamesV3(t *testing.T) {
testCases := []resourceNameTestCase{
{
"Servers_Get",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}",
"SingleServer",
},
{
"Servers_Get",
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}",
"SingleServer",
},
}
for _, tc := range testCases {
require.NotEmpty(t, tc.expected) // test invariant
actual, _ := createResourceName(tc.operationID, tc.path, 3)
assert.Equal(t, tc.expected, actual)
}
for _, tc := range testCases {
actual, _ := createResourceName(tc.operationID, tc.path, 2)
assert.NotEqual(t, tc.expected, actual)
}
}
func TestAutoName(t *testing.T) {
testCases := [][]string{
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}", "resourceGroupName", "random"},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}", "serverName", "random"},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}", "databaseName", "copy"},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}", "serverName", ""},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}", "name", "random"},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}", "siteName", ""},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/config/authsettings", "name", ""},
{"/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/costAllocationRules/{ruleName}", "ruleName", "random"},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}", "endpointName", "random"},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/customDomains/{customDomainName}", "customDomainName", "random"},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}", "endpointName", "random"},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/customDomains/{customDomainName}", "customDomainName", "random"},
{"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/jobSchedules/{jobScheduleId}", "jobScheduleId", "uuid", "uuid"},
{"/{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}", "roleAssignmentName", "uuid"},
{"/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}", "roleDefinitionId", "uuid"},
}
for _, values := range testCases {
path := values[0]
name := values[1]
expected := values[2]
format := ""
if len(values) > 3 {
format = values[2]
}
namer := NewAutoNamer(path)
actual, ok := namer.AutoName(name, format)
if !ok && expected != "" {
assert.Fail(t, "expected auto-name for %q %q", path, name)
}
assert.Equal(t, expected, string(actual))
}
}
func TestTraverseProperties(t *testing.T) {
properties := map[string]AzureAPIProperty{
"properties": {
Type: "object",
Ref: "#/types/azure-native:keyvault:VaultProperties",
},
"location": {
Type: "string",
},
}
res := AzureAPIResource{
PutParameters: []AzureAPIParameter{
{
Location: "body",
Name: "bodyProperties",
Body: &AzureAPIType{
Properties: properties,
},
},
},
}
// Mock the type lookup to only return the type referenced in the resource above
lookupType := func(ref string) (*AzureAPIType, bool, error) {
if ref == "#/types/azure-native:keyvault:VaultProperties" {
return &AzureAPIType{
Properties: map[string]AzureAPIProperty{
"accessPolicies": {
Type: "array",
Items: &AzureAPIProperty{
Type: "object",
Ref: "#/types/azure-native:keyvault:AccessPolicyEntry",
},
Containers: []string{"container"}, // not the case in the real KV spec but we want to test this
},
},
}, true, nil
}
if ref == "#/types/azure-native:keyvault:AccessPolicyEntry" {
return &AzureAPIType{
Properties: map[string]AzureAPIProperty{
"permissions": {
Type: "array",
Items: &AzureAPIProperty{
Type: "string", // not true in the real KV spec but good enough
},
Containers: []string{"container2", "container3"},
MaintainSubResourceIfUnset: true,
},
"other_array": {
Type: "array",
Items: &AzureAPIProperty{
Type: "string",
},
},
},
}, true, nil
}
return nil, false, nil
}
t.Run("including containers", func(t *testing.T) {
visited := map[string][]string{}
visitor := func(name string, property AzureAPIProperty, path []string) {
visited[name] = path
}
TraverseProperties(properties, lookupType, true, visitor)
expected := map[string][]string{
"properties": {},
"accessPolicies": {"properties", "container"},
"permissions": {"properties", "container", "accessPolicies", "container2", "container3"},
"other_array": {"properties", "container", "accessPolicies"},
"location": {},
}
assert.Equal(t, expected, visited)
})
t.Run("without containers", func(t *testing.T) {
visited := map[string][]string{}
visitor := func(name string, property AzureAPIProperty, path []string) {
visited[name] = path
}
TraverseProperties(properties, lookupType, false, visitor)
expected := map[string][]string{
"properties": {},
"accessPolicies": {"properties"},
"permissions": {"properties", "accessPolicies"},
"other_array": {"properties", "accessPolicies"},
"location": {},
}
assert.Equal(t, expected, visited)
})
t.Run("collect subresource properties with containers", func(t *testing.T) {
paths := res.PathsToSubResourcePropertiesToMaintain(true, lookupType)
assert.Equal(t, 1, len(paths))
assert.Equal(t, []string{"properties", "container", "accessPolicies", "container2", "container3", "permissions"}, paths[0])
})
t.Run("collect subresource properties without containers", func(t *testing.T) {
paths := res.PathsToSubResourcePropertiesToMaintain(false, lookupType)
assert.Equal(t, 1, len(paths))
assert.Equal(t, []string{"properties", "accessPolicies", "permissions"}, paths[0])
})
}
func TestResourceModuleNaming(t *testing.T) {
t.Run("Standard case", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/EnterpriseKnowledgeGraph/resource-manager/Microsoft.EnterpriseKnowledgeGraph/preview/2018-12-03/EnterpriseKnowledgeGraphSwagger.json",
"/providers/Microsoft.EnterpriseKnowledgeGraph/operations")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "EnterpriseKnowledgeGraph",
SpecFolderName: "EnterpriseKnowledgeGraph",
NamespaceWithoutPrefix: "EnterpriseKnowledgeGraph",
RpNamespace: "Microsoft.EnterpriseKnowledgeGraph",
}, naming)
})
t.Run("Standard case v3", func(t *testing.T) {
naming, err := GetModuleName(3,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/EnterpriseKnowledgeGraph/resource-manager/Microsoft.EnterpriseKnowledgeGraph/preview/2018-12-03/EnterpriseKnowledgeGraphSwagger.json",
"/providers/Microsoft.EnterpriseKnowledgeGraph/operations")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "EnterpriseKnowledgeGraph",
SpecFolderName: "EnterpriseKnowledgeGraph",
NamespaceWithoutPrefix: "EnterpriseKnowledgeGraph",
RpNamespace: "Microsoft.EnterpriseKnowledgeGraph",
}, naming)
})
// go/pulumi-azure-native/azure-rest-api-specs/specification/dfp/resource-manager/Microsoft.Dynamics365Fraudprotection/preview/2021-02-01-preview/dfp.json
t.Run("Prefer namespace from file path", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/dfp/resource-manager/Microsoft.Dynamics365Fraudprotection/preview/2021-02-01-preview/dfp.json",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dynamics365FraudProtection/instances/{instanceName}")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "Dynamics365Fraudprotection",
SpecFolderName: "dfp",
NamespaceWithoutPrefix: "Dynamics365Fraudprotection",
RpNamespace: "Microsoft.Dynamics365Fraudprotection",
}, naming)
})
t.Run("PaloAltoNetworks namespace", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/paloaltonetworks/resource-manager/PaloAltoNetworks.Cloudngfw/preview/2022-08-29-preview/PaloAltoNetworks.Cloudngfw.json",
"/providers/PaloAltoNetworks.Cloudngfw/globalRulestacks")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "Cloudngfw",
SpecFolderName: "paloaltonetworks",
NamespaceWithoutPrefix: "Cloudngfw",
RpNamespace: "PaloAltoNetworks.Cloudngfw",
}, naming)
})
t.Run("Well known namespace", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/domainservices/resource-manager/Microsoft.AAD/stable/2017-06-01/examples/GetDomainService.json",
"/subscriptions/1639790a-76a2-4ac4-98d9-8562f5dfcb4d/resourceGroups/sva-tt-WUS/providers/Microsoft.AAD/domainServices/zdomain.zforest.com")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "Aad",
SpecFolderName: "domainservices",
NamespaceWithoutPrefix: "Aad",
RpNamespace: "Microsoft.AAD",
}, naming)
})
t.Run("When the namespace from the file path and URI don't match, return empty", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/EnterpriseKnowledgeGraph/resource-manager/Microsoft.One/preview/2018-12-03/EnterpriseKnowledgeGraphSwagger.json",
"/providers/Microsoft.Two/operations")
assert.ErrorContains(t, err, "resolved module name mismatch: file: One, uri: Two")
assert.Equal(t, ModuleNaming{}, naming)
})
t.Run("Change lower case to title case", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/EnterpriseKnowledgeGraph/resource-manager/microsoft.fooBar/preview/2018-12-03/EnterpriseKnowledgeGraphSwagger.json",
"/providers/microsoft.fooBar/operations")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "FooBar",
SpecFolderName: "EnterpriseKnowledgeGraph",
NamespaceWithoutPrefix: "FooBar",
RpNamespace: "microsoft.fooBar",
}, naming)
})
t.Run("Folder named resource", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/videoanalyzer/resource-manager/Microsoft.Media/preview/2021-11-01-preview/PipelineTopologies.json",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/videoAnalyzers/{accountName}/edgeModules/{edgeModuleName}")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "VideoAnalyzer",
SpecFolderName: "videoanalyzer",
NamespaceWithoutPrefix: "Media",
RpNamespace: "Microsoft.Media",
}, naming)
})
t.Run("Network overrides not applied to v2", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/dns.json",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "Network",
SpecFolderName: "dns",
NamespaceWithoutPrefix: "Network",
RpNamespace: "Microsoft.Network",
}, naming)
})
t.Run("Network overrides applied to v3", func(t *testing.T) {
naming, err := GetModuleName(3,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/dns/resource-manager/Microsoft.Network/stable/2018-05-01/dns.json",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "Dns",
SpecFolderName: "dns",
NamespaceWithoutPrefix: "Network",
RpNamespace: "Microsoft.Network",
}, naming)
})
t.Run("Module name with numbers", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/storsimple8000series/resource-manager/Microsoft.StorSimple/stable/2017-06-01/storsimple.json",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "StorSimple",
SpecFolderName: "storsimple8000series",
NamespaceWithoutPrefix: "StorSimple",
RpNamespace: "Microsoft.StorSimple",
}, naming)
})
t.Run("File path with dots uses last match", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi.azure.native/azure-rest-api-specs/specification/videoanalyzer/resource-manager/Microsoft.Media/preview/2021-11-01-preview/PipelineTopologies.json",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/videoAnalyzers/{accountName}/edgeModules/{edgeModuleName}")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "VideoAnalyzer",
SpecFolderName: "videoanalyzer",
NamespaceWithoutPrefix: "Media",
RpNamespace: "Microsoft.Media",
}, naming)
})
t.Run("Nested specifications file path uses last match", func(t *testing.T) {
naming, err := GetModuleName(2,
"/go/pulumi-azure-native/azure-rest-api-specs/specification/dns/resource-manager/Microsoft.Network/specification/videoanalyzer/resource-manager/Microsoft.Media/preview/2021-11-01-preview/PipelineTopologies.json",
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/videoAnalyzers/{accountName}/edgeModules/{edgeModuleName}")
assert.Nil(t, err)
assert.Equal(t, ModuleNaming{
ResolvedName: "VideoAnalyzer",
SpecFolderName: "videoanalyzer",
NamespaceWithoutPrefix: "Media",
RpNamespace: "Microsoft.Media",
}, naming)
})
}
func ptr[T any](s T) *T {
return &s
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/ids.go | provider/pkg/resources/ids.go | // Copyright 2024, Pulumi Corporation.
package resources
import (
"fmt"
"regexp"
"strings"
"github.com/pkg/errors"
)
// ParseResourceID extracts templated values from the given resource ID based on the names of those templated
// values in an HTTP path. The structure of id and path must match: we validate it by building a regular
// expression based on the path parameters and matching the id.
func ParseResourceID(id, path string) (map[string]string, error) {
pathParts := strings.Split(path, "/")
regexParts := make([]string, len(pathParts))
// Track the names of the regex matches so we can map them back to the original names.
regexNames := make(map[string]string, len(pathParts))
regexMatchGroupNameReplacer := regexp.MustCompile(`[^a-zA-Z0-9]`)
for i, s := range pathParts {
if strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}") {
name := s[1 : len(s)-1]
regexName := regexMatchGroupNameReplacer.ReplaceAllString(name, "")
if clashingPathName, ok := regexNames[regexName]; ok {
return nil, errors.Errorf("clashing path names: '%s' and '%s' while parsing resource ID for path '%s", clashingPathName, name, path)
}
regexNames[regexName] = name
regexParts[i] = fmt.Sprintf("(?P<%s>.*?)", regexName)
} else {
regexParts[i] = pathParts[i]
}
}
expr := fmt.Sprintf("(?i)^%s$", strings.Join(regexParts, "/"))
pattern, err := regexp.Compile(expr)
if err != nil {
return nil, errors.Wrapf(err, "failed to compile expression '%s' for path '%s'", expr, path)
}
match := pattern.FindStringSubmatch(id)
if len(match) < len(pattern.SubexpNames()) {
return nil, errors.Errorf("failed to parse '%s' against the path '%s'", id, path)
}
result := map[string]string{}
for i, regexpGroupName := range pattern.SubexpNames() {
if i > 0 && regexpGroupName != "" {
originalName := regexNames[regexpGroupName]
result[originalName] = match[i]
}
}
return result, nil
}
// ParseToken extracts the module, version, and resource/type name from a resource token.
func ParseToken(tok string) (string, string, string, error) {
parts := strings.Split(tok, ":")
if len(parts) != 3 {
return "", "", "", errors.Errorf("malformed token '%s'", tok)
}
subparts := strings.Split(parts[1], "/")
if len(subparts) == 2 {
return subparts[0], subparts[1], parts[2], nil
}
return parts[1], "", parts[2], nil
}
// BuildToken constructs a resource token from the given module, API version, and resource name.
func BuildToken(mod string, apiVersion string, name string) string {
if apiVersion == "" {
return fmt.Sprintf("azure-native:%s:%s", mod, name)
}
return fmt.Sprintf("azure-native:%s/%s:%s", mod, apiVersion, name)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_storage_azidentity.go | provider/pkg/resources/customresources/custom_storage_azidentity.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package customresources
import (
"context"
"encoding/base64"
"fmt"
"net/http"
neturl "net/url"
"regexp"
"strings"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/appendblob"
azureblob "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
func getStorageAccountStaticWebsiteSchema() *schema.ResourceSpec {
return &schema.ResourceSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "Enables the static website feature of a storage account.",
Type: "object",
Properties: map[string]schema.PropertySpec{
containerName: {
Description: "The name of the container to upload blobs to.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
indexDocument: {
Description: "The webpage that Azure Storage serves for requests to the root of a website or any sub-folder. For example, 'index.html'. The value is case-sensitive.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
error404Document: {
Description: "The absolute path to a custom webpage that should be used when a request is made which does not correspond to an existing file.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
},
Required: []string{containerName},
},
InputProperties: map[string]schema.PropertySpec{
resourceGroupName: {
Description: "The name of the resource group within the user's subscription. The name is case insensitive.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
accountName: {
Description: "The name of the storage account within the specified resource group.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
indexDocument: {
Description: "The webpage that Azure Storage serves for requests to the root of a website or any sub-folder. For example, 'index.html'. The value is case-sensitive.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
error404Document: {
Description: "The absolute path to a custom webpage that should be used when a request is made which does not correspond to an existing file.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
},
RequiredInputs: []string{resourceGroupName, accountName},
}
}
func getStorageAccountStaticWebsiteMetadata() *resources.AzureAPIResource {
return &resources.AzureAPIResource{
Path: staticWebsitePath,
PutParameters: []resources.AzureAPIParameter{
{Name: subscriptionId, Location: "path", IsRequired: true, Value: &resources.AzureAPIProperty{Type: "string"}},
{Name: resourceGroupName, Location: "path", IsRequired: true, Value: &resources.AzureAPIProperty{Type: "string"}},
{Name: accountName, Location: "path", IsRequired: true, Value: &resources.AzureAPIProperty{Type: "string"}},
{
Name: "properties",
Location: "body",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
indexDocument: {Type: "string"},
error404Document: {Type: "string"},
},
},
},
},
}
}
// newStorageAccountStaticWebsite creates a custom resource to mark Azure Storage Account as a static website.
func storageAccountStaticWebsite_azidentity(env cloud.Configuration, creds azcore.TokenCredential) *CustomResource {
r := staticWebsite_azidentity{
env: env,
creds: creds,
}
return &CustomResource{
path: staticWebsitePath,
tok: "azure-native:storage:StorageAccountStaticWebsite",
Create: r.createOrUpdate,
Update: r.update,
Read: r.read,
Delete: r.delete,
LegacySchema: getStorageAccountStaticWebsiteSchema(),
Meta: getStorageAccountStaticWebsiteMetadata(),
}
}
func getStorageAccountURL(saName string, env cloud.Configuration) (string, error) {
storageEndpoint := strings.TrimPrefix(env.Suffixes.StorageEndpoint, ".")
if storageEndpoint == "" {
return "", errors.New("The provider configuration must include a value for storageEndpoint")
}
urlStr := fmt.Sprintf("https://%s.blob.%s", saName, storageEndpoint)
_, err := neturl.Parse(urlStr)
if err != nil || saName == "" {
return "", errors.Errorf("invalid storage account URL: %v", err)
}
return urlStr, nil
}
func (r *staticWebsite_azidentity) newStorageAccountClient(properties resource.PropertyMap) (*azblob.Client, error) {
return newStorageAccountClient(properties, r.env, r.creds)
}
func (r *staticWebsite_azidentity) newStorageAccountClientForAccount(accName string) (*azblob.Client, error) {
return newStorageAccountClientForAccount(accName, r.env, r.creds)
}
func newStorageAccountClient(properties resource.PropertyMap, env cloud.Configuration, creds azcore.TokenCredential) (*azblob.Client, error) {
acc := properties[accountName]
if !acc.HasValue() || !acc.IsString() {
return nil, errors.Errorf("%q not found in resource state", accountName)
}
accName := acc.StringValue()
return newStorageAccountClientForAccount(accName, env, creds)
}
func newStorageAccountClientForAccount(accName string, env cloud.Configuration, creds azcore.TokenCredential) (*azblob.Client, error) {
saUrl, err := getStorageAccountURL(accName, env)
if err != nil {
return nil, err
}
return azblob.NewClient(saUrl, creds, nil)
}
type staticWebsite_azidentity struct {
env cloud.Configuration
creds azcore.TokenCredential
}
func (r *staticWebsite_azidentity) update(ctx context.Context, id string, properties, oldState resource.PropertyMap) (map[string]interface{}, error) {
return r.createOrUpdate(ctx, id, properties)
}
func (r *staticWebsite_azidentity) createOrUpdate(ctx context.Context, id string, properties resource.PropertyMap) (map[string]interface{}, error) {
accountClient, err := r.newStorageAccountClient(properties)
if err != nil {
return nil, err
}
siteProps := &service.SetPropertiesOptions{
StaticWebsite: &service.StaticWebsite{
Enabled: pulumi.BoolRef(true),
},
}
if p := properties[indexDocument]; p.HasValue() && p.IsString() {
siteProps.StaticWebsite.IndexDocument = pulumi.StringRef(p.StringValue())
}
if p := properties[error404Document]; p.HasValue() && p.IsString() {
siteProps.StaticWebsite.ErrorDocument404Path = pulumi.StringRef(p.StringValue())
}
if _, err := accountClient.ServiceClient().SetProperties(ctx, siteProps); err != nil {
acc := properties[accountName].StringValue()
return nil, errors.Wrapf(err, "error updating storage account %q service properties", acc)
}
outputs := properties.Mappable()
outputs[containerName] = "$web"
return outputs, nil
}
func is404StorageError(err error) bool {
var respErr *azcore.ResponseError
if errors.As(err, &respErr) {
return respErr.StatusCode == http.StatusNotFound
}
return false
}
// getStorageAccountName returns the storage account name from the resource ID or the properties. It tries properties
// first. When importing, there is no state yet and `properties` is empty.
func getStorageAccountName(resourceId string, properties resource.PropertyMap) (string, error) {
if p := properties[accountName]; p.HasValue() && p.IsString() {
return p.StringValue(), nil
}
match := storageAccountPathRegex.FindStringSubmatch(resourceId)
if len(match) != 4 {
return "", errors.Errorf("could not parse storage account name from resource ID %q", resourceId)
}
return match[3], nil
}
func (r *staticWebsite_azidentity) read(ctx context.Context, id string, properties resource.PropertyMap) (map[string]interface{}, bool, error) {
saName, err := getStorageAccountName(id, properties)
if err != nil {
return nil, false, err
}
dataClient, err := r.newStorageAccountClientForAccount(saName)
if err != nil {
return nil, false, err
}
// Storage Account does not exist => return empty state.
_, err = dataClient.ServiceClient().GetAccountInfo(ctx, nil)
if err != nil {
if is404StorageError(err) {
return nil, false, nil
}
return nil, false, err
}
accountProps, err := dataClient.ServiceClient().GetProperties(ctx, nil)
if err != nil {
return nil, false, errors.Wrapf(err, "error reading storage account %q service properties", saName)
}
if accountProps.StaticWebsite == nil || (accountProps.StaticWebsite.Enabled == nil || !*accountProps.StaticWebsite.Enabled) {
// Static Website not enabled, return empty state.
return nil, false, nil
}
outputs := properties.Mappable()
outputs[containerName] = "$web"
outputs[indexDocument] = accountProps.StaticWebsite.IndexDocument
outputs[error404Document] = accountProps.StaticWebsite.ErrorDocument404Path
return outputs, true, nil
}
func (r *staticWebsite_azidentity) delete(ctx context.Context, id string, inputs, state resource.PropertyMap) error {
accountClient, err := r.newStorageAccountClient(inputs)
if err != nil {
return err
}
// Storage Account does not exist => delete is a no-op.
_, err = accountClient.ServiceClient().GetAccountInfo(ctx, nil)
if err != nil {
if is404StorageError(err) {
return nil
}
return err
}
acc := inputs[accountName].StringValue()
siteProps := &service.SetPropertiesOptions{
StaticWebsite: &service.StaticWebsite{
Enabled: pulumi.BoolRef(false),
},
}
if _, err := accountClient.ServiceClient().SetProperties(ctx, siteProps); err != nil {
return errors.Wrapf(err, "error updating storage account %q service properties", acc)
}
return nil
}
func getBlobTypes() map[string]schema.ComplexTypeSpec {
return map[string]schema.ComplexTypeSpec{
"azure-native:storage:BlobAccessTier": {
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "The access tier of a storage blob.",
Type: "string",
},
Enum: []schema.EnumValueSpec{
{
Value: "Hot",
Description: "Optimized for storing data that is accessed frequently.",
},
{
Value: "Cool",
Description: "Optimized for storing data that is infrequently accessed and stored for at least 30 days.",
},
{
Value: "Archive",
Description: "Optimized for storing data that is rarely accessed and stored for at least 180 days with flexible latency requirements, on the order of hours.",
},
},
},
"azure-native:storage:BlobType": {
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "The type of a storage blob to be created.",
Type: "string",
},
Enum: []schema.EnumValueSpec{
{
Value: "Block",
Description: "Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually.",
},
{
Value: "Append",
Description: "Append blobs are made up of blocks like block blobs, but are optimized for append operations.",
},
},
},
}
}
func getBlobSchema() *schema.ResourceSpec {
return &schema.ResourceSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "Manages a Blob within a Storage Container. For the supported combinations of properties and features please see [here](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-feature-support-in-storage-accounts).",
Type: "object",
Properties: map[string]schema.PropertySpec{
accessTier: {
Description: "The access tier of the storage blob. Only supported for standard storage accounts, not premium.",
TypeSpec: schema.TypeSpec{Ref: "#/types/azure-native:storage:BlobAccessTier"},
},
contentMd5: {
Description: "The MD5 sum of the blob contents.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
contentType: {
Description: "The content type of the storage blob.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
metadata: {
Description: "A map of custom blob metadata.",
TypeSpec: schema.TypeSpec{Type: "object", AdditionalProperties: &schema.TypeSpec{Type: "string"}},
},
nameProp: {
Description: "The name of the storage blob.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
typeProp: {
Description: "The type of the storage blob to be created.",
TypeSpec: schema.TypeSpec{Ref: "#/types/azure-native:storage:BlobType"},
},
url: {
Description: "The URL of the blob.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
},
Required: []string{metadata, nameProp, typeProp, url},
},
InputProperties: map[string]schema.PropertySpec{
accessTier: {
Description: "The access tier of the storage blob. Only supported for standard storage accounts, not premium.",
TypeSpec: schema.TypeSpec{Ref: "#/types/azure-native:storage:BlobAccessTier"},
},
accountName: {
Description: "Specifies the storage account in which to create the storage container.",
TypeSpec: schema.TypeSpec{Type: "string"},
WillReplaceOnChanges: true,
},
blobName: {
Description: "The name of the storage blob. Must be unique within the storage container the blob is located. If this property is not specified it will be set to the name of the resource.",
TypeSpec: schema.TypeSpec{Type: "string"},
WillReplaceOnChanges: true,
},
containerName: {
Description: "The name of the storage container in which this blob should be created.",
TypeSpec: schema.TypeSpec{Type: "string"},
WillReplaceOnChanges: true,
},
contentMd5: {
Description: "The MD5 sum of the blob contents, base64-encoded. Cannot be defined if blob type is Append.",
TypeSpec: schema.TypeSpec{Type: "string"},
WillReplaceOnChanges: true,
},
contentType: {
Description: "The content type of the storage blob. Defaults to `application/octet-stream`.",
TypeSpec: schema.TypeSpec{Type: "string"},
},
metadata: {
Description: "A map of custom blob metadata.",
TypeSpec: schema.TypeSpec{Type: "object", AdditionalProperties: &schema.TypeSpec{Type: "string"}},
},
resourceGroupName: {
Description: "The name of the resource group within the user's subscription.",
TypeSpec: schema.TypeSpec{Type: "string"},
WillReplaceOnChanges: true,
},
source: {
Description: "An asset to copy to the blob contents. This field cannot be specified for Append blobs.",
TypeSpec: schema.TypeSpec{Ref: "pulumi.json#/Asset"},
WillReplaceOnChanges: true,
},
typeProp: {
Description: "The type of the storage blob to be created. Defaults to 'Block'.",
TypeSpec: schema.TypeSpec{Ref: "#/types/azure-native:storage:BlobType"},
Default: "Block",
WillReplaceOnChanges: true,
},
},
RequiredInputs: []string{resourceGroupName, accountName, containerName},
}
}
func getBlobMetadata() *resources.AzureAPIResource {
return &resources.AzureAPIResource{
Path: blobPath,
PutParameters: []resources.AzureAPIParameter{
{Name: subscriptionId, Location: "path", IsRequired: true, Value: &resources.AzureAPIProperty{Type: "string"}},
{Name: resourceGroupName, Location: "path", IsRequired: true, Value: &resources.AzureAPIProperty{Type: "string"}},
{Name: accountName, Location: "path", IsRequired: true, Value: &resources.AzureAPIProperty{Type: "string"}},
{Name: containerName, Location: "path", IsRequired: true, Value: &resources.AzureAPIProperty{Type: "string"}},
{Name: blobName, Location: "path", IsRequired: true, Value: &resources.AzureAPIProperty{Type: "string", AutoName: "copy"}},
{
Name: "properties",
Location: "body",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
accessTier: {Type: "string"},
contentMd5: {Type: "string", ForceNew: true},
contentType: {Type: "string"},
metadata: {Type: "object", AdditionalProperties: &resources.AzureAPIProperty{Type: "string"}},
source: {Ref: "pulumi.json#/Asset", ForceNew: true},
typeProp: {Type: "string", ForceNew: true},
},
RequiredProperties: []string{resourceGroupName, accountName, containerName, blobName, typeProp},
},
},
},
}
}
// newBlob_azidentity creates a custom resource for a Storage Blob.
func newBlob_azidentity(env cloud.Configuration, creds azcore.TokenCredential) *CustomResource {
r := blob_azidentity{
creds: creds,
env: env,
}
return &CustomResource{
path: blobPath,
tok: "azure-native:storage:Blob",
Create: r.create,
Update: r.update,
Delete: r.delete,
Read: r.read,
Types: getBlobTypes(),
LegacySchema: getBlobSchema(),
Meta: getBlobMetadata(),
}
}
var subscriptionIDPattern = regexp.MustCompile(`(?i)^/subscriptions/(.+?)/`)
func parseSubscriptionID(resourceID string) string {
match := subscriptionIDPattern.FindStringSubmatch(resourceID)
if len(match) == 0 {
return ""
}
return match[1]
}
type blob_azidentity struct {
creds azcore.TokenCredential
env cloud.Configuration
}
func (r *blob_azidentity) newBlobClient(ctx context.Context, properties resource.PropertyMap, subID string) (*azureblob.Client, error) {
return newBlobClient(ctx, properties, subID, r.env, r.creds)
}
func (r *blob_azidentity) newAppendBlobClient(ctx context.Context, properties resource.PropertyMap, subID string) (*appendblob.Client, error) {
return newAppendBlobClient(ctx, properties, subID, r.env, r.creds)
}
func (r *blob_azidentity) newBlockBlobClient(ctx context.Context, properties resource.PropertyMap, subID string) (*blockblob.Client, error) {
return newBlockBlobClient(ctx, properties, subID, r.env, r.creds)
}
func newBlobClient(ctx context.Context, properties resource.PropertyMap, subID string, env cloud.Configuration, creds azcore.TokenCredential) (*azureblob.Client, error) {
saUrl, keyCred, err := blobClientDependencies(ctx, properties, subID, env, creds)
if err != nil {
return nil, err
}
return azureblob.NewClientWithSharedKeyCredential(saUrl, keyCred, nil)
}
func newAppendBlobClient(ctx context.Context, properties resource.PropertyMap, subID string, env cloud.Configuration, creds azcore.TokenCredential) (*appendblob.Client, error) {
saUrl, keyCred, err := blobClientDependencies(ctx, properties, subID, env, creds)
if err != nil {
return nil, err
}
return appendblob.NewClientWithSharedKeyCredential(saUrl, keyCred, nil)
}
func newBlockBlobClient(ctx context.Context, properties resource.PropertyMap, subID string, env cloud.Configuration, creds azcore.TokenCredential) (*blockblob.Client, error) {
saUrl, keyCred, err := blobClientDependencies(ctx, properties, subID, env, creds)
if err != nil {
return nil, err
}
return blockblob.NewClientWithSharedKeyCredential(saUrl, keyCred, nil)
}
// blobClientDependencies retrieves the necessary dependencies for creating a blob client: the
// blob's URL and a shared key credential.
func blobClientDependencies(ctx context.Context, properties resource.PropertyMap, subId string, env cloud.Configuration, creds azcore.TokenCredential) (string, *azblob.SharedKeyCredential, error) {
accName, rgName, err := parseStorageAccountInput(properties)
if err != nil {
return "", nil, err
}
blobUrl, err := getBlobURL(properties, env)
if err != nil {
return blobUrl, nil, err
}
keyCred, err := newSharedKeyCredential(ctx, subId, accName, rgName, creds, env)
if err != nil {
return blobUrl, nil, err
}
return blobUrl, keyCred, nil
}
func parseStorageAccountInput(properties resource.PropertyMap) (accName, rgName string, err error) {
acc := properties[accountName]
if !acc.HasValue() || !acc.IsString() {
err = errors.Errorf("%q not found in resource state", accountName)
return
}
accName = acc.StringValue()
rg := properties[resourceGroupName]
if !rg.HasValue() || !rg.IsString() {
err = errors.Errorf("%q not found in resource state", resourceGroupName)
return
}
rgName = rg.StringValue()
return
}
// getStorageAccountKey retrieves the primary key for the given storage account.
func getStorageAccountKey(ctx context.Context, accClient *armstorage.AccountsClient, rgName, accName string) (*string, error) {
keys, err := accClient.ListKeys(ctx, rgName, accName, nil)
if err != nil {
return nil, err
}
if len(keys.Keys) == 0 || keys.Keys[0].Value == nil {
return nil, errors.Errorf("no keys for storage account %q (resource group %q)", accName, rgName)
}
return keys.Keys[0].Value, nil
}
// newSharedKeyCredential creates a credential for the given storage account using the primary storage account key.
func newSharedKeyCredential(ctx context.Context, subId, accName, rgName string, creds azcore.TokenCredential, env cloud.Configuration) (*azblob.SharedKeyCredential, error) {
clientOptions := &arm.ClientOptions{
ClientOptions: azcore.ClientOptions{
Cloud: env.Configuration,
},
}
accClient, err := armstorage.NewAccountsClient(subId, creds, clientOptions)
if err != nil {
return nil, err
}
return newSharedKeyCredentialWithClient(ctx, accName, rgName, accClient)
}
// separate for test, otherwise called from newSharedKeyCredential
func newSharedKeyCredentialWithClient(ctx context.Context, accName, rgName string, accClient *armstorage.AccountsClient) (*azblob.SharedKeyCredential, error) {
accountKey, err := getStorageAccountKey(ctx, accClient, rgName, accName)
if err != nil {
return nil, err
}
return azblob.NewSharedKeyCredential(accName, *accountKey)
}
func getBlobURL(properties resource.PropertyMap, env cloud.Configuration) (string, error) {
acc := properties[accountName]
if !acc.HasValue() || !acc.IsString() {
return "", errors.Errorf("%q not found in resource state", accountName)
}
container := properties[containerName]
if !container.HasValue() || !container.IsString() {
return "", errors.Errorf("%q not found in resource state", containerName)
}
blobName := properties[blobName]
if !blobName.HasValue() || !blobName.IsString() {
return "", errors.Errorf("%q not found in resource state", blobName)
}
saUrl, err := getStorageAccountURL(acc.StringValue(), env)
if err != nil {
return "", err
}
return fmt.Sprintf("%s/%s/%s", saUrl, container.StringValue(), blobName.StringValue()), nil
}
func populateAzureBlobMetadata(properties resource.PropertyMap) map[string]*string {
metaData := make(map[string]*string)
if properties[metadata].HasValue() {
metadataRaw := properties[metadata]
if !metadataRaw.IsObject() {
logging.V(5).Infof("Warning: property 'metadata' is not an object, skipping: %v", metadataRaw)
return metaData
}
for k, v := range metadataRaw.ObjectValue() {
if v.IsString() {
metaData[string(k)] = pulumi.StringRef(v.StringValue())
} else {
logging.V(5).Infof("Warning: metadata for key '%q' is not a string, skipping: %v", k, v)
}
}
}
return metaData
}
func (r *blob_azidentity) create(ctx context.Context, id string, properties resource.PropertyMap) (map[string]interface{}, error) {
subID := parseSubscriptionID(id)
blobClient, err := r.newBlobClient(ctx, properties, subID)
if err != nil {
return nil, err
}
acc := properties[accountName].StringValue()
container := properties[containerName].StringValue()
name := properties[blobName].StringValue()
metaData := populateAzureBlobMetadata(properties)
var ct string
if properties[contentType].HasValue() {
ct = properties[contentType].StringValue()
}
blobType := strings.ToLower(properties[typeProp].StringValue())
switch blobType {
case "append":
if properties[source].HasValue() {
return nil, errors.New("a source cannot be specified for an Append blob")
}
appendClient, err := r.newAppendBlobClient(ctx, properties, subID)
if err != nil {
return nil, err
}
if _, err := appendClient.Create(ctx, &appendblob.CreateOptions{
Metadata: metaData,
HTTPHeaders: &azureblob.HTTPHeaders{
BlobContentType: &ct,
},
}); err != nil {
return nil, err
}
case "block":
blockClient, err := r.newBlockBlobClient(ctx, properties, subID)
if err != nil {
return nil, err
}
opts := blockblob.UploadBufferOptions{
HTTPHeaders: &azureblob.HTTPHeaders{
BlobContentType: &ct,
},
Metadata: metaData,
}
if properties[contentMd5].HasValue() {
md5 := properties[contentMd5].StringValue()
md5Bytes, err := base64.StdEncoding.DecodeString(md5)
if err != nil {
return nil, err
}
opts.HTTPHeaders.BlobContentMD5 = md5Bytes
}
input := []byte{}
if properties[source].HasValue() {
bytes, err := readAssetBytes(properties[source])
if err != nil {
return nil, err
}
input = bytes
}
if _, err := blockClient.UploadBuffer(ctx, input, &opts); err != nil {
return nil, err
}
default:
return nil, errors.Errorf("unsupported blob type: %q", blobType)
}
if properties[accessTier].HasValue() {
tier := azureblob.AccessTier(properties[accessTier].StringValue())
if _, err := blobClient.SetTier(ctx, tier, nil); err != nil {
return nil, errors.Wrapf(err, "updating access tier for blob %q (container %q / account %q)", name, container, acc)
}
}
state, found, err := r.readBlob(ctx, properties, blobPropertiesReaderFromClient(blobClient))
if !found {
return nil, errors.New("newly created blob is not found")
}
return state, err
}
func (r *blob_azidentity) update(ctx context.Context, id string, properties, oldState resource.PropertyMap) (map[string]interface{}, error) {
subID := parseSubscriptionID(id)
dataClient, err := r.newBlobClient(ctx, properties, subID)
if err != nil {
return nil, err
}
acc := properties[accountName].StringValue()
container := properties[containerName].StringValue()
name := properties[blobName].StringValue()
if properties[contentType].HasValue() {
ct := properties[contentType].StringValue()
if _, err := dataClient.SetHTTPHeaders(ctx, azureblob.HTTPHeaders{
BlobContentType: &ct,
}, nil); err != nil {
return nil, errors.Wrapf(err, "updating properties for blob %q (container %q / account %q)", name, container, acc)
}
}
meta := populateAzureBlobMetadata(properties)
if len(meta) > 0 {
if _, err := dataClient.SetMetadata(ctx, meta, nil); err != nil {
return nil, errors.Wrapf(err, "updating metadata for blob %q (container %q / account %q)", name, container, acc)
}
}
if properties[accessTier].HasValue() {
tier := azureblob.AccessTier(properties[accessTier].StringValue())
if _, err := dataClient.SetTier(ctx, tier, nil); err != nil {
return nil, errors.Wrapf(err, "updating access tier for blob %q (container %q / account %q)", name, container, acc)
}
}
state, found, err := r.readBlob(ctx, properties, blobPropertiesReaderFromClient(dataClient))
if !found {
return nil, errors.New("newly created blob is not found")
}
return state, err
}
func (r *blob_azidentity) delete(ctx context.Context, id string, inputs, state resource.PropertyMap) error {
subID := parseSubscriptionID(id)
blobsClient, err := r.newBlobClient(ctx, inputs, subID)
if err != nil {
return err
}
ref := func(s azureblob.DeleteSnapshotsOptionType) *azureblob.DeleteSnapshotsOptionType { return &s }
if _, err := blobsClient.Delete(ctx, &azureblob.DeleteOptions{
DeleteSnapshots: ref(azureblob.DeleteSnapshotsOptionTypeInclude),
}); err != nil {
// Storage Account does not exist => delete is a no-op.
if is404StorageError(err) {
return nil
}
acc := inputs[accountName].StringValue()
container := inputs[containerName].StringValue()
name := inputs[blobName].StringValue()
return errors.Wrapf(err, "deleting blob %q (container %q / account %q)", name, container, acc)
}
return nil
}
func (r *blob_azidentity) read(ctx context.Context, id string, properties resource.PropertyMap) (map[string]interface{}, bool, error) {
var subID string
if len(properties) == 0 && id != "" {
if idProps, ok := parseBlobIdProperties(id); ok {
properties = idProps
subID = properties[subscriptionId].StringValue()
}
}
if subID == "" {
subID = parseSubscriptionID(id)
}
blobsClient, err := r.newBlobClient(ctx, properties, subID)
if err != nil {
return nil, false, err
}
return r.readBlob(ctx, properties, blobPropertiesReaderFromClient(blobsClient))
}
// An abstraction over Client.GetProperties() to allow substituting a fake in testing.
type blobPropertiesReader func(ctx context.Context) (azureblob.GetPropertiesResponse, error)
func blobPropertiesReaderFromClient(client *azureblob.Client) blobPropertiesReader {
return func(ctx context.Context) (azureblob.GetPropertiesResponse, error) {
return client.GetProperties(ctx, nil)
}
}
func (r *blob_azidentity) readBlob(ctx context.Context, properties resource.PropertyMap, reader blobPropertiesReader) (map[string]any, bool, error) {
acc := properties[accountName].StringValue()
container := properties[containerName].StringValue()
name := properties[blobName].StringValue()
props, err := reader(ctx)
if err != nil {
if is404StorageError(err) {
return nil, false, nil
}
return nil, false, errors.Wrapf(err, "retrieving blob properties %q (container %q / account %q)", name, container, acc)
}
blobURL, err := getBlobURL(properties, r.env)
if err != nil {
return nil, false, err
}
return azblobToPulumiProperties(name,
properties[resourceGroupName].StringValue(),
acc,
container,
// The previous implementation's id from `blobsClient.GetResourceID(acc, container, name)`
// was also the blob URL, so the id in state should be identical. See
// https://github.com/tombuildsstuff/giovanni/blob/v0.15.1/storage/2018-11-09/blob/blobs/resource_id.go#L13
blobURL,
props),
true, nil
}
func azblobToPulumiProperties(name, rg, account, container, azureResourceId string, props azureblob.GetPropertiesResponse) map[string]any {
result := map[string]any{
resourceGroupName: rg,
accountName: account,
containerName: container,
blobName: name,
nameProp: name,
contentMd5: base64.StdEncoding.EncodeToString(props.ContentMD5),
contentType: *props.ContentType,
metadata: props.Metadata,
typeProp: strings.TrimSuffix(string(*props.BlobType), "Blob"),
url: azureResourceId,
}
// We can't serialize an empty string as that would be an invalid enum value.
if props.AccessTier != nil && *props.AccessTier != "" {
result[accessTier] = *props.AccessTier
}
return result
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_webapp.go | provider/pkg/resources/customresources/custom_webapp.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package customresources
import (
"context"
"fmt"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/provider/crud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/versionLookup"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
const webAppResourceType = "azure-native:web:WebApp"
const webAppSlotResourceType = "azure-native:web:WebAppSlot"
const webAppPath = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}"
// webApp is a custom resource for web:WebApp. It overrides Read and Delete, for independent reasons.
func webApp(crudClientFactory crud.ResourceCrudClientFactory, azureClient azure.AzureClient, lookupResource resources.ResourceLookupFunc) (*CustomResource, error) {
return makeWebAppResource(webAppResourceType, webAppPath, crudClientFactory, azureClient, lookupResource)
}
// webAppSlot is a custom resource for web:WebAppSlot. It overrides Read and Delete, for independent reasons.
func webAppSlot(crudClientFactory crud.ResourceCrudClientFactory, azureClient azure.AzureClient, lookupResource resources.ResourceLookupFunc) (*CustomResource, error) {
return makeWebAppResource(webAppSlotResourceType,
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/slots/{slot}",
crudClientFactory, azureClient, lookupResource)
}
// webApp is a custom resource for web:WebApp. It overrides Read and Delete, for independent reasons.
func makeWebAppResource(resourceType, path string, crudClientFactory crud.ResourceCrudClientFactory, azureClient azure.AzureClient, lookupResource resources.ResourceLookupFunc) (*CustomResource, error) {
// The arguments can be nil when the custom resource is constructed only for feature lookups
var crudClient crud.ResourceCrudClient
if crudClientFactory != nil && lookupResource != nil {
var err error
crudClient, err = createCrudClient(crudClientFactory, lookupResource, resourceType)
if err != nil {
return nil, err
}
}
return &CustomResource{
path: path,
tok: resourceType,
// WebApp.SiteConfig is created and updated via a PUT to the WebApp itself, but a GET of
// the WebApp does not return the SiteConfig. We need to make a separate GET request to
// /config/web and merge the results. #1468
Read: func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, bool, error) {
// We assume that WebApp and WebAppSlot share their API version since they are almost identical.
apiVersion, ok := versionLookup.GetDefaultApiVersionForResource("Web", "WebApp")
if !ok {
apiVersion = "2022-09-01" // default as of 2024-07
logging.V(3).Infof("Warning: could not find default API version for %s. Using %s", resourceType, apiVersion)
}
webAppResponse, err := crudClient.Read(ctx, id, "")
if err != nil {
if azure.IsNotFound(err) {
return nil, false, nil
}
return nil, false, err
}
siteConfigResponse, err := azureClient.Get(ctx, id+"/config/web", apiVersion, nil)
if err != nil {
return nil, false, err
}
if err := mergeWebAppSiteConfig(webAppResponse, siteConfigResponse); err != nil {
return nil, true, err
}
responseInSdkShape := crudClient.ResponseBodyToSdkOutputs(webAppResponse)
filterResponse(responseInSdkShape)
return responseInSdkShape, true, nil
},
// https://github.com/pulumi/pulumi-azure-native/issues/1529
Delete: func(ctx context.Context, id string, inputs, state resource.PropertyMap) error {
res, ok, err := lookupResource(resourceType)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("resource %q not found", resourceType)
}
return azureClient.Delete(ctx, id, res.APIVersion, res.DeleteAsyncStyle, map[string]any{
// Don't delete the app service plan even if this was the last web app in it. It's
// a separate Pulumi resource.
"deleteEmptyServerFarm": false,
})
},
}, nil
}
// A generic hook to modify the response returned after Read() of a WebApp.
// Removes redacted publishingUsername from siteConfig to avoid meaningless diffs, #1468.
func filterResponse(response map[string]any) {
if siteConfig, ok := util.GetInnerMap(response, "siteConfig"); ok {
if username, ok := siteConfig["publishingUsername"]; ok {
if usernameStr, ok := username.(string); ok && usernameStr == "REDACTED" {
delete(siteConfig, "publishingUsername")
}
}
}
}
// Add siteConfig, that we got from a separate request, to the webApp response.
func mergeWebAppSiteConfig(webApp, siteConfig map[string]any) error {
if outerProperties, ok := util.GetInnerMap(webApp, "properties"); ok {
outerProperties["siteConfig"] = siteConfig["properties"]
return nil
}
return fmt.Errorf("'properties' not found in response, cannot update siteConfig")
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_postgres_config.go | provider/pkg/resources/customresources/custom_postgres_config.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package customresources
import (
"context"
"fmt"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/provider/crud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
)
// Server configuration cannot be deleted, only reset to the default value, and to do that we need
// to retrieve the default value first. See
// [the implementation in `az`](https://github.com/Azure/azure-cli/blob/f92f7233659890b427f4f6f486db5610cdca1020/src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py#L473)
// which does the same thing.
// The Azure Postgres team confirmed that both source and value must be set:
// https://github.com/Azure/azure-rest-api-specs/issues/30143#issuecomment-2379605761.
func postgresFlexibleServerConfiguration(crudClientFactory crud.ResourceCrudClientFactory, lookupResource resources.ResourceLookupFunc) (*CustomResource, error) {
// The arguments can be nil when the custom resource is constructed only for feature lookups
var crudClient crud.ResourceCrudClient
if crudClientFactory != nil && lookupResource != nil {
var err error
crudClient, err = createCrudClient(crudClientFactory, lookupResource, "azure-native:dbforpostgresql:Configuration")
if err != nil {
return nil, err
}
}
return &CustomResource{
path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/configurations/{configurationName}",
Delete: func(ctx context.Context, id string, inputs, state resource.PropertyMap) error {
conf, err := crudClient.Read(ctx, id, "")
if err != nil {
return err
}
defaultValue := getValueFromAzureResponse(conf, "defaultValue")
if defaultValue == nil {
return fmt.Errorf("unexpected Postgres Configuration does not have a default value: %v", conf)
}
// Also read the configuration "source" and send it back. This is actually wrong, but
// quoting the az implementation:
// > "this should be 'system-default' but there is currently a bug in PG, so keeping as
// > what it is for now this will reset source to be 'system-default' anyway"
source := getValueFromAzureResponse(conf, "source")
if source == nil {
return fmt.Errorf("unexpected Postgres Configuration does not have a source: %v", conf)
}
_, queryParams, err := crudClient.PrepareAzureRESTIdAndQuery(nil)
if err != nil {
return err
}
result, _, err := crudClient.CreateOrUpdate(ctx, id, map[string]any{
"properties": map[string]any{
"value": defaultValue,
"source": source,
},
}, queryParams)
if err != nil {
return err
}
newValue := getValueFromAzureResponse(result, "value")
if newValue != defaultValue {
return fmt.Errorf("failed to reset Postgres Configuration to default value '%v': %v", defaultValue, newValue)
}
return nil
},
isSingleton: true,
}, nil
}
func getValueFromAzureResponse(resp map[string]any, key string) any {
if props, ok := resp["properties"]; ok {
if propsMap, ok := props.(map[string]any); ok {
return propsMap[key]
}
}
return nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/customresources.go | provider/pkg/resources/customresources/customresources.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package customresources
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/keyvault/armkeyvault"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/provider/crud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
. "github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
// OriginalStateKey is a map key used to store the original state of a resource.
// It can be used to reset the resource to its original state when the resource is deleted, or to restore individual
// properties of a resource to their defaults when they are removed from the resource.
const OriginalStateKey = "__orig_state"
type CustomReadFunc func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]any, bool, error)
// CustomResource is a manual SDK-based implementation of a (part of) resource when Azure API is missing some
// crucial operations.
type CustomResource struct {
path string
// tok is the resource token for this custom resource, used both for looking up the resource in the schema and for
// the resource name. To use the tok for schema lookup but give the resource a different name, set CustomResourceName.
tok string
// Types are net-new auxiliary types defined for this resource. Optional.
// Deprecated: Use Schema instead.
Types map[string]schema.ComplexTypeSpec
// TypeOverrides define types that already exist in the auto-generated schema but we want to override
// to our custom shape and behavior. Optional.
// Deprecated: Use Schema instead.
TypeOverrides map[string]schema.ComplexTypeSpec
// Resource schema. Optional, by default the schema is assumed to be included in Azure Open API specs.
// Deprecated: Use Schema instead.
LegacySchema *schema.ResourceSpec
// Resource & types, schema & metadata modifications function.
// Optional, runs after main schema is generated allowing for modifications.
// The resource and types (both schema and metadata) returned will be written back into the schema and metadata.
// This can also include new types which were not present in the original schema.
// Any dangling, unreferenced types will be removed from the schema automatically.
// Returning nil will skip the resource and make no changes.
Schema func(resource *ResourceDefinition) (*ResourceDefinition, error)
// Resource metadata. Defines the parameters and properties that are used for diff calculation and validation.
// Optional, by default the metadata is assumed to be derived from Azure Open API specs.
// Deprecated: Use Schema instead.
Meta *AzureAPIResource
// MetaTypes are net-new auxiliary metadata types defined for this resource. Optional.
// Deprecated: Use Schema instead.
MetaTypes map[string]AzureAPIType
// MetaTypeOverrides define meta types that already exist in the auto-generated metadata but we want to override
// to our custom shape and behavior. Optional.
// Deprecated: Use Schema instead.
MetaTypeOverrides map[string]AzureAPIType
// GetIdAndQuery returns the resource id and query parameters for the custom resource. Optional, by default the provider gets the
// resource ID and query parameters from crud.ResourceCrudClient.PrepareAzureRESTIdAndQuery.
GetIdAndQuery func(ctx context.Context, inputs resource.PropertyMap, crudClient crud.ResourceCrudClient) (string, map[string]any, error)
// Create a new resource from a map of input values. Returns a map of resource outputs that match the schema shape.
Create func(ctx context.Context, id string, inputs resource.PropertyMap) (map[string]interface{}, error)
CanCreate func(ctx context.Context, id string) error
// Read the state of an existing resource. Constructs the resource ID based on input values. Returns a map of
// resource outputs. If the requested resource does not exist, the second result is false. In that case, the
// error must be nil.
Read CustomReadFunc
// Update an existing resource with a map of input values. Returns a map of resource outputs that match the schema shape.
Update func(ctx context.Context, id string, news, olds resource.PropertyMap) (map[string]interface{}, error)
// Delete an existing resource. Constructs the resource ID based on input values.
Delete func(ctx context.Context, id string, previousInputs, state resource.PropertyMap) error
// Only used when we want to specify a `tok` that exists in the spec so we can look up the resource, but we want
// the custom resource's name to be different.
CustomResourceName string
// Optional. If specified, only include schema and metadata from the spec for this version. Has no effect for
// resources that don't use the Azure spec. Format is 2020-01-30 or 2020-01-30-preview.
apiVersion *string
// IsSingleton is true if the resource is a singleton resource that cannot be created or deleted, only initialized
// and reset to a default state. Normally, we infer this from whether the `Delete` property is set. In some cases
// we need to set it explicitly if the resource is a singleton but does have a `Delete` property implementing a
// custom reset to the default state.
isSingleton bool
}
// ResourceDefinition is a combination of the external schema and runtime metadata
// for a resource and its associated types.
type ResourceDefinition struct {
Resource schema.ResourceSpec
Types map[string]schema.ComplexTypeSpec
MetaResource AzureAPIResource
MetaTypes map[string]AzureAPIType
}
// makePropertyNotRequired removes a property from the various lists of required properties, but leaves the property itself.
func (r *ResourceDefinition) makePropertyNotRequired(property string) {
r.Resource.RequiredInputs = util.RemoveFromSlice(r.Resource.RequiredInputs, property)
r.Resource.ObjectTypeSpec.Required = util.RemoveFromSlice(r.Resource.ObjectTypeSpec.Required, property)
if body, hasBody := r.MetaResource.BodyParameter(); hasBody {
body.Body.RequiredProperties = util.RemoveFromSlice(body.Body.RequiredProperties, property)
}
}
// ApplySchemas applies custom schema modifications to the given package.
// These modifications should never overlap with each other, but we apply in a deterministic order to ensure
// that the end result of the modifications is consistent.
func ApplySchemas(pkg *schema.PackageSpec, meta *AzureAPIMetadata) error {
for _, r := range util.MapOrdered(featureLookup) {
if err := r.ApplySchema(pkg, meta); err != nil {
return fmt.Errorf("failed to apply schema modifications for resource %s: %w", r.tok, err)
}
}
return nil
}
func (r *CustomResource) ApplySchema(pkg *schema.PackageSpec, meta *AzureAPIMetadata) error {
if r.tok == "" || r.Schema == nil {
return nil
}
tok := r.tok
if r.CustomResourceName != "" {
module, version, _, err := resources.ParseToken(tok)
if err != nil {
return fmt.Errorf("failed to parse token %s: %w", tok, err)
}
tok = resources.BuildToken(module, version, r.CustomResourceName)
}
existingResource, resourceAlreadyExists := pkg.Resources[tok]
var originalResource *ResourceDefinition
types := map[string]schema.ComplexTypeSpec{} // Hoist scope for easy lookup when checking if the type is new.
if resourceAlreadyExists {
resourceMeta, resourceMetadataFound := meta.Resources[tok]
if !resourceMetadataFound {
return fmt.Errorf("metadata for resource %s not found", tok)
}
VisitResourceTypes(pkg, tok, func(tok string, t schema.ComplexTypeSpec) {
// Capture referenced schema types
types[tok] = t
})
metaTypes := map[string]AzureAPIType{}
for n := range types {
if mt, metaTypeFound := meta.Types[n]; metaTypeFound {
metaTypes[n] = mt
} else {
logging.V(9).Infof("metadata for type %s not found, assuming it's an enum", n)
}
}
originalResource = &ResourceDefinition{
Resource: existingResource,
Types: types,
MetaResource: resourceMeta,
MetaTypes: metaTypes,
}
}
customResource, err := r.Schema(originalResource)
if err != nil {
if !resourceAlreadyExists && len(pkg.Resources) < 100 {
logging.V(5).Infof("warning: error applying custom resource schema modifications for %s: '%s'; continuing since this is likely a test run with only %d resources",
tok, err, len(pkg.Resources))
return nil
}
return fmt.Errorf("failed to apply custom resource schema modifications for %s: %w", tok, err)
}
if customResource == nil {
return nil
}
pkg.Resources[tok] = customResource.Resource
for typeToken, typeSchema := range customResource.Types {
if _, isExistingType := types[typeToken]; !isExistingType {
// New type, ensure it doesn't conflict
if _, existsInPackage := pkg.Types[typeToken]; existsInPackage {
return fmt.Errorf("new type from custom resource modification %s already exists in package", typeToken)
}
}
pkg.Types[typeToken] = typeSchema
}
meta.Resources[tok] = customResource.MetaResource
for n, t := range customResource.MetaTypes {
// Skip validation of meta types as they should be 1:1 with schema types
meta.Types[n] = t
}
return nil
}
// BuildCustomResources creates a map of custom resources for given environment parameters.
func BuildCustomResources(
azureClient azure.AzureClient,
lookupResource ResourceLookupFunc,
crudClientFactory crud.ResourceCrudClientFactory,
subscriptionID string,
cloud cloud.Configuration,
tokenCred azcore.TokenCredential) (map[string]*CustomResource, error) {
logging.V(9).Infof("building custom resources for cloud %q", cloud.Name)
armKVClient, err := armkeyvault.NewVaultsClient(subscriptionID, tokenCred, &arm.ClientOptions{})
if err != nil {
return nil, err
}
customWebApp, err := webApp(crudClientFactory, azureClient, lookupResource)
if err != nil {
return nil, err
}
customWebAppSlot, err := webAppSlot(crudClientFactory, azureClient, lookupResource)
if err != nil {
return nil, err
}
postgresConf, err := postgresFlexibleServerConfiguration(crudClientFactory, lookupResource)
if err != nil {
return nil, err
}
protectedItem, err := recoveryServicesProtectedItem(subscriptionID, tokenCred)
if err != nil {
return nil, err
}
pimRoleManagementPolicy, err := pimRoleManagementPolicy(lookupResource, crudClientFactory)
if err != nil {
return nil, err
}
pimRoleEligibilitySchedule, err := pimRoleEligibilitySchedule(lookupResource, crudClientFactory, tokenCred)
if err != nil {
return nil, err
}
customRoleAssignment, err := roleAssignment(lookupResource, crudClientFactory, azureClient, tokenCred)
if err != nil {
return nil, err
}
resources := []*CustomResource{
keyVaultAccessPolicy(armKVClient),
// Customization of regular resources
blobContainerLegalHold(azureClient),
portalDashboard(),
customWebApp,
customWebAppSlot,
postgresConf,
protectedItem,
pimRoleManagementPolicy,
pimRoleEligibilitySchedule,
customRoleAssignment,
}
resources = append(resources, keyVaultSecret(cloud, tokenCred))
resources = append(resources, keyVaultKey(cloud, tokenCred))
resources = append(resources, storageAccountStaticWebsite_azidentity(cloud, tokenCred))
resources = append(resources, newBlob_azidentity(cloud, tokenCred))
result := map[string]*CustomResource{}
for _, r := range resources {
result[r.path] = r
}
return result, nil
}
// featureLookup is a map of custom resource to lookup their capabilities.
var featureLookup, _ = BuildCustomResources(nil, nil, nil, "", cloud.Configuration{}, nil)
// IncludeCustomResource returns isCustom=true if a custom resource is defined for the given path, and include=true if
// the given API version should be included.
// Note on the `apiVersion` parameter: using the `openapi.ApiVersion` type would create an import cycle.
func IncludeCustomResource(path, apiVersion string) (isCustom, include bool) {
var resource *CustomResource
resource, isCustom = featureLookup[path]
if !isCustom {
return
}
include = resource.apiVersion == nil || *resource.apiVersion == apiVersion
return
}
// HasCustomDelete returns true if a custom DELETE operation is defined for a given API path.
func HasCustomDelete(path string) bool {
if res, ok := featureLookup[path]; ok {
return res.Delete != nil
}
return false
}
func IsSingleton(path string) bool {
if res, ok := featureLookup[path]; ok {
return res.isSingleton
}
return false
}
func GetCustomResourceName(path string) (string, bool) {
if res, ok := featureLookup[path]; ok {
return res.CustomResourceName, res.CustomResourceName != ""
}
return "", false
}
// SchemaMixins returns the map of custom resource schema definitions per resource token.
func SchemaMixins() map[string]schema.ResourceSpec {
specs := map[string]schema.ResourceSpec{}
for _, r := range featureLookup {
if r.tok != "" && r.LegacySchema != nil {
specs[r.tok] = *r.LegacySchema
}
}
return specs
}
// SchemaTypeMixins returns the map of custom resource schema definitions per resource token.
func SchemaTypeMixins() map[string]schema.ComplexTypeSpec {
types := map[string]schema.ComplexTypeSpec{}
for _, r := range featureLookup {
for n, v := range r.Types {
types[n] = v
}
}
return types
}
// SchemaTypeOverrides returns the map of custom resource schema overrides per resource token.
func SchemaTypeOverrides() map[string]schema.ComplexTypeSpec {
types := map[string]schema.ComplexTypeSpec{}
for _, r := range featureLookup {
for n, v := range r.TypeOverrides {
types[n] = v
}
}
return types
}
// MetaMixins returns the map of custom resource metadata definitions per resource token.
func MetaMixins() map[string]AzureAPIResource {
meta := map[string]AzureAPIResource{}
for _, r := range featureLookup {
if r.tok != "" && r.Meta != nil {
meta[r.tok] = *r.Meta
}
}
return meta
}
// MetaMixins returns the map of custom resource metadata definitions per resource token.
func MetaTypeMixins() map[string]AzureAPIType {
types := map[string]AzureAPIType{}
for _, r := range featureLookup {
for n, v := range r.MetaTypes {
types[n] = v
}
}
return types
}
// MetaTypeOverrides returns the map of custom resource metadata overrides per resource token.
func MetaTypeOverrides() map[string]AzureAPIType {
types := map[string]AzureAPIType{}
for _, r := range featureLookup {
for n, v := range r.MetaTypeOverrides {
types[n] = v
}
}
return types
}
// createCrudClient creates a CRUD client for the given resource type, looking up the fully
// qualified `resourceToken` like "azure-native:web:WebApp" via `lookupResource`.
func createCrudClient(
crudClientFactory crud.ResourceCrudClientFactory, lookupResource ResourceLookupFunc, resourceToken string,
) (crud.ResourceCrudClient, error) {
res, ok, err := lookupResource(resourceToken)
if err != nil {
return nil, err
}
if !ok {
return nil, fmt.Errorf("resource %s not found", resourceToken)
}
return crudClientFactory(&res), nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_pim_test.go | provider/pkg/resources/customresources/custom_pim_test.go | package customresources
import (
"context"
"encoding/json"
"testing"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/convert"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/provider/crud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/deepcopy"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCanCreateRoleManagementPolicy(t *testing.T) {
t.Parallel()
t.Run("returns nil", func(t *testing.T) {
t.Parallel()
r, err := pimRoleManagementPolicy(nil, nil)
require.NoError(t, err)
assert.Nil(t, r.CanCreate(context.Background(), ""))
})
}
func TestCreateRoleManagementPolicy(t *testing.T) {
t.Parallel()
roleManagementPolicyResource := resources.AzureAPIResource{}
t.Run("happy path", func(t *testing.T) {
t.Parallel()
azureClient := azure.MockAzureClient{
GetResponse: map[string]any{"original": "policy"},
}
mockClient := crud.NewResourceCrudClient(&azureClient, nil, nil, "123", &roleManagementPolicyResource)
roleManagementPolicyClient := &roleManagementPolicyClient{
client: mockClient,
}
out, err := roleManagementPolicyClient.create(context.Background(), "/id", resource.PropertyMap{})
require.NoError(t, err)
// we read the original policy
assert.Equal(t, []string{"/id"}, azureClient.GetIds)
// we preserved the original policy in state
assert.Equal(t, out[OriginalStateKey], map[string]any{"original": "policy"})
})
t.Run("error on read", func(t *testing.T) {
t.Parallel()
azureClient := azure.MockAzureClient{
GetResponseErr: errors.New("error"),
}
mockClient := crud.NewResourceCrudClient(&azureClient, nil, nil, "123", &roleManagementPolicyResource)
roleManagementPolicyClient := &roleManagementPolicyClient{
client: mockClient,
}
out, err := roleManagementPolicyClient.create(context.Background(), "/id", resource.PropertyMap{})
require.Error(t, err)
assert.Nil(t, out)
})
t.Run("error on put", func(t *testing.T) {
t.Parallel()
azureClient := azure.MockAzureClient{
PutResponseErr: errors.New("error"),
}
mockClient := crud.NewResourceCrudClient(&azureClient, nil, nil, "123", &roleManagementPolicyResource)
roleManagementPolicyClient := &roleManagementPolicyClient{
client: mockClient,
}
out, err := roleManagementPolicyClient.create(context.Background(), "/id", resource.PropertyMap{})
require.Error(t, err)
assert.Nil(t, out)
})
}
func TestUpdateRoleManagementPolicy(t *testing.T) {
t.Parallel()
roleManagementPolicyResource := resources.AzureAPIResource{
PutParameters: []resources.AzureAPIParameter{
{
Name: "properties",
Location: "body",
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"rules": {
Type: "array",
Items: &resources.AzureAPIProperty{
Type: "object",
OneOf: []string{"azure-native:authorization:RoleManagementPolicyExpirationRule"},
},
},
},
},
},
},
}
expirationRule := resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"id": {Type: "string"},
"isExpirationRequired": {Type: "boolean"},
},
}
lookupType := func(ref string) (*resources.AzureAPIType, bool, error) {
if ref == "#/types/azure-native:authorization:RoleManagementPolicyExpirationRule" {
return &expirationRule, true, nil
}
return nil, false, nil
}
converter := convert.NewSdkShapeConverterFull(map[string]resources.AzureAPIType{
"azure-native:authorization:RoleManagementPolicyExpirationRule": expirationRule,
})
// "isExpirationRequired" changes from false to true. The original "false" value is preserved.
t.Run("restores deleted rules", func(t *testing.T) {
t.Parallel()
azureClient := azure.MockAzureClient{}
mockClient := crud.NewResourceCrudClient(&azureClient, lookupType, &converter, "123", &roleManagementPolicyResource)
roleManagementPolicyClient := &roleManagementPolicyClient{
client: mockClient,
}
oldsPlain := map[string]any{
"rules": []map[string]any{
{"id": "rule1", "isExpirationRequired": false},
},
OriginalStateKey: map[string]any{
"properties": map[string]any{
"rules": []map[string]any{
{"id": "rule1", "isExpirationRequired": false},
},
},
},
}
olds := resource.NewPropertyMapFromMap(oldsPlain)
newsPlain := map[string]any{
"rules": []map[string]any{
{"id": "rule1", "isExpirationRequired": true},
},
}
news := resource.NewPropertyMapFromMap(newsPlain)
// The return value is mostly empty because `roleManagementPolicyResource` is a dummy without the response properties.
out, err := roleManagementPolicyClient.update(context.Background(), "/id", news, olds)
require.NoError(t, err)
assert.Equal(t, []string{"/id"}, azureClient.PutIds)
assert.Len(t, azureClient.PutBodies, 1)
// We cannot use `assert.Equals` because in one object "rules" is a `[]map[string]map[string]any`, in the other a `[]map[string]any`.
expectedBody, err := json.Marshal(newsPlain)
require.NoError(t, err)
actualBody, err := json.Marshal(azureClient.PutBodies[0])
require.NoError(t, err)
assert.JSONEq(t, string(expectedBody), string(actualBody))
// Check the original state is preserved.
// We cannot use `assert.Equals` because in one object "rules" is a `[]map[string]map[string]any`, in the other a `[]map[string]any`.
assert.Contains(t, out, OriginalStateKey)
expectedOriginalState, err := json.Marshal(oldsPlain[OriginalStateKey])
require.NoError(t, err)
actualOriginalState, err := json.Marshal(out[OriginalStateKey])
require.NoError(t, err)
assert.JSONEq(t, string(expectedOriginalState), string(actualOriginalState))
})
t.Run("error on PUT", func(t *testing.T) {
t.Parallel()
azureClient := azure.MockAzureClient{
PutResponseErr: errors.New("error"),
}
mockClient := crud.NewResourceCrudClient(&azureClient, lookupType, &converter, "123", &roleManagementPolicyResource)
roleManagementPolicyClient := &roleManagementPolicyClient{
client: mockClient,
}
out, err := roleManagementPolicyClient.update(context.Background(), "/id", resource.PropertyMap{}, resource.PropertyMap{})
require.Error(t, err)
assert.Nil(t, out)
})
}
func TestRestoreDefaultsForDeletedRules(t *testing.T) {
t.Run("nothing to restore", func(t *testing.T) {
// There's one rule, it's in the original state with a different value for isExpirationRequired.
olds := map[string]any{
"rules": []map[string]any{
{"id": "rule1", "isExpirationRequired": true},
},
OriginalStateKey: map[string]any{
"properties": map[string]any{
"rules": []map[string]any{
{"id": "rule1", "isExpirationRequired": false},
},
},
},
}
// One rule is modified and another added, but none is removed.
news := map[string]any{
"rules": []map[string]any{
{"id": "rule1", "isExpirationRequired": false},
{"id": "rule2"},
},
}
newsPropertyMap := resource.NewPropertyMapFromMap(news)
newsPropertyMapCopy := deepcopy.Copy(newsPropertyMap)
restoreDefaultsForDeletedRules(resource.NewPropertyMapFromMap(olds), newsPropertyMap)
assert.Equal(t, newsPropertyMap, newsPropertyMapCopy)
})
t.Run("one deleted rule to restore", func(t *testing.T) {
// There's one rule, it's in the original state with a different value for isExpirationRequired.
olds := map[string]any{
"rules": []map[string]any{
{"id": "rule1", "isExpirationRequired": true},
},
OriginalStateKey: map[string]any{
"properties": map[string]any{
"rules": []map[string]any{
{"id": "rule1", "isExpirationRequired": false},
},
},
},
}
// The old rule is removed and another added.
news := map[string]any{
"rules": []map[string]any{
{"id": "rule2"},
},
}
newsPropertyMap := resource.NewPropertyMapFromMap(news)
newsPropertyMapCopy := deepcopy.Copy(newsPropertyMap).(resource.PropertyMap)
restoreDefaultsForDeletedRules(resource.NewPropertyMapFromMap(olds), newsPropertyMap)
assert.NotEqual(t, newsPropertyMap, newsPropertyMapCopy)
assert.Equal(t,
[]resource.PropertyValue{
resource.NewObjectProperty(resource.NewPropertyMapFromMap(map[string]any{"id": "rule1", "isExpirationRequired": false})),
resource.NewObjectProperty(resource.NewPropertyMapFromMap(map[string]any{"id": "rule2"})),
},
newsPropertyMap["rules"].ArrayValue(),
)
})
t.Run("all rules deleted", func(t *testing.T) {
// There are two rules in the original state, one with a different value for isExpirationRequired.
origRules := []map[string]any{
{"id": "rule1", "isExpirationRequired": false},
{"id": "rule2"},
}
olds := map[string]any{
"rules": []map[string]any{
{"id": "rule1", "isExpirationRequired": true},
{"id": "rule2"},
},
OriginalStateKey: map[string]any{
"properties": map[string]any{
"rules": origRules,
},
},
}
// No rules left. OriginalState is optional, it's read from `olds`.
news := map[string]any{}
newsPropertyMap := resource.NewPropertyMapFromMap(news)
newsPropertyMapCopy := deepcopy.Copy(newsPropertyMap).(resource.PropertyMap)
restoreDefaultsForDeletedRules(resource.NewPropertyMapFromMap(olds), newsPropertyMap)
assert.NotEqual(t, newsPropertyMap, newsPropertyMapCopy)
rules := newsPropertyMap["rules"].ArrayValue()
require.Len(t, rules, len(origRules))
assert.Equal(t,
[]resource.PropertyValue{
resource.NewObjectProperty(resource.NewPropertyMapFromMap(origRules[0])),
resource.NewObjectProperty(resource.NewPropertyMapFromMap(origRules[1])),
},
newsPropertyMap["rules"].ArrayValue(),
)
})
t.Run("restores rules never specified by user", func(t *testing.T) {
// Original state from Azure has 3 rules, but user only ever specified 1 in their Pulumi program
origRules := []map[string]any{
{"id": "rule1", "maximumDuration": "P365D"},
{"id": "rule2", "isExpirationRequired": false},
{"id": "rule3", "notificationLevel": "All"},
}
// User only specified rule1 in their Pulumi program
olds := map[string]any{
"rules": []map[string]any{
{"id": "rule1", "maximumDuration": "P365D"},
},
OriginalStateKey: map[string]any{
"properties": map[string]any{
"rules": origRules,
},
},
}
// User modifies rule1
news := map[string]any{
"rules": []map[string]any{
{"id": "rule1", "maximumDuration": "P90D"},
},
}
newsPropertyMap := resource.NewPropertyMapFromMap(news)
restoreDefaultsForDeletedRules(resource.NewPropertyMapFromMap(olds), newsPropertyMap)
// Should include the modified rule1 AND the unspecified rule2 and rule3 from original state
rules := newsPropertyMap["rules"].ArrayValue()
require.Len(t, rules, 3)
assert.Equal(t,
[]resource.PropertyValue{
resource.NewObjectProperty(resource.NewPropertyMapFromMap(map[string]any{"id": "rule1", "maximumDuration": "P90D"})),
resource.NewObjectProperty(resource.NewPropertyMapFromMap(map[string]any{"id": "rule2", "isExpirationRequired": false})),
resource.NewObjectProperty(resource.NewPropertyMapFromMap(map[string]any{"id": "rule3", "notificationLevel": "All"})),
},
newsPropertyMap["rules"].ArrayValue(),
)
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_webapp_read_test.go | provider/pkg/resources/customresources/custom_webapp_read_test.go | package customresources
import (
"testing"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"github.com/stretchr/testify/require"
)
func TestFilterRedactedPublishingUsername(t *testing.T) {
for name, testCase := range map[string]struct {
response map[string]any
shouldContainPublishingUsername bool
}{
"realName": {
response: map[string]any{
"siteConfig": map[string]any{"publishingUsername": "$1234"},
},
shouldContainPublishingUsername: true,
},
"redactedName": {
response: map[string]any{
"siteConfig": map[string]any{"publishingUsername": "REDACTED"},
},
shouldContainPublishingUsername: false,
},
"noName": { // don't panic
response: map[string]any{
"siteConfig": map[string]any{},
},
shouldContainPublishingUsername: false,
},
"noSiteConfig": { // don't panic
response: map[string]any{},
shouldContainPublishingUsername: false,
},
} {
t.Run(name, func(t *testing.T) {
filterResponse(testCase.response)
siteConfig, ok := util.GetInnerMap(testCase.response, "siteConfig")
require.Equal(t, name != "noSiteConfig", ok)
_, ok = siteConfig["publishingUsername"]
require.Equal(t, testCase.shouldContainPublishingUsername, ok)
})
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_recoveryservices_test.go | provider/pkg/resources/customresources/custom_recoveryservices_test.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package customresources
import (
"context"
"testing"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
recovery "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/recoveryservices/armrecoveryservicesbackup/v4"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/provider/crud"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// func not var to ensure we have separate copies for separate tests.
func standardAzureFileshareProtectedItemInput() resource.PropertyMap {
return resource.NewPropertyMapFromMap(map[string]any{
"containerName": "container",
"fabricName": "Azure",
"protectedItemName": "fileshare",
resourceGroupName: "rg",
"vaultName": "vault",
"properties": map[string]any{
"protectedItemType": "AzureFileShareProtectedItem",
"policyId": "policy",
"sourceResourceId": "azure/sa1",
},
})
}
func TestGetIdAndQuery(t *testing.T) {
t.Parallel()
// A minimal copy of the actual resource metadata, reduced to what's needed for the test.
protectedItemResource := resources.AzureAPIResource{
APIVersion: "2023-04-01",
Path: protectedItemPath,
PutParameters: []resources.AzureAPIParameter{
{
Name: "resourceGroupName",
Location: "path",
Value: &resources.AzureAPIProperty{},
},
{
Name: "vaultName",
Location: "path",
Value: &resources.AzureAPIProperty{},
},
{
Name: "subscriptionId",
Location: "path",
Value: &resources.AzureAPIProperty{},
},
{
Name: "fabricName",
Location: "path",
Value: &resources.AzureAPIProperty{},
},
{
Name: "containerName",
Location: "path",
Value: &resources.AzureAPIProperty{},
},
{
Name: "protectedItemName",
Location: "path",
Value: &resources.AzureAPIProperty{},
},
{
Name: "properties",
Location: "body",
Value: &resources.AzureAPIProperty{},
Body: &resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"protectedItemType": {Type: "string"},
"policyId": {Type: "string"},
"sourceResourceId": {Type: "string"},
},
},
},
},
}
reader := &mockSystemNameReader{systemNames: []string{"azurefileshare;339f9859"}}
azureClient := azure.MockAzureClient{}
crudClient := crud.NewResourceCrudClient(&azureClient, nil, nil, "123", &protectedItemResource)
id, queryParams, err := getIdAndQuery(context.Background(), standardAzureFileshareProtectedItemInput(), crudClient, reader)
require.NoError(t, err)
assert.Equal(t, "/subscriptions/123/resourceGroups/rg/providers/Microsoft.RecoveryServices/vaults/vault/backupFabrics/Azure/protectionContainers/container/protectedItems/azurefileshare%3B339f9859", id)
// Query params should be identical to non-custom ones.
_, regularQueryParams, err := crudClient.PrepareAzureRESTIdAndQuery(resource.PropertyMap{})
require.NoError(t, err)
assert.Equal(t, regularQueryParams, queryParams)
}
func TestRetrieveSystemName(t *testing.T) {
t.Parallel()
t.Run("happy path", func(t *testing.T) {
t.Parallel()
reader := &mockSystemNameReader{systemNames: []string{"systemName"}}
systemName, err := retrieveSystemName(context.Background(), standardAzureFileshareProtectedItemInput(), reader, 1, 0*time.Second)
assert.NoError(t, err)
assert.Equal(t, "systemName", systemName)
assert.True(t, reader.inquireCalled)
})
t.Run("no system name is found", func(t *testing.T) {
t.Parallel()
reader := &mockSystemNameReader{systemNames: []string{""}}
systemName, err := retrieveSystemName(context.Background(), standardAzureFileshareProtectedItemInput(), reader, 1, 0*time.Second)
assert.Error(t, err)
assert.Empty(t, systemName)
assert.True(t, reader.inquireCalled)
})
t.Run("system name is found after multiple attempts", func(t *testing.T) {
t.Parallel()
reader := &mockSystemNameReader{
systemNames: []string{"", "", "systemName", ""},
errors: []error{nil, nil, nil, nil},
}
systemName, err := retrieveSystemName(context.Background(), standardAzureFileshareProtectedItemInput(), reader, 5, 0*time.Second)
assert.NoError(t, err)
assert.Equal(t, "systemName", systemName)
assert.True(t, reader.inquireCalled)
})
t.Run("stops after max attempts", func(t *testing.T) {
t.Parallel()
reader := &mockSystemNameReader{
systemNames: []string{"", "", "systemName"},
errors: []error{nil, nil, nil},
}
systemName, err := retrieveSystemName(context.Background(), standardAzureFileshareProtectedItemInput(), reader, 2, 0*time.Second)
assert.Error(t, err)
assert.Empty(t, systemName)
assert.True(t, reader.inquireCalled)
})
t.Run("no system name for protected item of type other than AzureFileShareProtectedItem", func(t *testing.T) {
t.Parallel()
input := standardAzureFileshareProtectedItemInput()
input["properties"].ObjectValue()["protectedItemType"] = resource.NewStringProperty("SomeOtherProtectedItem")
reader := &mockSystemNameReader{systemNames: []string{"test"}, errors: []error{nil}}
systemName, err := retrieveSystemName(context.Background(), input, reader, 1, 0*time.Second)
assert.NoError(t, err)
assert.Empty(t, systemName)
assert.False(t, reader.inquireCalled)
})
}
type mockSystemNameReader struct {
systemNames []string
errors []error
attempt int
// Was the /inquire API resp. the SDK's ProtectionContainersClient.Inquire called?
inquireCalled bool
}
func (m *mockSystemNameReader) readSystemNameFromProtectableItem(ctx context.Context, input *protectedItemProperties) (string, error) {
name := m.systemNames[m.attempt]
var err error
if len(m.errors) > m.attempt {
err = m.errors[m.attempt]
}
m.attempt++
return name, err
}
func (m *mockSystemNameReader) inquireContainer(ctx context.Context, input *protectedItemProperties) error {
m.inquireCalled = true
return nil
}
func TestFindSystemName(t *testing.T) {
t.Parallel()
t.Run("happy path", func(t *testing.T) {
t.Parallel()
friendlyName := "friendlyName"
storageAccountName := "storageAccountName"
items := []*recovery.WorkloadProtectableItemResource{
{
Name: to.Ptr("different one"),
Properties: &recovery.AzureFileShareProtectableItem{
FriendlyName: to.Ptr("different name"),
ParentContainerFriendlyName: to.Ptr(storageAccountName),
},
},
{
Name: to.Ptr("different two"),
Properties: &recovery.AzureFileShareProtectableItem{
FriendlyName: to.Ptr(friendlyName),
ParentContainerFriendlyName: to.Ptr("different storage account name"),
},
},
{
Name: to.Ptr("systemName"),
Properties: &recovery.AzureFileShareProtectableItem{
FriendlyName: to.Ptr(friendlyName),
ParentContainerFriendlyName: to.Ptr(storageAccountName),
},
},
}
systemName, err := findSystemName(items, "friendlyName", "storageAccountName")
assert.NoError(t, err)
assert.Equal(t, "systemName", systemName)
})
t.Run("returns empty string if no matching item is found", func(t *testing.T) {
t.Parallel()
items := []*recovery.WorkloadProtectableItemResource{
{
Name: to.Ptr("different one"),
Properties: &recovery.AzureFileShareProtectableItem{
FriendlyName: to.Ptr("different name"),
ParentContainerFriendlyName: to.Ptr("different storageAccountName"),
},
},
}
systemName, err := findSystemName(items, "friendlyName", "storageAccountName")
assert.NoError(t, err)
assert.Equal(t, "", systemName)
})
t.Run("returns error if the item is not a file share", func(t *testing.T) {
t.Parallel()
items := []*recovery.WorkloadProtectableItemResource{
{
Name: to.Ptr("systemName"),
Properties: &recovery.AzureVMWorkloadProtectableItem{
FriendlyName: to.Ptr("friendlyName"),
},
},
}
systemName, err := findSystemName(items, "friendlyName", "storageAccountName")
assert.Error(t, err)
assert.Equal(t, "", systemName)
})
t.Run("no items", func(t *testing.T) {
t.Parallel()
systemName, err := findSystemName(nil, "friendlyName", "storageAccountName")
assert.NoError(t, err)
assert.Equal(t, "", systemName)
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_roleassignment_test.go | provider/pkg/resources/customresources/custom_roleassignment_test.go | // Copyright 2025, Pulumi Corporation. All rights reserved.
package customresources
import (
"context"
"encoding/json"
"fmt"
"testing"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// mockRoleAssignmentClient mocks the roleAssignmentClient interface for testing
type mockRoleAssignmentClient struct {
tenantID string
tenantIDError error
capturedSubsID string
responseOutputs map[string]any
}
func (m *mockRoleAssignmentClient) getTenantId(ctx context.Context, subscriptionId string) (string, error) {
m.capturedSubsID = subscriptionId
if m.tenantIDError != nil {
return "", m.tenantIDError
}
return m.tenantID, nil
}
func (m *mockRoleAssignmentClient) convertResponseToOutputs(response map[string]any) map[string]any {
if m.responseOutputs != nil {
return m.responseOutputs
}
return response
}
func TestExtractSubscriptionId(t *testing.T) {
t.Parallel()
t.Run("valid resource ID", func(t *testing.T) {
t.Parallel()
resourceId := "/subscriptions/12345678-1234-1234-1234-123456789abc/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity"
subscriptionId, err := extractSubscriptionId(resourceId)
require.NoError(t, err)
assert.Equal(t, "12345678-1234-1234-1234-123456789abc", subscriptionId)
})
t.Run("resource ID at subscription level", func(t *testing.T) {
t.Parallel()
resourceId := "/subscriptions/abcd-efgh-ijkl/providers/Microsoft.Authorization/roleDefinitions/role1"
subscriptionId, err := extractSubscriptionId(resourceId)
require.NoError(t, err)
assert.Equal(t, "abcd-efgh-ijkl", subscriptionId)
})
t.Run("invalid resource ID - no subscriptions segment", func(t *testing.T) {
t.Parallel()
resourceId := "/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity"
_, err := extractSubscriptionId(resourceId)
require.Error(t, err)
assert.Contains(t, err.Error(), "could not extract subscription ID")
})
t.Run("empty resource ID", func(t *testing.T) {
t.Parallel()
_, err := extractSubscriptionId("")
require.Error(t, err)
assert.Contains(t, err.Error(), "could not extract subscription ID")
})
}
func TestReadRoleAssignment_CrossTenant(t *testing.T) {
t.Parallel()
roleAssignmentID := "/subscriptions/sub-123/providers/Microsoft.Authorization/roleAssignments/role-456"
delegatedIdentityResourceID := "/subscriptions/delegated-sub-789/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity"
tenantID := "tenant-abc"
// Mock Azure API response for role assignment
roleAssignmentResponse := map[string]any{
"id": roleAssignmentID,
"name": "role-456",
"type": "Microsoft.Authorization/roleAssignments",
"properties": map[string]any{
"roleDefinitionId": "/subscriptions/sub-123/providers/Microsoft.Authorization/roleDefinitions/role-def-1",
"principalId": "principal-123",
"principalType": "ServicePrincipal",
"delegatedManagedIdentityResourceId": delegatedIdentityResourceID,
},
}
mockAzureClient := &azure.MockAzureClient{
GetResponse: roleAssignmentResponse,
}
mockClient := &mockRoleAssignmentClient{
tenantID: tenantID,
responseOutputs: map[string]any{
"id": roleAssignmentID,
"name": "role-456",
"roleDefinitionId": "/subscriptions/sub-123/providers/Microsoft.Authorization/roleDefinitions/role-def-1",
"principalId": "principal-123",
"delegatedManagedIdentityResourceId": delegatedIdentityResourceID,
},
}
res := &resources.AzureAPIResource{
APIVersion: "2022-04-01",
ReadPath: "",
ReadQueryParams: map[string]any{},
}
inputs := resource.PropertyMap{
"delegatedManagedIdentityResourceId": resource.NewStringProperty(delegatedIdentityResourceID),
}
outputs, found, err := readRoleAssignment(context.Background(), roleAssignmentID, inputs, mockClient, res, mockAzureClient)
require.NoError(t, err)
assert.True(t, found)
assert.NotNil(t, outputs)
// Verify subscription ID was extracted and looked up
assert.Equal(t, "delegated-sub-789", mockClient.capturedSubsID)
// Verify the GET request was made to the correct URL
require.Len(t, mockAzureClient.GetIds, 1)
assert.Equal(t, roleAssignmentID, mockAzureClient.GetIds[0])
// Verify API version
require.Len(t, mockAzureClient.GetApiVersions, 1)
assert.Equal(t, "2022-04-01", mockAzureClient.GetApiVersions[0])
}
func TestReadRoleAssignment_CrossTenant_WithExistingQueryParams(t *testing.T) {
t.Parallel()
roleAssignmentID := "/subscriptions/sub-123/providers/Microsoft.Authorization/roleAssignments/role-456"
delegatedIdentityResourceID := "/subscriptions/delegated-sub-789/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity"
tenantID := "tenant-abc"
mockAzureClient := &azure.MockAzureClient{
GetResponse: map[string]any{"id": roleAssignmentID},
}
mockClient := &mockRoleAssignmentClient{
tenantID: tenantID,
responseOutputs: map[string]any{"id": roleAssignmentID},
}
// Resource with existing query parameters
res := &resources.AzureAPIResource{
APIVersion: "2022-04-01",
ReadPath: "",
ReadQueryParams: map[string]any{
"api-version": "2022-04-01",
},
}
inputs := resource.PropertyMap{
"delegatedManagedIdentityResourceId": resource.NewStringProperty(delegatedIdentityResourceID),
}
_, found, err := readRoleAssignment(context.Background(), roleAssignmentID, inputs, mockClient, res, mockAzureClient)
require.NoError(t, err)
assert.True(t, found)
// Note: We can't directly verify query params with the current MockAzureClient implementation,
// but we verify the call was made successfully
require.Len(t, mockAzureClient.GetIds, 1)
}
func TestReadRoleAssignment_SameTenant(t *testing.T) {
t.Parallel()
roleAssignmentID := "/subscriptions/sub-123/providers/Microsoft.Authorization/roleAssignments/role-456"
roleAssignmentResponse := map[string]any{
"id": roleAssignmentID,
"name": "role-456",
"type": "Microsoft.Authorization/roleAssignments",
"properties": map[string]any{
"roleDefinitionId": "/subscriptions/sub-123/providers/Microsoft.Authorization/roleDefinitions/role-def-1",
"principalId": "principal-123",
"principalType": "User",
},
}
mockAzureClient := &azure.MockAzureClient{
GetResponse: roleAssignmentResponse,
}
// Client that should NOT be called for tenant ID lookup
mockClient := &mockRoleAssignmentClient{
tenantIDError: fmt.Errorf("should not be called"),
responseOutputs: map[string]any{
"id": roleAssignmentID,
"name": "role-456",
"roleDefinitionId": "/subscriptions/sub-123/providers/Microsoft.Authorization/roleDefinitions/role-def-1",
"principalId": "principal-123",
},
}
res := &resources.AzureAPIResource{
APIVersion: "2022-04-01",
ReadPath: "",
ReadQueryParams: map[string]any{},
}
// No delegatedManagedIdentityResourceId in inputs
inputs := resource.PropertyMap{}
outputs, found, err := readRoleAssignment(context.Background(), roleAssignmentID, inputs, mockClient, res, mockAzureClient)
require.NoError(t, err)
assert.True(t, found)
assert.NotNil(t, outputs)
// Verify tenant ID lookup was NOT called (capturedSubsID should be empty)
assert.Empty(t, mockClient.capturedSubsID)
// Verify the GET request was made
require.Len(t, mockAzureClient.GetIds, 1)
assert.Equal(t, roleAssignmentID, mockAzureClient.GetIds[0])
}
func TestReadRoleAssignment_InvalidDelegatedIdentityResourceId(t *testing.T) {
t.Parallel()
roleAssignmentID := "/subscriptions/sub-123/providers/Microsoft.Authorization/roleAssignments/role-456"
invalidResourceID := "/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity"
mockAzureClient := &azure.MockAzureClient{}
mockClient := &mockRoleAssignmentClient{}
res := &resources.AzureAPIResource{
APIVersion: "2022-04-01",
}
inputs := resource.PropertyMap{
"delegatedManagedIdentityResourceId": resource.NewStringProperty(invalidResourceID),
}
_, found, err := readRoleAssignment(context.Background(), roleAssignmentID, inputs, mockClient, res, mockAzureClient)
require.Error(t, err)
assert.False(t, found)
assert.Contains(t, err.Error(), "failed to extract subscription ID")
}
func TestReadRoleAssignment_SubscriptionLookupFails(t *testing.T) {
t.Parallel()
roleAssignmentID := "/subscriptions/sub-123/providers/Microsoft.Authorization/roleAssignments/role-456"
delegatedIdentityResourceID := "/subscriptions/delegated-sub-789/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity"
mockAzureClient := &azure.MockAzureClient{}
mockClient := &mockRoleAssignmentClient{
tenantIDError: fmt.Errorf("subscription lookup failed"),
}
res := &resources.AzureAPIResource{
APIVersion: "2022-04-01",
}
inputs := resource.PropertyMap{
"delegatedManagedIdentityResourceId": resource.NewStringProperty(delegatedIdentityResourceID),
}
_, found, err := readRoleAssignment(context.Background(), roleAssignmentID, inputs, mockClient, res, mockAzureClient)
require.Error(t, err)
assert.False(t, found)
assert.Contains(t, err.Error(), "failed to get tenant ID for subscription")
}
func TestReadRoleAssignment_AzureGetFails(t *testing.T) {
t.Parallel()
roleAssignmentID := "/subscriptions/sub-123/providers/Microsoft.Authorization/roleAssignments/role-456"
delegatedIdentityResourceID := "/subscriptions/delegated-sub-789/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity"
mockAzureClient := &azure.MockAzureClient{
GetResponseErr: fmt.Errorf("role assignment not found"),
}
mockClient := &mockRoleAssignmentClient{
tenantID: "tenant-123",
}
res := &resources.AzureAPIResource{
APIVersion: "2022-04-01",
}
inputs := resource.PropertyMap{
"delegatedManagedIdentityResourceId": resource.NewStringProperty(delegatedIdentityResourceID),
}
_, found, err := readRoleAssignment(context.Background(), roleAssignmentID, inputs, mockClient, res, mockAzureClient)
require.Error(t, err)
assert.False(t, found)
assert.Contains(t, err.Error(), "role assignment not found")
}
func TestReadRoleAssignment_NullDelegatedIdentityResourceId(t *testing.T) {
t.Parallel()
roleAssignmentID := "/subscriptions/sub-123/providers/Microsoft.Authorization/roleAssignments/role-456"
mockAzureClient := &azure.MockAzureClient{
GetResponse: map[string]any{"id": roleAssignmentID},
}
mockClient := &mockRoleAssignmentClient{
tenantIDError: fmt.Errorf("should not be called"),
responseOutputs: map[string]any{"id": roleAssignmentID},
}
res := &resources.AzureAPIResource{
APIVersion: "2022-04-01",
}
// delegatedManagedIdentityResourceId is explicitly null
inputs := resource.PropertyMap{
"delegatedManagedIdentityResourceId": resource.NewNullProperty(),
}
outputs, found, err := readRoleAssignment(context.Background(), roleAssignmentID, inputs, mockClient, res, mockAzureClient)
require.NoError(t, err)
assert.True(t, found)
assert.NotNil(t, outputs)
// Verify tenant ID lookup was NOT called
assert.Empty(t, mockClient.capturedSubsID)
}
// Example response format from Azure API for documentation
const exampleRoleAssignmentResponse = `
{
"id": "/subscriptions/a925f2f7-5c63-4b7b-8799-25a5f97bc3b2/providers/Microsoft.Authorization/roleAssignments/b0f43c54-e787-4862-89b1-a653fa9cf747",
"type": "Microsoft.Authorization/roleAssignments",
"name": "b0f43c54-e787-4862-89b1-a653fa9cf747",
"properties": {
"roleDefinitionId": "/providers/Microsoft.Authorization/roleDefinitions/0b5fe924-9a61-425c-96af-cfe6e287ca2d",
"principalId": "ce2ce14e-85d7-4629-bdbc-454d0519d987",
"principalType": "User",
"scope": "/subscriptions/a925f2f7-5c63-4b7b-8799-25a5f97bc3b2"
}
}
`
func TestResponseParsing(t *testing.T) {
t.Parallel()
// Verify we can parse the example response
var response map[string]any
err := json.Unmarshal([]byte(exampleRoleAssignmentResponse), &response)
require.NoError(t, err)
assert.Contains(t, response, "properties")
props := response["properties"].(map[string]any)
assert.Contains(t, props, "roleDefinitionId")
assert.Contains(t, props, "principalId")
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_recoveryservices.go | provider/pkg/resources/customresources/custom_recoveryservices.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package customresources
import (
"context"
"fmt"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
recovery "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/recoveryservices/armrecoveryservicesbackup/v4"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/provider/crud"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
const (
protectedItemPath = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}"
recoveryServicesAzureStorageFilter = "backupManagementType eq 'AzureStorage'"
)
type protectedItem struct {
protectedItemType string
policyID string
// For file shares, this is the storage account ID.
sourceResourceId string
}
type protectedItemProperties struct {
protectedItem
// The internal name of the protected item, also called system name. It looks like
// "azurefileshare;339f98592ed6329dc5f83bdbb8675bd3528bf58d2246d5e172615186febdc45c". It's determined by
// readSystemNameFromProtectableItem.
name string
resourceGroupName string
recoveryVaultName string
containerName string
itemName string
fabricName string
}
// A custom resource for Microsoft.RecoveryServices ProtectedItem, specifically the file share protected item. It looks
// up the magic "system name" of the file share and adds it to the inputs. For other types of protected items, it does
// nothing. #1420
func recoveryServicesProtectedItem(subscription string, cred azcore.TokenCredential) (*CustomResource, error) {
clientFactory, err := recovery.NewClientFactory(subscription, cred, nil)
if err != nil {
return nil, fmt.Errorf("failed to create recovery services client factory: %w", err)
}
reader := &systemNameReaderImpl{
protectableItemsClient: clientFactory.NewBackupProtectableItemsClient(),
protectionContainersClient: clientFactory.NewProtectionContainersClient(),
}
return &CustomResource{
path: protectedItemPath,
tok: "azure-native:recoveryservices:ProtectedItem",
GetIdAndQuery: func(ctx context.Context, inputs resource.PropertyMap, crudClient crud.ResourceCrudClient) (string, map[string]any, error) {
return getIdAndQuery(ctx, inputs, crudClient, reader)
},
}, nil
}
// getIdAndQuery replaces the default implementation of crud.ResourceCrudClient.PrepareAzureRESTIdAndQuery. It doesn't
// change queryParams, only the id, to replace the file share's friendly name with the system name.
func getIdAndQuery(ctx context.Context, inputs resource.PropertyMap, crudClient crud.ResourceCrudClient, reader systemNameReader) (string, map[string]any, error) {
systemName, err := retrieveSystemName(ctx, inputs, reader, 10, 30*time.Second)
if err != nil {
return "", nil, fmt.Errorf("failed to retrieve system name: %w", err)
}
inputsCopy := resource.NewPropertyMapFromMap(inputs.Mappable()) // deep copy
if systemName != "" {
inputsCopy["protectedItemName"] = resource.NewStringProperty(systemName)
}
origId, queryParams, err := crudClient.PrepareAzureRESTIdAndQuery(inputsCopy)
if err != nil {
return "", nil, fmt.Errorf("failed to prepare Azure REST ID and query: %w", err)
}
return origId, queryParams, nil
}
// retrieveSystemName looks up the system name of a file share protected item in Azure.
func retrieveSystemName(ctx context.Context, input resource.PropertyMap, reader systemNameReader, maxAttempts int, waitBetweenAttempts time.Duration) (string, error) {
item, err := extractProtectedItemProperties(input)
if err != nil {
return "", fmt.Errorf("failed to extract protected item properties from input: %w", err)
}
if item.protectedItemType != "AzureFileShareProtectedItem" {
logging.V(9).Infof("not modifying protected item of type %s", item.protectedItemType)
return "", nil
}
err = reader.inquireContainer(ctx, item)
if err != nil {
return "", fmt.Errorf("failed to inquire protection container %s: %w", item.containerName, err)
}
logging.V(9).Infof("looking up system name for %s", item.itemName)
// Based on observations during testing, the system name is usually, but not always immediately available.
// The /inquire request above should be awaited according to the docs, but the SDK doesn't actually support that.
for i := 1; i <= maxAttempts; i++ {
systemName, err := reader.readSystemNameFromProtectableItem(ctx, item)
if err != nil {
return "", fmt.Errorf("failed to read system name for protectable item: %w", err)
}
if systemName != "" {
logging.V(9).Infof("found system name %s for %s in attempt %d", systemName, item.itemName, i)
return systemName, nil
}
if i < maxAttempts {
time.Sleep(waitBetweenAttempts)
}
}
return "", fmt.Errorf("failed to retrieve system name after %d attempts", maxAttempts)
}
// systemNameReader is an interface for getting the Azure system name of a protected item.
// The system name looks like "azurefileshare;339f98592ed6329dc5f83bdbb8675bd3528bf58d2246d5e172615186febdc45c" and
// needs to be determined by iterating over the protected items in scope and matching by the human-readable name.
// Abstracted into an interface to allow for testing.
type systemNameReader interface {
// inquireContainer makes a request to /inquire, a special recovery services API that triggers a background job to
// update the protectable items in scope.
inquireContainer(ctx context.Context, input *protectedItemProperties) error
readSystemNameFromProtectableItem(ctx context.Context, input *protectedItemProperties) (string, error)
}
type systemNameReaderImpl struct {
protectableItemsClient *recovery.BackupProtectableItemsClient
protectionContainersClient *recovery.ProtectionContainersClient
}
func (s *systemNameReaderImpl) readSystemNameFromProtectableItem(ctx context.Context, input *protectedItemProperties) (string, error) {
segments := strings.Split(input.sourceResourceId, "/")
storageAccountName := segments[len(segments)-1]
protectablePager := s.protectableItemsClient.NewListPager(input.recoveryVaultName, input.resourceGroupName, &recovery.BackupProtectableItemsClientListOptions{
Filter: to.Ptr(recoveryServicesAzureStorageFilter),
})
for protectablePager.More() {
page, err := protectablePager.NextPage(ctx)
if err != nil {
return "", fmt.Errorf("failed to get next page of protectable items: %w", err)
}
systemName, err := findSystemName(page.Value, input.itemName, storageAccountName)
if err != nil {
return "", fmt.Errorf("failed to find system name for protectable item: %w", err)
}
if systemName != "" {
return systemName, nil
}
}
return "", nil
}
func (s *systemNameReaderImpl) inquireContainer(ctx context.Context, item *protectedItemProperties) error {
// the first return value is an empty struct, so we can ignore it
_, err := s.protectionContainersClient.Inquire(ctx, item.recoveryVaultName, item.resourceGroupName, item.fabricName, item.containerName,
&recovery.ProtectionContainersClientInquireOptions{
Filter: to.Ptr(recoveryServicesAzureStorageFilter),
})
return err
}
// findSystemName finds the system name of the file share protected item by looking through the given protectable items
// for one that matches the target friendly name and storage account name.
func findSystemName(protectableItems []*recovery.WorkloadProtectableItemResource, targetFriendlyName, storageAccountName string) (string, error) {
for _, item := range protectableItems {
protectableFileShare, ok := item.Properties.(*recovery.AzureFileShareProtectableItem)
if !ok {
itemType := "unknown"
if item.Type != nil {
itemType = *item.Type
}
return "", fmt.Errorf("protectable item of type %s is not a file share", itemType)
}
friendlyName := *protectableFileShare.FriendlyName
containerName := *protectableFileShare.ParentContainerFriendlyName
if friendlyName == targetFriendlyName && containerName == storageAccountName {
return *item.Name, nil
}
}
return "", nil
}
func extractProtectedItemProperties(properties resource.PropertyMap) (*protectedItemProperties, error) {
rg, err := getRequiredStringProperty(properties, resourceGroupName)
if err != nil {
return nil, err
}
// not set for new resources
var name string
if systemName, ok := properties["name"]; ok {
name = systemName.StringValue()
}
recoveryVaultName, err := getRequiredStringProperty(properties, "vaultName")
if err != nil {
return nil, err
}
containerName, err := getRequiredStringProperty(properties, "containerName")
if err != nil {
return nil, err
}
itemName, err := getRequiredStringProperty(properties, "protectedItemName")
if err != nil {
return nil, err
}
fabricName, err := getRequiredStringProperty(properties, "fabricName")
if err != nil {
return nil, err
}
if !properties.HasValue("properties") {
return nil, fmt.Errorf("'properties' not found in input")
}
itemProperties := properties["properties"].ObjectValue()
itemType, err := getRequiredStringProperty(itemProperties, "protectedItemType")
if err != nil {
return nil, err
}
policyID, err := getRequiredStringProperty(itemProperties, "policyId")
if err != nil {
return nil, err
}
sourceResourceId, err := getRequiredStringProperty(itemProperties, "sourceResourceId")
if err != nil {
return nil, err
}
return &protectedItemProperties{
name: name,
protectedItem: protectedItem{
protectedItemType: itemType,
policyID: policyID,
sourceResourceId: sourceResourceId,
},
resourceGroupName: rg,
recoveryVaultName: recoveryVaultName,
containerName: containerName,
itemName: itemName,
fabricName: fabricName,
}, nil
}
func getRequiredStringProperty(properties resource.PropertyMap, key resource.PropertyKey) (string, error) {
prop, ok := properties[key]
if !ok {
return "", fmt.Errorf("%s not found", key)
}
if !prop.IsString() {
return "", fmt.Errorf("%s is not a string", key)
}
return prop.StringValue(), nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_blob_container_legal_hold.go | provider/pkg/resources/customresources/custom_blob_container_legal_hold.go | package customresources
import (
"context"
"strings"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure"
. "github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/util"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/versionLookup"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
const lhPath = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/blobServices/default/containers/{containerName}/legalHold"
const tagsProp = "tags"
const allowProtectedAppendWritesAllProp = "allowProtectedAppendWritesAll"
var legalHoldProperties = map[string]schema.PropertySpec{
resourceGroupName: {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "Name of the resource group that contains the storage account.",
},
accountName: {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "Name of the Storage Account.",
},
containerName: {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "Name of the Blob Container.",
},
tagsProp: {
TypeSpec: schema.TypeSpec{Type: "array", Items: &schema.TypeSpec{Type: "string"}},
Description: "List of legal hold tags. Each tag should be 3 to 23 alphanumeric characters and is normalized to lower case at SRP.",
},
allowProtectedAppendWritesAllProp: {
TypeSpec: schema.TypeSpec{Type: "boolean"},
Description: "When enabled, new blocks can be written to both 'Append and Bock Blobs' while maintaining legal hold protection and compliance. Only new blocks can be added and any existing blocks cannot be modified or deleted.",
},
}
func blobContainerLegalHold(azureClient azure.AzureClient) *CustomResource {
apiVersion, ok := versionLookup.GetDefaultApiVersionForResource("Storage", "BlobContainer")
if !ok {
// default as of 2024-02-16
apiVersion = "2022-09-01"
logging.V(3).Infof("Warning: could not find default API version for storage:blobContainer. Using %s", apiVersion)
}
return &CustomResource{
tok: "azure-native:storage:BlobContainerLegalHold",
path: lhPath,
LegacySchema: &schema.ResourceSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: ".",
Type: "object",
Properties: legalHoldProperties,
},
InputProperties: legalHoldProperties,
RequiredInputs: []string{resourceGroupName, accountName, containerName, tagsProp},
},
Meta: &AzureAPIResource{
Path: lhPath,
PutParameters: []AzureAPIParameter{
{Name: subscriptionId, Location: "path", IsRequired: true, Value: &AzureAPIProperty{Type: "string"}},
{Name: resourceGroupName, Location: "path", IsRequired: true, Value: &AzureAPIProperty{Type: "string"}},
{Name: accountName, Location: "path", IsRequired: true, Value: &AzureAPIProperty{Type: "string"}},
{Name: containerName, Location: "path", IsRequired: true, Value: &AzureAPIProperty{Type: "string"}},
{
Name: "properties",
Location: "body",
Body: &AzureAPIType{
Properties: map[string]AzureAPIProperty{
tagsProp: {
Type: "array",
Items: &AzureAPIProperty{
Type: "string",
},
},
allowProtectedAppendWritesAllProp: {
Type: "boolean",
},
},
RequiredProperties: []string{resourceGroupName, accountName, containerName, tagsProp},
},
},
},
},
Create: func(ctx context.Context, id string, properties resource.PropertyMap) (map[string]any, error) {
createPath := strings.TrimSuffix(id, "/legalHold") + "/setLegalHold"
p := properties.Mappable()
tagsVal, ok := p[tagsProp]
if !ok {
return nil, errors.New("missing required property 'tags'")
}
tags, ok := tagsVal.([]any)
if !ok {
return nil, errors.New("property 'tags' must be an array")
}
if len(tags) == 0 {
return nil, errors.New("property 'tags' must not be empty")
}
body := map[string]any{
tagsProp: tags,
}
if allowProtectedAppendWritesAllVal, ok := p[allowProtectedAppendWritesAllProp]; ok {
if allowProtectedAppendWritesAll, ok := allowProtectedAppendWritesAllVal.(bool); ok {
body[allowProtectedAppendWritesAllProp] = allowProtectedAppendWritesAll
}
}
return post(ctx, createPath, body, apiVersion, azureClient)
},
Read: func(ctx context.Context, id string, properties resource.PropertyMap) (map[string]any, bool, error) {
containerId := strings.TrimSuffix(id, "/legalHold")
container, err := azureClient.Get(ctx, containerId, "2022-09-01", nil)
if err != nil {
if azure.IsNotFound(err) {
return nil, false, nil
}
return nil, false, err
}
legalHoldProp, ok := util.GetInnerMap(container, "properties", "legalHold")
if !ok {
return nil, false, nil
}
if hasLegalHold, ok := legalHoldProp["hasLegalHold"]; ok && hasLegalHold.(bool) {
// Annoyingly, when reading the blob container, the legal hold data is returned in
// a different format than what 'set' and 'clear' accept and return, so we convert.
// From: { "hasLegalHold": true,
// "tags": [ { "tag": "tag1" }, { "tag": "tag2" } ],
// "protectedAppendWritesHistory": { "allowProtectedAppendWritesAll": true } }
// To: { "tags": [ "tag1", "tag2" ],
// "allowProtectedAppendWritesAll": true }
result := map[string]any{}
if tags, ok := legalHoldProp[tagsProp]; ok {
tagsResult := []string{}
if tagsArr, ok := tags.([]any); ok {
for _, tagObj := range tagsArr {
if tagObjMap, ok := tagObj.(map[string]any); ok {
if tag, ok := tagObjMap["tag"]; ok {
tagsResult = append(tagsResult, tag.(string))
}
}
}
}
result[tagsProp] = tagsResult
}
if hist, ok := util.GetInnerMap(legalHoldProp, "protectedAppendWritesHistory"); ok {
if allow, ok := hist["allowProtectedAppendWritesAll"]; ok {
result[allowProtectedAppendWritesAllProp] = allow.(bool)
}
}
return result, true, nil
}
return nil, false, nil
},
Update: func(ctx context.Context, id string, properties, oldState resource.PropertyMap) (map[string]any, error) {
basePath := strings.TrimSuffix(id, "/legalHold")
setPath := basePath + "/setLegalHold"
clearPath := basePath + "/clearLegalHold"
input := properties.Mappable()
olds := oldState.Mappable()
// We need to handle added and removed tags separately.
tags, err := readTags(input)
if err != nil {
return nil, err
}
oldTags, err := readTags(olds)
if err != nil {
return nil, err
}
addedTags := tags.Subtract(oldTags)
removedTags := oldTags.Subtract(tags)
// not set -> set => true
// set -> not set => false
// set -> set => true or no-op
// not set -> not set => false or no-op
allowProtected := false
if allowProtectedAppendWritesAllVal, ok := input[allowProtectedAppendWritesAllProp]; ok {
if allowProtectedAppendWritesAll, ok := allowProtectedAppendWritesAllVal.(bool); ok {
allowProtected = allowProtectedAppendWritesAll
}
}
allowProtectedPrev := false
if allowProtectedAppendWritesAllValPrev, ok := olds[allowProtectedAppendWritesAllProp]; ok {
if allowProtectedAppendWritesAllPrev, ok := allowProtectedAppendWritesAllValPrev.(bool); ok {
allowProtectedPrev = allowProtectedAppendWritesAllPrev
}
}
allowProtectedChanged := allowProtected != allowProtectedPrev
if addedTags.Any() || allowProtectedChanged {
body := map[string]any{
tagsProp: addedTags.SortedValues(),
allowProtectedAppendWritesAllProp: allowProtected,
}
_, err = post(ctx, setPath, body, apiVersion, azureClient)
if err != nil {
return nil, err
}
}
if removedTags.Any() {
body := map[string]any{
tagsProp: removedTags.SortedValues(),
}
_, err = post(ctx, clearPath, body, apiVersion, azureClient)
if err != nil {
return nil, err
}
}
return input, nil
},
Delete: func(ctx context.Context, id string, inputs, state resource.PropertyMap) error {
path := strings.TrimSuffix(id, "/legalHold") + "/clearLegalHold"
tags, err := readTags(inputs.Mappable())
if err != nil {
return err
}
body := map[string]any{
tagsProp: tags.SortedValues(),
}
_, err = post(ctx, path, body, apiVersion, azureClient)
return err
},
}
}
func post(ctx context.Context, path string, body map[string]any, apiVersion string, azureClient azure.AzureClient) (map[string]any, error) {
queryParams := map[string]any{
"api-version": apiVersion,
}
resp, err := azureClient.Post(ctx, path, body, queryParams)
if err != nil {
return nil, err
}
return resp.(map[string]any), nil
}
func readTags(p map[string]any) (codegen.StringSet, error) {
tagsVal, ok := p[tagsProp]
if !ok {
return nil, errors.New("missing required property 'tags'")
}
tags, ok := tagsVal.([]any)
if !ok {
return nil, errors.New("property 'tags' must be an array")
}
strTags := codegen.NewStringSet()
for _, tag := range tags {
strTags.Add(tag.(string))
}
return strTags, nil
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_pim_eligibility_test.go | provider/pkg/resources/customresources/custom_pim_eligibility_test.go | // Copyright 2025, Pulumi Corporation. All rights reserved.
package customresources
import (
"context"
"slices"
"testing"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/authorization/armauthorization/v3"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPendingStatus(t *testing.T) {
t.Parallel()
pending := []armauthorization.Status{
armauthorization.StatusGranted,
armauthorization.StatusPendingAdminDecision,
armauthorization.StatusPendingApproval,
armauthorization.StatusPendingApprovalProvisioning,
armauthorization.StatusPendingEvaluation,
armauthorization.StatusPendingExternalProvisioning,
armauthorization.StatusPendingProvisioning,
armauthorization.StatusPendingRevocation,
armauthorization.StatusPendingScheduleCreation,
}
t.Run("pending status", func(t *testing.T) {
t.Parallel()
for _, status := range pending {
assert.True(t, statusIsPending(&status), status)
}
})
t.Run("terminal status", func(t *testing.T) {
t.Parallel()
for _, status := range armauthorization.PossibleStatusValues() {
if slices.Contains(pending, status) {
continue
}
assert.False(t, statusIsPending(&status), status)
}
})
}
type fakePimEligibilityScheduleClient struct {
scheduleToFind *armauthorization.RoleEligibilitySchedule
scheduleFindError error
curScheduleIndex int
schedule func(numCall int) (*armauthorization.RoleEligibilitySchedule, error)
cancelCalls int
cancelError error
createError error
capturedCreate *struct {
scope string
name string
parameters armauthorization.RoleEligibilityScheduleRequest
}
mapScheduleToOutputsCalls int
}
func (c *fakePimEligibilityScheduleClient) findSchedule(ctx context.Context, scope, principalID, roleDefinitionID string) (*armauthorization.RoleEligibilitySchedule, error) {
if c.scheduleFindError != nil {
return nil, c.scheduleFindError
}
return c.scheduleToFind, nil
}
func (c *fakePimEligibilityScheduleClient) getSchedule(ctx context.Context, scope, scheduleName string) (*armauthorization.RoleEligibilitySchedule, error) {
s, err := c.schedule(c.curScheduleIndex)
c.curScheduleIndex++
return s, err
}
func (c *fakePimEligibilityScheduleClient) createSchedule(ctx context.Context, scope string, roleEligibilityScheduleRequestName string,
parameters armauthorization.RoleEligibilityScheduleRequest,
) (armauthorization.RoleEligibilityScheduleRequestsClientCreateResponse, error) {
c.capturedCreate = &struct {
scope string
name string
parameters armauthorization.RoleEligibilityScheduleRequest
}{
scope: scope,
name: roleEligibilityScheduleRequestName,
parameters: parameters,
}
return armauthorization.RoleEligibilityScheduleRequestsClientCreateResponse{}, c.createError
}
func (c *fakePimEligibilityScheduleClient) cancelSchedule(ctx context.Context, scope, scheduleName string) (armauthorization.RoleEligibilityScheduleRequestsClientCancelResponse, error) {
c.cancelCalls++
if c.cancelError != nil {
return armauthorization.RoleEligibilityScheduleRequestsClientCancelResponse{}, c.cancelError
}
return armauthorization.RoleEligibilityScheduleRequestsClientCancelResponse{}, nil
}
func (c *fakePimEligibilityScheduleClient) mapScheduleToOutputs(schedule *armauthorization.RoleEligibilitySchedule) (map[string]any, error) {
c.mapScheduleToOutputsCalls++
return map[string]any{}, nil
}
func TestCreatePimEligibilitySchedule(t *testing.T) {
t.Parallel()
pimRoleEligibilityScheduleTickerInterval = 1 * time.Second
validInputs := resource.PropertyMap{
"scope": resource.NewStringProperty("scope"),
"principalId": resource.NewStringProperty("principalID"),
"roleDefinitionId": resource.NewStringProperty("roleDefinitionID"),
}
t.Run("happy path", func(t *testing.T) {
client := &fakePimEligibilityScheduleClient{
scheduleToFind: &armauthorization.RoleEligibilitySchedule{
Properties: &armauthorization.RoleEligibilityScheduleProperties{
PrincipalID: pulumi.StringRef("principalID"),
RoleDefinitionID: pulumi.StringRef("roleDefinitionID"),
},
},
}
_, err := createPimEligibilitySchedule(context.Background(), "/id/is/not/used", validInputs, client, 5*time.Second)
require.NoError(t, err)
require.NotNil(t, client.capturedCreate)
assert.True(t, isValidGUID(client.capturedCreate.name), client.capturedCreate.name)
assert.Equal(t, "scope", client.capturedCreate.scope)
require.NotNil(t, client.capturedCreate.parameters.Properties.PrincipalID)
assert.Equal(t, "principalID", *client.capturedCreate.parameters.Properties.PrincipalID)
require.NotNil(t, client.capturedCreate.parameters.Properties.RoleDefinitionID)
assert.Equal(t, "roleDefinitionID", *client.capturedCreate.parameters.Properties.RoleDefinitionID)
})
t.Run("invalid input", func(t *testing.T) {
client := &fakePimEligibilityScheduleClient{}
_, err := createPimEligibilitySchedule(context.Background(), "/id/is/not/used", resource.PropertyMap{}, client, 4*time.Second)
require.Error(t, err)
assert.Contains(t, err.Error(), "is required")
})
t.Run("error creating schedule", func(t *testing.T) {
client := &fakePimEligibilityScheduleClient{
createError: errors.New("error creating schedule"),
}
_, err := createPimEligibilitySchedule(context.Background(), "/id/is/not/used", validInputs, client, 4*time.Second)
require.Error(t, err)
assert.Contains(t, err.Error(), "error creating schedule")
})
t.Run("error polling for schedule", func(t *testing.T) {
client := &fakePimEligibilityScheduleClient{
scheduleFindError: errors.New("error finding schedule"),
}
_, err := createPimEligibilitySchedule(context.Background(), "/id/is/not/used", validInputs, client, 4*time.Second)
require.Error(t, err)
assert.Contains(t, err.Error(), "error finding schedule")
})
t.Run("timeout polling for schedule", func(t *testing.T) {
client := &fakePimEligibilityScheduleClient{}
_, err := createPimEligibilitySchedule(context.Background(), "/id/is/not/used", validInputs, client, 1*time.Second)
require.Error(t, err)
assert.Contains(t, err.Error(), "timed out")
})
}
func TestDeletePimEligibilitySchedule(t *testing.T) {
t.Parallel()
pimRoleEligibilityScheduleTickerInterval = 1 * time.Second
guid := uuid.New().String()
createScheduleData := func(status armauthorization.Status) (resource.PropertyMap, *armauthorization.RoleEligibilitySchedule) {
validInputs := resource.PropertyMap{
"name": resource.NewStringProperty(guid),
"scope": resource.NewStringProperty("scope"),
"principalId": resource.NewStringProperty("principalID"),
"roleDefinitionId": resource.NewStringProperty("roleDefinitionID"),
"status": resource.NewStringProperty(string(status)),
}
schedule := &armauthorization.RoleEligibilitySchedule{
Name: pulumi.StringRef(guid),
Properties: &armauthorization.RoleEligibilityScheduleProperties{
PrincipalID: pulumi.StringRef("principalID"),
RoleDefinitionID: pulumi.StringRef("roleDefinitionID"),
Scope: pulumi.StringRef("scope"),
Status: &status,
},
}
return validInputs, schedule
}
t.Run("happy path, pending schedule", func(t *testing.T) {
t.Parallel()
validInputs, schedule := createScheduleData(armauthorization.StatusPendingApproval)
client := &fakePimEligibilityScheduleClient{
schedule: func(_ int) (*armauthorization.RoleEligibilitySchedule, error) { return schedule, nil },
}
err := deletePimEligibilitySchedule(context.Background(), "/id/is/not/used", validInputs, client, 5*time.Second)
require.NoError(t, err)
assert.Equal(t, 1, client.cancelCalls)
assert.Nil(t, client.capturedCreate)
})
t.Run("happy path, active schedule", func(t *testing.T) {
t.Parallel()
validInputs, schedule := createScheduleData(armauthorization.StatusScheduleCreated)
client := &fakePimEligibilityScheduleClient{
// On the third polling request, the schedule is gone.
schedule: func(numCall int) (*armauthorization.RoleEligibilitySchedule, error) {
if numCall < 3 {
return schedule, nil
}
return nil, &azcore.ResponseError{StatusCode: 404}
},
}
err := deletePimEligibilitySchedule(context.Background(), "/id/is/not/used", validInputs, client, 5*time.Second)
require.NoError(t, err)
assert.Equal(t, 0, client.cancelCalls)
require.NotNil(t, client.capturedCreate) // deletion is a new request with type=remove
assert.Equal(t, armauthorization.RequestTypeAdminRemove, *client.capturedCreate.parameters.Properties.RequestType)
assert.Equal(t, "scope", client.capturedCreate.scope)
assert.True(t, isValidGUID(client.capturedCreate.name), client.capturedCreate.name)
})
t.Run("active schedule, deletion times out", func(t *testing.T) {
t.Parallel()
validInputs, schedule := createScheduleData(armauthorization.StatusScheduleCreated)
client := &fakePimEligibilityScheduleClient{
schedule: func(_ int) (*armauthorization.RoleEligibilitySchedule, error) { return schedule, nil },
}
err := deletePimEligibilitySchedule(context.Background(), "/id/is/not/used", validInputs, client, 3*time.Second)
require.Error(t, err)
assert.Contains(t, err.Error(), "timed out")
assert.Equal(t, 0, client.cancelCalls)
require.NotNil(t, client.capturedCreate)
assert.Equal(t, "scope", client.capturedCreate.scope)
assert.True(t, isValidGUID(client.capturedCreate.name), client.capturedCreate.name)
assert.Equal(t, armauthorization.RequestTypeAdminRemove, *client.capturedCreate.parameters.Properties.RequestType)
})
}
// isValidGUID checks if the provided string is a valid GUID/UUID.
func isValidGUID(guid string) bool {
_, err := uuid.Parse(guid)
return err == nil
}
func TestUpdateResourceDescription(t *testing.T) {
t.Parallel()
t.Run("no existing description", func(t *testing.T) {
t.Parallel()
resource := &ResourceDefinition{
Resource: schema.ResourceSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "",
},
},
}
updateResourceDescription(resource, "foo bar")
assert.Equal(t, "foo bar", resource.Resource.Description)
})
t.Run("existing description without API version", func(t *testing.T) {
t.Parallel()
resource := &ResourceDefinition{
Resource: schema.ResourceSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "existing description",
},
},
}
updateResourceDescription(resource, "foo bar")
assert.Equal(t, "foo bar", resource.Resource.Description)
})
t.Run("existing description with API versions", func(t *testing.T) {
t.Parallel()
resource := &ResourceDefinition{
Resource: schema.ResourceSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: `Role Eligibility schedule request
Azure REST API version: 2020-10-01.
Other available API versions: 2020-10-01-preview, 2022-04-01-preview, 2024-02-01-preview, 2024-09-01-preview.
## Import
...`,
},
},
}
updateResourceDescription(resource, "foo bar.\n\nmore info.")
assert.Equal(t, `foo bar.
more info.
Azure REST API version: 2020-10-01.
Other available API versions: 2020-10-01-preview, 2022-04-01-preview, 2024-02-01-preview, 2024-09-01-preview.
## Import
...`, resource.Resource.Description)
})
}
func TestInputsToSdk(t *testing.T) {
t.Parallel()
validRequiredInputs := resource.PropertyMap{
"name": resource.NewStringProperty(uuid.New().String()),
"scope": resource.NewStringProperty("scope"),
"principalId": resource.NewStringProperty("principalID"),
"roleDefinitionId": resource.NewStringProperty("roleDefinitionID"),
}
t.Run("happy path", func(t *testing.T) {
t.Parallel()
sdk, err := inputsToSdk(validRequiredInputs)
require.NoError(t, err)
assert.Equal(t, "scope", *sdk.Properties.Scope)
assert.Equal(t, "principalID", *sdk.Properties.PrincipalID)
assert.Equal(t, "roleDefinitionID", *sdk.Properties.RoleDefinitionID)
})
t.Run("required fields missing", func(t *testing.T) {
t.Parallel()
for _, prop := range []string{"scope", "principalId", "roleDefinitionId"} {
inputs := validRequiredInputs.Copy()
delete(inputs, resource.PropertyKey(prop))
_, err := inputsToSdk(inputs)
require.Error(t, err)
assert.Contains(t, err.Error(), prop+" is required")
}
})
t.Run("scheduleInfo", func(t *testing.T) {
t.Parallel()
inputs := validRequiredInputs.Copy()
now := time.Now()
inputs["scheduleInfo"] = resource.NewObjectProperty(resource.PropertyMap{
"startDateTime": resource.NewStringProperty(now.Format(time.RFC3339)),
"expiration": resource.NewObjectProperty(resource.PropertyMap{
"duration": resource.NewStringProperty("P1D"),
"type": resource.NewStringProperty("AfterDuration"),
}),
})
sdk, err := inputsToSdk(inputs)
require.NoError(t, err)
require.NotNil(t, sdk.Properties.ScheduleInfo)
assert.WithinDuration(t, now, *sdk.Properties.ScheduleInfo.StartDateTime, 1*time.Second)
assert.Equal(t, "P1D", *sdk.Properties.ScheduleInfo.Expiration.Duration)
assert.Equal(t, armauthorization.TypeAfterDuration, *sdk.Properties.ScheduleInfo.Expiration.Type)
})
t.Run("scheduleInfo with NoExpiration", func(t *testing.T) {
t.Parallel()
inputs := validRequiredInputs.Copy()
now := time.Now()
inputs["scheduleInfo"] = resource.NewObjectProperty(resource.PropertyMap{
"startDateTime": resource.NewStringProperty(now.Format(time.RFC3339)),
"expiration": resource.NewObjectProperty(resource.PropertyMap{
"type": resource.NewStringProperty("NoExpiration"),
}),
})
sdk, err := inputsToSdk(inputs)
require.NoError(t, err)
require.NotNil(t, sdk.Properties.ScheduleInfo)
assert.WithinDuration(t, now, *sdk.Properties.ScheduleInfo.StartDateTime, 1*time.Second)
assert.Nil(t, sdk.Properties.ScheduleInfo.Expiration.Duration)
assert.Nil(t, sdk.Properties.ScheduleInfo.Expiration.EndDateTime)
assert.Equal(t, armauthorization.TypeNoExpiration, *sdk.Properties.ScheduleInfo.Expiration.Type)
})
t.Run("scheduleInfo with AfterDateTime", func(t *testing.T) {
t.Parallel()
inputs := validRequiredInputs.Copy()
now := time.Now()
endTime := now.Add(24 * time.Hour)
inputs["scheduleInfo"] = resource.NewObjectProperty(resource.PropertyMap{
"startDateTime": resource.NewStringProperty(now.Format(time.RFC3339)),
"expiration": resource.NewObjectProperty(resource.PropertyMap{
"endDateTime": resource.NewStringProperty(endTime.Format(time.RFC3339)),
"type": resource.NewStringProperty("AfterDateTime"),
}),
})
sdk, err := inputsToSdk(inputs)
require.NoError(t, err)
require.NotNil(t, sdk.Properties.ScheduleInfo)
assert.WithinDuration(t, now, *sdk.Properties.ScheduleInfo.StartDateTime, 1*time.Second)
assert.Nil(t, sdk.Properties.ScheduleInfo.Expiration.Duration)
require.NotNil(t, sdk.Properties.ScheduleInfo.Expiration.EndDateTime)
assert.WithinDuration(t, endTime, *sdk.Properties.ScheduleInfo.Expiration.EndDateTime, 1*time.Second)
assert.Equal(t, armauthorization.TypeAfterDateTime, *sdk.Properties.ScheduleInfo.Expiration.Type)
})
t.Run("misc optional properties", func(t *testing.T) {
t.Parallel()
inputs := validRequiredInputs.Copy()
inputs["justification"] = resource.NewStringProperty("foo bar")
inputs["status"] = resource.NewStringProperty(string(armauthorization.StatusPendingApproval))
inputs["ticketInfo"] = resource.NewObjectProperty(resource.PropertyMap{
"ticketNumber": resource.NewStringProperty("123456"),
"ticketSystem": resource.NewStringProperty("pulumi"),
})
sdk, err := inputsToSdk(inputs)
require.NoError(t, err)
assert.Equal(t, "foo bar", *sdk.Properties.Justification)
assert.Equal(t, armauthorization.StatusPendingApproval, *sdk.Properties.Status)
require.NotNil(t, sdk.Properties.TicketInfo)
assert.Equal(t, "123456", *sdk.Properties.TicketInfo.TicketNumber)
assert.Equal(t, "pulumi", *sdk.Properties.TicketInfo.TicketSystem)
})
}
func TestReadPimEligibilitySchedule(t *testing.T) {
t.Parallel()
guid := uuid.New().String()
validRequiredInputs := resource.PropertyMap{
"name": resource.NewStringProperty(guid),
"scope": resource.NewStringProperty("scope"),
"principalId": resource.NewStringProperty("principalID"),
"roleDefinitionId": resource.NewStringProperty("roleDefinitionID"),
}
existingSchedule := &armauthorization.RoleEligibilitySchedule{
Name: pulumi.StringRef(guid),
Properties: &armauthorization.RoleEligibilityScheduleProperties{
PrincipalID: pulumi.StringRef("principalID"),
RoleDefinitionID: pulumi.StringRef("roleDefinitionID"),
Scope: pulumi.StringRef("scope"),
},
}
t.Run("found", func(t *testing.T) {
t.Parallel()
client := &fakePimEligibilityScheduleClient{
scheduleToFind: existingSchedule,
}
result, found, err := read(context.Background(), "/id/is/not/used", validRequiredInputs, client)
require.NoError(t, err)
assert.True(t, found)
assert.NotNil(t, result)
})
t.Run("not found", func(t *testing.T) {
t.Parallel()
client := &fakePimEligibilityScheduleClient{}
inputs := validRequiredInputs.Copy()
result, found, err := read(context.Background(), "/id/is/not/used", inputs, client)
require.NoError(t, err)
assert.False(t, found)
assert.Nil(t, result)
})
t.Run("error converting inputs", func(t *testing.T) {
t.Parallel()
client := &fakePimEligibilityScheduleClient{}
inputs := validRequiredInputs.Copy()
delete(inputs, "scope")
result, found, err := read(context.Background(), "/id/is/not/used", inputs, client)
require.Error(t, err)
assert.Contains(t, err.Error(), "scope is required")
assert.False(t, found)
assert.Nil(t, result)
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_storage_azidentity_test.go | provider/pkg/resources/customresources/custom_storage_azidentity_test.go | package customresources
import (
"context"
"crypto/md5"
"encoding/base64"
"net/http"
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake"
azpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage/fake"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
azureblob "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestReadWithClient(t *testing.T) {
blob := blob_azidentity{
creds: &azfake.TokenCredential{},
env: cloud.AzurePublic,
}
properties := resource.NewPropertyMapFromMap(map[string]any{
accountName: "myaccount",
blobName: "myblob",
containerName: "mycontainer",
resourceGroupName: "myrg",
})
azureProperties := azureblob.GetPropertiesResponse{
BlobType: ref(azureblob.BlobTypeBlockBlob),
ContentMD5: []byte("contentMD5"),
ContentType: ref("text/plain"),
Metadata: map[string]*string{
"meta1": ref("value1"),
},
}
var reader blobPropertiesReader = func(ctx context.Context) (azureblob.GetPropertiesResponse, error) {
return azureProperties, nil
}
blobProperties, found, err := blob.readBlob(context.Background(), properties, reader)
require.NoError(t, err)
assert.True(t, found)
assert.NotNil(t, blobProperties)
assert.Equal(t, "myrg", blobProperties[resourceGroupName])
assert.Equal(t, "myaccount", blobProperties[accountName])
assert.Equal(t, "mycontainer", blobProperties[containerName])
assert.Equal(t, "myblob", blobProperties[blobName])
assert.Equal(t, "myblob", blobProperties[nameProp])
assert.Equal(t, "Block", blobProperties[typeProp])
assert.Equal(t, "Y29udGVudE1ENQ==", blobProperties[contentMd5])
assert.Equal(t, "text/plain", blobProperties[contentType])
assert.Equal(t, azureProperties.Metadata, blobProperties[metadata])
assert.Equal(t, "https://myaccount.blob.core.windows.net/mycontainer/myblob", blobProperties[url])
}
func TestReadFromUSGovWithClient(t *testing.T) {
blob := blob_azidentity{
creds: &azfake.TokenCredential{},
env: cloud.AzureGovernment,
}
properties := resource.NewPropertyMapFromMap(map[string]any{
accountName: "myaccount",
blobName: "myblob",
containerName: "mycontainer",
resourceGroupName: "myrg",
})
azureProperties := azureblob.GetPropertiesResponse{
BlobType: ref(azureblob.BlobTypeBlockBlob),
ContentType: ref("text/plain"),
}
var reader blobPropertiesReader = func(ctx context.Context) (azureblob.GetPropertiesResponse, error) {
return azureProperties, nil
}
blobProperties, found, err := blob.readBlob(context.Background(), properties, reader)
require.NoError(t, err)
assert.True(t, found)
assert.Equal(t, "https://myaccount.blob.core.usgovcloudapi.net/mycontainer/myblob", blobProperties[url])
}
func fakeListKeysStorageAccountServer(keys []*armstorage.AccountKey) fake.AccountsServer {
return fake.AccountsServer{
ListKeys: func(ctx context.Context, resourceGroupName string, accountName string, options *armstorage.AccountsClientListKeysOptions) (resp azfake.Responder[armstorage.AccountsClientListKeysResponse], errResp azfake.ErrorResponder) {
keysResp := armstorage.AccountsClientListKeysResponse{
AccountListKeysResult: armstorage.AccountListKeysResult{
Keys: keys,
},
}
resp.SetResponse(http.StatusOK, keysResp, nil)
return
},
}
}
func TestNewSharedKeyCredentialWithClient(t *testing.T) {
t.Run("happy path", func(t *testing.T) {
base64Key := base64.StdEncoding.EncodeToString([]byte("key1valueasfgasgfdsfgdafgfadlgjas"))
accountsServer := fakeListKeysStorageAccountServer([]*armstorage.AccountKey{
{
KeyName: ref("key1"),
Value: ref(base64Key),
},
})
client, err := armstorage.NewAccountsClient("subscriptionID", &azfake.TokenCredential{}, &arm.ClientOptions{
ClientOptions: azcore.ClientOptions{
Transport: fake.NewAccountsServerTransport(&accountsServer),
},
})
require.NoError(t, err)
c, err := newSharedKeyCredentialWithClient(context.Background(), "myaccount", "myrg", client)
require.NoError(t, err)
require.NotNil(t, c)
})
t.Run("no keys", func(t *testing.T) {
accountsServer := fakeListKeysStorageAccountServer([]*armstorage.AccountKey{})
client, err := armstorage.NewAccountsClient("subscriptionID", &azfake.TokenCredential{}, &arm.ClientOptions{
ClientOptions: azcore.ClientOptions{
Transport: fake.NewAccountsServerTransport(&accountsServer),
},
})
require.NoError(t, err)
_, err = newSharedKeyCredentialWithClient(context.Background(), "myaccount", "myrg", client)
require.Error(t, err)
require.Contains(t, err.Error(), "no keys")
})
}
func TestNewSharedKeyCredentialWithCloudConfig(t *testing.T) {
t.Run("Azure Government Cloud", func(t *testing.T) {
base64Key := base64.StdEncoding.EncodeToString([]byte("key1valueasfgasgfdsfgdafgfadlgjas"))
accountsServer := fakeListKeysStorageAccountServer([]*armstorage.AccountKey{
{
KeyName: ref("key1"),
Value: ref(base64Key),
},
})
// Mock transport to capture and validate the request
var capturedRequest *http.Request
mockTransport := &requestCapturingTransporter{
fakeTransport: fake.NewAccountsServerTransport(&accountsServer),
onRequest: func(req *http.Request) {
capturedRequest = req
},
}
// Test that the function accepts Azure Government cloud config and passes it correctly
creds := &azfake.TokenCredential{}
// This tests our modified newSharedKeyCredential function with Government cloud
c, err := func() (*azblob.SharedKeyCredential, error) {
clientOptions := &arm.ClientOptions{
ClientOptions: azcore.ClientOptions{
Cloud: cloud.AzureGovernment.Configuration,
Transport: mockTransport,
},
}
accClient, err := armstorage.NewAccountsClient("subscriptionID", creds, clientOptions)
if err != nil {
return nil, err
}
return newSharedKeyCredentialWithClient(context.Background(), "myaccount", "myrg", accClient)
}()
require.NoError(t, err)
require.NotNil(t, c)
require.NotNil(t, capturedRequest)
// Verify that the request was made to the government cloud endpoint
expectedHost := "management.usgovcloudapi.net"
require.Equal(t, expectedHost, capturedRequest.URL.Host,
"Expected request to be made to Azure Government cloud endpoint")
})
t.Run("Azure Public Cloud", func(t *testing.T) {
base64Key := base64.StdEncoding.EncodeToString([]byte("key1valueasfgasgfdsfgdafgfadlgjas"))
accountsServer := fakeListKeysStorageAccountServer([]*armstorage.AccountKey{
{
KeyName: ref("key1"),
Value: ref(base64Key),
},
})
// Mock transport to capture and validate the request
var capturedRequest *http.Request
mockTransport := &requestCapturingTransporter{
fakeTransport: fake.NewAccountsServerTransport(&accountsServer),
onRequest: func(req *http.Request) {
capturedRequest = req
},
}
// Test that the function works with public cloud config
creds := &azfake.TokenCredential{}
c, err := func() (*azblob.SharedKeyCredential, error) {
clientOptions := &arm.ClientOptions{
ClientOptions: azcore.ClientOptions{
Cloud: cloud.AzurePublic.Configuration,
Transport: mockTransport,
},
}
accClient, err := armstorage.NewAccountsClient("subscriptionID", creds, clientOptions)
if err != nil {
return nil, err
}
return newSharedKeyCredentialWithClient(context.Background(), "myaccount", "myrg", accClient)
}()
require.NoError(t, err)
require.NotNil(t, c)
require.NotNil(t, capturedRequest)
// Verify that the request was made to the public cloud endpoint
expectedHost := "management.azure.com"
require.Equal(t, expectedHost, capturedRequest.URL.Host,
"Expected request to be made to Azure Public cloud endpoint")
})
}
func TestParseStorageAccountInput(t *testing.T) {
t.Run("happy path", func(t *testing.T) {
props := resource.NewPropertyMapFromMap(map[string]any{
accountName: "myaccount",
resourceGroupName: "myrg",
})
account, rg, err := parseStorageAccountInput(props)
require.NoError(t, err)
assert.Equal(t, "myaccount", account)
assert.Equal(t, "myrg", rg)
})
t.Run("no account", func(t *testing.T) {
props := resource.NewPropertyMapFromMap(map[string]any{
resourceGroupName: "myrg",
})
_, _, err := parseStorageAccountInput(props)
require.Error(t, err)
})
t.Run("no RG", func(t *testing.T) {
props := resource.NewPropertyMapFromMap(map[string]any{
accountName: "myaccount",
})
_, _, err := parseStorageAccountInput(props)
require.Error(t, err)
})
}
func TestStorageAccountUrls(t *testing.T) {
t.Run("empty account", func(t *testing.T) {
_, err := getStorageAccountURL("", cloud.AzurePublic)
assert.Error(t, err)
})
t.Run("invalid chars", func(t *testing.T) {
_, err := getStorageAccountURL("not^^valid", cloud.AzurePublic)
assert.Error(t, err)
})
t.Run("ok public", func(t *testing.T) {
url, err := getStorageAccountURL("myaccount", cloud.AzurePublic)
assert.NoError(t, err)
assert.Equal(t, "https://myaccount.blob.core.windows.net", url)
})
t.Run("ok china", func(t *testing.T) {
url, err := getStorageAccountURL("myaccount", cloud.AzureChina)
assert.NoError(t, err)
assert.Equal(t, "https://myaccount.blob.core.chinacloudapi.cn", url)
})
t.Run("ok usgov", func(t *testing.T) {
url, err := getStorageAccountURL("myaccount", cloud.AzureGovernment)
assert.NoError(t, err)
assert.Equal(t, "https://myaccount.blob.core.usgovcloudapi.net", url)
})
}
func TestBlobUrls(t *testing.T) {
t.Run("ok public", func(t *testing.T) {
properties := map[string]any{
accountName: "myaccount",
containerName: "mycontainer",
blobName: "myblob",
}
url, err := getBlobURL(resource.NewPropertyMapFromMap(properties), cloud.AzurePublic)
assert.NoError(t, err)
assert.Equal(t, "https://myaccount.blob.core.windows.net/mycontainer/myblob", url)
})
t.Run("must have account", func(t *testing.T) {
properties := map[string]any{
containerName: "mycontainer",
blobName: "myblob",
}
_, err := getBlobURL(resource.NewPropertyMapFromMap(properties), cloud.AzurePublic)
assert.Error(t, err)
})
t.Run("must have container", func(t *testing.T) {
properties := map[string]any{
accountName: "myaccount",
blobName: "myblob",
}
_, err := getBlobURL(resource.NewPropertyMapFromMap(properties), cloud.AzurePublic)
assert.Error(t, err)
})
t.Run("must have blob", func(t *testing.T) {
properties := map[string]any{
accountName: "myaccount",
containerName: "mycontainer",
}
_, err := getBlobURL(resource.NewPropertyMapFromMap(properties), cloud.AzurePublic)
assert.Error(t, err)
})
}
func TestPopulateAzureBlobMetadata(t *testing.T) {
t.Run("no metadata", func(t *testing.T) {
properties := resource.PropertyMap{}
m := populateAzureBlobMetadata(properties)
assert.Empty(t, m)
})
t.Run("metadata is not an object", func(t *testing.T) {
properties := resource.PropertyMap{
metadata: resource.NewStringProperty("not an object"),
}
m := populateAzureBlobMetadata(properties)
assert.Empty(t, m)
})
t.Run("metadata with mixed properties", func(t *testing.T) {
properties := resource.PropertyMap{
metadata: resource.NewObjectProperty(resource.PropertyMap{
"k1": resource.NewStringProperty("v1"),
"k2": resource.NewNumberProperty(42),
"k3": resource.NewObjectProperty(resource.PropertyMap{}),
}),
}
m := populateAzureBlobMetadata(properties)
assert.Len(t, m, 1)
assert.Equal(t, "v1", *m["k1"])
})
}
func TestAzblobToPulumiProperties(t *testing.T) {
rg := "myrg"
storageAccount := "mystorageaccount"
container := "mycontainer"
name := "myblob"
blobUrl := "https://mystorageaccount.blob.core.windows.net/mycontainer/myblob"
setup := func() azureblob.GetPropertiesResponse {
md5Sum := md5.Sum([]byte("content"))
return azureblob.GetPropertiesResponse{
AccessTier: ref(string(azureblob.AccessTierHot)),
BlobType: ref(azureblob.BlobTypeBlockBlob),
ContentMD5: md5Sum[:],
ContentType: ref("text/plain"),
Metadata: map[string]*string{
"k1": ref("v1"),
},
}
}
t.Run("all properties", func(t *testing.T) {
azblob := setup()
pulumiBlob := azblobToPulumiProperties(name, rg, storageAccount, container, blobUrl, azblob)
assert.Contains(t, pulumiBlob, accountName)
assert.Equal(t, storageAccount, pulumiBlob[accountName])
assert.Contains(t, pulumiBlob, containerName)
assert.Equal(t, container, pulumiBlob[containerName])
assert.Contains(t, pulumiBlob, blobName)
assert.Equal(t, name, pulumiBlob[blobName])
assert.Contains(t, pulumiBlob, accessTier)
assert.Equal(t, string(azureblob.AccessTierHot), pulumiBlob[accessTier])
assert.Contains(t, pulumiBlob, typeProp)
assert.Equal(t, "Block", pulumiBlob[typeProp])
assert.Contains(t, pulumiBlob, contentMd5)
assert.Equal(t, base64.StdEncoding.EncodeToString(azblob.ContentMD5), pulumiBlob[contentMd5])
assert.Contains(t, pulumiBlob, contentType)
assert.Equal(t, "text/plain", pulumiBlob[contentType])
require.Contains(t, pulumiBlob, metadata)
m := pulumiBlob[metadata].(map[string]*string)
assert.Equal(t, ref("v1"), m["k1"])
assert.Contains(t, pulumiBlob, url)
assert.Equal(t, blobUrl, pulumiBlob[url])
})
t.Run("no access tier", func(t *testing.T) {
azblob := setup()
azblob.AccessTier = nil
pulumiBlob := azblobToPulumiProperties(name, rg, storageAccount, container, blobUrl, azblob)
assert.NotContains(t, pulumiBlob, accessTier)
azblob.AccessTier = ref("")
pulumiBlob = azblobToPulumiProperties(name, rg, storageAccount, container, blobUrl, azblob)
assert.NotContains(t, pulumiBlob, accessTier)
})
}
func TestGetStorageAccountName(t *testing.T) {
validID := "/subscriptions/123/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/acc/staticWebsite"
t.Run("from properties", func(t *testing.T) {
properties := resource.NewPropertyMapFromMap(map[string]any{
accountName: "myaccount",
})
name, err := getStorageAccountName(validID, properties)
require.NoError(t, err)
assert.Equal(t, "myaccount", name)
})
t.Run("from ID", func(t *testing.T) {
name, err := getStorageAccountName(validID, resource.PropertyMap{})
require.NoError(t, err)
assert.Equal(t, "acc", name)
})
t.Run("invalid ID", func(t *testing.T) {
_, err := getStorageAccountName("invalid", resource.PropertyMap{})
require.Error(t, err)
})
t.Run("falls back to ID", func(t *testing.T) {
name, err := getStorageAccountName(validID, resource.PropertyMap{})
require.NoError(t, err)
assert.Equal(t, "acc", name)
})
}
func ref[T any](t T) *T { return &t }
// requestCapturingTransporter is a test helper that captures HTTP requests
type requestCapturingTransporter struct {
fakeTransport azpolicy.Transporter
onRequest func(*http.Request)
}
func (r *requestCapturingTransporter) Do(req *http.Request) (*http.Response, error) {
if r.onRequest != nil {
r.onRequest(req)
}
return r.fakeTransport.Do(req)
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/customresources_test.go | provider/pkg/resources/customresources/customresources_test.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package customresources
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestIsSingleton(t *testing.T) {
assert.False(t, IsSingleton(""))
assert.False(t, IsSingleton("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}"))
postgresResource, err := postgresFlexibleServerConfiguration(nil, nil)
require.NoError(t, err)
assert.True(t, postgresResource.isSingleton)
assert.True(t, IsSingleton(postgresResource.path))
}
func TestIncludeCustomResource(t *testing.T) {
t.Run("Include any API version for WebApp", func(t *testing.T) {
isCustom, include := IncludeCustomResource(webAppPath, "1888-11-11")
assert.True(t, isCustom)
assert.True(t, include)
})
t.Run("Include specific API version for Role Eligibility Schedule Request", func(t *testing.T) {
isCustom, include := IncludeCustomResource(PimRoleEligibilityScheduleRequestPath, "2020-10-01")
assert.True(t, isCustom)
assert.True(t, include)
})
t.Run("Don't include other API versions for Role Eligibility Schedule Request", func(t *testing.T) {
isCustom, include := IncludeCustomResource(PimRoleEligibilityScheduleRequestPath, "2024-07-01")
assert.True(t, isCustom)
assert.False(t, include)
})
t.Run("Non-custom resource", func(t *testing.T) {
isCustom, include := IncludeCustomResource(
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}",
"2020-10-01")
assert.False(t, isCustom)
assert.False(t, include)
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_portal_dashboard.go | provider/pkg/resources/customresources/custom_portal_dashboard.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package customresources
import (
"fmt"
"reflect"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/resources"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
)
// portalDashboard creates an override for the portal:Dashboard resource types.
//
// This change is needed because the Azure API open API specs define DashboardPartMetadata as a discriminated type but
// with only a concrete type defined. The API supports a multitude of part types, but the open API spec only describes
// one of them. The result of this is that we generate a discriminated union which is so restricted that it can't be used
// in practice.
//
// The override does two things:
// 1. Defines a new type DashboardPartMetadata with three properties: type, inputs, and settings. Inputs and settings are
// loosely typed collections to allow for arbitrary JSON objects.
// 2. Overrides the 'metadata' property type of the portal:DashboardParts type to be DashboardPartMetadata.
//
// The override effectively removes the discriminated union and replaces it with a single loosely-typed structure.
// We override both input and output (Response) types.
func portalDashboard() *CustomResource {
return &CustomResource{
tok: "azure-native:portal:Dashboard",
Schema: func(resource *ResourceDefinition) (*ResourceDefinition, error) {
if resource == nil {
// This should only happen if we're running with a namespace or version filter for testing, so we'll allow it to pass.
return nil, nil
}
existingDashboardPartsType := resource.Types["azure-native:portal:DashboardParts"]
if !reflect.DeepEqual(existingDashboardPartsType, expectedDashboardPartsType("")) {
return nil, fmt.Errorf("unexpected azure-native:portal:DashboardParts type: %#v", existingDashboardPartsType)
}
resource.Types["azure-native:portal:DashboardParts"] = dashboardPartsType("")
existingDashboardPartsTypeResponse := resource.Types["azure-native:portal:DashboardPartsResponse"]
if !reflect.DeepEqual(existingDashboardPartsTypeResponse, expectedDashboardPartsType("Response")) {
return nil, fmt.Errorf("unexpected azure-native:portal:DashboardPartsResponse type: %#v", existingDashboardPartsTypeResponse)
}
resource.Types["azure-native:portal:DashboardPartsResponse"] = dashboardPartsType("Response")
existingMarkdownPartMetadataType := resource.Types["azure-native:portal:MarkdownPartMetadata"]
if !reflect.DeepEqual(existingMarkdownPartMetadataType, expectedMarkdownPartMetadataType("")) {
return nil, fmt.Errorf("unexpected azure-native:portal:MarkdownPartMetadata type: %#v", existingMarkdownPartMetadataType)
}
if _, ok := resource.Types["azure-native:portal:DashboardPartMetadata"]; ok {
return nil, fmt.Errorf("unexpected existing azure-native:portal:DashboardPartMetadata type")
}
resource.Types["azure-native:portal:DashboardPartMetadata"] = dashboardPartMetadataType()
existingMarkdownPartMetadataResponseType := resource.Types["azure-native:portal:MarkdownPartMetadataResponse"]
if !reflect.DeepEqual(existingMarkdownPartMetadataResponseType, expectedMarkdownPartMetadataType("Response")) {
return nil, fmt.Errorf("unexpected azure-native:portal:MarkdownPartMetadataResponse type: %#v", existingMarkdownPartMetadataResponseType)
}
if _, ok := resource.Types["azure-native:portal:DashboardPartMetadataResponse"]; ok {
return nil, fmt.Errorf("unexpected existing azure-native:portal:DashboardPartMetadataResponse type")
}
resource.Types["azure-native:portal:DashboardPartMetadataResponse"] = dashboardPartMetadataType()
resource.MetaTypes["azure-native:portal:DashboardParts"] = dashboardPartsApiType("")
resource.MetaTypes["azure-native:portal:DashboardPartsResponse"] = dashboardPartsApiType("Response")
resource.MetaTypes["azure-native:portal:DashboardPartMetadata"] = dashboardPartMetadataApiType()
resource.MetaTypes["azure-native:portal:DashboardPartMetadataResponse"] = dashboardPartMetadataApiType()
return resource, nil
},
}
}
func dashboardPartsType(suffix string) schema.ComplexTypeSpec {
return schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "A dashboard part.",
Type: "object",
Properties: map[string]schema.PropertySpec{
"metadata": {
TypeSpec: schema.TypeSpec{
Type: "object",
Ref: fmt.Sprintf("#/types/azure-native:portal:DashboardPartMetadata%s", suffix),
},
Description: "The dashboard's part metadata.",
},
"position": {
TypeSpec: schema.TypeSpec{
Type: "object",
Ref: fmt.Sprintf("#/types/azure-native:portal:DashboardPartsPosition%s", suffix),
},
Description: "The dashboard's part position.",
},
},
Required: []string{"position"},
},
}
}
func expectedDashboardPartsType(suffix string) schema.ComplexTypeSpec {
return schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "A dashboard part.",
Properties: map[string]schema.PropertySpec{
"metadata": {
TypeSpec: schema.TypeSpec{
Type: "object",
Ref: fmt.Sprintf("#/types/azure-native:portal:MarkdownPartMetadata%s", suffix),
},
Description: "The dashboard part's metadata.",
},
"position": {
TypeSpec: schema.TypeSpec{
Type: "object",
Ref: fmt.Sprintf("#/types/azure-native:portal:DashboardPartsPosition%s", suffix),
},
Description: "The dashboard's part position.",
},
},
Type: "object",
Required: []string{"position"},
},
}
}
func dashboardPartsApiType(suffix string) resources.AzureAPIType {
return resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"metadata": {
Type: "object",
Ref: fmt.Sprintf("#/types/azure-native:portal:DashboardPartMetadata%s", suffix),
},
"position": {
Type: "object",
Ref: fmt.Sprintf("#/types/azure-native:portal:DashboardPartsPosition%s", suffix),
},
},
RequiredProperties: []string{"position"},
}
}
func dashboardPartMetadataType() schema.ComplexTypeSpec {
return schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "A dashboard part metadata.",
Type: "object",
Properties: map[string]schema.PropertySpec{
"type": {
TypeSpec: schema.TypeSpec{Type: "string"},
Description: "The type of dashboard part.",
},
"inputs": {
TypeSpec: schema.TypeSpec{
Type: "array",
Items: &schema.TypeSpec{Ref: "pulumi.json#/Any"},
},
Description: "Inputs to dashboard part.",
},
"settings": {
TypeSpec: schema.TypeSpec{
Type: "object",
AdditionalProperties: &schema.TypeSpec{Ref: "pulumi.json#/Any"},
},
Description: "Settings of dashboard part.",
},
},
Required: []string{"type"},
},
}
}
func expectedMarkdownPartMetadataType(suffix string) schema.ComplexTypeSpec {
return schema.ComplexTypeSpec{
ObjectTypeSpec: schema.ObjectTypeSpec{
Description: "Markdown part metadata.",
Properties: map[string]schema.PropertySpec{
"inputs": {
TypeSpec: schema.TypeSpec{
Type: "array",
Items: &schema.TypeSpec{Ref: "pulumi.json#/Any"},
},
Description: "Input to dashboard part.",
},
"settings": {
TypeSpec: schema.TypeSpec{
Type: "object",
Ref: fmt.Sprintf("#/types/azure-native:portal:MarkdownPartMetadataSettings%s", suffix),
},
Description: "Markdown part settings.",
},
"type": {
TypeSpec: schema.TypeSpec{
Type: "string",
},
Description: "The dashboard part metadata type.\nExpected value is 'Extension/HubsExtension/PartType/MarkdownPart'.",
Const: "Extension/HubsExtension/PartType/MarkdownPart",
},
},
Type: "object",
Required: []string{"type"},
},
}
}
func dashboardPartMetadataApiType() resources.AzureAPIType {
return resources.AzureAPIType{
Properties: map[string]resources.AzureAPIProperty{
"type": {
Type: "string",
},
"inputs": {
Type: "array",
Items: &resources.AzureAPIProperty{Ref: "pulumi.json#/Any"},
},
"settings": {
Type: "object",
AdditionalProperties: &resources.AzureAPIProperty{Ref: "pulumi.json#/Any"},
},
},
RequiredProperties: []string{"type"},
}
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_postgres_config_test.go | provider/pkg/resources/customresources/custom_postgres_config_test.go | // Copyright 2024, Pulumi Corporation. All rights reserved.
package customresources
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestGetValueFromAzureResponse(t *testing.T) {
t.Run("happy path", func(t *testing.T) {
resp := map[string]any{
"properties": map[string]any{
"defaultValue": "foo",
},
}
defaultValue := getValueFromAzureResponse(resp, "defaultValue")
require.NotNil(t, defaultValue)
require.Equal(t, "foo", defaultValue)
})
t.Run("empty response", func(t *testing.T) {
require.Nil(t, getValueFromAzureResponse(map[string]any{}, "defaultValue"))
})
t.Run("nil response", func(t *testing.T) {
require.Nil(t, getValueFromAzureResponse(nil, "defaultValue"))
})
t.Run("missing property", func(t *testing.T) {
require.Nil(t, getValueFromAzureResponse(map[string]any{
"properties": map[string]any{},
}, "defaultValue"))
})
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
pulumi/pulumi-azure-native | https://github.com/pulumi/pulumi-azure-native/blob/1f14b038c133f406184984d9980dfcacb7141599/provider/pkg/resources/customresources/custom_keyvault.go | provider/pkg/resources/customresources/custom_keyvault.go | // Copyright 2021, Pulumi Corporation. All rights reserved.
package customresources
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys"
"github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets"
"github.com/pkg/errors"
"github.com/pulumi/pulumi-azure-native/v2/provider/pkg/azure/cloud"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
)
// Note: These are "hybrid" resources: schema, create, update, read use default implementation, while DELETE is overridden.
// DELETE is implemented via the KeyVault "data plane" API, because it isn't available via ARM.
// keyVaultSecret creates a custom resource for Azure KeyVault Secret.
func keyVaultSecret(cloud cloud.Configuration, tokenCred azcore.TokenCredential) *CustomResource {
return &CustomResource{
path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/secrets/{secretName}",
Delete: func(ctx context.Context, id string, inputs, state resource.PropertyMap) error {
vaultName := inputs["vaultName"]
if !vaultName.HasValue() || !vaultName.IsString() {
return errors.New("vaultName not found in resource state")
}
secretName := inputs["secretName"]
if !secretName.HasValue() || !secretName.IsString() {
return errors.New("secretName not found in resource state")
}
keyVaultDNSSuffix := strings.TrimPrefix(cloud.Suffixes.KeyVaultDNS, ".")
if keyVaultDNSSuffix == "" {
return errors.New("The provider configuration must include a value for keyVaultDNSSuffix")
}
vaultUrl := fmt.Sprintf("https://%s.%s", vaultName.StringValue(), keyVaultDNSSuffix)
kvClient, err := azsecrets.NewClient(vaultUrl, tokenCred, nil)
if err != nil {
return err
}
logging.V(9).Infof("connecting to vault: %s", vaultUrl)
_, err = kvClient.DeleteSecret(ctx, secretName.StringValue(), nil)
return reportDeletionError(err)
},
}
}
// keyVaultKey creates a custom resource for Azure KeyVault Key.
func keyVaultKey(cloud cloud.Configuration, tokenCred azcore.TokenCredential) *CustomResource {
return &CustomResource{
path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/keys/{keyName}",
Delete: func(ctx context.Context, id string, inputs, state resource.PropertyMap) error {
vaultName := inputs["vaultName"]
if !vaultName.HasValue() || !vaultName.IsString() {
return errors.New("vaultName not found in resource state")
}
keyName := inputs["keyName"]
if !keyName.HasValue() || !keyName.IsString() {
return errors.New("keyName not found in resource state")
}
keyVaultDNSSuffix := strings.TrimPrefix(cloud.Suffixes.KeyVaultDNS, ".")
if keyVaultDNSSuffix == "" {
return errors.New("The provider configuration must include a value for keyVaultDNSSuffix")
}
vaultUrl := fmt.Sprintf("https://%s.%s", vaultName.StringValue(), keyVaultDNSSuffix)
kvClient, err := azkeys.NewClient(vaultUrl, tokenCred, nil)
if err != nil {
return err
}
logging.V(9).Infof("connecting to vault: %s", vaultUrl)
_, err = kvClient.DeleteKey(ctx, keyName.StringValue(), nil)
return reportDeletionError(err)
},
}
}
func reportDeletionError(err error) error {
if detailed, ok := err.(*azcore.ResponseError); ok && detailed.StatusCode == http.StatusNotFound {
return nil
}
return err
}
| go | Apache-2.0 | 1f14b038c133f406184984d9980dfcacb7141599 | 2026-01-07T09:42:26.479506Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.