Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion cmd/login/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@ func (h *handler) execute(ctx context.Context) error {

h.spinner.Update("Fetching user context...")
if err := h.fetchTenantConfig(ctx, tokenSet); err != nil {
h.log.Debug().Err(err).Msgf("failed to fetch user context — %s not written", tenantctx.ContextFile)
h.spinner.StopAll()
return fmt.Errorf("failed to fetch user context: %w", err)
}

// Stop spinner before final output
Expand Down
44 changes: 44 additions & 0 deletions cmd/login/login_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package login

import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
Expand All @@ -16,9 +18,51 @@ import (
"github.com/smartcontractkit/cre-cli/internal/credentials"
"github.com/smartcontractkit/cre-cli/internal/environments"
"github.com/smartcontractkit/cre-cli/internal/oauth"
"github.com/smartcontractkit/cre-cli/internal/tenantctx"
"github.com/smartcontractkit/cre-cli/internal/ui"
)

func TestFetchTenantConfig_GQLError_ReturnsError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"errors": []map[string]string{{"message": "unauthorized"}},
})
}))
defer srv.Close()

tmp := t.TempDir()
t.Setenv("HOME", tmp)
log := zerolog.Nop()
h := &handler{
log: &log,
environmentSet: &environments.EnvironmentSet{
EnvName: "STAGING",
GraphQLURL: srv.URL,
},
}

tokenSet := &credentials.CreLoginTokenSet{
AccessToken: "test-access-token",
IDToken: "test-id-token",
ExpiresIn: 3600,
TokenType: "Bearer",
}

err := h.fetchTenantConfig(context.Background(), tokenSet)
if err == nil {
t.Fatal("expected error when GQL fetch fails")
}
if !strings.Contains(err.Error(), "fetch user context") {
t.Errorf("expected fetch user context error, got: %v", err)
}

contextPath := filepath.Join(tmp, credentials.ConfigDir, tenantctx.ContextFile)
if _, statErr := os.Stat(contextPath); statErr == nil {
t.Errorf("expected %s not to be written on fetch failure", tenantctx.ContextFile)
}
}

func TestLogin_NonInteractive_ReturnsError(t *testing.T) {
// Create a parent command with the global --non-interactive persistent flag,
// since in production this flag is defined on the root command.
Expand Down
19 changes: 17 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
"github.com/smartcontractkit/cre-cli/internal/runtime"
"github.com/smartcontractkit/cre-cli/internal/settings"
"github.com/smartcontractkit/cre-cli/internal/telemetry"
"github.com/smartcontractkit/cre-cli/internal/tenantctx"
"github.com/smartcontractkit/cre-cli/internal/ui"
intupdate "github.com/smartcontractkit/cre-cli/internal/update"
)
Expand Down Expand Up @@ -236,7 +237,14 @@ func newRootCommand() *cobra.Command {
spinner.Update("Loading user context...")
}
if err := runtimeContext.AttachTenantContext(cmd.Context()); err != nil {
ui.Warning("Failed to load user context")
if showSpinner {
spinner.Stop()
}
ui.ErrorWithSuggestions("Failed to load user context", []string{
"Run `cre login` to fetch your user context",
fmt.Sprintf("Ensure ~/.cre/%s exists and is readable", tenantctx.ContextFile),
Copy link
Copy Markdown
Collaborator

@anirudhwarrier anirudhwarrier Jun 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider replacing ~ with value returned by os.UserHomeDir()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

})
return fmt.Errorf("user context required: %w", err)
}

// Check if organization is ungated for commands that require it
Expand Down Expand Up @@ -295,7 +303,14 @@ func newRootCommand() *cobra.Command {
spinner.Update("Loading user context...")
}
if err := runtimeContext.AttachTenantContext(cmd.Context()); err != nil {
ui.Warning("Failed to load user context")
if showSpinner {
spinner.Stop()
}
ui.ErrorWithSuggestions("Failed to load user context", []string{
"Run `cre login` to fetch your user context",
fmt.Sprintf("Ensure ~/.cre/%s exists and is readable", tenantctx.ContextFile),
})
return fmt.Errorf("user context required: %w", err)
}
}
}
Expand Down
63 changes: 54 additions & 9 deletions internal/testutil/graphql_mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,56 @@ import (
"github.com/smartcontractkit/cre-cli/internal/environments"
)

