From a100d8244a500aaf4f92259422abaaadcc28178c Mon Sep 17 00:00:00 2001 From: Moises Martinez Date: Fri, 6 Nov 2026 22:38:21 +0100 Subject: [PATCH 1/2] feat(container-registry): onboard tf driver for container registry --- .../containerregistry_artifactories.md | 60 + .../containerregistry_artifactory.md | 55 + .../containerregistry_replication_adapters.md | 48 + docs/index.md | 1 + .../containerregistry_artifactory.md | 106 ++ .../data-source.tf | 7 + .../data-source.tf | 9 + .../data-source.tf | 7 + .../import-by-string-id.tf | 5 + .../resource.tf | 29 + go.mod | 1 + go.sum | 2 + stackit/internal/core/clienttestutils.go | 10 + stackit/internal/core/clientutils.go | 17 + stackit/internal/core/clientutils_test.go | 20 + stackit/internal/core/core.go | 3 + .../artifactories/datasource.go | 306 ++++ .../artifactories/datasource_test.go | 332 ++++ .../artifactory/datasource.go | 218 +++ .../artifactory/datasource_test.go | 273 ++++ .../containerregistry/artifactory/resource.go | 752 +++++++++ .../artifactory/resource_test.go | 1343 +++++++++++++++++ .../containerregistry_acc_test.go | 215 +++ .../replicationadapters/datasource.go | 202 +++ .../replicationadapters/datasource_test.go | 269 ++++ .../testdata/datasource-artifactories.tf | 7 + .../datasource-replication-adapters.tf | 7 + .../testdata/resource-max.tf | 36 + .../testdata/resource-min.tf | 12 + stackit/internal/testutil/testutil.go | 2 + stackit/provider.go | 14 + stackit/testdata/provider-all-attributes.tf | 1 + 32 files changed, 4369 insertions(+) create mode 100644 docs/data-sources/containerregistry_artifactories.md create mode 100644 docs/data-sources/containerregistry_artifactory.md create mode 100644 docs/data-sources/containerregistry_replication_adapters.md create mode 100644 docs/resources/containerregistry_artifactory.md create mode 100644 examples/data-sources/stackit_containerregistry_artifactories/data-source.tf create mode 100644 examples/data-sources/stackit_containerregistry_artifactory/data-source.tf create mode 100644 examples/data-sources/stackit_containerregistry_replication_adapters/data-source.tf create mode 100644 examples/resources/stackit_containerregistry_artifactory/import-by-string-id.tf create mode 100644 examples/resources/stackit_containerregistry_artifactory/resource.tf create mode 100644 stackit/internal/services/containerregistry/artifactories/datasource.go create mode 100644 stackit/internal/services/containerregistry/artifactories/datasource_test.go create mode 100644 stackit/internal/services/containerregistry/artifactory/datasource.go create mode 100644 stackit/internal/services/containerregistry/artifactory/datasource_test.go create mode 100644 stackit/internal/services/containerregistry/artifactory/resource.go create mode 100644 stackit/internal/services/containerregistry/artifactory/resource_test.go create mode 100644 stackit/internal/services/containerregistry/containerregistry_acc_test.go create mode 100644 stackit/internal/services/containerregistry/replicationadapters/datasource.go create mode 100644 stackit/internal/services/containerregistry/replicationadapters/datasource_test.go create mode 100644 stackit/internal/services/containerregistry/testdata/datasource-artifactories.tf create mode 100644 stackit/internal/services/containerregistry/testdata/datasource-replication-adapters.tf create mode 100644 stackit/internal/services/containerregistry/testdata/resource-max.tf create mode 100644 stackit/internal/services/containerregistry/testdata/resource-min.tf diff --git a/docs/data-sources/containerregistry_artifactories.md b/docs/data-sources/containerregistry_artifactories.md new file mode 100644 index 000000000..5003fa8c5 --- /dev/null +++ b/docs/data-sources/containerregistry_artifactories.md @@ -0,0 +1,60 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "stackit_containerregistry_artifactories Data Source - stackit" +subcategory: "" +description: |- + Container registry artifactories list data source schema. +--- + +# stackit_containerregistry_artifactories (Data Source) + +Container registry artifactories list data source schema. + +## Example Usage + +```terraform +locals { + project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +} + +data "stackit_containerregistry_artifactories" "this" { + project_id = local.project_id +} +``` + + +## Schema + +### Required + +- `project_id` (String) STACKIT project ID to which the container registry artifactories are associated. + +### Optional + +- `region` (String) STACKIT region where the container registry artifactories are located. If not defined, the provider default_region is used. + +### Read-Only + +- `artifactories` (Attributes List) List of container registry artifactories. (see [below for nested schema](#nestedatt--artifactories)) +- `id` (String) Terraform's internal data source ID, structured as `project_id`,`region`. + + +### Nested Schema for `artifactories` + +Read-Only: + +- `artifactory_id` (String) The unique identifier of the container registry artifactory. +- `create_time` (String) The date and time the creation of the STACKIT artifactory was triggered. +- `name` (String) A user-chosen name to distinguish multiple STACKIT artifactories. +- `proxy` (Attributes) Proxy configuration if this artifactory is created as a proxy-cache for an upstream registry. (see [below for nested schema](#nestedatt--artifactories--proxy)) +- `state` (String) The current state of the STACKIT artifactory. +- `url` (String) The base URL of the STACKIT artifactory. + + +### Nested Schema for `artifactories.proxy` + +Read-Only: + +- `description` (String) Description of the upstream registry. +- `registry_type` (String) Which replication adapter to use for this registry. +- `url` (String) Upstream registry URL to proxy. diff --git a/docs/data-sources/containerregistry_artifactory.md b/docs/data-sources/containerregistry_artifactory.md new file mode 100644 index 000000000..0f06ddddc --- /dev/null +++ b/docs/data-sources/containerregistry_artifactory.md @@ -0,0 +1,55 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "stackit_containerregistry_artifactory Data Source - stackit" +subcategory: "" +description: |- + Container registry artifactory data source schema. +--- + +# stackit_containerregistry_artifactory (Data Source) + +Container registry artifactory data source schema. + +## Example Usage + +```terraform +locals { + project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + artifactory_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +} + +data "stackit_containerregistry_artifactory" "this" { + project_id = local.project_id + artifactory_id = local.artifactory_id +} +``` + + +## Schema + +### Required + +- `artifactory_id` (String) The unique identifier of the container registry artifactory. +- `project_id` (String) STACKIT project ID to which the container registry artifactory is associated. + +### Optional + +- `region` (String) STACKIT region where the container registry artifactory is located. If not defined, the provider default_region is used. + +### Read-Only + +- `create_time` (String) The date and time the creation of the STACKIT artifactory was triggered. +- `id` (String) Terraform's internal resource ID, structured as `project_id`,`region`,`artifactory_id`. +- `name` (String) A user-chosen name to distinguish multiple STACKIT artifactories. +- `proxy` (Attributes) Proxy configuration if this artifactory is created as a proxy-cache for an upstream registry. (see [below for nested schema](#nestedatt--proxy)) +- `state` (String) The current state of the STACKIT artifactory. +- `url` (String) The base URL of the STACKIT artifactory. + + +### Nested Schema for `proxy` + +Read-Only: + +- `description` (String) Description of the upstream registry. +- `registry_type` (String) Which replication adapter to use for this registry. +- `url` (String) Upstream registry URL to proxy. diff --git a/docs/data-sources/containerregistry_replication_adapters.md b/docs/data-sources/containerregistry_replication_adapters.md new file mode 100644 index 000000000..e7a5db589 --- /dev/null +++ b/docs/data-sources/containerregistry_replication_adapters.md @@ -0,0 +1,48 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "stackit_containerregistry_replication_adapters Data Source - stackit" +subcategory: "" +description: |- + Container registry replication adapters data source schema. +--- + +# stackit_containerregistry_replication_adapters (Data Source) + +Container registry replication adapters data source schema. + +## Example Usage + +```terraform +locals { + project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +} + +data "stackit_containerregistry_replication_adapters" "this" { + project_id = local.project_id +} +``` + + +## Schema + +### Required + +- `project_id` (String) STACKIT project ID to which the replication adapters are associated. + +### Optional + +- `region` (String) STACKIT region where the replication adapters are located. If not defined, the provider default_region is used. + +### Read-Only + +- `id` (String) Terraform's internal data source ID, structured as `project_id`,`region`. +- `replication_adapters` (Attributes List) List of supported replication adapters. (see [below for nested schema](#nestedatt--replication_adapters)) + + +### Nested Schema for `replication_adapters` + +Read-Only: + +- `credential_type` (String) User-hint for what type of credentials are expected for the replication adapter type. +- `display_name` (String) Human-friendly name of the provider the adapter relates to. +- `registry_type` (String) Identifies the replication adapter. diff --git a/docs/index.md b/docs/index.md index 5419deaa8..67328b34c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -177,6 +177,7 @@ See this [example](https://professional-service.git.onstackit.cloud/professional - `authorization_custom_endpoint` (String) Custom endpoint for the Membership service - `automation_custom_endpoint` (String) Custom endpoint for the Automation service - `cdn_custom_endpoint` (String) Custom endpoint for the CDN service +- `container_registry_custom_endpoint` (String) Custom endpoint for the Container Registry service - `credentials_path` (String) Path of JSON from where the credentials are read. Takes precedence over the env var `STACKIT_CREDENTIALS_PATH`. Default value is `~/.stackit/credentials.json`. - `default_region` (String) Region will be used as the default location for regional services. Not all services require a region, some are global - `dns_custom_endpoint` (String) Custom endpoint for the DNS service diff --git a/docs/resources/containerregistry_artifactory.md b/docs/resources/containerregistry_artifactory.md new file mode 100644 index 000000000..58e603572 --- /dev/null +++ b/docs/resources/containerregistry_artifactory.md @@ -0,0 +1,106 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "stackit_containerregistry_artifactory Resource - stackit" +subcategory: "" +description: |- + Container registry artifactory resource schema. +--- + +# stackit_containerregistry_artifactory (Resource) + +Container registry artifactory resource schema. + +## Example Usage + +```terraform +locals { + project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + region = "eu01" + name = "my-registry" +} + +# Standard container registry artifactory +resource "stackit_containerregistry_artifactory" "this" { + project_id = local.project_id + name = local.name +} + +# Container registry artifactory configured as a Docker Hub proxy-cache with write-only credentials +resource "stackit_containerregistry_artifactory" "docker_hub_proxy" { + project_id = local.project_id + name = "my-docker-hub-mirror" + + proxy = { + registry_type = "docker-hub" + url = "https://registry-1.docker.io" + description = "Docker Hub pull-through cache" + + credentials = { + access_key = "my-dockerhub-username" + access_secret_wo = "my-dockerhub-access-token" + access_secret_wo_version = 1 + } + } +} +``` + + +## Schema + +### Required + +- `name` (String) A user-chosen name to distinguish multiple STACKIT artifactories. +- `project_id` (String) STACKIT project ID to which the container registry artifactory is associated. + +### Optional + +- `proxy` (Attributes) Proxy configuration if this artifactory is created as a proxy-cache for an upstream registry. (see [below for nested schema](#nestedatt--proxy)) +- `region` (String) STACKIT region where the container registry artifactory is located. If not defined, the provider default_region is used. + +### Read-Only + +- `artifactory_id` (String) The unique identifier of the container registry artifactory. +- `create_time` (String) The date and time the creation of the STACKIT artifactory was triggered. +- `id` (String) Terraform's internal resource ID, structured as `project_id`,`region`,`artifactory_id`. +- `state` (String) The current state of the STACKIT artifactory. +- `url` (String) The base URL of the STACKIT artifactory. + + +### Nested Schema for `proxy` + +Required: + +- `registry_type` (String) Which replication adapter to use for this registry. +- `url` (String) Upstream registry URL to proxy. + +Optional: + +- `credentials` (Attributes) Credentials for the upstream registry. (see [below for nested schema](#nestedatt--proxy--credentials)) +- `description` (String) Description of the upstream registry. + + +### Nested Schema for `proxy.credentials` + +Required: + +- `access_key` (String) Access key or username for the upstream registry. + +Optional: + +- `access_secret` (String, Sensitive) Access secret or password for the upstream registry. Write-only argument `access_secret_wo` should be preferred. +- `access_secret_wo` (String, Sensitive, [Write-only](https://developer.hashicorp.com/terraform/language/resources/ephemeral#write-only-arguments)) Write-only access secret or password for the upstream registry - never stored in state and never returned by the API. To rotate the secret, update this value AND increment `access_secret_wo_version`. Changing this field alone will NOT trigger an update. +- `access_secret_wo_version` (Number) User-managed rotation counter for `access_secret_wo`. Must be incremented every time `access_secret_wo` is updated. + +## Import + +Import is supported using the following syntax: + +In Terraform v1.5.0 and later, the [` + "`" + `import` + "`" + ` block](https://developer.hashicorp.com/terraform/language/import) can be used with the ` + "`" + `id` + "`" + ` attribute, for example: + +```terraform +# Only use the import statement if you want to import an existing Container Registry artifactory +import { + to = stackit_containerregistry_artifactory.this + id = "${local.project_id},${local.region},ARTIFACTORY_ID" +} +``` diff --git a/examples/data-sources/stackit_containerregistry_artifactories/data-source.tf b/examples/data-sources/stackit_containerregistry_artifactories/data-source.tf new file mode 100644 index 000000000..ae6f655d8 --- /dev/null +++ b/examples/data-sources/stackit_containerregistry_artifactories/data-source.tf @@ -0,0 +1,7 @@ +locals { + project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +} + +data "stackit_containerregistry_artifactories" "this" { + project_id = local.project_id +} diff --git a/examples/data-sources/stackit_containerregistry_artifactory/data-source.tf b/examples/data-sources/stackit_containerregistry_artifactory/data-source.tf new file mode 100644 index 000000000..bbfc97729 --- /dev/null +++ b/examples/data-sources/stackit_containerregistry_artifactory/data-source.tf @@ -0,0 +1,9 @@ +locals { + project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + artifactory_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +} + +data "stackit_containerregistry_artifactory" "this" { + project_id = local.project_id + artifactory_id = local.artifactory_id +} diff --git a/examples/data-sources/stackit_containerregistry_replication_adapters/data-source.tf b/examples/data-sources/stackit_containerregistry_replication_adapters/data-source.tf new file mode 100644 index 000000000..0d390add9 --- /dev/null +++ b/examples/data-sources/stackit_containerregistry_replication_adapters/data-source.tf @@ -0,0 +1,7 @@ +locals { + project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" +} + +data "stackit_containerregistry_replication_adapters" "this" { + project_id = local.project_id +} diff --git a/examples/resources/stackit_containerregistry_artifactory/import-by-string-id.tf b/examples/resources/stackit_containerregistry_artifactory/import-by-string-id.tf new file mode 100644 index 000000000..a159d2a81 --- /dev/null +++ b/examples/resources/stackit_containerregistry_artifactory/import-by-string-id.tf @@ -0,0 +1,5 @@ +# Only use the import statement if you want to import an existing Container Registry artifactory +import { + to = stackit_containerregistry_artifactory.this + id = "${local.project_id},${local.region},ARTIFACTORY_ID" +} diff --git a/examples/resources/stackit_containerregistry_artifactory/resource.tf b/examples/resources/stackit_containerregistry_artifactory/resource.tf new file mode 100644 index 000000000..e2e9451fc --- /dev/null +++ b/examples/resources/stackit_containerregistry_artifactory/resource.tf @@ -0,0 +1,29 @@ +locals { + project_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + region = "eu01" + name = "my-registry" +} + +# Standard container registry artifactory +resource "stackit_containerregistry_artifactory" "this" { + project_id = local.project_id + name = local.name +} + +# Container registry artifactory configured as a Docker Hub proxy-cache with write-only credentials +resource "stackit_containerregistry_artifactory" "docker_hub_proxy" { + project_id = local.project_id + name = "my-docker-hub-mirror" + + proxy = { + registry_type = "docker-hub" + url = "https://registry-1.docker.io" + description = "Docker Hub pull-through cache" + + credentials = { + access_key = "my-dockerhub-username" + access_secret_wo = "my-dockerhub-access-token" + access_secret_wo_version = 1 + } + } +} diff --git a/go.mod b/go.mod index 28adff653..67417cc63 100644 --- a/go.mod +++ b/go.mod @@ -40,6 +40,7 @@ require ( github.com/stackitcloud/stackit-sdk-go/services/postgresflex v1.16.0 github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v1.5.0 github.com/stackitcloud/stackit-sdk-go/services/redis v1.6.0 + github.com/stackitcloud/stackit-sdk-go/services/registry v0.1.0 github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.28.0 github.com/stackitcloud/stackit-sdk-go/services/scf v0.11.0 github.com/stackitcloud/stackit-sdk-go/services/secretsmanager v0.20.0 diff --git a/go.sum b/go.sum index bec98011a..f091d0c69 100644 --- a/go.sum +++ b/go.sum @@ -211,6 +211,8 @@ github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v1.5.0 h1:SAro5TWVJDDyi github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v1.5.0/go.mod h1:mjYkyr/A/+9rZnX5IOLEoAMFqHsRCIToZWpsYzYBwWo= github.com/stackitcloud/stackit-sdk-go/services/redis v1.6.0 h1:5UEPilI+RCuXEM8jm4ibREoZAsSAGI1+KnJ0oapye7Q= github.com/stackitcloud/stackit-sdk-go/services/redis v1.6.0/go.mod h1:/wE98YN+s1s1OcaEPt8Z2xO0Y46Gur3nXlg1AiiMNeY= +github.com/stackitcloud/stackit-sdk-go/services/registry v0.1.0 h1:Z52pSNI1o1vi6h25ZQRl26lPMXFRq8RQVEjGlNA+Pwk= +github.com/stackitcloud/stackit-sdk-go/services/registry v0.1.0/go.mod h1:9ew0RfPiwsDbd2OApdaAfTJgZyJbtKKP63NNZz3RWBQ= github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.28.0 h1:rZB1f9g5M/2mWKXsJIfMvGcFpFWkDQFjG28V/d1ezWw= github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.28.0/go.mod h1:IsId3wbkp5oaO0JEaHZpZnbVW6KFHlAptwB+1iG3v3w= github.com/stackitcloud/stackit-sdk-go/services/scf v0.11.0 h1:tdRyQFfGHFiXNhURdHSdesh7ym3y2R9A39B4ywj2Coc= diff --git a/stackit/internal/core/clienttestutils.go b/stackit/internal/core/clienttestutils.go index f9b54c2ef..bd329f555 100644 --- a/stackit/internal/core/clienttestutils.go +++ b/stackit/internal/core/clienttestutils.go @@ -28,6 +28,7 @@ import ( postgresflex "github.com/stackitcloud/stackit-sdk-go/services/postgresflex/v3api" rabbitmq "github.com/stackitcloud/stackit-sdk-go/services/rabbitmq/v2api" redis "github.com/stackitcloud/stackit-sdk-go/services/redis/v2api" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" resourcemanager "github.com/stackitcloud/stackit-sdk-go/services/resourcemanager/v0api" scf "github.com/stackitcloud/stackit-sdk-go/services/scf/v1api" secretsmanagerV1Alpha "github.com/stackitcloud/stackit-sdk-go/services/secretsmanager/v1alphaapi" @@ -54,6 +55,7 @@ type MockClientFactory struct { AlbWafV1ClientMock albWaf.DefaultAPI AuthorizationV2ClientMock authorization.DefaultAPI CdnV1ClientMock cdnSdk.DefaultAPI + ContainerRegistryV1ClientMock registry.DefaultAPI DnsV1ClientMock dns.DefaultAPI DremioV2BetaClientMock dremioSdk.DefaultAPI EdgeV1ClientMock edge.DefaultAPI @@ -324,6 +326,14 @@ func (m *MockClientFactory) newCdnV1Client() (cdnSdk.DefaultAPI, error) { return cdnSdk.DefaultAPIServiceMock{}, nil } +func (m *MockClientFactory) newContainerRegistryV1Client() (registry.DefaultAPI, error) { + if m.ContainerRegistryV1ClientMock != nil { + return m.ContainerRegistryV1ClientMock, nil + } + + return registry.DefaultAPIServiceMock{}, nil +} + func (m *MockClientFactory) newIaaSV2AlphaClient() (iaasV2Alpha.DefaultAPI, error) { if m.IaaSV2ClientMock != nil { return m.IaasV2AlphaClientMock, nil diff --git a/stackit/internal/core/clientutils.go b/stackit/internal/core/clientutils.go index 45ffa7990..77d070ca1 100644 --- a/stackit/internal/core/clientutils.go +++ b/stackit/internal/core/clientutils.go @@ -38,6 +38,7 @@ import ( postgresflex "github.com/stackitcloud/stackit-sdk-go/services/postgresflex/v3api" rabbitmq "github.com/stackitcloud/stackit-sdk-go/services/rabbitmq/v2api" redis "github.com/stackitcloud/stackit-sdk-go/services/redis/v2api" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" resourcemanager "github.com/stackitcloud/stackit-sdk-go/services/resourcemanager/v0api" scf "github.com/stackitcloud/stackit-sdk-go/services/scf/v1api" secretsmanagerV1Alpha "github.com/stackitcloud/stackit-sdk-go/services/secretsmanager/v1alphaapi" @@ -65,6 +66,7 @@ type ClientFactory interface { newAuthorizationV2Client() (authorization.DefaultAPI, error) newAutomationV1Client() (automation.DefaultAPI, error) newCdnV1Client() (cdn.DefaultAPI, error) + newContainerRegistryV1Client() (registry.DefaultAPI, error) newDnsV1Client() (dns.DefaultAPI, error) newDremioV1BetaClient() (dremio.DefaultAPI, error) newEdgeV1Client() (edge.DefaultAPI, error) @@ -118,6 +120,10 @@ func initClientCollection(clientFactory ClientFactory) (*ClientCollection, error g.Go(func() (err error) { cc.VpnV1Client, err = clientFactory.newVpnV1Client(); return err }) g.Go(func() (err error) { cc.IaaSv2AlphaClient, err = clientFactory.newIaaSV2AlphaClient(); return err }) g.Go(func() (err error) { cc.CdnV1Client, err = clientFactory.newCdnV1Client(); return err }) + g.Go(func() (err error) { + cc.ContainerRegistryV1Client, err = clientFactory.newContainerRegistryV1Client() + return err + }) g.Go(func() (err error) { cc.PostgresflexV3Client, err = clientFactory.newPostgresflexV3Client(); return err }) g.Go(func() (err error) { cc.AlbV2Client, err = clientFactory.newAlbV2Client(); return err }) g.Go(func() (err error) { cc.SkeV2Client, err = clientFactory.newSkeV2Client(); return err }) @@ -500,6 +506,17 @@ func (f *DefaultClientFactory) newCdnV1Client() (cdn.DefaultAPI, error) { return apiClient.DefaultAPI, nil } +func (f *DefaultClientFactory) newContainerRegistryV1Client() (registry.DefaultAPI, error) { + apiClientConfigOptions := f.defaultConfigOptions(f.CustomEndpoints.ContainerRegistryCustomEndpoint) + + apiClient, err := registry.NewAPIClient(apiClientConfigOptions...) + if err != nil { + return nil, fmt.Errorf("configuring ContainerRegistryV1 client: %w. This is an error related to the provider configuration, not to the resource configuration", err) + } + + return apiClient.DefaultAPI, nil +} + func (f *DefaultClientFactory) newIaaSV2AlphaClient() (iaasV2Alpha.DefaultAPI, error) { apiClientConfigOptions := f.defaultConfigOptions(f.CustomEndpoints.IaaSCustomEndpoint) diff --git a/stackit/internal/core/clientutils_test.go b/stackit/internal/core/clientutils_test.go index 66be322fc..5f864dc33 100644 --- a/stackit/internal/core/clientutils_test.go +++ b/stackit/internal/core/clientutils_test.go @@ -36,6 +36,7 @@ import ( postgresflex "github.com/stackitcloud/stackit-sdk-go/services/postgresflex/v3api" rabbitmq "github.com/stackitcloud/stackit-sdk-go/services/rabbitmq/v2api" redis "github.com/stackitcloud/stackit-sdk-go/services/redis/v2api" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" resourcemanager "github.com/stackitcloud/stackit-sdk-go/services/resourcemanager/v0api" scf "github.com/stackitcloud/stackit-sdk-go/services/scf/v1api" secretsmanagerV1Alpha "github.com/stackitcloud/stackit-sdk-go/services/secretsmanager/v1alphaapi" @@ -748,6 +749,25 @@ func TestDefaultClientFactory_newCdnV1Client(t *testing.T) { test.run(t) } +func TestDefaultClientFactory_newContainerRegistryV1Client(t *testing.T) { + test := testHelper[registry.DefaultAPI]{ + factoryMethod: (*DefaultClientFactory).newContainerRegistryV1Client, + clientInitFunc: func(opts ...config.ConfigurationOption) registry.DefaultAPI { + client, err := registry.NewAPIClient(opts...) + if err != nil { + t.Fatalf("error creating client: %v", err) + } + + return client.DefaultAPI + }, + customEndpointSetter: func(cfg *CustomEndpointConfig) { + cfg.ContainerRegistryCustomEndpoint = testCustomEndpoint + }, + } + + test.run(t) +} + func TestDefaultClientFactory_newIaaSV2AlphaClient(t *testing.T) { test := testHelper[iaasV2Alpha.DefaultAPI]{ factoryMethod: (*DefaultClientFactory).newIaaSV2AlphaClient, diff --git a/stackit/internal/core/core.go b/stackit/internal/core/core.go index 6b4266c1f..2bbf10a8d 100644 --- a/stackit/internal/core/core.go +++ b/stackit/internal/core/core.go @@ -38,6 +38,7 @@ import ( postgresflex "github.com/stackitcloud/stackit-sdk-go/services/postgresflex/v3api" rabbitmq "github.com/stackitcloud/stackit-sdk-go/services/rabbitmq/v2api" redis "github.com/stackitcloud/stackit-sdk-go/services/redis/v2api" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" resourcemanager "github.com/stackitcloud/stackit-sdk-go/services/resourcemanager/v0api" scf "github.com/stackitcloud/stackit-sdk-go/services/scf/v1api" secretsmanagerV1Alpha "github.com/stackitcloud/stackit-sdk-go/services/secretsmanager/v1alphaapi" @@ -79,6 +80,7 @@ type CustomEndpointConfig struct { AuthorizationCustomEndpoint string AutomationCustomEndpoint string CdnCustomEndpoint string + ContainerRegistryCustomEndpoint string DnsCustomEndpoint string DremioCustomEndpoint string EdgeCloudCustomEndpoint string @@ -215,6 +217,7 @@ type ClientCollection struct { AuthorizationV2Client authorization.DefaultAPI AutomationV1Client automation.DefaultAPI CdnV1Client cdn.DefaultAPI + ContainerRegistryV1Client registry.DefaultAPI DnsV1Client dns.DefaultAPI DremioV1BetaClient dremio.DefaultAPI EdgeV1Client edge.DefaultAPI diff --git a/stackit/internal/services/containerregistry/artifactories/datasource.go b/stackit/internal/services/containerregistry/artifactories/datasource.go new file mode 100644 index 000000000..6fb9b5bd2 --- /dev/null +++ b/stackit/internal/services/containerregistry/artifactories/datasource.go @@ -0,0 +1,306 @@ +package artifactories + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" + + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core" + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils" + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate" +) + +var ( + _ datasource.DataSource = &artifactoriesDataSource{} +) + +type DataSourceModel struct { + Id types.String `tfsdk:"id"` + ProjectId types.String `tfsdk:"project_id"` + Region types.String `tfsdk:"region"` + Artifactories types.List `tfsdk:"artifactories"` +} + +type artifactoryItemModel struct { + ArtifactoryId types.String `tfsdk:"artifactory_id"` + Name types.String `tfsdk:"name"` + CreateTime types.String `tfsdk:"create_time"` + State types.String `tfsdk:"state"` + Url types.String `tfsdk:"url"` + Proxy types.Object `tfsdk:"proxy"` +} + +type proxyItemModel struct { + Description types.String `tfsdk:"description"` + + RegistryType types.String `tfsdk:"registry_type"` + + Url types.String `tfsdk:"url"` +} + +var proxyTypes = map[string]attr.Type{ + + "description": types.StringType, + + "registry_type": types.StringType, + + "url": types.StringType, +} + +var artifactoryItemTypes = map[string]attr.Type{ + + "artifactory_id": types.StringType, + + "name": types.StringType, + + "create_time": types.StringType, + + "state": types.StringType, + + "url": types.StringType, + + "proxy": types.ObjectType{AttrTypes: proxyTypes}, +} + +var descriptions = map[string]string{ + + "id": "Terraform's internal data source ID, structured as `project_id`,`region`.", + + "project_id": "STACKIT project ID to which the container registry artifactories are associated.", + + "region": "STACKIT region where the container registry artifactories are located. If not defined, the provider default_region is used.", + + "artifactories": "List of container registry artifactories.", + + "artifactory_id": "The unique identifier of the container registry artifactory.", + + "name": "A user-chosen name to distinguish multiple STACKIT artifactories.", + + "create_time": "The date and time the creation of the STACKIT artifactory was triggered.", + + "state": "The current state of the STACKIT artifactory.", + + "url": "The base URL of the STACKIT artifactory.", + + "proxy": "Proxy configuration if this artifactory is created as a proxy-cache for an upstream registry.", + + "proxy.registry_type": "Which replication adapter to use for this registry.", + + "proxy.url": "Upstream registry URL to proxy.", + + "proxy.description": "Description of the upstream registry.", +} + +func NewArtifactoriesDataSource() datasource.DataSource { + return &artifactoriesDataSource{} +} + +type artifactoriesDataSource struct { + client registry.DefaultAPI + providerData core.ProviderData +} + +func (d *artifactoriesDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_containerregistry_artifactories" +} + +func (d *artifactoriesDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { + providerData, clients, ok := core.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) + if !ok { + return + } + + d.providerData = providerData + d.client = clients.ContainerRegistryV1Client + tflog.Info(ctx, "Container Registry client configured") +} + +func (d *artifactoriesDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + Description: "Container registry artifactories list data source schema.", + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + Description: descriptions["id"], + Computed: true, + }, + "project_id": schema.StringAttribute{ + Description: descriptions["project_id"], + Required: true, + Validators: []validator.String{ + validate.UUID(), + validate.NoSeparator(), + }, + }, + "region": schema.StringAttribute{ + Description: descriptions["region"], + Optional: true, + Computed: true, + }, + "artifactories": schema.ListNestedAttribute{ + Description: descriptions["artifactories"], + Computed: true, + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + "artifactory_id": schema.StringAttribute{ + Description: descriptions["artifactory_id"], + Computed: true, + }, + "name": schema.StringAttribute{ + Description: descriptions["name"], + Computed: true, + }, + "create_time": schema.StringAttribute{ + Description: descriptions["create_time"], + Computed: true, + }, + "state": schema.StringAttribute{ + Description: descriptions["state"], + Computed: true, + }, + "url": schema.StringAttribute{ + Description: descriptions["url"], + Computed: true, + }, + "proxy": schema.SingleNestedAttribute{ + Description: descriptions["proxy"], + Computed: true, + Attributes: map[string]schema.Attribute{ + "registry_type": schema.StringAttribute{ + Description: descriptions["proxy.registry_type"], + Computed: true, + }, + "url": schema.StringAttribute{ + Description: descriptions["proxy.url"], + Computed: true, + }, + "description": schema.StringAttribute{ + Description: descriptions["proxy.description"], + Computed: true, + }, + }, + }, + }, + }, + }, + }, + } +} + +func (d *artifactoriesDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform + var model DataSourceModel + diags := req.Config.Get(ctx, &model) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + ctx = core.InitProviderContext(ctx) + + projectId := model.ProjectId.ValueString() + region := d.providerData.GetRegionWithOverride(model.Region) + ctx = tflog.SetField(ctx, "project_id", projectId) + ctx = tflog.SetField(ctx, "region", region) + + var allArtifactories []registry.Artifactory + apiReq := d.client.ListArtifactories(ctx, projectId, region) + for { + listResp, err := apiReq.Execute() + if err != nil { + utils.LogError( + ctx, + &resp.Diagnostics, + err, + "Error reading artifactories", + fmt.Sprintf("Calling API: %v", err), + map[int]string{ + http.StatusNotFound: fmt.Sprintf("Project %q or region %q not found", projectId, region), + }, + ) + return + } + + if listResp == nil { + break + } + + allArtifactories = append(allArtifactories, listResp.Artifactories...) + + if listResp.NextPageToken == nil || *listResp.NextPageToken == "" { + break + } + + apiReq = apiReq.NextPageToken(*listResp.NextPageToken) + } + + ctx = core.LogResponse(ctx) + + err := mapFields(ctx, allArtifactories, &model, region) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading artifactories", fmt.Sprintf("Mapping API response: %v", err)) + return + } + + diags = resp.State.Set(ctx, &model) + resp.Diagnostics.Append(diags...) + tflog.Info(ctx, "Container Registry artifactories read") +} + +func mapFields(ctx context.Context, artifactories []registry.Artifactory, model *DataSourceModel, region string) error { + if model == nil { + return fmt.Errorf("model is nil") + } + + model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region) + model.Region = types.StringValue(region) + + items := make([]attr.Value, 0, len(artifactories)) + for _, art := range artifactories { + item := artifactoryItemModel{ + ArtifactoryId: types.StringValue(art.Id), + Name: types.StringValue(art.Name), + CreateTime: types.StringValue(art.CreateTime.Format(time.RFC3339)), + State: types.StringValue(string(art.State)), + Url: types.StringValue(art.Url), + } + + if art.Proxy == nil { + item.Proxy = types.ObjectNull(proxyTypes) + } else { + p := proxyItemModel{ + RegistryType: types.StringValue(art.Proxy.RegistryType), + Url: types.StringValue(art.Proxy.Url), + Description: types.StringPointerValue(art.Proxy.Description), + } + + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, p) + if diags.HasError() { + return fmt.Errorf("mapping proxy: %w", core.DiagsToError(diags)) + } + item.Proxy = proxyObj + } + + itemObj, diags := types.ObjectValueFrom(ctx, artifactoryItemTypes, item) + if diags.HasError() { + return fmt.Errorf("mapping artifactory item: %w", core.DiagsToError(diags)) + } + + items = append(items, itemObj) + } + + itemsList, diags := types.ListValue(types.ObjectType{AttrTypes: artifactoryItemTypes}, items) + if diags.HasError() { + return fmt.Errorf("mapping artifactories list: %w", core.DiagsToError(diags)) + } + model.Artifactories = itemsList + + return nil +} diff --git a/stackit/internal/services/containerregistry/artifactories/datasource_test.go b/stackit/internal/services/containerregistry/artifactories/datasource_test.go new file mode 100644 index 000000000..0435b1640 --- /dev/null +++ b/stackit/internal/services/containerregistry/artifactories/datasource_test.go @@ -0,0 +1,332 @@ +package artifactories + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/stackitcloud/stackit-sdk-go/core/oapierror" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" + + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core" +) + +var testTime = time.Now() + +func TestArtifactoriesDataSource_Metadata(t *testing.T) { + ds := NewArtifactoriesDataSource() + var resp datasource.MetadataResponse + ds.Metadata(context.Background(), datasource.MetadataRequest{ProviderTypeName: "stackit"}, &resp) + if resp.TypeName != "stackit_containerregistry_artifactories" { + t.Errorf("expected type name %q, got %q", "stackit_containerregistry_artifactories", resp.TypeName) + } +} + +func TestArtifactoriesDataSource_Schema(t *testing.T) { + ds := NewArtifactoriesDataSource() + var resp datasource.SchemaResponse + ds.Schema(context.Background(), datasource.SchemaRequest{}, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + if len(resp.Schema.Attributes) == 0 { + t.Errorf("expected non-empty schema attributes") + } +} + +func TestArtifactoriesDataSource_Configure(t *testing.T) { + ds := &artifactoriesDataSource{} + ctx := context.Background() + + t.Run("valid provider data", func(t *testing.T) { + providerData, err := core.NewProviderDataInternal(core.ProviderData{}, &core.MockClientFactory{}) + if err != nil { + t.Fatalf("unexpected error creating provider data: %v", err) + } + var resp datasource.ConfigureResponse + ds.Configure(ctx, datasource.ConfigureRequest{ProviderData: providerData}, &resp) + if resp.Diagnostics.HasError() { + t.Errorf("unexpected error diagnostics: %v", resp.Diagnostics) + } + if ds.client == nil { + t.Error("expected client to be configured") + } + }) + + t.Run("nil provider data", func(t *testing.T) { + var resp datasource.ConfigureResponse + ds.Configure(ctx, datasource.ConfigureRequest{ProviderData: nil}, &resp) + if resp.Diagnostics.HasError() { + t.Errorf("expected no error diagnostics on nil provider data, got %v", resp.Diagnostics) + } + }) + + t.Run("invalid provider data type", func(t *testing.T) { + var resp datasource.ConfigureResponse + ds.Configure(ctx, datasource.ConfigureRequest{ProviderData: "invalid"}, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error diagnostics on invalid provider data") + } + }) +} + +func TestMapFields(t *testing.T) { + ctx := context.Background() + + desc := "upstream docker" + artifactories := []registry.Artifactory{ + { + Id: "art-1", + Name: "artifactory-1", + ConsumedQuotaBytes: 100, + CreateTime: testTime, + State: registry.ARTIFACTORYSTATE_ACTIVE, + Url: "https://art-1.cr.stackit.cloud", + }, + { + Id: "art-2", + Name: "artifactory-2", + ConsumedQuotaBytes: 200, + CreateTime: testTime, + State: registry.ARTIFACTORYSTATE_ACTIVE, + Url: "https://art-2.cr.stackit.cloud", + Proxy: ®istry.Proxy{ + RegistryType: "docker-hub", + Url: "https://registry-1.docker.io", + Description: &desc, + Credentials: ®istry.RedactedCredentials{ + AccessKey: "test-user", + }, + }, + }, + } + + model := &DataSourceModel{ + ProjectId: types.StringValue("pid"), + } + + err := mapFields(ctx, artifactories, model, "reg") + if err != nil { + t.Fatalf("mapFields() error = %v", err) + } + + if model.Id.ValueString() != "pid,reg" { + t.Errorf("expected id 'pid,reg', got %q", model.Id.ValueString()) + } + if model.Region.ValueString() != "reg" { + t.Errorf("expected region 'reg', got %q", model.Region.ValueString()) + } + + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyItemModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Description: types.StringValue("upstream docker"), + }) + if diags.HasError() { + t.Fatalf("creating proxyObj: %v", diags) + } + + item1, diags := types.ObjectValueFrom(ctx, artifactoryItemTypes, artifactoryItemModel{ + ArtifactoryId: types.StringValue("art-1"), + Name: types.StringValue("artifactory-1"), + CreateTime: types.StringValue(testTime.Format(time.RFC3339)), + State: types.StringValue(string(registry.ARTIFACTORYSTATE_ACTIVE)), + Url: types.StringValue("https://art-1.cr.stackit.cloud"), + Proxy: types.ObjectNull(proxyTypes), + }) + if diags.HasError() { + t.Fatalf("creating item1: %v", diags) + } + + item2, diags := types.ObjectValueFrom(ctx, artifactoryItemTypes, artifactoryItemModel{ + ArtifactoryId: types.StringValue("art-2"), + Name: types.StringValue("artifactory-2"), + CreateTime: types.StringValue(testTime.Format(time.RFC3339)), + State: types.StringValue(string(registry.ARTIFACTORYSTATE_ACTIVE)), + Url: types.StringValue("https://art-2.cr.stackit.cloud"), + Proxy: proxyObj, + }) + if diags.HasError() { + t.Fatalf("creating item2: %v", diags) + } + + expectedList, diags := types.ListValue(types.ObjectType{AttrTypes: artifactoryItemTypes}, []attr.Value{item1, item2}) + if diags.HasError() { + t.Fatalf("creating expectedList: %v", diags) + } + + expectedModel := &DataSourceModel{ + Id: types.StringValue("pid,reg"), + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + Artifactories: expectedList, + } + + if diff := cmp.Diff(model, expectedModel); diff != "" { + t.Errorf("mapFields() mismatch (-got +want):\n%s", diff) + } +} + +func TestMapFields_EdgeCases(t *testing.T) { + ctx := context.Background() + + t.Run("nil model", func(t *testing.T) { + err := mapFields(ctx, []registry.Artifactory{}, nil, "reg") + if err == nil { + t.Error("expected error for nil model") + } + }) + + t.Run("empty artifactories", func(t *testing.T) { + model := &DataSourceModel{ + ProjectId: types.StringValue("pid"), + } + err := mapFields(ctx, []registry.Artifactory{}, model, "reg") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if model.Artifactories.IsNull() { + t.Error("expected artifactories list not to be null") + } + if len(model.Artifactories.Elements()) != 0 { + t.Errorf("expected 0 elements, got %d", len(model.Artifactories.Elements())) + } + }) + + t.Run("proxy without credentials", func(t *testing.T) { + artifactories := []registry.Artifactory{ + { + Id: "art-proxy-no-creds", + Name: "artifactory-no-creds", + ConsumedQuotaBytes: 50, + CreateTime: testTime, + State: registry.ARTIFACTORYSTATE_ACTIVE, + Url: "https://art-no-creds.cr.stackit.cloud", + Proxy: ®istry.Proxy{ + RegistryType: "docker-hub", + Url: "https://registry-1.docker.io", + }, + }, + } + model := &DataSourceModel{ + ProjectId: types.StringValue("pid"), + } + err := mapFields(ctx, artifactories, model, "reg") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(model.Artifactories.Elements()) != 1 { + t.Fatalf("expected 1 element, got %d", len(model.Artifactories.Elements())) + } + }) +} + +func TestArtifactoriesDataSource_Read(t *testing.T) { + ctx := context.Background() + dsBase := NewArtifactoriesDataSource() + var schemaResp datasource.SchemaResponse + dsBase.Schema(ctx, datasource.SchemaRequest{}, &schemaResp) + + configAttrTypes := map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "artifactories": types.ListType{ElemType: types.ObjectType{AttrTypes: artifactoryItemTypes}}, + } + + configModel := DataSourceModel{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + Id: types.StringNull(), + Artifactories: types.ListNull(types.ObjectType{AttrTypes: artifactoryItemTypes}), + } + configVal, diags := types.ObjectValueFrom(ctx, configAttrTypes, configModel) + if diags.HasError() { + t.Fatalf("unexpected diags creating configVal: %v", diags) + } + rawVal, err := configVal.ToTerraformValue(ctx) + if err != nil { + t.Fatalf("unexpected error converting to terraform value: %v", err) + } + + req := datasource.ReadRequest{ + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + } + + t.Run("read success", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + ListArtifactoriesExecuteMock: new(func(_ registry.ApiListArtifactoriesRequest) (*registry.ArtifactoryList, error) { + return ®istry.ArtifactoryList{ + Artifactories: []registry.Artifactory{ + { + Id: "art-1", + Name: "artifactory-1", + ConsumedQuotaBytes: 100, + CreateTime: testTime, + State: registry.ARTIFACTORYSTATE_ACTIVE, + Url: "https://art-1.cr.stackit.cloud", + }, + }, + }, nil + }), + } + ds := &artifactoriesDataSource{client: mockClient} + + resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}} + ds.Read(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + + var resultModel DataSourceModel + diags = resp.State.Get(ctx, &resultModel) + if diags.HasError() { + t.Fatalf("unexpected diags getting state: %v", diags) + } + if resultModel.Id.ValueString() != "pid,reg" { + t.Errorf("expected id 'pid,reg', got %q", resultModel.Id.ValueString()) + } + if len(resultModel.Artifactories.Elements()) != 1 { + t.Errorf("expected 1 artifactory, got %d", len(resultModel.Artifactories.Elements())) + } + }) + + t.Run("read API error", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + ListArtifactoriesExecuteMock: new(func(_ registry.ApiListArtifactoriesRequest) (*registry.ArtifactoryList, error) { + return nil, fmt.Errorf("api error") + }), + } + ds := &artifactoriesDataSource{client: mockClient} + + resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}} + ds.Read(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected diagnostics on read API error") + } + }) + + t.Run("read 404 not found", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + ListArtifactoriesExecuteMock: new(func(_ registry.ApiListArtifactoriesRequest) (*registry.ArtifactoryList, error) { + return nil, &oapierror.GenericOpenAPIError{StatusCode: 404} + }), + } + ds := &artifactoriesDataSource{client: mockClient} + + resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}} + ds.Read(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected diagnostics on read 404") + } + }) +} diff --git a/stackit/internal/services/containerregistry/artifactory/datasource.go b/stackit/internal/services/containerregistry/artifactory/datasource.go new file mode 100644 index 000000000..6786a00e6 --- /dev/null +++ b/stackit/internal/services/containerregistry/artifactory/datasource.go @@ -0,0 +1,218 @@ +package artifactory + +import ( + "context" + "fmt" + "net/http" + "time" + + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" + + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core" + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils" + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate" +) + +var ( + _ datasource.DataSource = &artifactoryDataSource{} +) + +type DataSourceModel struct { + Id types.String `tfsdk:"id"` + ProjectId types.String `tfsdk:"project_id"` + Region types.String `tfsdk:"region"` + ArtifactoryId types.String `tfsdk:"artifactory_id"` + Name types.String `tfsdk:"name"` + CreateTime types.String `tfsdk:"create_time"` + State types.String `tfsdk:"state"` + Url types.String `tfsdk:"url"` + Proxy types.Object `tfsdk:"proxy"` +} + +type dsProxyModel struct { + Description types.String `tfsdk:"description"` + RegistryType types.String `tfsdk:"registry_type"` + Url types.String `tfsdk:"url"` +} + +var dsProxyTypes = map[string]attr.Type{ + "description": types.StringType, + "registry_type": types.StringType, + "url": types.StringType, +} + +func NewArtifactoryDataSource() datasource.DataSource { + return &artifactoryDataSource{} +} + +type artifactoryDataSource struct { + client registry.DefaultAPI + providerData core.ProviderData +} + +func (d *artifactoryDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_containerregistry_artifactory" +} + +func (d *artifactoryDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { + providerData, clients, ok := core.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) + if !ok { + return + } + + d.providerData = providerData + d.client = clients.ContainerRegistryV1Client + tflog.Info(ctx, "Container Registry client configured") +} + +func (d *artifactoryDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + Description: "Container registry artifactory data source schema.", + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + Description: descriptions["id"], + Computed: true, + }, + "project_id": schema.StringAttribute{ + Description: descriptions["project_id"], + Required: true, + Validators: []validator.String{ + validate.UUID(), + validate.NoSeparator(), + }, + }, + "region": schema.StringAttribute{ + Description: descriptions["region"], + Optional: true, + Computed: true, + }, + "artifactory_id": schema.StringAttribute{ + Description: descriptions["artifactory_id"], + Required: true, + Validators: []validator.String{ + validate.NoSeparator(), + }, + }, + "name": schema.StringAttribute{ + Description: descriptions["name"], + Computed: true, + }, + "create_time": schema.StringAttribute{ + Description: descriptions["create_time"], + Computed: true, + }, + "state": schema.StringAttribute{ + Description: descriptions["state"], + Computed: true, + }, + "url": schema.StringAttribute{ + Description: descriptions["url"], + Computed: true, + }, + "proxy": schema.SingleNestedAttribute{ + Description: descriptions["proxy"], + Computed: true, + Attributes: map[string]schema.Attribute{ + "registry_type": schema.StringAttribute{ + Description: descriptions["proxy.registry_type"], + Computed: true, + }, + "url": schema.StringAttribute{ + Description: descriptions["proxy.url"], + Computed: true, + }, + "description": schema.StringAttribute{ + Description: descriptions["proxy.description"], + Computed: true, + }, + }, + }, + }, + } +} + +func (d *artifactoryDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform + var model DataSourceModel + diags := req.Config.Get(ctx, &model) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + ctx = core.InitProviderContext(ctx) + + projectId := model.ProjectId.ValueString() + region := d.providerData.GetRegionWithOverride(model.Region) + artifactoryId := model.ArtifactoryId.ValueString() + ctx = tflog.SetField(ctx, "project_id", projectId) + ctx = tflog.SetField(ctx, "region", region) + ctx = tflog.SetField(ctx, "artifactory_id", artifactoryId) + + artifactory, err := d.client.GetArtifactory(ctx, projectId, region, artifactoryId).Execute() + if err != nil { + utils.LogError( + ctx, + &resp.Diagnostics, + err, + "Error reading artifactory", + fmt.Sprintf("Calling API: %v", err), + map[int]string{ + http.StatusNotFound: fmt.Sprintf("Artifactory %q not found", artifactoryId), + }, + ) + return + } + + ctx = core.LogResponse(ctx) + + err = mapDataSourceFields(ctx, artifactory, &model, region) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading artifactory", fmt.Sprintf("Mapping API response: %v", err)) + return + } + + diags = resp.State.Set(ctx, &model) + resp.Diagnostics.Append(diags...) + tflog.Info(ctx, "Container Registry artifactory read") +} + +func mapDataSourceFields(ctx context.Context, artifactory *registry.Artifactory, model *DataSourceModel, region string) error { + if artifactory == nil { + return fmt.Errorf("artifactory is nil") + } + if model == nil { + return fmt.Errorf("model is nil") + } + + model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, artifactory.Id) + model.Region = types.StringValue(region) + model.ArtifactoryId = types.StringValue(artifactory.Id) + model.Name = types.StringValue(artifactory.Name) + model.CreateTime = types.StringValue(artifactory.CreateTime.Format(time.RFC3339)) + model.State = types.StringValue(string(artifactory.State)) + model.Url = types.StringValue(artifactory.Url) + + if artifactory.Proxy == nil { + model.Proxy = types.ObjectNull(dsProxyTypes) + } else { + p := dsProxyModel{ + RegistryType: types.StringValue(artifactory.Proxy.RegistryType), + Url: types.StringValue(artifactory.Proxy.Url), + Description: types.StringPointerValue(artifactory.Proxy.Description), + } + + proxyObj, diags := types.ObjectValueFrom(ctx, dsProxyTypes, p) + if diags.HasError() { + return fmt.Errorf("mapping proxy: %w", core.DiagsToError(diags)) + } + model.Proxy = proxyObj + } + + return nil +} diff --git a/stackit/internal/services/containerregistry/artifactory/datasource_test.go b/stackit/internal/services/containerregistry/artifactory/datasource_test.go new file mode 100644 index 000000000..4a64c3c38 --- /dev/null +++ b/stackit/internal/services/containerregistry/artifactory/datasource_test.go @@ -0,0 +1,273 @@ +package artifactory + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/stackitcloud/stackit-sdk-go/core/oapierror" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" + + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core" +) + +func fixtureDataSourceModel(t *testing.T, mods ...func(model *DataSourceModel)) *DataSourceModel { + t.Helper() + model := &DataSourceModel{ + Id: types.StringValue("pid,reg,art-id-123"), + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Name: types.StringValue("my-artifactory"), + CreateTime: types.StringValue(testTime.Format(time.RFC3339)), + State: types.StringValue(string(registry.ARTIFACTORYSTATE_ACTIVE)), + Url: types.StringValue("https://art-id-123.cr.stackit.cloud"), + Proxy: types.ObjectNull(dsProxyTypes), + } + for _, mod := range mods { + mod(model) + } + return model +} + +func TestArtifactoryDataSource_Metadata(t *testing.T) { + ds := NewArtifactoryDataSource() + var resp datasource.MetadataResponse + ds.Metadata(context.Background(), datasource.MetadataRequest{ProviderTypeName: "stackit"}, &resp) + if resp.TypeName != "stackit_containerregistry_artifactory" { + t.Errorf("expected type name %q, got %q", "stackit_containerregistry_artifactory", resp.TypeName) + } +} + +func TestArtifactoryDataSource_Schema(t *testing.T) { + ds := NewArtifactoryDataSource() + var resp datasource.SchemaResponse + ds.Schema(context.Background(), datasource.SchemaRequest{}, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + if len(resp.Schema.Attributes) == 0 { + t.Errorf("expected non-empty schema attributes") + } +} + +func TestArtifactoryDataSource_Configure(t *testing.T) { + ds := &artifactoryDataSource{} + ctx := context.Background() + + t.Run("valid provider data", func(t *testing.T) { + providerData, err := core.NewProviderDataInternal(core.ProviderData{}, &core.MockClientFactory{}) + if err != nil { + t.Fatalf("unexpected error creating provider data: %v", err) + } + var resp datasource.ConfigureResponse + ds.Configure(ctx, datasource.ConfigureRequest{ProviderData: providerData}, &resp) + if resp.Diagnostics.HasError() { + t.Errorf("unexpected error diagnostics: %v", resp.Diagnostics) + } + if ds.client == nil { + t.Error("expected client to be configured") + } + }) + + t.Run("nil provider data", func(t *testing.T) { + var resp datasource.ConfigureResponse + ds.Configure(ctx, datasource.ConfigureRequest{ProviderData: nil}, &resp) + if resp.Diagnostics.HasError() { + t.Errorf("expected no error diagnostics on nil provider data, got %v", resp.Diagnostics) + } + }) + + t.Run("invalid provider data type", func(t *testing.T) { + var resp datasource.ConfigureResponse + ds.Configure(ctx, datasource.ConfigureRequest{ProviderData: "invalid"}, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error diagnostics on invalid provider data") + } + }) +} + +func TestMapDataSourceFields(t *testing.T) { + ctx := context.Background() + + tests := []struct { + description string + input *registry.Artifactory + expected *DataSourceModel + wantErr bool + }{ + { + description: "min values (no proxy)", + input: fixtureArtifactory(), + expected: fixtureDataSourceModel(t), + }, + { + description: "values with proxy", + input: fixtureArtifactory(func(art *registry.Artifactory) { + desc := "Docker Hub mirror" + art.Proxy = ®istry.Proxy{ + RegistryType: "docker-hub", + Url: "https://registry-1.docker.io", + Description: &desc, + } + }), + expected: fixtureDataSourceModel(t, func(model *DataSourceModel) { + proxyObj, diags := types.ObjectValueFrom(ctx, dsProxyTypes, dsProxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Description: types.StringValue("Docker Hub mirror"), + }) + if diags.HasError() { + t.Fatalf("unexpected diags creating proxy: %v", diags) + } + model.Proxy = proxyObj + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + model := &DataSourceModel{ + ProjectId: types.StringValue("pid"), + } + err := mapDataSourceFields(ctx, tt.input, model, "reg") + if (err != nil) != tt.wantErr { + t.Fatalf("mapDataSourceFields() error = %v, wantErr %v", err, tt.wantErr) + } + if diff := cmp.Diff(model, tt.expected); diff != "" { + t.Errorf("mapDataSourceFields() mismatch (-got +want):\n%s", diff) + } + }) + } +} + +func TestMapDataSourceFields_EdgeCases(t *testing.T) { + ctx := context.Background() + + t.Run("nil artifactory", func(t *testing.T) { + model := &DataSourceModel{ + ProjectId: types.StringValue("pid"), + } + err := mapDataSourceFields(ctx, nil, model, "reg") + if err == nil { + t.Error("expected error when artifactory is nil") + } + }) + + t.Run("nil model", func(t *testing.T) { + art := fixtureArtifactory() + err := mapDataSourceFields(ctx, art, nil, "reg") + if err == nil { + t.Error("expected error when model is nil") + } + }) +} + +func TestArtifactoryDataSource_Read(t *testing.T) { + ctx := context.Background() + dsBase := NewArtifactoryDataSource() + var schemaResp datasource.SchemaResponse + dsBase.Schema(ctx, datasource.SchemaRequest{}, &schemaResp) + + configAttrTypes := map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "artifactory_id": types.StringType, + "name": types.StringType, + "create_time": types.StringType, + "state": types.StringType, + "url": types.StringType, + "proxy": types.ObjectType{AttrTypes: dsProxyTypes}, + } + + configModel := DataSourceModel{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Id: types.StringNull(), + Name: types.StringNull(), + CreateTime: types.StringNull(), + State: types.StringNull(), + Url: types.StringNull(), + Proxy: types.ObjectNull(dsProxyTypes), + } + configVal, diags := types.ObjectValueFrom(ctx, configAttrTypes, configModel) + if diags.HasError() { + t.Fatalf("unexpected diags creating configVal: %v", diags) + } + rawVal, err := configVal.ToTerraformValue(ctx) + if err != nil { + t.Fatalf("unexpected error converting to terraform value: %v", err) + } + + req := datasource.ReadRequest{ + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + } + + t.Run("read success", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return fixtureArtifactory(), nil + }), + } + ds := &artifactoryDataSource{client: mockClient} + + resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}} + ds.Read(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + + var resultModel DataSourceModel + diags = resp.State.Get(ctx, &resultModel) + if diags.HasError() { + t.Fatalf("unexpected diags getting state: %v", diags) + } + if resultModel.Id.ValueString() != "pid,reg,art-id-123" { + t.Errorf("expected id 'pid,reg,art-id-123', got %q", resultModel.Id.ValueString()) + } + if resultModel.Name.ValueString() != "my-artifactory" { + t.Errorf("expected name 'my-artifactory', got %q", resultModel.Name.ValueString()) + } + }) + + t.Run("read API error", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return nil, fmt.Errorf("api error") + }), + } + ds := &artifactoryDataSource{client: mockClient} + + resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}} + ds.Read(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected diagnostics on read API error") + } + }) + + t.Run("read 404 not found", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return nil, &oapierror.GenericOpenAPIError{StatusCode: 404} + }), + } + ds := &artifactoryDataSource{client: mockClient} + + resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}} + ds.Read(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected diagnostics on read 404") + } + }) +} diff --git a/stackit/internal/services/containerregistry/artifactory/resource.go b/stackit/internal/services/containerregistry/artifactory/resource.go new file mode 100644 index 000000000..eab78ab0f --- /dev/null +++ b/stackit/internal/services/containerregistry/artifactory/resource.go @@ -0,0 +1,752 @@ +package artifactory + +import ( + "context" + "errors" + "fmt" + "net/http" + "regexp" + "strings" + "time" + + "github.com/hashicorp/terraform-plugin-framework-validators/int64validator" + "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator" + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" + "github.com/hashicorp/terraform-plugin-log/tflog" + "github.com/stackitcloud/stackit-sdk-go/core/oapierror" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" + "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api/wait" + + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core" + tfutils "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils" + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate" +) + +var ( + _ resource.Resource = &artifactoryResource{} + _ resource.ResourceWithConfigure = &artifactoryResource{} + _ resource.ResourceWithImportState = &artifactoryResource{} + _ resource.ResourceWithModifyPlan = &artifactoryResource{} +) + +type Model struct { + Id types.String `tfsdk:"id"` + ProjectId types.String `tfsdk:"project_id"` + Region types.String `tfsdk:"region"` + ArtifactoryId types.String `tfsdk:"artifactory_id"` + Name types.String `tfsdk:"name"` + CreateTime types.String `tfsdk:"create_time"` + State types.String `tfsdk:"state"` + Url types.String `tfsdk:"url"` + Proxy types.Object `tfsdk:"proxy"` +} + +type proxyModel struct { + Description types.String `tfsdk:"description"` + RegistryType types.String `tfsdk:"registry_type"` + Url types.String `tfsdk:"url"` + Credentials types.Object `tfsdk:"credentials"` +} + +type credentialsModel struct { + AccessKey types.String `tfsdk:"access_key"` + AccessSecret types.String `tfsdk:"access_secret"` + AccessSecretWo types.String `tfsdk:"access_secret_wo"` + AccessSecretWoVersion types.Int64 `tfsdk:"access_secret_wo_version"` +} + +var credentialsTypes = map[string]attr.Type{ + "access_key": types.StringType, + "access_secret": types.StringType, + "access_secret_wo": types.StringType, + "access_secret_wo_version": types.Int64Type, +} + +var proxyTypes = map[string]attr.Type{ + "description": types.StringType, + "registry_type": types.StringType, + "url": types.StringType, + "credentials": types.ObjectType{AttrTypes: credentialsTypes}, +} + +var descriptions = map[string]string{ //nolint:gosec // linter false positive + + "id": "Terraform's internal resource ID, structured as `project_id`,`region`,`artifactory_id`.", + + "project_id": "STACKIT project ID to which the container registry artifactory is associated.", + + "region": "STACKIT region where the container registry artifactory is located. If not defined, the provider default_region is used.", + + "artifactory_id": "The unique identifier of the container registry artifactory.", + + "name": "A user-chosen name to distinguish multiple STACKIT artifactories.", + + "create_time": "The date and time the creation of the STACKIT artifactory was triggered.", + + "state": "The current state of the STACKIT artifactory.", + + "url": "The base URL of the STACKIT artifactory.", + + "proxy": "Proxy configuration if this artifactory is created as a proxy-cache for an upstream registry.", + + "proxy.registry_type": "Which replication adapter to use for this registry.", + + "proxy.url": "Upstream registry URL to proxy.", + + "proxy.description": "Description of the upstream registry.", + + "proxy.credentials": "Credentials for the upstream registry.", + + "proxy.credentials.access_key": "Access key or username for the upstream registry.", + + "proxy.credentials.access_secret": "Access secret or password for the upstream registry. Write-only argument `access_secret_wo` should be preferred.", + + "proxy.credentials.access_secret_wo": "Write-only access secret or password for the upstream registry - never stored in state and never returned by the API. To rotate the secret, update this value AND increment `access_secret_wo_version`. Changing this field alone will NOT trigger an update.", + + "proxy.credentials.access_secret_wo_version": "User-managed rotation counter for `access_secret_wo`. Must be incremented every time `access_secret_wo` is updated.", +} + +func NewArtifactoryResource() resource.Resource { + return &artifactoryResource{} +} + +type artifactoryResource struct { + client registry.DefaultAPI + + providerData core.ProviderData +} + +// ModifyPlan implements resource.ResourceWithModifyPlan. + +func (r *artifactoryResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) { // nolint:gocritic // function signature required by Terraform + var configModel Model + + if req.Config.Raw.IsNull() { + return + } + + resp.Diagnostics.Append(req.Config.Get(ctx, &configModel)...) + + if resp.Diagnostics.HasError() { + return + } + + var planModel Model + + resp.Diagnostics.Append(req.Plan.Get(ctx, &planModel)...) + + if resp.Diagnostics.HasError() { + return + } + + tfutils.AdaptRegion(ctx, configModel.Region, &planModel.Region, r.providerData.GetRegion(), resp) + + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(resp.Plan.Set(ctx, planModel)...) + + if resp.Diagnostics.HasError() { + return + } +} + +func (r *artifactoryResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_containerregistry_artifactory" +} + +func (r *artifactoryResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + providerData, clients, ok := core.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) + if !ok { + return + } + + r.providerData = providerData + r.client = clients.ContainerRegistryV1Client + tflog.Info(ctx, "Container Registry client configured") +} + +func (r *artifactoryResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + Description: "Container registry artifactory resource schema.", + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + Description: descriptions["id"], + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "project_id": schema.StringAttribute{ + Description: descriptions["project_id"], + Required: true, + Validators: []validator.String{ + validate.UUID(), + validate.NoSeparator(), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "region": schema.StringAttribute{ + Description: descriptions["region"], + Optional: true, + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "artifactory_id": schema.StringAttribute{ + Description: descriptions["artifactory_id"], + Computed: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.UseStateForUnknown(), + }, + }, + "name": schema.StringAttribute{ + Description: descriptions["name"], + Required: true, + Validators: []validator.String{ + stringvalidator.RegexMatches( + regexp.MustCompile(`^[a-z0-9]+(?:[._-][a-z0-9]+)*$`), + "Must consist of lowercase alphanumeric characters, optionally separated by single '.', '_', or '-' characters.", + ), + }, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "create_time": schema.StringAttribute{ + Description: descriptions["create_time"], + Computed: true, + }, + "state": schema.StringAttribute{ + Description: descriptions["state"], + Computed: true, + }, + "url": schema.StringAttribute{ + Description: descriptions["url"], + Computed: true, + }, + "proxy": schema.SingleNestedAttribute{ + Description: descriptions["proxy"], + Optional: true, + Attributes: map[string]schema.Attribute{ + "registry_type": schema.StringAttribute{ + Description: descriptions["proxy.registry_type"], + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplace(), + }, + }, + "url": schema.StringAttribute{ + Description: descriptions["proxy.url"], + Required: true, + }, + "description": schema.StringAttribute{ + Description: descriptions["proxy.description"], + Optional: true, + }, + "credentials": schema.SingleNestedAttribute{ + Description: descriptions["proxy.credentials"], + Optional: true, + Attributes: map[string]schema.Attribute{ + "access_key": schema.StringAttribute{ + Description: descriptions["proxy.credentials.access_key"], + Required: true, + }, + "access_secret": schema.StringAttribute{ + Description: descriptions["proxy.credentials.access_secret"], + Optional: true, + Sensitive: true, + Validators: []validator.String{ + stringvalidator.ConflictsWith( + path.MatchRelative().AtParent().AtName("access_secret_wo"), + path.MatchRelative().AtParent().AtName("access_secret_wo_version"), + ), + stringvalidator.PreferWriteOnlyAttribute( + path.MatchRoot("proxy").AtName("credentials").AtName("access_secret_wo"), + ), + }, + }, + "access_secret_wo": schema.StringAttribute{ + Description: descriptions["proxy.credentials.access_secret_wo"], + Optional: true, + WriteOnly: true, + Sensitive: true, + Validators: []validator.String{ + stringvalidator.ConflictsWith(path.MatchRelative().AtParent().AtName("access_secret")), + stringvalidator.AlsoRequires(path.MatchRelative().AtParent().AtName("access_secret_wo_version")), + }, + }, + "access_secret_wo_version": schema.Int64Attribute{ + Description: descriptions["proxy.credentials.access_secret_wo_version"], + Optional: true, + Validators: []validator.Int64{ + int64validator.AlsoRequires(path.MatchRelative().AtParent().AtName("access_secret_wo")), + int64validator.ConflictsWith(path.MatchRelative().AtParent().AtName("access_secret")), + }, + }, + }, + }, + }, + }, + }, + } +} + +func (r *artifactoryResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { // nolint:gocritic // function signature required by Terraform + var model Model + diags := req.Plan.Get(ctx, &model) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + var configModel Model + if req.Config.Schema != nil && req.Config.Raw.Type() != nil { + diags = req.Config.Get(ctx, &configModel) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + } + + ctx = core.InitProviderContext(ctx) + + projectId := model.ProjectId.ValueString() + region := r.providerData.GetRegionWithOverride(model.Region) + ctx = tflog.SetField(ctx, "project_id", projectId) + ctx = tflog.SetField(ctx, "region", region) + + payload, err := toCreatePayload(ctx, &model, &configModel) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating artifactory", fmt.Sprintf("Creating API payload: %v", err)) + return + } + + createResp, err := r.client.CreateArtifactory(ctx, projectId, region).CreateArtifactoryPayload(*payload).Execute() + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating artifactory", fmt.Sprintf("Calling API: %v", err)) + return + } + + ctx = core.LogResponse(ctx) + + if createResp == nil || createResp.Id == "" { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating artifactory", "Create API response: Incomplete response (id missing)") + return + } + + artifactoryId := createResp.Id + ctx = tfutils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{ + "project_id": projectId, + "region": region, + "artifactory_id": artifactoryId, + }) + if resp.Diagnostics.HasError() { + return + } + + waitResp, err := wait.CreateArtifactoryWaitHandler(ctx, r.client, projectId, region, artifactoryId).WaitWithContext(ctx) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating artifactory", fmt.Sprintf("Waiting for artifactory to be ready: %v", err)) + return + } + + err = mapFields(ctx, waitResp, &model, region) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error creating artifactory", fmt.Sprintf("Mapping API response: %v", err)) + return + } + + diags = resp.State.Set(ctx, &model) + resp.Diagnostics.Append(diags...) + tflog.Info(ctx, "Container Registry artifactory created") +} + +func (r *artifactoryResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { // nolint:gocritic // function signature required by Terraform + var model Model + diags := req.State.Get(ctx, &model) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + ctx = core.InitProviderContext(ctx) + + projectId := model.ProjectId.ValueString() + region := r.providerData.GetRegionWithOverride(model.Region) + artifactoryId := model.ArtifactoryId.ValueString() + ctx = tflog.SetField(ctx, "project_id", projectId) + ctx = tflog.SetField(ctx, "region", region) + ctx = tflog.SetField(ctx, "artifactory_id", artifactoryId) + + artifactory, err := r.client.GetArtifactory(ctx, projectId, region, artifactoryId).Execute() + if err != nil { + var oapiErr *oapierror.GenericOpenAPIError + if errors.As(err, &oapiErr) && oapiErr.StatusCode == http.StatusNotFound { + resp.State.RemoveResource(ctx) + return + } + core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading artifactory", fmt.Sprintf("Calling API: %v", err)) + return + } + + ctx = core.LogResponse(ctx) + + if artifactory.State == registry.ARTIFACTORYSTATE_DELETED { + resp.State.RemoveResource(ctx) + return + } + + err = mapFields(ctx, artifactory, &model, region) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading artifactory", fmt.Sprintf("Mapping API response: %v", err)) + return + } + + diags = resp.State.Set(ctx, &model) + resp.Diagnostics.Append(diags...) + tflog.Info(ctx, "Container Registry artifactory read") +} + +func (r *artifactoryResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { // nolint:gocritic // function signature required by Terraform + var plan Model + diags := req.Plan.Get(ctx, &plan) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + var state Model + if req.State.Schema != nil && req.State.Raw.Type() != nil { + diags = req.State.Get(ctx, &state) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + } + + var configModel Model + if req.Config.Schema != nil && req.Config.Raw.Type() != nil { + diags = req.Config.Get(ctx, &configModel) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + } + + ctx = core.InitProviderContext(ctx) + + projectId := plan.ProjectId.ValueString() + region := r.providerData.GetRegionWithOverride(plan.Region) + artifactoryId := plan.ArtifactoryId.ValueString() + ctx = tflog.SetField(ctx, "project_id", projectId) + ctx = tflog.SetField(ctx, "region", region) + ctx = tflog.SetField(ctx, "artifactory_id", artifactoryId) + + payload, err := toUpdatePayload(ctx, &plan, &state, &configModel) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating artifactory", fmt.Sprintf("Creating API payload: %v", err)) + return + } + + _, err = r.client.PatchArtifactory(ctx, projectId, region, artifactoryId).PatchArtifactoryPayload(*payload).Execute() + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating artifactory", fmt.Sprintf("Calling API: %v", err)) + return + } + + ctx = core.LogResponse(ctx) + + waitResp, err := wait.UpdateArtifactoryWaitHandler(ctx, r.client, projectId, region, artifactoryId).WaitWithContext(ctx) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating artifactory", fmt.Sprintf("Waiting for artifactory update: %v", err)) + return + } + + err = mapFields(ctx, waitResp, &plan, region) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error updating artifactory", fmt.Sprintf("Mapping API response: %v", err)) + return + } + + diags = resp.State.Set(ctx, &plan) + resp.Diagnostics.Append(diags...) + tflog.Info(ctx, "Container Registry artifactory updated") +} + +func (r *artifactoryResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { // nolint:gocritic // function signature required by Terraform + var model Model + diags := req.State.Get(ctx, &model) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + ctx = core.InitProviderContext(ctx) + + projectId := model.ProjectId.ValueString() + region := r.providerData.GetRegionWithOverride(model.Region) + artifactoryId := model.ArtifactoryId.ValueString() + ctx = tflog.SetField(ctx, "project_id", projectId) + ctx = tflog.SetField(ctx, "region", region) + ctx = tflog.SetField(ctx, "artifactory_id", artifactoryId) + + err := r.client.DeleteArtifactory(ctx, projectId, region, artifactoryId).Execute() + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting artifactory", fmt.Sprintf("Calling API: %v", err)) + return + } + + ctx = core.LogResponse(ctx) + + _, err = wait.DeleteArtifactoryWaitHandler(ctx, r.client, projectId, region, artifactoryId).WaitWithContext(ctx) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error deleting artifactory", fmt.Sprintf("Waiting for artifactory to be deleted: %v", err)) + return + } + + tflog.Info(ctx, "Container Registry artifactory deleted") +} + +func (r *artifactoryResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + idParts := strings.Split(req.ID, core.Separator) + if len(idParts) != 3 || idParts[0] == "" || idParts[1] == "" || idParts[2] == "" { + core.LogAndAddError(ctx, &resp.Diagnostics, + "Error importing artifactory", + fmt.Sprintf("Expected import identifier with format: [project_id],[region],[artifactory_id] Got: %q", req.ID), + ) + return + } + + ctx = tfutils.SetAndLogStateFields(ctx, &resp.Diagnostics, &resp.State, map[string]any{ + "project_id": idParts[0], + "region": idParts[1], + "artifactory_id": idParts[2], + }) + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...) + tflog.Info(ctx, "Container Registry artifactory state imported") +} + +func toCreatePayload(ctx context.Context, model, configModel *Model) (*registry.CreateArtifactoryPayload, error) { + if model == nil { + return nil, fmt.Errorf("model input is nil") + } + + payload := registry.NewCreateArtifactoryPayload(model.Name.ValueString()) + + if !model.Proxy.IsNull() && !model.Proxy.IsUnknown() { + var p proxyModel + diags := model.Proxy.As(ctx, &p, basetypes.ObjectAsOptions{}) + if diags.HasError() { + return nil, fmt.Errorf("converting proxy object: %v", diags.Errors()) + } + + proxyReq := registry.NewCreateProxyRequest(p.RegistryType.ValueString(), p.Url.ValueString()) + if !p.Description.IsNull() && !p.Description.IsUnknown() { + proxyReq.SetDescription(p.Description.ValueString()) + } + + if !p.Credentials.IsNull() && !p.Credentials.IsUnknown() { + var creds credentialsModel + diags := p.Credentials.As(ctx, &creds, basetypes.ObjectAsOptions{}) + if diags.HasError() { + return nil, fmt.Errorf("converting credentials object: %v", diags.Errors()) + } + + var configCreds *credentialsModel + if configModel != nil && !configModel.Proxy.IsNull() && !configModel.Proxy.IsUnknown() { + var cp proxyModel + if d := configModel.Proxy.As(ctx, &cp, basetypes.ObjectAsOptions{}); !d.HasError() && !cp.Credentials.IsNull() && !cp.Credentials.IsUnknown() { + var cc credentialsModel + if d2 := cp.Credentials.As(ctx, &cc, basetypes.ObjectAsOptions{}); !d2.HasError() { + configCreds = &cc + } + } + } + + secret := getAccessSecret(&creds, nil, configCreds, false) + if secret == nil { + return nil, fmt.Errorf("either access_secret or access_secret_wo must be provided in proxy.credentials") + } + + proxyReq.SetCredentials(*registry.NewCredentials(creds.AccessKey.ValueString(), *secret)) + } + + payload.SetProxy(*proxyReq) + } + + return payload, nil +} + +func toUpdatePayload(ctx context.Context, model, stateModel, configModel *Model) (*registry.PatchArtifactoryPayload, error) { + if model == nil { + return nil, fmt.Errorf("model input is nil") + } + + payload := registry.NewPatchArtifactoryPayload() + + if !model.Proxy.IsNull() && !model.Proxy.IsUnknown() { + var p proxyModel + diags := model.Proxy.As(ctx, &p, basetypes.ObjectAsOptions{}) + if diags.HasError() { + return nil, fmt.Errorf("converting proxy object: %v", diags.Errors()) + } + + updateProxyReq := registry.NewUpdateProxyRequest() + if !p.Url.IsNull() && !p.Url.IsUnknown() { + updateProxyReq.SetUrl(p.Url.ValueString()) + } + if !p.Description.IsNull() && !p.Description.IsUnknown() { + updateProxyReq.SetDescription(p.Description.ValueString()) + } + + if !p.Credentials.IsNull() && !p.Credentials.IsUnknown() { + var creds credentialsModel + diags := p.Credentials.As(ctx, &creds, basetypes.ObjectAsOptions{}) + if diags.HasError() { + return nil, fmt.Errorf("converting credentials object: %v", diags.Errors()) + } + + var stateCreds *credentialsModel + if stateModel != nil && !stateModel.Proxy.IsNull() && !stateModel.Proxy.IsUnknown() { + var sp proxyModel + if d := stateModel.Proxy.As(ctx, &sp, basetypes.ObjectAsOptions{}); !d.HasError() && !sp.Credentials.IsNull() && !sp.Credentials.IsUnknown() { + var sc credentialsModel + if d2 := sp.Credentials.As(ctx, &sc, basetypes.ObjectAsOptions{}); !d2.HasError() { + stateCreds = &sc + } + } + } + + var configCreds *credentialsModel + if configModel != nil && !configModel.Proxy.IsNull() && !configModel.Proxy.IsUnknown() { + var cp proxyModel + if d := configModel.Proxy.As(ctx, &cp, basetypes.ObjectAsOptions{}); !d.HasError() && !cp.Credentials.IsNull() && !cp.Credentials.IsUnknown() { + var cc credentialsModel + if d2 := cp.Credentials.As(ctx, &cc, basetypes.ObjectAsOptions{}); !d2.HasError() { + configCreds = &cc + } + } + } + + secret := getAccessSecret(&creds, stateCreds, configCreds, true) + if secret != nil { + updateProxyReq.SetCredentials(*registry.NewCredentials(creds.AccessKey.ValueString(), *secret)) + } + } + + payload.SetProxy(*updateProxyReq) + } + + return payload, nil +} + +func getAccessSecret(planCreds, stateCreds, configCreds *credentialsModel, isUpdate bool) *string { + if planCreds == nil { + return nil + } + // 1. Legacy field + if !planCreds.AccessSecret.IsNull() && !planCreds.AccessSecret.IsUnknown() { + return planCreds.AccessSecret.ValueStringPointer() + } + // 2. Write-only field + if configCreds != nil && !configCreds.AccessSecretWo.IsNull() && !configCreds.AccessSecretWo.IsUnknown() { + if !isUpdate { + return configCreds.AccessSecretWo.ValueStringPointer() + } + // On update, only send if version was bumped (or previously not set) + if stateCreds == nil || !planCreds.AccessSecretWoVersion.Equal(stateCreds.AccessSecretWoVersion) { + return configCreds.AccessSecretWo.ValueStringPointer() + } + } + return nil +} + +func mapFields(ctx context.Context, artifactory *registry.Artifactory, model *Model, region string) error { + if artifactory == nil { + return fmt.Errorf("artifactory is nil") + } + if model == nil { + return fmt.Errorf("model is nil") + } + + var artifactoryId string + if model.ArtifactoryId.ValueString() != "" { + artifactoryId = model.ArtifactoryId.ValueString() + } else if artifactory.Id != "" { + artifactoryId = artifactory.Id + } else { + return fmt.Errorf("artifactory id not present") + } + + model.Id = tfutils.BuildInternalTerraformId(model.ProjectId.ValueString(), region, artifactoryId) + model.Region = types.StringValue(region) + model.ArtifactoryId = types.StringValue(artifactoryId) + model.Name = types.StringValue(artifactory.Name) + model.CreateTime = types.StringValue(artifactory.CreateTime.Format(time.RFC3339)) + model.State = types.StringValue(string(artifactory.State)) + model.Url = types.StringValue(artifactory.Url) + + if artifactory.Proxy == nil { + model.Proxy = types.ObjectNull(proxyTypes) + } else { + var p proxyModel + if !model.Proxy.IsNull() && !model.Proxy.IsUnknown() { + diags := model.Proxy.As(ctx, &p, basetypes.ObjectAsOptions{UnhandledNullAsEmpty: true}) + if diags.HasError() { + return fmt.Errorf("converting proxy object: %v", diags.Errors()) + } + } + + p.RegistryType = types.StringValue(artifactory.Proxy.RegistryType) + p.Url = types.StringValue(artifactory.Proxy.Url) + p.Description = types.StringPointerValue(artifactory.Proxy.Description) + + if artifactory.Proxy.Credentials == nil { + p.Credentials = types.ObjectNull(credentialsTypes) + } else { + var creds credentialsModel + if !p.Credentials.IsNull() && !p.Credentials.IsUnknown() { + diags := p.Credentials.As(ctx, &creds, basetypes.ObjectAsOptions{UnhandledNullAsEmpty: true}) + if diags.HasError() { + return fmt.Errorf("converting credentials object: %v", diags.Errors()) + } + } + + creds.AccessKey = types.StringValue(artifactory.Proxy.Credentials.AccessKey) + if tfutils.IsUndefined(creds.AccessSecret) { + creds.AccessSecret = types.StringNull() + } + creds.AccessSecretWo = types.StringNull() + if tfutils.IsUndefined(creds.AccessSecretWoVersion) { + creds.AccessSecretWoVersion = types.Int64Null() + } + + credsObj, diags := types.ObjectValueFrom(ctx, credentialsTypes, creds) + if diags.HasError() { + return fmt.Errorf("mapping credentials: %w", core.DiagsToError(diags)) + } + p.Credentials = credsObj + } + + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, p) + if diags.HasError() { + return fmt.Errorf("mapping proxy: %w", core.DiagsToError(diags)) + } + model.Proxy = proxyObj + } + + return nil +} diff --git a/stackit/internal/services/containerregistry/artifactory/resource_test.go b/stackit/internal/services/containerregistry/artifactory/resource_test.go new file mode 100644 index 000000000..d3e8fc34a --- /dev/null +++ b/stackit/internal/services/containerregistry/artifactory/resource_test.go @@ -0,0 +1,1343 @@ +package artifactory + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" + "github.com/hashicorp/terraform-plugin-go/tftypes" + "github.com/stackitcloud/stackit-sdk-go/core/oapierror" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" + + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core" +) + +var testTime = time.Now() + +func fixtureArtifactory(mods ...func(art *registry.Artifactory)) *registry.Artifactory { + art := ®istry.Artifactory{ + Id: "art-id-123", + Name: "my-artifactory", + ConsumedQuotaBytes: 1024, + CreateTime: testTime, + State: registry.ARTIFACTORYSTATE_ACTIVE, + Url: "https://art-id-123.cr.stackit.cloud", + } + for _, mod := range mods { + mod(art) + } + return art +} + +func fixtureModel(t *testing.T, mods ...func(model *Model)) *Model { + t.Helper() + model := &Model{ + Id: types.StringValue("pid,reg,art-id-123"), + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Name: types.StringValue("my-artifactory"), + CreateTime: types.StringValue(testTime.Format(time.RFC3339)), + State: types.StringValue(string(registry.ARTIFACTORYSTATE_ACTIVE)), + Url: types.StringValue("https://art-id-123.cr.stackit.cloud"), + Proxy: types.ObjectNull(proxyTypes), + } + for _, mod := range mods { + mod(model) + } + return model +} + +func TestMapFields(t *testing.T) { + ctx := context.Background() + + tests := []struct { + description string + input *registry.Artifactory + expected *Model + wantErr bool + }{ + { + description: "min values (no proxy)", + input: fixtureArtifactory(), + expected: fixtureModel(t), + }, + { + description: "max values (with proxy and credentials)", + input: fixtureArtifactory(func(art *registry.Artifactory) { + desc := "Docker Hub mirror" + art.Proxy = ®istry.Proxy{ + RegistryType: "docker-hub", + Url: "https://registry-1.docker.io", + Description: &desc, + Credentials: ®istry.RedactedCredentials{ + AccessKey: "test-user", + }, + } + }), + expected: fixtureModel(t, func(model *Model) { + credsObj, diags := types.ObjectValueFrom(ctx, credentialsTypes, credentialsModel{ + AccessKey: types.StringValue("test-user"), + AccessSecret: types.StringNull(), + }) + if diags.HasError() { + t.Fatalf("unexpected diags creating creds: %v", diags) + } + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Description: types.StringValue("Docker Hub mirror"), + Credentials: credsObj, + }) + if diags.HasError() { + t.Fatalf("unexpected diags creating proxy: %v", diags) + } + model.Proxy = proxyObj + }), + }, + } + + for _, tt := range tests { + t.Run(tt.description, func(t *testing.T) { + model := &Model{ + ProjectId: types.StringValue("pid"), + } + err := mapFields(ctx, tt.input, model, "reg") + if (err != nil) != tt.wantErr { + t.Fatalf("mapFields() error = %v, wantErr %v", err, tt.wantErr) + } + if diff := cmp.Diff(model, tt.expected); diff != "" { + t.Errorf("mapFields() mismatch (-got +want):\n%s", diff) + } + }) + } +} + +func TestToCreatePayload(t *testing.T) { + ctx := context.Background() + + t.Run("without proxy", func(t *testing.T) { + model := &Model{ + Name: types.StringValue("my-artifactory"), + Proxy: types.ObjectNull(proxyTypes), + } + + payload, err := toCreatePayload(ctx, model, model) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if payload.Name != "my-artifactory" { + t.Errorf("expected name %q, got %q", "my-artifactory", payload.Name) + } + if payload.Proxy != nil { + t.Errorf("expected proxy to be nil, got %v", payload.Proxy) + } + }) + + t.Run("with proxy and credentials", func(t *testing.T) { + credsObj, diags := types.ObjectValueFrom(ctx, credentialsTypes, credentialsModel{ + AccessKey: types.StringValue("user"), + AccessSecret: types.StringValue("secret"), + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Description: types.StringValue("Docker Hub mirror"), + Credentials: credsObj, + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + + model := &Model{ + Name: types.StringValue("my-artifactory"), + Proxy: proxyObj, + } + + payload, err := toCreatePayload(ctx, model, model) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if payload.Proxy == nil { + t.Fatal("expected proxy to not be nil") + } + if payload.Proxy.RegistryType != "docker-hub" { + t.Errorf("expected registry_type docker-hub, got %q", payload.Proxy.RegistryType) + } + if payload.Proxy.Url != "https://registry-1.docker.io" { + t.Errorf("expected url https://registry-1.docker.io, got %q", payload.Proxy.Url) + } + if payload.Proxy.Description == nil || *payload.Proxy.Description != "Docker Hub mirror" { + t.Errorf("expected description 'Docker Hub mirror', got %v", payload.Proxy.Description) + } + if payload.Proxy.Credentials == nil || payload.Proxy.Credentials.AccessKey != "user" || payload.Proxy.Credentials.AccessSecret != "secret" { + t.Errorf("expected credentials user/secret, got %v", payload.Proxy.Credentials) + } + }) + + t.Run("with proxy and write-only credentials", func(t *testing.T) { + credsObj, diags := types.ObjectValueFrom(ctx, credentialsTypes, credentialsModel{ + AccessKey: types.StringValue("user"), + AccessSecret: types.StringNull(), + AccessSecretWo: types.StringValue("wo-secret"), + AccessSecretWoVersion: types.Int64Value(1), + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Description: types.StringValue("Docker Hub mirror"), + Credentials: credsObj, + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + + model := &Model{ + Name: types.StringValue("my-artifactory"), + Proxy: proxyObj, + } + + payload, err := toCreatePayload(ctx, model, model) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if payload.Proxy == nil || payload.Proxy.Credentials == nil || payload.Proxy.Credentials.AccessSecret != "wo-secret" { + t.Errorf("expected access_secret 'wo-secret', got %v", payload.Proxy) + } + }) +} + +func TestToUpdatePayload(t *testing.T) { + ctx := context.Background() + + t.Run("without proxy", func(t *testing.T) { + model := &Model{ + Proxy: types.ObjectNull(proxyTypes), + } + + payload, err := toUpdatePayload(ctx, model, nil, model) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if payload.Proxy != nil { + t.Errorf("expected proxy to be nil, got %v", payload.Proxy) + } + }) + + t.Run("with proxy and credentials", func(t *testing.T) { + credsObj, diags := types.ObjectValueFrom(ctx, credentialsTypes, credentialsModel{ + AccessKey: types.StringValue("updated-user"), + AccessSecret: types.StringValue("updated-secret"), + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-2.docker.io"), + Description: types.StringValue("Updated description"), + Credentials: credsObj, + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + + model := &Model{ + Proxy: proxyObj, + } + + payload, err := toUpdatePayload(ctx, model, nil, model) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if payload.Proxy == nil { + t.Fatal("expected proxy to not be nil") + } + if payload.Proxy.Url == nil || *payload.Proxy.Url != "https://registry-2.docker.io" { + t.Errorf("expected url https://registry-2.docker.io, got %v", payload.Proxy.Url) + } + if payload.Proxy.Description == nil || *payload.Proxy.Description != "Updated description" { + t.Errorf("expected description 'Updated description', got %v", payload.Proxy.Description) + } + if payload.Proxy.Credentials == nil || payload.Proxy.Credentials.AccessKey != "updated-user" || payload.Proxy.Credentials.AccessSecret != "updated-secret" { + t.Errorf("expected credentials updated-user/updated-secret, got %v", payload.Proxy.Credentials) + } + }) + + t.Run("with proxy, stateModel, and configModel write-only rotation", func(t *testing.T) { + // state: old version 1 + stateCredsObj, diags := types.ObjectValueFrom(ctx, credentialsTypes, credentialsModel{ + AccessKey: types.StringValue("user"), + AccessSecret: types.StringNull(), + AccessSecretWo: types.StringNull(), + AccessSecretWoVersion: types.Int64Value(1), + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + stateProxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Credentials: stateCredsObj, + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + stateModel := &Model{Proxy: stateProxyObj} + + // plan: bumped version 2 + planCredsObj, diags := types.ObjectValueFrom(ctx, credentialsTypes, credentialsModel{ + AccessKey: types.StringValue("user"), + AccessSecret: types.StringNull(), + AccessSecretWo: types.StringNull(), + AccessSecretWoVersion: types.Int64Value(2), + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + planProxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Credentials: planCredsObj, + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + planModel := &Model{Proxy: planProxyObj} + + // config: write-only secret provided + configCredsObj, diags := types.ObjectValueFrom(ctx, credentialsTypes, credentialsModel{ + AccessKey: types.StringValue("user"), + AccessSecret: types.StringNull(), + AccessSecretWo: types.StringValue("new-wo-secret"), + AccessSecretWoVersion: types.Int64Value(2), + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + configProxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Credentials: configCredsObj, + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + configModel := &Model{Proxy: configProxyObj} + + payload, err := toUpdatePayload(ctx, planModel, stateModel, configModel) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if payload.Proxy == nil || payload.Proxy.Credentials == nil || payload.Proxy.Credentials.AccessSecret != "new-wo-secret" { + t.Errorf("expected access_secret 'new-wo-secret', got %v", payload.Proxy) + } + }) +} + +func TestNewArtifactoryResource(t *testing.T) { + r := NewArtifactoryResource() + if r == nil { + t.Fatal("expected non-nil resource") + } +} + +func TestArtifactoryResource_ModifyPlan(t *testing.T) { + ctx := context.Background() + r := &artifactoryResource{ + providerData: core.ProviderData{}, + } + var schemaResp resource.SchemaResponse + r.Schema(ctx, resource.SchemaRequest{}, &schemaResp) + + t.Run("raw is null", func(t *testing.T) { + req := resource.ModifyPlanRequest{ + Config: tfsdk.Config{ + Raw: tftypes.NewValue(tftypes.String, nil), + }, + } + var resp resource.ModifyPlanResponse + r.ModifyPlan(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + }) + + t.Run("adapt region from provider data", func(t *testing.T) { + rWithRegion := &artifactoryResource{ + providerData: core.ProviderData{ + DefaultRegion: "eu01", + }, + } + configModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringNull(), + Name: types.StringValue("name"), + Proxy: types.ObjectNull(proxyTypes), + } + configVal, _ := types.ObjectValueFrom(ctx, map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "artifactory_id": types.StringType, + "name": types.StringType, + "create_time": types.StringType, + "state": types.StringType, + "url": types.StringType, + "proxy": types.ObjectType{AttrTypes: proxyTypes}, + }, configModel) + rawVal, _ := configVal.ToTerraformValue(ctx) + + planModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringNull(), + Name: types.StringValue("name"), + Proxy: types.ObjectNull(proxyTypes), + } + plan := tfsdk.Plan{Schema: schemaResp.Schema} + _ = plan.Set(ctx, planModel) + + req := resource.ModifyPlanRequest{ + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + Plan: plan, + } + resp := resource.ModifyPlanResponse{ + Plan: plan, + } + rWithRegion.ModifyPlan(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + + var updatedPlan Model + _ = resp.Plan.Get(ctx, &updatedPlan) + if updatedPlan.Region.ValueString() != "eu01" { + t.Errorf("expected adapted region 'eu01', got %q", updatedPlan.Region.ValueString()) + } + }) +} + +func TestArtifactoryResource_Metadata(t *testing.T) { + r := NewArtifactoryResource() + var resp resource.MetadataResponse + r.Metadata(context.Background(), resource.MetadataRequest{ProviderTypeName: "stackit"}, &resp) + if resp.TypeName != "stackit_containerregistry_artifactory" { + t.Errorf("expected type name %q, got %q", "stackit_containerregistry_artifactory", resp.TypeName) + } +} + +func TestArtifactoryResource_Schema(t *testing.T) { + r := NewArtifactoryResource() + var resp resource.SchemaResponse + r.Schema(context.Background(), resource.SchemaRequest{}, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + if len(resp.Schema.Attributes) == 0 { + t.Errorf("expected non-empty schema attributes") + } +} + +func TestArtifactoryResource_Configure(t *testing.T) { + r := &artifactoryResource{} + ctx := context.Background() + + t.Run("valid provider data", func(t *testing.T) { + providerData, err := core.NewProviderDataInternal(core.ProviderData{}, &core.MockClientFactory{}) + if err != nil { + t.Fatalf("unexpected error creating provider data: %v", err) + } + var resp resource.ConfigureResponse + r.Configure(ctx, resource.ConfigureRequest{ProviderData: providerData}, &resp) + if resp.Diagnostics.HasError() { + t.Errorf("unexpected error diagnostics: %v", resp.Diagnostics) + } + if r.client == nil { + t.Error("expected client to be configured") + } + }) + + t.Run("nil provider data", func(t *testing.T) { + var resp resource.ConfigureResponse + r.Configure(ctx, resource.ConfigureRequest{ProviderData: nil}, &resp) + if resp.Diagnostics.HasError() { + t.Errorf("expected no error diagnostics on nil provider data, got %v", resp.Diagnostics) + } + }) + + t.Run("invalid provider data type", func(t *testing.T) { + var resp resource.ConfigureResponse + r.Configure(ctx, resource.ConfigureRequest{ProviderData: "invalid"}, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error diagnostics on invalid provider data") + } + }) +} + +func TestMapFields_EdgeCases(t *testing.T) { + ctx := context.Background() + + t.Run("nil artifactory", func(t *testing.T) { + model := &Model{} + err := mapFields(ctx, nil, model, "reg") + if err == nil { + t.Error("expected error for nil artifactory") + } + }) + + t.Run("nil model", func(t *testing.T) { + art := fixtureArtifactory() + err := mapFields(ctx, art, nil, "reg") + if err == nil { + t.Error("expected error for nil model") + } + }) + + t.Run("proxy without credentials", func(t *testing.T) { + art := fixtureArtifactory(func(a *registry.Artifactory) { + a.Proxy = ®istry.Proxy{ + RegistryType: "docker-hub", + Url: "https://registry-1.docker.io", + } + }) + model := &Model{ + ProjectId: types.StringValue("pid"), + } + err := mapFields(ctx, art, model, "reg") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if model.Proxy.IsNull() { + t.Error("expected proxy to not be null") + } + }) + + t.Run("existing model with proxy and credentials preserves version", func(t *testing.T) { + credsObj, diags := types.ObjectValueFrom(ctx, credentialsTypes, credentialsModel{ + AccessKey: types.StringValue("initial-user"), + AccessSecret: types.StringNull(), + AccessSecretWo: types.StringNull(), + AccessSecretWoVersion: types.Int64Value(42), + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Description: types.StringValue("desc"), + Credentials: credsObj, + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + model := &Model{ + ProjectId: types.StringValue("pid"), + Proxy: proxyObj, + } + + art := fixtureArtifactory(func(a *registry.Artifactory) { + desc := "updated desc" + a.Proxy = ®istry.Proxy{ + RegistryType: "docker-hub", + Url: "https://registry-1.docker.io", + Description: &desc, + Credentials: ®istry.RedactedCredentials{ + AccessKey: "new-user", + }, + } + }) + + err := mapFields(ctx, art, model, "reg") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if model.Proxy.IsNull() { + t.Fatal("expected proxy not to be null") + } + + var p proxyModel + diags = model.Proxy.As(ctx, &p, basetypes.ObjectAsOptions{}) + if diags.HasError() { + t.Fatalf("unexpected diags converting proxy: %v", diags) + } + var creds credentialsModel + diags = p.Credentials.As(ctx, &creds, basetypes.ObjectAsOptions{}) + if diags.HasError() { + t.Fatalf("unexpected diags converting creds: %v", diags) + } + if creds.AccessKey.ValueString() != "new-user" { + t.Errorf("expected access_key 'new-user', got %q", creds.AccessKey.ValueString()) + } + if creds.AccessSecretWoVersion.ValueInt64() != 42 { + t.Errorf("expected access_secret_wo_version 42, got %v", creds.AccessSecretWoVersion.ValueInt64()) + } + }) + + t.Run("artifactory id not present", func(t *testing.T) { + art := ®istry.Artifactory{} + model := &Model{ + ProjectId: types.StringValue("pid"), + } + err := mapFields(ctx, art, model, "reg") + if err == nil { + t.Error("expected error when artifactory id is missing") + } + }) +} + +func TestToPayloads_EdgeCases(t *testing.T) { + ctx := context.Background() + + t.Run("toCreatePayload nil model", func(t *testing.T) { + _, err := toCreatePayload(ctx, nil, nil) + if err == nil { + t.Error("expected error for nil model") + } + }) + + t.Run("toCreatePayload proxy without credentials", func(t *testing.T) { + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Credentials: types.ObjectNull(credentialsTypes), + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + model := &Model{ + Name: types.StringValue("my-artifactory"), + Proxy: proxyObj, + } + payload, err := toCreatePayload(ctx, model, model) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if payload.Proxy == nil { + t.Fatal("expected proxy not nil") + } + if payload.Proxy.Credentials != nil { + t.Errorf("expected credentials to be nil, got %v", payload.Proxy.Credentials) + } + }) + + t.Run("toUpdatePayload nil model", func(t *testing.T) { + _, err := toUpdatePayload(ctx, nil, nil, nil) + if err == nil { + t.Error("expected error for nil model") + } + }) + + t.Run("toUpdatePayload proxy without credentials", func(t *testing.T) { + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-2.docker.io"), + Credentials: types.ObjectNull(credentialsTypes), + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + model := &Model{ + Proxy: proxyObj, + } + payload, err := toUpdatePayload(ctx, model, nil, model) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if payload.Proxy == nil { + t.Fatal("expected proxy not nil") + } + if payload.Proxy.Credentials != nil { + t.Errorf("expected credentials to be nil, got %v", payload.Proxy.Credentials) + } + }) + + t.Run("toCreatePayload credentials without secret returns error", func(t *testing.T) { + credsObj, diags := types.ObjectValueFrom(ctx, credentialsTypes, credentialsModel{ + AccessKey: types.StringValue("user"), + AccessSecret: types.StringNull(), + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + proxyObj, diags := types.ObjectValueFrom(ctx, proxyTypes, proxyModel{ + RegistryType: types.StringValue("docker-hub"), + Url: types.StringValue("https://registry-1.docker.io"), + Credentials: credsObj, + }) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + model := &Model{ + Name: types.StringValue("my-artifactory"), + Proxy: proxyObj, + } + _, err := toCreatePayload(ctx, model, model) + if err == nil { + t.Error("expected error when neither access_secret nor access_secret_wo is set") + } + }) + + t.Run("getAccessSecret edge cases", func(t *testing.T) { + if s := getAccessSecret(nil, nil, nil, false); s != nil { + t.Errorf("expected nil for nil planCreds, got %v", s) + } + creds := &credentialsModel{ + AccessSecret: types.StringNull(), + AccessSecretWo: types.StringValue("secret"), + AccessSecretWoVersion: types.Int64Value(1), + } + stateCreds := &credentialsModel{ + AccessSecretWoVersion: types.Int64Value(1), + } + if s := getAccessSecret(creds, stateCreds, creds, true); s != nil { + t.Errorf("expected nil when version unchanged on update, got %v", s) + } + }) +} + +func TestArtifactoryResource_ImportState(t *testing.T) { + r, ok := NewArtifactoryResource().(resource.ResourceWithImportState) + if !ok { + t.Fatalf("expected resource to implement resource.ResourceWithImportState") + } + ctx := context.Background() + + var schemaResp resource.SchemaResponse + r.Schema(ctx, resource.SchemaRequest{}, &schemaResp) + + t.Run("valid import id", func(t *testing.T) { + req := resource.ImportStateRequest{ + ID: "pid,reg,art-id-123", + } + state := tfsdk.State{Schema: schemaResp.Schema} + diags := state.Set(ctx, &Model{Proxy: types.ObjectNull(proxyTypes)}) + if diags.HasError() { + t.Fatalf("unexpected diags initializing state: %v", diags) + } + resp := resource.ImportStateResponse{ + State: state, + } + r.ImportState(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + var model Model + diags = resp.State.Get(ctx, &model) + if diags.HasError() { + t.Fatalf("unexpected diags getting state: %v", diags) + } + if model.ProjectId.ValueString() != "pid" { + t.Errorf("expected project_id 'pid', got %q", model.ProjectId.ValueString()) + } + if model.Region.ValueString() != "reg" { + t.Errorf("expected region 'reg', got %q", model.Region.ValueString()) + } + if model.ArtifactoryId.ValueString() != "art-id-123" { + t.Errorf("expected artifactory_id 'art-id-123', got %q", model.ArtifactoryId.ValueString()) + } + }) + + t.Run("invalid import id - missing parts", func(t *testing.T) { + req := resource.ImportStateRequest{ + ID: "pid,reg", + } + var resp resource.ImportStateResponse + r.ImportState(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error for missing parts") + } + }) + + t.Run("invalid import id - empty parts", func(t *testing.T) { + req := resource.ImportStateRequest{ + ID: "pid,,art-id-123", + } + var resp resource.ImportStateResponse + r.ImportState(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error for empty part") + } + }) +} + +func TestArtifactoryResource_Read(t *testing.T) { + ctx := context.Background() + rBase := NewArtifactoryResource() + var schemaResp resource.SchemaResponse + rBase.Schema(ctx, resource.SchemaRequest{}, &schemaResp) + + t.Run("read success", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return fixtureArtifactory(), nil + }), + } + r := &artifactoryResource{client: mockClient} + initialModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Proxy: types.ObjectNull(proxyTypes), + } + state := tfsdk.State{Schema: schemaResp.Schema} + diags := state.Set(ctx, initialModel) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + + req := resource.ReadRequest{State: state} + resp := resource.ReadResponse{State: state} + r.Read(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + }) + + t.Run("read 404 not found removes resource", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return nil, &oapierror.GenericOpenAPIError{StatusCode: 404} + }), + } + r := &artifactoryResource{client: mockClient} + initialModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Proxy: types.ObjectNull(proxyTypes), + } + state := tfsdk.State{Schema: schemaResp.Schema} + diags := state.Set(ctx, initialModel) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + + req := resource.ReadRequest{State: state} + resp := resource.ReadResponse{State: state} + r.Read(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + }) + + t.Run("read deleted state removes resource", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + art := fixtureArtifactory() + art.State = registry.ARTIFACTORYSTATE_DELETED + return art, nil + }), + } + r := &artifactoryResource{client: mockClient} + initialModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Proxy: types.ObjectNull(proxyTypes), + } + state := tfsdk.State{Schema: schemaResp.Schema} + diags := state.Set(ctx, initialModel) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + + req := resource.ReadRequest{State: state} + resp := resource.ReadResponse{State: state} + r.Read(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + }) + + t.Run("read API error", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return nil, fmt.Errorf("api error") + }), + } + r := &artifactoryResource{client: mockClient} + initialModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Proxy: types.ObjectNull(proxyTypes), + } + state := tfsdk.State{Schema: schemaResp.Schema} + diags := state.Set(ctx, initialModel) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + + req := resource.ReadRequest{State: state} + resp := resource.ReadResponse{State: state} + r.Read(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected diagnostics on read API error") + } + }) +} + +func TestArtifactoryResource_Create(t *testing.T) { + ctx := context.Background() + var schemaResp resource.SchemaResponse + rBase := NewArtifactoryResource() + rBase.Schema(ctx, resource.SchemaRequest{}, &schemaResp) + + t.Run("create success", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + CreateArtifactoryExecuteMock: new(func(_ registry.ApiCreateArtifactoryRequest) (*registry.Artifactory, error) { + return fixtureArtifactory(), nil + }), + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return fixtureArtifactory(), nil + }), + } + r := &artifactoryResource{client: mockClient} + planModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + Name: types.StringValue("my-artifactory"), + Proxy: types.ObjectNull(proxyTypes), + } + plan := tfsdk.Plan{Schema: schemaResp.Schema} + _ = plan.Set(ctx, planModel) + configVal, _ := types.ObjectValueFrom(ctx, map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "artifactory_id": types.StringType, + "name": types.StringType, + "create_time": types.StringType, + "state": types.StringType, + "url": types.StringType, + "proxy": types.ObjectType{AttrTypes: proxyTypes}, + }, planModel) + rawVal, _ := configVal.ToTerraformValue(ctx) + req := resource.CreateRequest{ + Plan: plan, + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + } + var resp resource.CreateResponse + resp.State = tfsdk.State{Schema: schemaResp.Schema} + _ = resp.State.Set(ctx, &Model{Proxy: types.ObjectNull(proxyTypes)}) + + r.Create(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics on create success: %v", resp.Diagnostics) + } + + var resultModel Model + diags := resp.State.Get(ctx, &resultModel) + if diags.HasError() { + t.Fatalf("unexpected diags getting state: %v", diags) + } + if resultModel.Id.ValueString() != "pid,reg,art-id-123" { + t.Errorf("expected id 'pid,reg,art-id-123', got %q", resultModel.Id.ValueString()) + } + if resultModel.ArtifactoryId.ValueString() != "art-id-123" { + t.Errorf("expected artifactory_id 'art-id-123', got %q", resultModel.ArtifactoryId.ValueString()) + } + }) + + t.Run("create response missing ID", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + CreateArtifactoryExecuteMock: new(func(_ registry.ApiCreateArtifactoryRequest) (*registry.Artifactory, error) { + return ®istry.Artifactory{}, nil + }), + } + r := &artifactoryResource{client: mockClient} + planModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + Name: types.StringValue("my-artifactory"), + Proxy: types.ObjectNull(proxyTypes), + } + plan := tfsdk.Plan{Schema: schemaResp.Schema} + _ = plan.Set(ctx, planModel) + configVal, _ := types.ObjectValueFrom(ctx, map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "artifactory_id": types.StringType, + "name": types.StringType, + "create_time": types.StringType, + "state": types.StringType, + "url": types.StringType, + "proxy": types.ObjectType{AttrTypes: proxyTypes}, + }, planModel) + rawVal, _ := configVal.ToTerraformValue(ctx) + req := resource.CreateRequest{ + Plan: plan, + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + } + var resp resource.CreateResponse + resp.State = tfsdk.State{Schema: schemaResp.Schema} + _ = resp.State.Set(ctx, &Model{Proxy: types.ObjectNull(proxyTypes)}) + + r.Create(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error diagnostics when create response ID is missing") + } + }) + + t.Run("create wait error", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + CreateArtifactoryExecuteMock: new(func(_ registry.ApiCreateArtifactoryRequest) (*registry.Artifactory, error) { + return fixtureArtifactory(), nil + }), + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return nil, fmt.Errorf("polling error") + }), + } + r := &artifactoryResource{client: mockClient} + planModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + Name: types.StringValue("my-artifactory"), + Proxy: types.ObjectNull(proxyTypes), + } + plan := tfsdk.Plan{Schema: schemaResp.Schema} + _ = plan.Set(ctx, planModel) + configVal, _ := types.ObjectValueFrom(ctx, map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "artifactory_id": types.StringType, + "name": types.StringType, + "create_time": types.StringType, + "state": types.StringType, + "url": types.StringType, + "proxy": types.ObjectType{AttrTypes: proxyTypes}, + }, planModel) + rawVal, _ := configVal.ToTerraformValue(ctx) + req := resource.CreateRequest{ + Plan: plan, + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + } + var resp resource.CreateResponse + resp.State = tfsdk.State{Schema: schemaResp.Schema} + _ = resp.State.Set(ctx, &Model{Proxy: types.ObjectNull(proxyTypes)}) + + r.Create(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error diagnostics when waiter fails") + } + }) + + t.Run("create API error", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + CreateArtifactoryExecuteMock: new(func(_ registry.ApiCreateArtifactoryRequest) (*registry.Artifactory, error) { + return nil, fmt.Errorf("api create error") + }), + } + r := &artifactoryResource{client: mockClient} + planModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + Name: types.StringValue("test-art"), + Proxy: types.ObjectNull(proxyTypes), + } + plan := tfsdk.Plan{Schema: schemaResp.Schema} + _ = plan.Set(ctx, planModel) + configVal, _ := types.ObjectValueFrom(ctx, map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "artifactory_id": types.StringType, + "name": types.StringType, + "create_time": types.StringType, + "state": types.StringType, + "url": types.StringType, + "proxy": types.ObjectType{AttrTypes: proxyTypes}, + }, planModel) + rawVal, _ := configVal.ToTerraformValue(ctx) + req := resource.CreateRequest{ + Plan: plan, + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + } + var resp resource.CreateResponse + resp.State = tfsdk.State{Schema: schemaResp.Schema} + _ = resp.State.Set(ctx, &Model{Proxy: types.ObjectNull(proxyTypes)}) + r.Create(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error diagnostics on create API failure") + } + }) +} + +func TestArtifactoryResource_Update(t *testing.T) { + ctx := context.Background() + var schemaResp resource.SchemaResponse + rBase := NewArtifactoryResource() + rBase.Schema(ctx, resource.SchemaRequest{}, &schemaResp) + + t.Run("update success", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + PatchArtifactoryExecuteMock: new(func(_ registry.ApiPatchArtifactoryRequest) (*registry.Artifactory, error) { + return fixtureArtifactory(), nil + }), + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return fixtureArtifactory(), nil + }), + } + r := &artifactoryResource{client: mockClient} + planModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Name: types.StringValue("my-artifactory"), + Proxy: types.ObjectNull(proxyTypes), + } + plan := tfsdk.Plan{Schema: schemaResp.Schema} + _ = plan.Set(ctx, planModel) + state := tfsdk.State{Schema: schemaResp.Schema} + _ = state.Set(ctx, planModel) + configVal, _ := types.ObjectValueFrom(ctx, map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "artifactory_id": types.StringType, + "name": types.StringType, + "create_time": types.StringType, + "state": types.StringType, + "url": types.StringType, + "proxy": types.ObjectType{AttrTypes: proxyTypes}, + }, planModel) + rawVal, _ := configVal.ToTerraformValue(ctx) + req := resource.UpdateRequest{ + Plan: plan, + State: state, + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + } + var resp resource.UpdateResponse + resp.State = tfsdk.State{Schema: schemaResp.Schema} + _ = resp.State.Set(ctx, &Model{Proxy: types.ObjectNull(proxyTypes)}) + r.Update(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics on update success: %v", resp.Diagnostics) + } + }) + + t.Run("update API error", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + PatchArtifactoryExecuteMock: new(func(_ registry.ApiPatchArtifactoryRequest) (*registry.Artifactory, error) { + return nil, fmt.Errorf("api patch error") + }), + } + r := &artifactoryResource{client: mockClient} + planModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Name: types.StringValue("test-art"), + Proxy: types.ObjectNull(proxyTypes), + } + plan := tfsdk.Plan{Schema: schemaResp.Schema} + _ = plan.Set(ctx, planModel) + state := tfsdk.State{Schema: schemaResp.Schema} + _ = state.Set(ctx, planModel) + configVal, _ := types.ObjectValueFrom(ctx, map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "artifactory_id": types.StringType, + "name": types.StringType, + "create_time": types.StringType, + "state": types.StringType, + "url": types.StringType, + "proxy": types.ObjectType{AttrTypes: proxyTypes}, + }, planModel) + rawVal, _ := configVal.ToTerraformValue(ctx) + req := resource.UpdateRequest{ + Plan: plan, + State: state, + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + } + var resp resource.UpdateResponse + resp.State = tfsdk.State{Schema: schemaResp.Schema} + _ = resp.State.Set(ctx, &Model{Proxy: types.ObjectNull(proxyTypes)}) + r.Update(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error diagnostics on update API failure") + } + }) + + t.Run("update wait error", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + PatchArtifactoryExecuteMock: new(func(_ registry.ApiPatchArtifactoryRequest) (*registry.Artifactory, error) { + return fixtureArtifactory(), nil + }), + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return nil, fmt.Errorf("wait polling error") + }), + } + r := &artifactoryResource{client: mockClient} + planModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Name: types.StringValue("my-artifactory"), + Proxy: types.ObjectNull(proxyTypes), + } + plan := tfsdk.Plan{Schema: schemaResp.Schema} + _ = plan.Set(ctx, planModel) + state := tfsdk.State{Schema: schemaResp.Schema} + _ = state.Set(ctx, planModel) + configVal, _ := types.ObjectValueFrom(ctx, map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "artifactory_id": types.StringType, + "name": types.StringType, + "create_time": types.StringType, + "state": types.StringType, + "url": types.StringType, + "proxy": types.ObjectType{AttrTypes: proxyTypes}, + }, planModel) + rawVal, _ := configVal.ToTerraformValue(ctx) + req := resource.UpdateRequest{ + Plan: plan, + State: state, + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + } + var resp resource.UpdateResponse + resp.State = tfsdk.State{Schema: schemaResp.Schema} + _ = resp.State.Set(ctx, &Model{Proxy: types.ObjectNull(proxyTypes)}) + r.Update(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error diagnostics on update wait error") + } + }) +} + +func TestArtifactoryResource_Delete(t *testing.T) { + ctx := context.Background() + var schemaResp resource.SchemaResponse + rBase := NewArtifactoryResource() + rBase.Schema(ctx, resource.SchemaRequest{}, &schemaResp) + + t.Run("delete success", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + DeleteArtifactoryExecuteMock: new(func(_ registry.ApiDeleteArtifactoryRequest) error { + return nil + }), + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return nil, &oapierror.GenericOpenAPIError{StatusCode: 404} + }), + } + r := &artifactoryResource{client: mockClient} + initialModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Proxy: types.ObjectNull(proxyTypes), + } + state := tfsdk.State{Schema: schemaResp.Schema} + diags := state.Set(ctx, initialModel) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + req := resource.DeleteRequest{State: state} + var resp resource.DeleteResponse + r.Delete(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics on delete success: %v", resp.Diagnostics) + } + }) + + t.Run("delete wait error", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + DeleteArtifactoryExecuteMock: new(func(_ registry.ApiDeleteArtifactoryRequest) error { + return nil + }), + GetArtifactoryExecuteMock: new(func(_ registry.ApiGetArtifactoryRequest) (*registry.Artifactory, error) { + return nil, fmt.Errorf("wait polling error") + }), + } + r := &artifactoryResource{client: mockClient} + initialModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Proxy: types.ObjectNull(proxyTypes), + } + state := tfsdk.State{Schema: schemaResp.Schema} + diags := state.Set(ctx, initialModel) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + req := resource.DeleteRequest{State: state} + var resp resource.DeleteResponse + r.Delete(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error diagnostics on delete wait error") + } + }) + + t.Run("delete API error", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + DeleteArtifactoryExecuteMock: new(func(_ registry.ApiDeleteArtifactoryRequest) error { + return fmt.Errorf("api delete error") + }), + } + r := &artifactoryResource{client: mockClient} + initialModel := &Model{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ArtifactoryId: types.StringValue("art-id-123"), + Proxy: types.ObjectNull(proxyTypes), + } + state := tfsdk.State{Schema: schemaResp.Schema} + diags := state.Set(ctx, initialModel) + if diags.HasError() { + t.Fatalf("unexpected diags: %v", diags) + } + req := resource.DeleteRequest{State: state} + var resp resource.DeleteResponse + r.Delete(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected diagnostics on delete error") + } + }) +} diff --git a/stackit/internal/services/containerregistry/containerregistry_acc_test.go b/stackit/internal/services/containerregistry/containerregistry_acc_test.go new file mode 100644 index 000000000..ed1f421ba --- /dev/null +++ b/stackit/internal/services/containerregistry/containerregistry_acc_test.go @@ -0,0 +1,215 @@ +package containerregistry_test + +import ( + "context" + _ "embed" + "errors" + "fmt" + "net/http" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/stackitcloud/stackit-sdk-go/core/oapierror" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" + + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/testutil" +) + +//go:embed testdata/resource-min.tf +var resourceMin string + +//go:embed testdata/resource-max.tf +var resourceMax string + +//go:embed testdata/datasource-artifactories* +var datasourceArtifactories string + +//go:embed testdata/datasource-replication-adapters.tf +var datasourceReplicationAdapters string + +var ( + artifactoryNameMin = fmt.Sprintf("cr-min-%s", acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)) + artifactoryNameMax = fmt.Sprintf("cr-max-%s", acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)) + + testConfigVarsMin = config.Variables{ + "project_id": config.StringVariable(testutil.ProjectId), + "name": config.StringVariable(artifactoryNameMin), + } +) + +func TestAccContainerRegistryArtifactoryLifecycle(t *testing.T) { + resource.Test(t, resource.TestCase{ + ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories, + CheckDestroy: testAccCheckContainerRegistryArtifactoryDestroy, + Steps: []resource.TestStep{ + // Step 1: Create minimal Artifactory + { + Config: testutil.NewConfigBuilder().BuildProviderConfig() + "\n" + resourceMin, + ConfigVariables: testConfigVarsMin, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("stackit_containerregistry_artifactory.this", "project_id", testutil.ProjectId), + resource.TestCheckResourceAttr("stackit_containerregistry_artifactory.this", "name", artifactoryNameMin), + resource.TestCheckResourceAttrSet("stackit_containerregistry_artifactory.this", "id"), + resource.TestCheckResourceAttrSet("stackit_containerregistry_artifactory.this", "artifactory_id"), + resource.TestCheckResourceAttrSet("stackit_containerregistry_artifactory.this", "url"), + ), + }, + // Step 2: Read via Artifactory DataSource + { + Config: testutil.NewConfigBuilder().BuildProviderConfig() + "\n" + resourceMin + ` +data "stackit_containerregistry_artifactory" "this" { + project_id = stackit_containerregistry_artifactory.this.project_id + artifactory_id = stackit_containerregistry_artifactory.this.artifactory_id +}`, + ConfigVariables: testConfigVarsMin, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair( + "stackit_containerregistry_artifactory.this", "artifactory_id", + "data.stackit_containerregistry_artifactory.this", "artifactory_id", + ), + resource.TestCheckResourceAttrPair( + "stackit_containerregistry_artifactory.this", "name", + "data.stackit_containerregistry_artifactory.this", "name", + ), + ), + }, + // Step 3: Read via Artifactories (plural) DataSource + { + Config: testutil.NewConfigBuilder().BuildProviderConfig() + "\n" + resourceMin + ` +data "stackit_containerregistry_artifactories" "this" { + project_id = stackit_containerregistry_artifactory.this.project_id +}`, + ConfigVariables: testConfigVarsMin, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("data.stackit_containerregistry_artifactories.this", "project_id", testutil.ProjectId), + resource.TestCheckResourceAttrSet("data.stackit_containerregistry_artifactories.this", "id"), + resource.TestCheckResourceAttrSet("data.stackit_containerregistry_artifactories.this", "artifactories.#"), + ), + }, + // Step 4: Import state + { + ConfigVariables: testConfigVarsMin, + ResourceName: "stackit_containerregistry_artifactory.this", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccContainerRegistryArtifactoryMax(t *testing.T) { + dockerUsername := os.Getenv("TF_ACC_CONTAINER_REGISTRY_DOCKER_USERNAME") + dockerPassword := os.Getenv("TF_ACC_CONTAINER_REGISTRY_DOCKER_PASSWORD") + if dockerUsername == "" || dockerPassword == "" { + t.Skip("Skipping TestAccContainerRegistryArtifactoryMax: TF_ACC_CONTAINER_REGISTRY_DOCKER_USERNAME or TF_ACC_CONTAINER_REGISTRY_DOCKER_PASSWORD not set") + } + + testConfigVarsMax := config.Variables{ + "project_id": config.StringVariable(testutil.ProjectId), + "name": config.StringVariable(artifactoryNameMax), + "docker_username": config.StringVariable(dockerUsername), + "docker_password": config.StringVariable(dockerPassword), + "docker_password_version": config.IntegerVariable(1), + } + + resource.Test(t, resource.TestCase{ + ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories, + CheckDestroy: testAccCheckContainerRegistryArtifactoryDestroy, + Steps: []resource.TestStep{ + { + Config: testutil.NewConfigBuilder().BuildProviderConfig() + "\n" + resourceMax, + ConfigVariables: testConfigVarsMax, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("stackit_containerregistry_artifactory.this", "project_id", testutil.ProjectId), + resource.TestCheckResourceAttr("stackit_containerregistry_artifactory.this", "name", artifactoryNameMax), + resource.TestCheckResourceAttr("stackit_containerregistry_artifactory.this", "proxy.registry_type", "docker-hub"), + resource.TestCheckResourceAttr("stackit_containerregistry_artifactory.this", "proxy.url", "https://registry-1.docker.io"), + resource.TestCheckResourceAttr("stackit_containerregistry_artifactory.this", "proxy.description", "Docker Hub mirror"), + resource.TestCheckResourceAttr("stackit_containerregistry_artifactory.this", "proxy.credentials.access_key", dockerUsername), + resource.TestCheckResourceAttr("stackit_containerregistry_artifactory.this", "proxy.credentials.access_secret_wo_version", "1"), + resource.TestCheckNoResourceAttr("stackit_containerregistry_artifactory.this", "proxy.credentials.access_secret"), + resource.TestCheckNoResourceAttr("stackit_containerregistry_artifactory.this", "proxy.credentials.access_secret_wo"), + resource.TestCheckResourceAttrSet("stackit_containerregistry_artifactory.this", "id"), + ), + }, + }, + }) +} + +func TestAccContainerRegistryArtifactoriesDataSource(t *testing.T) { + resource.Test(t, resource.TestCase{ + ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testutil.NewConfigBuilder().BuildProviderConfig() + "\n" + datasourceArtifactories, + ConfigVariables: config.Variables{ + "project_id": config.StringVariable(testutil.ProjectId), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("data.stackit_containerregistry_artifactories.this", "project_id", testutil.ProjectId), + resource.TestCheckResourceAttrSet("data.stackit_containerregistry_artifactories.this", "id"), + resource.TestCheckResourceAttrSet("data.stackit_containerregistry_artifactories.this", "artifactories.#"), + ), + }, + }, + }) +} + +func TestAccContainerRegistryReplicationAdaptersDataSource(t *testing.T) { + resource.Test(t, resource.TestCase{ + ProtoV6ProviderFactories: testutil.TestAccProtoV6ProviderFactories, + Steps: []resource.TestStep{ + { + Config: testutil.NewConfigBuilder().BuildProviderConfig() + "\n" + datasourceReplicationAdapters, + ConfigVariables: config.Variables{ + "project_id": config.StringVariable(testutil.ProjectId), + }, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("data.stackit_containerregistry_replication_adapters.this", "project_id", testutil.ProjectId), + resource.TestCheckResourceAttrSet("data.stackit_containerregistry_replication_adapters.this", "id"), + resource.TestCheckResourceAttrSet("data.stackit_containerregistry_replication_adapters.this", "replication_adapters.#"), + ), + }, + }, + }) +} + +func testAccCheckContainerRegistryArtifactoryDestroy(s *terraform.State) error { + ctx := context.Background() + + client, err := registry.NewAPIClient( + testutil.NewConfigBuilder().BuildClientOptions(testutil.ContainerRegistryCustomEndpoint, false)..., + ) + if err != nil { + return fmt.Errorf("creating API client: %w", err) + } + + for _, rs := range s.RootModule().Resources { + if rs.Type != "stackit_containerregistry_artifactory" { + continue + } + + projectId := rs.Primary.Attributes["project_id"] + region := rs.Primary.Attributes["region"] + artifactoryId := rs.Primary.Attributes["artifactory_id"] + + artifactory, err := client.DefaultAPI.GetArtifactory(ctx, projectId, region, artifactoryId).Execute() + if err == nil { + if artifactory != nil && artifactory.State != registry.ARTIFACTORYSTATE_DELETED { + return fmt.Errorf("artifactory %q still exists with state %q", artifactoryId, artifactory.State) + } + continue + } + + var oapiErr *oapierror.GenericOpenAPIError + if !errors.As(err, &oapiErr) || oapiErr.StatusCode != http.StatusNotFound { + return fmt.Errorf("verifying artifactory destroyed: %w", err) + } + } + + return nil +} diff --git a/stackit/internal/services/containerregistry/replicationadapters/datasource.go b/stackit/internal/services/containerregistry/replicationadapters/datasource.go new file mode 100644 index 000000000..f84565bf4 --- /dev/null +++ b/stackit/internal/services/containerregistry/replicationadapters/datasource.go @@ -0,0 +1,202 @@ +package replicationadapters + +import ( + "context" + "fmt" + "net/http" + + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-log/tflog" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" + + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core" + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/utils" + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/validate" +) + +var ( + _ datasource.DataSource = &replicationAdaptersDataSource{} +) + +type DataSourceModel struct { + Id types.String `tfsdk:"id"` + ProjectId types.String `tfsdk:"project_id"` + Region types.String `tfsdk:"region"` + ReplicationAdapters types.List `tfsdk:"replication_adapters"` +} + +type replicationAdapterModel struct { + CredentialType types.String `tfsdk:"credential_type"` + DisplayName types.String `tfsdk:"display_name"` + RegistryType types.String `tfsdk:"registry_type"` +} + +var replicationAdapterTypes = map[string]attr.Type{ + "credential_type": types.StringType, + "display_name": types.StringType, + "registry_type": types.StringType, +} + +var descriptions = map[string]string{ //nolint:gosec // linter false positive + "id": "Terraform's internal data source ID, structured as `project_id`,`region`.", + "project_id": "STACKIT project ID to which the replication adapters are associated.", + "region": "STACKIT region where the replication adapters are located. If not defined, the provider default_region is used.", + "replication_adapters": "List of supported replication adapters.", + "replication_adapters.credential_type": "User-hint for what type of credentials are expected for the replication adapter type.", + "replication_adapters.display_name": "Human-friendly name of the provider the adapter relates to.", + "replication_adapters.registry_type": "Identifies the replication adapter.", +} + +func NewReplicationAdaptersDataSource() datasource.DataSource { + return &replicationAdaptersDataSource{} +} + +type replicationAdaptersDataSource struct { + client registry.DefaultAPI + providerData core.ProviderData +} + +func (d *replicationAdaptersDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_containerregistry_replication_adapters" +} + +func (d *replicationAdaptersDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { + providerData, clients, ok := core.ParseProviderData(ctx, req.ProviderData, &resp.Diagnostics) + if !ok { + return + } + + d.providerData = providerData + d.client = clients.ContainerRegistryV1Client + tflog.Info(ctx, "Container Registry client configured") +} + +func (d *replicationAdaptersDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + Description: "Container registry replication adapters data source schema.", + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + Description: descriptions["id"], + Computed: true, + }, + "project_id": schema.StringAttribute{ + Description: descriptions["project_id"], + Required: true, + Validators: []validator.String{ + validate.UUID(), + validate.NoSeparator(), + }, + }, + "region": schema.StringAttribute{ + Description: descriptions["region"], + Optional: true, + Computed: true, + }, + "replication_adapters": schema.ListNestedAttribute{ + Description: descriptions["replication_adapters"], + Computed: true, + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + "credential_type": schema.StringAttribute{ + Description: descriptions["replication_adapters.credential_type"], + Computed: true, + }, + "display_name": schema.StringAttribute{ + Description: descriptions["replication_adapters.display_name"], + Computed: true, + }, + "registry_type": schema.StringAttribute{ + Description: descriptions["replication_adapters.registry_type"], + Computed: true, + }, + }, + }, + }, + }, + } +} + +func (d *replicationAdaptersDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { // nolint:gocritic // function signature required by Terraform + var model DataSourceModel + diags := req.Config.Get(ctx, &model) + resp.Diagnostics.Append(diags...) + if resp.Diagnostics.HasError() { + return + } + + ctx = core.InitProviderContext(ctx) + + projectId := model.ProjectId.ValueString() + region := d.providerData.GetRegionWithOverride(model.Region) + ctx = tflog.SetField(ctx, "project_id", projectId) + ctx = tflog.SetField(ctx, "region", region) + + listResp, err := d.client.ListReplicationAdapters(ctx, projectId, region).Execute() + if err != nil { + utils.LogError( + ctx, + &resp.Diagnostics, + err, + "Error reading replication adapters", + fmt.Sprintf("Calling API: %v", err), + map[int]string{ + http.StatusNotFound: fmt.Sprintf("Project %q or region %q not found", projectId, region), + }, + ) + return + } + + ctx = core.LogResponse(ctx) + + var adapters []registry.ReplicationAdapter + if listResp != nil { + adapters = listResp.ReplicationAdapters + } + + err = mapFields(ctx, adapters, &model, region) + if err != nil { + core.LogAndAddError(ctx, &resp.Diagnostics, "Error reading replication adapters", fmt.Sprintf("Mapping API response: %v", err)) + return + } + + diags = resp.State.Set(ctx, &model) + resp.Diagnostics.Append(diags...) + tflog.Info(ctx, "Container Registry replication adapters read") +} + +func mapFields(ctx context.Context, adapters []registry.ReplicationAdapter, model *DataSourceModel, region string) error { + if model == nil { + return fmt.Errorf("model is nil") + } + + model.Id = utils.BuildInternalTerraformId(model.ProjectId.ValueString(), region) + model.Region = types.StringValue(region) + + items := make([]attr.Value, 0, len(adapters)) + for _, adapter := range adapters { + item := replicationAdapterModel{ + CredentialType: types.StringValue(string(adapter.CredentialType)), + DisplayName: types.StringValue(adapter.DisplayName), + RegistryType: types.StringValue(adapter.RegistryType), + } + + itemObj, diags := types.ObjectValueFrom(ctx, replicationAdapterTypes, item) + if diags.HasError() { + return fmt.Errorf("mapping replication adapter item: %w", core.DiagsToError(diags)) + } + + items = append(items, itemObj) + } + + itemsList, diags := types.ListValue(types.ObjectType{AttrTypes: replicationAdapterTypes}, items) + if diags.HasError() { + return fmt.Errorf("mapping replication adapters list: %w", core.DiagsToError(diags)) + } + model.ReplicationAdapters = itemsList + + return nil +} diff --git a/stackit/internal/services/containerregistry/replicationadapters/datasource_test.go b/stackit/internal/services/containerregistry/replicationadapters/datasource_test.go new file mode 100644 index 000000000..3efe7ecf6 --- /dev/null +++ b/stackit/internal/services/containerregistry/replicationadapters/datasource_test.go @@ -0,0 +1,269 @@ +package replicationadapters + +import ( + "context" + "fmt" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/hashicorp/terraform-plugin-framework/attr" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/tfsdk" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/stackitcloud/stackit-sdk-go/core/oapierror" + registry "github.com/stackitcloud/stackit-sdk-go/services/registry/v1api" + + "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/core" +) + +func TestReplicationAdaptersDataSource_Metadata(t *testing.T) { + ds := NewReplicationAdaptersDataSource() + var resp datasource.MetadataResponse + ds.Metadata(context.Background(), datasource.MetadataRequest{ProviderTypeName: "stackit"}, &resp) + if resp.TypeName != "stackit_containerregistry_replication_adapters" { + t.Errorf("expected type name %q, got %q", "stackit_containerregistry_replication_adapters", resp.TypeName) + } +} + +func TestReplicationAdaptersDataSource_Schema(t *testing.T) { + ds := NewReplicationAdaptersDataSource() + var resp datasource.SchemaResponse + ds.Schema(context.Background(), datasource.SchemaRequest{}, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + if len(resp.Schema.Attributes) == 0 { + t.Errorf("expected non-empty schema attributes") + } +} + +func TestReplicationAdaptersDataSource_Configure(t *testing.T) { + ds := &replicationAdaptersDataSource{} + ctx := context.Background() + + t.Run("valid provider data", func(t *testing.T) { + providerData, err := core.NewProviderDataInternal(core.ProviderData{}, &core.MockClientFactory{}) + if err != nil { + t.Fatalf("unexpected error creating provider data: %v", err) + } + var resp datasource.ConfigureResponse + ds.Configure(ctx, datasource.ConfigureRequest{ProviderData: providerData}, &resp) + if resp.Diagnostics.HasError() { + t.Errorf("unexpected error diagnostics: %v", resp.Diagnostics) + } + if ds.client == nil { + t.Error("expected client to be configured") + } + }) + + t.Run("nil provider data", func(t *testing.T) { + var resp datasource.ConfigureResponse + ds.Configure(ctx, datasource.ConfigureRequest{ProviderData: nil}, &resp) + if resp.Diagnostics.HasError() { + t.Errorf("expected no error diagnostics on nil provider data, got %v", resp.Diagnostics) + } + }) + + t.Run("invalid provider data type", func(t *testing.T) { + var resp datasource.ConfigureResponse + ds.Configure(ctx, datasource.ConfigureRequest{ProviderData: "invalid"}, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected error diagnostics on invalid provider data") + } + }) +} + +func TestReplicationAdaptersDataSource_Read(t *testing.T) { + ctx := context.Background() + dsBase := NewReplicationAdaptersDataSource() + var schemaResp datasource.SchemaResponse + dsBase.Schema(ctx, datasource.SchemaRequest{}, &schemaResp) + + configAttrTypes := map[string]attr.Type{ + "id": types.StringType, + "project_id": types.StringType, + "region": types.StringType, + "replication_adapters": types.ListType{ElemType: types.ObjectType{AttrTypes: replicationAdapterTypes}}, + } + + configModel := DataSourceModel{ + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + Id: types.StringNull(), + ReplicationAdapters: types.ListNull(types.ObjectType{AttrTypes: replicationAdapterTypes}), + } + configVal, diags := types.ObjectValueFrom(ctx, configAttrTypes, configModel) + if diags.HasError() { + t.Fatalf("unexpected diags creating configVal: %v", diags) + } + rawVal, err := configVal.ToTerraformValue(ctx) + if err != nil { + t.Fatalf("unexpected error converting to terraform value: %v", err) + } + + req := datasource.ReadRequest{ + Config: tfsdk.Config{ + Schema: schemaResp.Schema, + Raw: rawVal, + }, + } + + t.Run("read success", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + ListReplicationAdaptersExecuteMock: new(func(_ registry.ApiListReplicationAdaptersRequest) (*registry.ReplicationAdapterList, error) { + return ®istry.ReplicationAdapterList{ + ReplicationAdapters: []registry.ReplicationAdapter{ + { + CredentialType: registry.REPLICATIONADAPTERCREDENTIALTYPE_BASIC, + DisplayName: "Docker Hub", + RegistryType: "docker-hub", + }, + }, + }, nil + }), + } + ds := &replicationAdaptersDataSource{client: mockClient} + + resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}} + ds.Read(ctx, req, &resp) + if resp.Diagnostics.HasError() { + t.Fatalf("unexpected diagnostics: %v", resp.Diagnostics) + } + + var resultModel DataSourceModel + diags = resp.State.Get(ctx, &resultModel) + if diags.HasError() { + t.Fatalf("unexpected diags getting state: %v", diags) + } + if resultModel.Id.ValueString() != "pid,reg" { + t.Errorf("expected id 'pid,reg', got %q", resultModel.Id.ValueString()) + } + if len(resultModel.ReplicationAdapters.Elements()) != 1 { + t.Errorf("expected 1 replication adapter, got %d", len(resultModel.ReplicationAdapters.Elements())) + } + }) + + t.Run("read API error", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + ListReplicationAdaptersExecuteMock: new(func(_ registry.ApiListReplicationAdaptersRequest) (*registry.ReplicationAdapterList, error) { + return nil, fmt.Errorf("api error") + }), + } + ds := &replicationAdaptersDataSource{client: mockClient} + + resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}} + ds.Read(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected diagnostics on read API error") + } + }) + + t.Run("read 404 not found", func(t *testing.T) { + mockClient := ®istry.DefaultAPIServiceMock{ + ListReplicationAdaptersExecuteMock: new(func(_ registry.ApiListReplicationAdaptersRequest) (*registry.ReplicationAdapterList, error) { + return nil, &oapierror.GenericOpenAPIError{StatusCode: 404} + }), + } + ds := &replicationAdaptersDataSource{client: mockClient} + + resp := datasource.ReadResponse{State: tfsdk.State{Schema: schemaResp.Schema}} + ds.Read(ctx, req, &resp) + if !resp.Diagnostics.HasError() { + t.Error("expected diagnostics on read 404") + } + }) +} + +func TestMapFields(t *testing.T) { + ctx := context.Background() + + adapters := []registry.ReplicationAdapter{ + { + CredentialType: registry.REPLICATIONADAPTERCREDENTIALTYPE_BASIC, + DisplayName: "Docker Hub", + RegistryType: "docker-hub", + }, + { + CredentialType: registry.REPLICATIONADAPTERCREDENTIALTYPE_OAUTH, + DisplayName: "GitHub Container Registry", + RegistryType: "ghcr", + }, + } + + model := &DataSourceModel{ + ProjectId: types.StringValue("pid"), + } + + err := mapFields(ctx, adapters, model, "reg") + if err != nil { + t.Fatalf("mapFields() error = %v", err) + } + + if model.Id.ValueString() != "pid,reg" { + t.Errorf("expected id 'pid,reg', got %q", model.Id.ValueString()) + } + if model.Region.ValueString() != "reg" { + t.Errorf("expected region 'reg', got %q", model.Region.ValueString()) + } + + item1, diags := types.ObjectValueFrom(ctx, replicationAdapterTypes, replicationAdapterModel{ + CredentialType: types.StringValue("basic"), + DisplayName: types.StringValue("Docker Hub"), + RegistryType: types.StringValue("docker-hub"), + }) + if diags.HasError() { + t.Fatalf("creating item1: %v", diags) + } + + item2, diags := types.ObjectValueFrom(ctx, replicationAdapterTypes, replicationAdapterModel{ + CredentialType: types.StringValue("oauth"), + DisplayName: types.StringValue("GitHub Container Registry"), + RegistryType: types.StringValue("ghcr"), + }) + if diags.HasError() { + t.Fatalf("creating item2: %v", diags) + } + + expectedList, diags := types.ListValue(types.ObjectType{AttrTypes: replicationAdapterTypes}, []attr.Value{item1, item2}) + if diags.HasError() { + t.Fatalf("creating expectedList: %v", diags) + } + + expectedModel := &DataSourceModel{ + Id: types.StringValue("pid,reg"), + ProjectId: types.StringValue("pid"), + Region: types.StringValue("reg"), + ReplicationAdapters: expectedList, + } + + if diff := cmp.Diff(model, expectedModel); diff != "" { + t.Errorf("mapFields() mismatch (-got +want):\n%s", diff) + } +} + +func TestMapFields_EdgeCases(t *testing.T) { + ctx := context.Background() + + t.Run("nil model", func(t *testing.T) { + err := mapFields(ctx, []registry.ReplicationAdapter{}, nil, "reg") + if err == nil { + t.Error("expected error for nil model") + } + }) + + t.Run("empty adapters", func(t *testing.T) { + model := &DataSourceModel{ + ProjectId: types.StringValue("pid"), + } + err := mapFields(ctx, []registry.ReplicationAdapter{}, model, "reg") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if model.ReplicationAdapters.IsNull() { + t.Error("expected adapters list not to be null") + } + if len(model.ReplicationAdapters.Elements()) != 0 { + t.Errorf("expected 0 elements, got %d", len(model.ReplicationAdapters.Elements())) + } + }) +} diff --git a/stackit/internal/services/containerregistry/testdata/datasource-artifactories.tf b/stackit/internal/services/containerregistry/testdata/datasource-artifactories.tf new file mode 100644 index 000000000..ce2b7b256 --- /dev/null +++ b/stackit/internal/services/containerregistry/testdata/datasource-artifactories.tf @@ -0,0 +1,7 @@ +variable "project_id" { + type = string +} + +data "stackit_containerregistry_artifactories" "this" { + project_id = var.project_id +} \ No newline at end of file diff --git a/stackit/internal/services/containerregistry/testdata/datasource-replication-adapters.tf b/stackit/internal/services/containerregistry/testdata/datasource-replication-adapters.tf new file mode 100644 index 000000000..59ef7b943 --- /dev/null +++ b/stackit/internal/services/containerregistry/testdata/datasource-replication-adapters.tf @@ -0,0 +1,7 @@ +variable "project_id" { + type = string +} + +data "stackit_containerregistry_replication_adapters" "this" { + project_id = var.project_id +} \ No newline at end of file diff --git a/stackit/internal/services/containerregistry/testdata/resource-max.tf b/stackit/internal/services/containerregistry/testdata/resource-max.tf new file mode 100644 index 000000000..66f8dc36c --- /dev/null +++ b/stackit/internal/services/containerregistry/testdata/resource-max.tf @@ -0,0 +1,36 @@ +variable "project_id" { + type = string +} + +variable "name" { + type = string +} + +variable "docker_username" { + type = string +} + +variable "docker_password" { + type = string + sensitive = true +} + +variable "docker_password_version" { + type = number + default = 1 +} + +resource "stackit_containerregistry_artifactory" "this" { + project_id = var.project_id + name = var.name + proxy = { + registry_type = "docker-hub" + url = "https://registry-1.docker.io" + description = "Docker Hub mirror" + credentials = { + access_key = var.docker_username + access_secret_wo = var.docker_password + access_secret_wo_version = var.docker_password_version + } + } +} \ No newline at end of file diff --git a/stackit/internal/services/containerregistry/testdata/resource-min.tf b/stackit/internal/services/containerregistry/testdata/resource-min.tf new file mode 100644 index 000000000..e9f70e35c --- /dev/null +++ b/stackit/internal/services/containerregistry/testdata/resource-min.tf @@ -0,0 +1,12 @@ +variable "project_id" { + type = string +} + +variable "name" { + type = string +} + +resource "stackit_containerregistry_artifactory" "this" { + project_id = var.project_id + name = var.name +} \ No newline at end of file diff --git a/stackit/internal/testutil/testutil.go b/stackit/internal/testutil/testutil.go index b422f9811..7aa57a805 100644 --- a/stackit/internal/testutil/testutil.go +++ b/stackit/internal/testutil/testutil.go @@ -79,6 +79,7 @@ var ( ALBCertCustomEndpoint = customEndpointConfig{envVarName: "TF_ACC_ALB_CERT_CUSTOM_ENDPOINT", providerName: "alb_certificates_custom_endpoint"} AlbWafCustomEndpoint = customEndpointConfig{envVarName: "TF_ACC_ALB_WAF_CUSTOM_ENDPOINT", providerName: "alb_waf_custom_endpoint"} CdnCustomEndpoint = customEndpointConfig{envVarName: "TF_ACC_CDN_CUSTOM_ENDPOINT", providerName: "cdn_custom_endpoint"} + ContainerRegistryCustomEndpoint = customEndpointConfig{envVarName: "TF_ACC_CONTAINER_REGISTRY_CUSTOM_ENDPOINT", providerName: "container_registry_custom_endpoint"} DnsCustomEndpoint = customEndpointConfig{envVarName: "TF_ACC_DNS_CUSTOM_ENDPOINT", providerName: "dns_custom_endpoint"} DremioCustomEndpoint = customEndpointConfig{envVarName: "TF_ACC_DREMIO_CUSTOM_ENDPOINT", providerName: "dremio_custom_endpoint"} EdgeCloudCustomEndpoint = customEndpointConfig{envVarName: "TF_ACC_EDGECLOUD_CUSTOM_ENDPOINT", providerName: "edgecloud_custom_endpoint"} @@ -122,6 +123,7 @@ var ( ALBCertCustomEndpoint, AlbWafCustomEndpoint, CdnCustomEndpoint, + ContainerRegistryCustomEndpoint, DnsCustomEndpoint, EdgeCloudCustomEndpoint, GitCustomEndpoint, diff --git a/stackit/provider.go b/stackit/provider.go index 1ca0f7ab8..857daa7c6 100644 --- a/stackit/provider.go +++ b/stackit/provider.go @@ -30,6 +30,9 @@ import ( automationVolume "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/automation/volume" cdnCustomDomain "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/cdn/customdomain" cdn "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/cdn/distribution" + containerRegistryArtifactories "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/containerregistry/artifactories" + containerRegistryArtifactory "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/containerregistry/artifactory" + containerRegistryReplicationAdapters "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/containerregistry/replicationadapters" dnsRecordSet "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/dns/recordset" dnsZone "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/dns/zone" dremioInstance "github.com/stackitcloud/terraform-provider-stackit/stackit/internal/services/dremio/instance" @@ -208,6 +211,7 @@ type providerModel struct { AuthorizationCustomEndpoint types.String `tfsdk:"authorization_custom_endpoint"` AutomationCustomEndpoint types.String `tfsdk:"automation_custom_endpoint"` CdnCustomEndpoint types.String `tfsdk:"cdn_custom_endpoint"` + ContainerRegistryCustomEndpoint types.String `tfsdk:"container_registry_custom_endpoint"` ALBCertificatesCustomEndpoint types.String `tfsdk:"alb_certificates_custom_endpoint"` AlbWafCustomEndpoint types.String `tfsdk:"alb_waf_custom_endpoint"` DnsCustomEndpoint types.String `tfsdk:"dns_custom_endpoint"` @@ -275,6 +279,7 @@ func (p *Provider) Schema(_ context.Context, _ provider.SchemaRequest, resp *pro "alb_custom_endpoint": "Custom endpoint for the Application Load Balancer service", "automation_custom_endpoint": "Custom endpoint for the Automation service", "cdn_custom_endpoint": "Custom endpoint for the CDN service", + "container_registry_custom_endpoint": "Custom endpoint for the Container Registry service", "dns_custom_endpoint": "Custom endpoint for the DNS service", "dremio_custom_endpoint": "Custom endpoint for the Dremio service", "edgecloud_custom_endpoint": "Custom endpoint for the Edge Cloud service", @@ -394,6 +399,10 @@ func (p *Provider) Schema(_ context.Context, _ provider.SchemaRequest, resp *pro Optional: true, Description: descriptions["cdn_custom_endpoint"], }, + "container_registry_custom_endpoint": schema.StringAttribute{ + Optional: true, + Description: descriptions["container_registry_custom_endpoint"], + }, "alb_certificates_custom_endpoint": schema.StringAttribute{ Optional: true, Description: descriptions["alb_certificates_custom_endpoint"], @@ -607,6 +616,7 @@ func (p *Provider) Configure(ctx context.Context, req provider.ConfigureRequest, setStringField(providerConfig.AuthorizationCustomEndpoint, func(v string) { customEndpointConfig.AuthorizationCustomEndpoint = v }) setStringField(providerConfig.AutomationCustomEndpoint, func(v string) { customEndpointConfig.AutomationCustomEndpoint = v }) setStringField(providerConfig.CdnCustomEndpoint, func(v string) { customEndpointConfig.CdnCustomEndpoint = v }) + setStringField(providerConfig.ContainerRegistryCustomEndpoint, func(v string) { customEndpointConfig.ContainerRegistryCustomEndpoint = v }) setStringField(providerConfig.DnsCustomEndpoint, func(v string) { customEndpointConfig.DnsCustomEndpoint = v }) setStringField(providerConfig.DremioCustomEndpoint, func(v string) { customEndpointConfig.DremioCustomEndpoint = v }) setStringField(providerConfig.EdgeCloudCustomEndpoint, func(v string) { customEndpointConfig.EdgeCloudCustomEndpoint = v }) @@ -761,6 +771,9 @@ func (p *Provider) DataSources(_ context.Context) []func() datasource.DataSource automationVolume.NewVolumeAutomationDataSource, cdn.NewDistributionDataSource, cdnCustomDomain.NewCustomDomainDataSource, + containerRegistryArtifactory.NewArtifactoryDataSource, + containerRegistryArtifactories.NewArtifactoriesDataSource, + containerRegistryReplicationAdapters.NewReplicationAdaptersDataSource, cert.NewCertificatesDataSource, compliancelock.NewComplianceLockDataSource, dnsRecordSet.NewRecordSetDataSource, @@ -888,6 +901,7 @@ func (p *Provider) Resources(_ context.Context) []func() resource.Resource { cdn.NewDistributionResource, cert.NewCertificatesResource, cdnCustomDomain.NewCustomDomainResource, + containerRegistryArtifactory.NewArtifactoryResource, dnsZone.NewZoneResource, dnsRecordSet.NewRecordSetResource, dremioInstance.NewInstanceResource, diff --git a/stackit/testdata/provider-all-attributes.tf b/stackit/testdata/provider-all-attributes.tf index f421bf50b..374f270af 100644 --- a/stackit/testdata/provider-all-attributes.tf +++ b/stackit/testdata/provider-all-attributes.tf @@ -12,6 +12,7 @@ provider "stackit" { service_account_email = "abc@abc.de" cdn_custom_endpoint = "https://cdn.api.eu01.stackit.cloud" dns_custom_endpoint = "https://dns.api.stackit.cloud" + containerregistry_custom_endpoint = "https://registry.api.stackit.cloud" edgecloud_custom_endpoint = "https://edge.api.stackit.cloud" git_custom_endpoint = "https://git.api.stackit.cloud" iaas_custom_endpoint = "https://iaas.api.stackit.cloud" From d24d9f6c4cc224811724ba0bd3cc3d7ee92c9d62 Mon Sep 17 00:00:00 2001 From: Moises Martinez Date: Wed, 18 Nov 2026 12:18:26 +0100 Subject: [PATCH 2/2] fix(containerregistry): use 3.0 version of sdk --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 03f8b5b1f..a950bc2e1 100644 --- a/go.mod +++ b/go.mod @@ -40,7 +40,7 @@ require ( github.com/stackitcloud/stackit-sdk-go/services/postgresflex v1.16.0 github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v1.5.0 github.com/stackitcloud/stackit-sdk-go/services/redis v1.6.0 - github.com/stackitcloud/stackit-sdk-go/services/registry v0.1.0 + github.com/stackitcloud/stackit-sdk-go/services/registry v0.3.0 github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.28.0 github.com/stackitcloud/stackit-sdk-go/services/scf v0.11.0 github.com/stackitcloud/stackit-sdk-go/services/secretsmanager v0.20.0 diff --git a/go.sum b/go.sum index 8fdac4d51..eb8adcba7 100644 --- a/go.sum +++ b/go.sum @@ -211,8 +211,8 @@ github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v1.5.0 h1:SAro5TWVJDDyi github.com/stackitcloud/stackit-sdk-go/services/rabbitmq v1.5.0/go.mod h1:mjYkyr/A/+9rZnX5IOLEoAMFqHsRCIToZWpsYzYBwWo= github.com/stackitcloud/stackit-sdk-go/services/redis v1.6.0 h1:5UEPilI+RCuXEM8jm4ibREoZAsSAGI1+KnJ0oapye7Q= github.com/stackitcloud/stackit-sdk-go/services/redis v1.6.0/go.mod h1:/wE98YN+s1s1OcaEPt8Z2xO0Y46Gur3nXlg1AiiMNeY= -github.com/stackitcloud/stackit-sdk-go/services/registry v0.1.0 h1:Z52pSNI1o1vi6h25ZQRl26lPMXFRq8RQVEjGlNA+Pwk= -github.com/stackitcloud/stackit-sdk-go/services/registry v0.1.0/go.mod h1:9ew0RfPiwsDbd2OApdaAfTJgZyJbtKKP63NNZz3RWBQ= +github.com/stackitcloud/stackit-sdk-go/services/registry v0.3.0 h1:2yKVVSeISuJiIY0Yi8TK7SdtMEqwZM2Ol2YQqs3GZ4Y= +github.com/stackitcloud/stackit-sdk-go/services/registry v0.3.0/go.mod h1:9ew0RfPiwsDbd2OApdaAfTJgZyJbtKKP63NNZz3RWBQ= github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.28.0 h1:rZB1f9g5M/2mWKXsJIfMvGcFpFWkDQFjG28V/d1ezWw= github.com/stackitcloud/stackit-sdk-go/services/resourcemanager v0.28.0/go.mod h1:IsId3wbkp5oaO0JEaHZpZnbVW6KFHlAptwB+1iG3v3w= github.com/stackitcloud/stackit-sdk-go/services/scf v0.11.0 h1:tdRyQFfGHFiXNhURdHSdesh7ym3y2R9A39B4ywj2Coc=