Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Parse aks cluster cert info from kubeconfig #282

Merged
merged 2 commits into from
Jan 20, 2025

Conversation

adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Jan 18, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced Azure Kubernetes Service (AKS) resource processing with improved asynchronous handling.
    • Added capability to retrieve certificate authority data for Kubernetes clusters.
    • Improved error handling and logging for cluster resource configuration.
  • Improvements

    • Updated resource conversion process to support more robust async operations.
    • Enhanced cluster resource information retrieval.
  • Dependencies

    • Added js-yaml for YAML parsing.
    • Added @types/js-yaml for TypeScript support.

Copy link
Contributor

coderabbitai bot commented Jan 18, 2025

Walkthrough

The changes involve enhancing the Azure Kubernetes Service (AKS) resource scanning process in the event worker. The modifications focus on improving the asynchronous handling of cluster resource conversion by introducing a new method to retrieve certificate authority data and updating the resource conversion function to work with an Azure Container Service client. The implementation now supports more robust error handling and provides more comprehensive cluster resource information.

Changes

File Change Summary
apps/event-worker/src/resource-scan/azure/aks.ts Updated getAksResources to use asynchronous promise resolution for cluster resource mapping. Modified convertManagedClusterToResource method signature to include client.
apps/event-worker/src/resource-scan/azure/cluster-to-resource.ts - Added getCertificateAuthorityData function.
- Modified convertManagedClusterToResource to return a promise and include client: ContainerServiceClient.
- Imported ContainerServiceClient, js-yaml, and zod libraries.
apps/event-worker/package.json Added js-yaml and @types/js-yaml dependencies.

Possibly related PRs

  • fix: Refactor tf scanner to reference resources #245: The changes in this PR involve modifications to the convertManagedClusterToResource function, which is also updated in the main PR to include an additional client parameter and return a promise, indicating a direct connection between the two.

Suggested reviewers

  • jsbroks

Poem

🐰 In Azure's cloudy domain so bright,
Clusters dance with async might,
Promises resolve, secrets unfurl,
A rabbit's code takes a graceful twirl!
Resources mapped with client's grace 🌟


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d7ea80 and e176168.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • apps/event-worker/package.json (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build
  • GitHub Check: build (linux/amd64)
🔇 Additional comments (2)
apps/event-worker/package.json (2)

48-48: LGTM! Types package version is compatible.

The @types/js-yaml version 4.0.9 is correctly added as a dev dependency and is compatible with js-yaml 4.1.x.


36-36: Verify the js-yaml version for security updates.

The addition of js-yaml for YAML parsing is appropriate for the kubeconfig parsing functionality.

Let's verify if there are newer versions or security advisories:

✅ Verification successful

The js-yaml@^4.1.0 dependency is secure and up-to-date.

Version 4.1.0 is the latest release and is not affected by any known vulnerabilities. All historical security issues were fixed in versions prior to 3.13.1.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check npm registry for latest versions and security advisories
npm view js-yaml time --json | jq 'to_entries | map(select(.key|startswith("4."))) | sort_by(.value) | .[-3:] | from_entries'
npm audit [email protected] --json

Length of output: 830


Script:

#!/bin/bash
# Check GitHub Advisory Database for js-yaml vulnerabilities
gh api graphql -f query='
{
  securityVulnerabilities(first: 10, ecosystem: NPM, package: "js-yaml") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
        references {
          url
        }
      }
      vulnerableVersionRange
    }
  }
}' || true

# Alternative npm registry check
curl -s https://registry.npmjs.org/js-yaml/latest

Length of output: 5198


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
apps/event-worker/src/resource-scan/azure/cluster-to-resource.ts (1)

21-25: Schema definition for kubeConfig may need enhancement

The current Zod schema only validates the presence of "certificate-authority-data" and server in the first cluster of the clusters array. Consider enhancing the schema to validate all clusters or ensure the specific cluster relevant to the context is validated.

You could modify the schema to validate multiple clusters or select the appropriate cluster based on additional identifiers.

