Skip to content

Commit

Permalink
chore(no-ticket): valid provided credentials in the plan phase
Browse files Browse the repository at this point in the history
  • Loading branch information
cloudsmith-iduffy committed Dec 1, 2024
1 parent 73d299a commit 4166ebb
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
5 changes: 5 additions & 0 deletions cloudsmith/provider_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ func newProviderConfig(apiHost, apiKey, userAgent string) (*providerConfig, diag
},
)

req := apiClient.UserApi.UserSelf(auth)
if _, _, err := apiClient.UserApi.UserSelfExecute(req); err != nil {
return nil, diag.FromErr(errors.New("invalid API credentials"))
}

return &providerConfig{Auth: auth, APIClient: apiClient}, nil
}

Expand Down
62 changes: 61 additions & 1 deletion cloudsmith/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@
package cloudsmith

import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"regexp"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

Expand All @@ -31,8 +36,63 @@ func testAccPreCheck(t *testing.T) {
if v := os.Getenv("CLOUDSMITH_API_KEY"); v == "" {
t.Fatal("CLOUDSMITH_API_KEY must be set for acceptance tests")
}

if v := os.Getenv("CLOUDSMITH_NAMESPACE"); v == "" {
t.Fatal("CLOUDSMITH_NAMESPACE must be set for acceptance tests")
}
}
func TestAccProvider_UserSelfValidation(t *testing.T) {
// Create mock server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/user/self/" {
w.Header().Set("Content-Type", "application/json")
if r.Header.Get("X-Api-Key") == "valid-token" {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, `{"email": "[email protected]", "name": "Test User", "slug": "test-user", "slug_perm": "test-user"}`)
} else {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, `{"error": "invalid API credentials"}`)
}
}
}))
defer server.Close()

tests := []struct {
name string
apiKey string
}{
{
name: "ValidToken",
apiKey: "valid-token",
},
{
name: "InvalidToken",
apiKey: "invalid-token",
},
}

for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Setenv("CLOUDSMITH_API_HOST", server.URL)
t.Setenv("CLOUDSMITH_API_KEY", tc.apiKey)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: selfConfig,
ExpectError: regexp.MustCompile("invalid API credentials"),
SkipFunc: func() (bool, error) {
// Skip error check for valid token case
return tc.apiKey == "valid-token", nil
},
},
},
})
})
}
}

var selfConfig string = `
data "cloudsmith_user_self" "this" {
}`

0 comments on commit 4166ebb

Please sign in to comment.