// MockGetCreOrganizationInfoGraphQLPayload returns a GraphQL response for getCreOrganizationInfo.
func MockGetCreOrganizationInfoGraphQLPayload() map[string]any {
return map[string]any{
"data": map[string]any{
"getCreOrganizationInfo": map[string]any{
"orgId": "test-org-id",
"derivedWorkflowOwners": []string{"ab12cd34ef56ab12cd34ef56ab12cd34ef56ab12"},
},
},
}
}

// QueryIsGetTenantConfig reports whether q is a getTenantConfig GraphQL operation.
func QueryIsGetTenantConfig(q string) bool {
return strings.Contains(q, "GetTenantConfig") || strings.Contains(q, "getTenantConfig")
}

// MockGetTenantConfigGraphQLPayload returns a GraphQL response for getTenantConfig
// suitable for E2E tests using the anvil-devnet workflow registry defaults.
func MockGetTenantConfigGraphQLPayload() map[string]any {
return map[string]any{
"data": map[string]any{
"getTenantConfig": map[string]any{
"tenantId": "test-tenant-id",
"defaultDonFamily": "test-don",
"vaultGatewayUrl": "https://vault.example.test",
"registries": []map[string]any{
{
"id": "anvil-devnet",
"label": "anvil-devnet",
"type": "ON_CHAIN",
"chainSelector": "6433500567565415381",
"address": "0x5FbDB2315678afecb367f032d93F642f64180aa3",
"secretsAuthFlows": []string{"OWNER_KEY_SIGNING"},
},
{
"id": "private",
"label": "Private (Chainlink-hosted)",
"type": "OFF_CHAIN",
"secretsAuthFlows": []string{"BROWSER"},
},
},
"forwarders": []any{},
},
},
}
}

// NewGraphQLMockServerGetOrganization starts an httptest.Server that responds to
// getCreOrganizationInfo with a fixed orgId and derivedWorkflowOwners.
// getCreOrganizationInfo and getTenantConfig with fixed test payloads.
// It sets EnvVarGraphQLURL so CLI commands use this server. Caller must defer srv.Close().
func NewGraphQLMockServerGetOrganization(t *testing.T) *httptest.Server {
t.Helper()
Expand All @@ -24,14 +72,11 @@ func NewGraphQLMockServerGetOrganization(t *testing.T) *httptest.Server {
_ = json.NewDecoder(r.Body).Decode(&req)
w.Header().Set("Content-Type", "application/json")
if strings.Contains(req.Query, "getCreOrganizationInfo") {
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{
"getCreOrganizationInfo": map[string]any{
"orgId": "test-org-id",
"derivedWorkflowOwners": []string{"ab12cd34ef56ab12cd34ef56ab12cd34ef56ab12"},
},
},
})
_ = json.NewEncoder(w).Encode(MockGetCreOrganizationInfoGraphQLPayload())
return
}
if QueryIsGetTenantConfig(req.Query) {
_ = json.NewEncoder(w).Encode(MockGetTenantConfigGraphQLPayload())
return
}
w.WriteHeader(http.StatusBadRequest)
Expand Down
13 changes: 5 additions & 8 deletions test/multi_command_flows/account_happy_path.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,11 @@ func RunAccountHappyPath(t *testing.T, tc TestConfig, testEthURL, chainName stri

// Handle authentication validation query
if strings.Contains(req.Query, "getCreOrganizationInfo") {
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{
"getCreOrganizationInfo": map[string]any{
"orgId": "test-org-id",
"derivedWorkflowOwners": []string{"ab12cd34ef56ab12cd34ef56ab12cd34ef56ab12"},
},
},
})
_ = json.NewEncoder(w).Encode(testutil.MockGetCreOrganizationInfoGraphQLPayload())
return
}
if testutil.QueryIsGetTenantConfig(req.Query) {
_ = json.NewEncoder(w).Encode(testutil.MockGetTenantConfigGraphQLPayload())
return
}

Expand Down
27 changes: 11 additions & 16 deletions test/multi_command_flows/secrets_happy_path.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/smartcontractkit/cre-cli/internal/credentials"
"github.com/smartcontractkit/cre-cli/internal/environments"
"github.com/smartcontractkit/cre-cli/internal/settings"
"github.com/smartcontractkit/cre-cli/internal/testutil"
)

// Hex-encoded tdh2easy.PublicKey blob returned by the gateway
Expand Down Expand Up @@ -63,14 +64,11 @@ func RunSecretsHappyPath(t *testing.T, tc TestConfig, chainName string) {

// Handle authentication validation query
if strings.Contains(req.Query, "getCreOrganizationInfo") {
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{
"getCreOrganizationInfo": map[string]any{
"orgId": "test-org-id",
"derivedWorkflowOwners": []string{"ab12cd34ef56ab12cd34ef56ab12cd34ef56ab12"},
},
},
})
_ = json.NewEncoder(w).Encode(testutil.MockGetCreOrganizationInfoGraphQLPayload())
return
}
if testutil.QueryIsGetTenantConfig(req.Query) {
_ = json.NewEncoder(w).Encode(testutil.MockGetTenantConfigGraphQLPayload())
return
}

Expand Down Expand Up @@ -258,14 +256,11 @@ func RunSecretsListMsig(t *testing.T, tc TestConfig, chainName string) {

// Handle authentication validation query
if strings.Contains(req.Query, "getCreOrganizationInfo") {
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{
"getCreOrganizationInfo": map[string]any{
"orgId": "test-org-id",
"derivedWorkflowOwners": []string{"ab12cd34ef56ab12cd34ef56ab12cd34ef56ab12"},
},
},
})
_ = json.NewEncoder(w).Encode(testutil.MockGetCreOrganizationInfoGraphQLPayload())
return
}
if testutil.QueryIsGetTenantConfig(req.Query) {
_ = json.NewEncoder(w).Encode(testutil.MockGetTenantConfigGraphQLPayload())
return
}

Expand Down
14 changes: 6 additions & 8 deletions test/multi_command_flows/workflow_happy_path_1.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/smartcontractkit/cre-cli/internal/credentials"
"github.com/smartcontractkit/cre-cli/internal/environments"
"github.com/smartcontractkit/cre-cli/internal/settings"
"github.com/smartcontractkit/cre-cli/internal/testutil"
)

// TestConfig represents test configuration
Expand Down Expand Up @@ -62,14 +63,11 @@ func workflowDeployEoaWithMockStorage(t *testing.T, tc TestConfig) (output strin

// Handle authentication validation query
if strings.Contains(req.Query, "getCreOrganizationInfo") {
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{
"getCreOrganizationInfo": map[string]any{
"orgId": "test-org-id",
"derivedWorkflowOwners": []string{"ab12cd34ef56ab12cd34ef56ab12cd34ef56ab12"},
},
},
})
_ = json.NewEncoder(w).Encode(testutil.MockGetCreOrganizationInfoGraphQLPayload())
return
}
if testutil.QueryIsGetTenantConfig(req.Query) {
_ = json.NewEncoder(w).Encode(testutil.MockGetTenantConfigGraphQLPayload())
return
}

Expand Down
27 changes: 11 additions & 16 deletions test/multi_command_flows/workflow_happy_path_2.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/smartcontractkit/cre-cli/internal/constants"
"github.com/smartcontractkit/cre-cli/internal/environments"
"github.com/smartcontractkit/cre-cli/internal/settings"
"github.com/smartcontractkit/cre-cli/internal/testutil"
)

// workflowDeployEoa deploys a workflow via CLI, mocking GraphQL + Origin.
Expand All @@ -35,14 +36,11 @@ func workflowDeployEoa(t *testing.T, tc TestConfig) string {

// Handle authentication validation query
if strings.Contains(req.Query, "getCreOrganizationInfo") {
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{
"getCreOrganizationInfo": map[string]any{
"orgId": "test-org-id",
"derivedWorkflowOwners": []string{"ab12cd34ef56ab12cd34ef56ab12cd34ef56ab12"},
},
},
})
_ = json.NewEncoder(w).Encode(testutil.MockGetCreOrganizationInfoGraphQLPayload())
return
}
if testutil.QueryIsGetTenantConfig(req.Query) {
_ = json.NewEncoder(w).Encode(testutil.MockGetTenantConfigGraphQLPayload())
return
}

Expand Down Expand Up @@ -156,14 +154,11 @@ func workflowDeployUpdateWithConfig(t *testing.T, tc TestConfig) string {

// Handle authentication validation query
if strings.Contains(req.Query, "getCreOrganizationInfo") {
_ = json.NewEncoder(w).Encode(map[string]any{
"data": map[string]any{
"getCreOrganizationInfo": map[string]any{
"orgId": "test-org-id",
"derivedWorkflowOwners": []string{"ab12cd34ef56ab12cd34ef56ab12cd34ef56ab12"},
},
},
})
_ = json.NewEncoder(w).Encode(testutil.MockGetCreOrganizationInfoGraphQLPayload())
return
}
if testutil.QueryIsGetTenantConfig(req.Query) {
_ = json.NewEncoder(w).Encode(testutil.MockGetTenantConfigGraphQLPayload())
return
}

Expand Down
Loading
Loading