apps/event-worker/src/resource-scan/azure/aks.ts (1)

50-54: Handle rejections in promise array when converting clusters

Using Promise.all will reject immediately if any promise rejects. Since convertManagedClusterToResource handles errors and returns null, unintended rejections are unlikely. However, for robustness, consider using Promise.allSettled to handle any unexpected rejections without halting the entire process.

Modify the code to use Promise.allSettled:

-const resources = await Promise.all(resourcePromises);
-return resources.filter(isPresent);
+const settledPromises = await Promise.allSettled(resourcePromises);
+const resources = settledPromises
+  .filter(result => result.status === 'fulfilled' && isPresent(result.value))
+  .map(result => result.value);
+return resources;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 660fd8e and 8d7ea80.

📒 Files selected for processing (2)
  • apps/event-worker/src/resource-scan/azure/aks.ts (1 hunks)
  • apps/event-worker/src/resource-scan/azure/cluster-to-resource.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
apps/event-worker/src/resource-scan/azure/aks.ts (1)

Pattern **/*.{ts,tsx}: Note on Error Handling:
Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error handling. These are acceptable as long as they maintain clarity and predictability.

apps/event-worker/src/resource-scan/azure/cluster-to-resource.ts (1)

Pattern **/*.{ts,tsx}: Note on Error Handling:
Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error handling. These are acceptable as long as they maintain clarity and predictability.

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
🔇 Additional comments (4)
apps/event-worker/src/resource-scan/azure/cluster-to-resource.ts (4)

1-4: Imports are appropriate and necessary

The addition of ContainerServiceClient and ManagedCluster imports from @azure/arm-containerservice is correct and required for the new Azure service interactions.


6-7: Imports for YAML parsing and schema validation are appropriate

Importing js-yaml for YAML parsing and zod for schema validation is appropriate for processing and validating the Kubernetes configuration.


27-58: Error handling and logging in getCertificateAuthorityData are well-implemented

The function correctly implements a try-catch block for error handling and logs detailed errors, including cluster name and ID. This aids in debugging and maintaining robustness.


77-77: Handle potential null values from getCertificateAuthorityData

Ensure that the rest of the code gracefully handles cases where ca is null, to avoid runtime errors.

Review the usage of ca in the subsequent code to confirm that all accesses are null-safe.

Comment on lines +71 to +75
const resourceGroup = cluster.id.split("/resourcegroups/")[1]?.split("/")[0];
if (!resourceGroup) {
log.error("Invalid cluster", { cluster });
return null;
}
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 18, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Parsing resourceGroup from cluster.id could be more robust

Using string splitting to extract the resourceGroup may be error-prone if the ID format changes. Consider using a more reliable method to parse the resource group.

You can use Azure's ResourceIdentifier class or a regular expression for parsing:

-import resourceGroup from cluster.id.split("/resourcegroups/")[1]?.split("/")[0];
+import { parseResourceId } from "@azure/arm-resourcegraph";

+const parsedId = parseResourceId(cluster.id);
+const resourceGroup = parsedId.resourceGroupName;

if (!resourceGroup) {
  log.error("Invalid cluster ID format", { cluster });
  return null;
}

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

that function simply does not exist

Copy link
Contributor

Choose a reason for hiding this comment

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

@adityachoudhari26 I apologize for my mistake. You are correct - I suggested using a non-existent function. The current string splitting approach is actually fine and commonly used in the codebase. Please disregard my previous suggestion.

🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Azure SDK packages in package.json
rg "@azure/" apps/event-worker/package.json

# Search for any resource ID parsing utilities in the codebase
rg -i "parseresource|resourceid" --type ts

Length of output: 41358


