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
29 changes: 26 additions & 3 deletions cmd/ctrlc/root/apply/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,32 @@ func runApply(ctx context.Context, filePatterns []string, selectorRaw string) er
log.Info("Applying resources", "count", len(specs), "files", len(files))

sortedSpecs := sortSpecsByOrder(specs)
results := providers.
DefaultProviderEngine.
BatchApply(applyCtx, sortedSpecs, providers.BatchApplyOptions{})

var resourceSpecs []*providers.ResourceItemSpec
var otherSpecs []providers.TypedSpec
for _, ts := range sortedSpecs {
if ts.Type == "Resource" {
if spec, ok := ts.Spec.(*providers.ResourceItemSpec); ok {
resourceSpecs = append(resourceSpecs, spec)
continue
}
}
otherSpecs = append(otherSpecs, ts)
}

var results []providers.Result

if len(resourceSpecs) > 0 {
resourceResults := providers.BatchUpsertResources(applyCtx, resourceSpecs)
results = append(results, resourceResults...)
}

if len(otherSpecs) > 0 {
otherResults := providers.
DefaultProviderEngine.
BatchApply(applyCtx, otherSpecs, providers.BatchApplyOptions{})
results = append(results, otherResults...)
}

printResults(results)

Expand Down
97 changes: 96 additions & 1 deletion internal/api/providers/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,107 @@ func (r *ResourceItemSpec) getProviderID(ctx Context) (string, error) {
if err != nil {
return "", fmt.Errorf("failed to create resource provider: %w", err)
}
if createResp.StatusCode() != http.StatusOK {
if createResp.StatusCode() != http.StatusAccepted {
return "", fmt.Errorf("failed to create resource provider: %s", createResp.Status())
}
return createResp.JSON202.Id, nil
Comment on lines +150 to 153
Copy link
Contributor

@coderabbitai coderabbitai bot Feb 25, 2026

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Guard against nil createResp.JSON202 before dereferencing.

The status check at Line 150 (200→202 fix) is correct. However, createResp.JSON202 is populated by the generated client only when the response body deserializes successfully. A 202 with an empty or malformed body leaves JSON202 nil, causing a nil-pointer panic at Line 153.

🛡️ Proposed fix
 if createResp.StatusCode() != http.StatusAccepted {
     return "", fmt.Errorf("failed to create resource provider: %s", createResp.Status())
 }
+if createResp.JSON202 == nil {
+    return "", fmt.Errorf("failed to create resource provider: empty response body")
+}
 return createResp.JSON202.Id, nil
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if createResp.StatusCode() != http.StatusAccepted {
return "", fmt.Errorf("failed to create resource provider: %s", createResp.Status())
}
return createResp.JSON202.Id, nil
if createResp.StatusCode() != http.StatusAccepted {
return "", fmt.Errorf("failed to create resource provider: %s", createResp.Status())
}
if createResp.JSON202 == nil {
return "", fmt.Errorf("failed to create resource provider: empty response body")
}
return createResp.JSON202.Id, nil
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/api/providers/resource.go` around lines 150 - 153, Check
createResp.JSON202 for nil before accessing its Id: if createResp.StatusCode()
!= http.StatusAccepted return the existing error, else if createResp.JSON202 ==
nil return a clear error (e.g., "received 202 but response body empty or
malformed") instead of dereferencing; update the return site that currently uses
createResp.JSON202.Id to first guard with a nil check and then return
createResp.JSON202.Id when non-nil.

Copy link
Member Author

Choose a reason for hiding this comment

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

This is a pre-existing pattern throughout the codebase — not something I introduced.

Please create an issue on this gh repo to come back and fix this later and more broadly.

Copy link
Contributor

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for patterns where JSON response fields are dereferenced without nil checks
# Looking for patterns like .JSON200, .JSON201, .JSON202 being accessed directly

echo "=== Searching for potential nil dereference patterns ==="
rg -n "\.JSON\d{3}\." --type go -A 1 -B 2

echo ""
echo "=== Count of direct JSON response field accesses ==="
rg "\.JSON\d{3}\." --type go | wc -l

Length of output: 9882


🏁 Script executed:

#!/bin/bash
# Create GitHub issue for tracking the nil pointer dereference pattern

gh issue create \
  --repo ctrlplanedev/cli \
  --title "Add nil checks for generated API client response bodies" \
  --body "## Description

Throughout the codebase, generated API client response fields (e.g., \`JSON200\`, \`JSON202\`, \`JSON201\`) are accessed directly without nil checks. These fields are only populated when the response body deserializes successfully. A response with the expected status code but an empty or malformed body will leave these fields nil, causing a nil pointer panic.

## Context

This pattern was identified during review of PR `#57` (specifically in \`internal/api/providers/resource.go\` around line 153 where \`createResp.JSON202.Id\` is accessed), but it appears to be a widespread pattern throughout the codebase.

## Proposed Solution

Add nil checks before dereferencing any generated client response body fields, for example:
- Check if \`resp.JSON200 == nil\` before accessing \`resp.JSON200.Field\`
- Return a descriptive error when the response body is nil despite receiving the expected status code

## Related

- PR: https://github.com/ctrlplanedev/cli/pull/57
- Comment: https://github.com/ctrlplanedev/cli/pull/57#discussion_r2854507891
- Requested by: `@zacharyblasczyk`" \
  --assignee zacharyblasczyk

Length of output: 45


@zacharyblasczyk Understood — I've created issue #58 to track adding nil checks for generated API client response bodies across the codebase. The search found ~48 instances of this pattern, confirming it's a broader issue that makes sense to address systematically in a separate PR.

}

// BatchUpsertResources groups resources by provider and makes one
// SetResourceProviderResources call per provider with all resources in that
// group. This avoids the overwrite problem where sequential single-resource
// calls replace the entire provider's resource set.
func BatchUpsertResources(ctx Context, specs []*ResourceItemSpec) []Result {
// Group by provider name
byProvider := make(map[string][]*ResourceItemSpec)
for _, spec := range specs {
providerName := spec.Provider
if providerName == "" {
providerName = "ctrlc-apply"
}
byProvider[providerName] = append(byProvider[providerName], spec)
}

var results []Result
for providerName, group := range byProvider {
// Resolve provider ID (create if needed) using the first spec
providerID, err := group[0].getProviderID(ctx)
if err != nil {
for _, spec := range group {
results = append(results, Result{
Type: resourceTypeName,
Name: spec.DisplayName,
Error: fmt.Errorf("failed to get provider %q: %w", providerName, err),
})
}
continue
}

// Build the batch resource list
apiResources := make([]api.ResourceProviderResource, 0, len(group))
for _, spec := range group {
metadata := spec.Metadata
if metadata == nil {
metadata = make(map[string]string)
}
config := spec.Config
if config == nil {
config = make(map[string]any)
}
apiResources = append(apiResources, api.ResourceProviderResource{
Identifier: spec.Identifier,
Name: spec.DisplayName,
Kind: spec.Kind,
Version: spec.Version,
Config: config,
Metadata: metadata,
})
}

// Single API call for all resources under this provider
resp, err := ctx.APIClient().SetResourceProviderResourcesWithResponse(
ctx.Ctx(), ctx.WorkspaceIDValue(), providerID,
api.SetResourceProviderResourcesJSONRequestBody{Resources: apiResources},
)
if err != nil {
for _, spec := range group {
results = append(results, Result{
Type: resourceTypeName,
Name: spec.DisplayName,
Error: fmt.Errorf("failed to upsert resources: %w", err),
})
}
continue
}
if resp.StatusCode() != http.StatusAccepted {
for _, spec := range group {
results = append(results, Result{
Type: resourceTypeName,
Name: spec.DisplayName,
Error: fmt.Errorf("failed to upsert resources: %s", resp.Status()),
})
}
continue
}

// Sync variables individually (each resource may have different vars)
for _, spec := range group {
result := Result{
Type: resourceTypeName,
Name: spec.DisplayName,
ID: spec.Identifier,
Action: "upserted",
}
if err := spec.syncVariables(ctx); err != nil {
result.Error = err
}
results = append(results, result)
}
}

return results
}

func (r *ResourceItemSpec) syncVariables(ctx Context) error {
vars := r.Variables
if vars == nil {
Expand Down