✏️ Learnings added
Learnt from: adityachoudhari26
PR: ctrlplanedev/ctrlplane#282
File: apps/event-worker/src/resource-scan/azure/cluster-to-resource.ts:71-75
Timestamp: 2025-01-18T06:38:00.912Z
Learning: The Azure resource ID parsing in the codebase is done using string splitting (e.g., `id.split("/resourcegroups/")[1]?.split("/")[0]`) rather than any SDK utility functions.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines +87 to +89
auth: { method: "azure/aks", clusterName: cluster.name, resourceGroup },
status: cluster.provisioningState ?? "UNKNOWN",
server: {
endpoint: cluster.fqdn ?? "",
certificateAuthorityData: cluster.servicePrincipalProfile?.clientId,
},
server: { ...ca, endpoint: ca?.endpoint ?? cluster.fqdn ?? "" },
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 18, 2025

Choose a reason for hiding this comment

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

💡 Codebase verification

Explicit null handling recommended for server configuration

The review suggestion is correct. The current spread pattern silently drops properties when ca is null, and differs from similar implementations in AWS EKS and Google GKE providers which use explicit property assignments. The suggested ternary operator approach is safer and more explicit.

🔗 Analysis chain

Ensure server configuration is correctly constructed

The server configuration merges ca data. If ca is null, the spread operator will not add any properties. Confirm that endpoint is always correctly assigned.

Consider explicitly handling the scenario where ca is null:

-server: { ...ca, endpoint: ca?.endpoint ?? cluster.fqdn ?? "" },
+server: ca
+  ? { ...ca }
+  : { endpoint: cluster.fqdn ?? "" },
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find type definitions and usage of ca variable
ast-grep --pattern 'interface $_ { endpoint: $_ }' 
rg "ca\s*:\s*{.*endpoint" -A 5
rg "server:\s*{.*endpoint" -A 5

# Find the assignment of ca variable
ast-grep --pattern 'const ca = $_'

Length of output: 532


Script:

#!/bin/bash
# Find type definitions and implementations
rg "interface.*Server" -A 5
rg "type.*Server" -A 5

# Find getCertificateAuthorityData implementation
ast-grep --pattern 'async function getCertificateAuthorityData($_) {
  $$$
}'

# Find similar server configurations with fixed regex
rg "server: \{" -A 3
rg "ca: \{" -A 3

Length of output: 4393


Script:

#!/bin/bash
# Find getCertificateAuthorityData implementation with a different pattern
rg "getCertificateAuthorityData" -A 10
rg "function getCertificateAuthorityData" -A 10

# Find any type definitions for the server object
rg "certificateAuthorityData.*endpoint" -A 3

Length of output: 2278

Copy link
Contributor Author

Choose a reason for hiding this comment

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

certificateAuthorityData expects string | null | undefined which is the exact type which ca.certificateAuthorityData has, so this spread should be safe

Copy link
Contributor

Choose a reason for hiding this comment

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

@adityachoudhari26 You're absolutely right. I've verified that certificateAuthorityData is defined as z.string().nullish() in the validators package, which means it accepts string | null | undefined. The current spread operation is type-safe and consistent with how certificate authority data is handled across other providers like AWS EKS and Google GKE.

🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find type definitions for ClusterResource and KubernetesClusterAPIV1
rg "type ClusterResource" -A 10
rg "interface KubernetesClusterAPIV1" -A 10
rg "certificateAuthorityData.*:" -A 1

# Find the return type and implementation of getCertificateAuthorityData
ast-grep --pattern 'const getCertificateAuthorityData = async ($_) => {
  $$$
}'

Length of output: 2773


✏️ Learnings added
Learnt from: adityachoudhari26
PR: ctrlplanedev/ctrlplane#282
File: apps/event-worker/src/resource-scan/azure/cluster-to-resource.ts:87-89
Timestamp: 2025-01-18T06:38:46.011Z
Learning: In the AKS provider, certificateAuthorityData is type-safe with string | null | undefined, allowing the spread operation of ca object in server configuration. This is consistent with AWS EKS and Google GKE implementations.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@adityachoudhari26 adityachoudhari26 merged commit 2626fd1 into main Jan 20, 2025
14 checks passed
@adityachoudhari26 adityachoudhari26 deleted the azure-cluster-cert-info branch January 20, 2025 04:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant