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

Fixed parse eks region #92

Merged
merged 1 commit into from
Feb 22, 2024
Merged

Fixed parse eks region #92

merged 1 commit into from
Feb 22, 2024

Conversation

dwertent
Copy link
Collaborator

@dwertent dwertent commented Feb 22, 2024

User description

Here is the error log:

{"level":"info","ts":"2024-02-06T13:36:52Z","msg":"credentials loaded from path","path":"/etc/credentials","accessKeyLength":36,"accountLength":36}
{"level":"info","ts":"2024-02-06T13:36:52Z","msg":"Starting swagger UI. baseURI: /openapi/v2/, docsEP: docs, rapidocEP: rapi, swaggerui: swaggerui"}
{"level":"info","ts":"2024-02-06T13:36:52Z","msg":"Started Kubescape server","port":"8080","version":""}
{"level":"info","ts":"2024-02-06T13:37:01Z","msg":"REST API received scan request","body":"{\"targetNames\":[\"allcontrols\",\"nsa\",\"mitre\",\"security\"],\"targetType\":\"Framework\",\"hostScanner\":false}"}
{"level":"info","ts":"2024-02-06T13:37:01Z","msg":"requesting scan","scanID":"9bf77782-58c5-4be4-8736-96f81ba1e471","api":"v1/scan"}
{"level":"info","ts":"2024-02-06T13:37:01Z","msg":"triggering scan","scanID":"9bf77782-58c5-4be4-8736-96f81ba1e471"}
{"level":"info","ts":"2024-02-06T13:37:01Z","msg":"scan triggered","ID":"9bf77782-58c5-4be4-8736-96f81ba1e471"}
{"level":"info","ts":"2024-02-06T13:37:01Z","msg":"Kubescape scanner initializing..."}
I0206 13:37:03.391816       1 request.go:696] Waited for 1.047025452s due to client-side throttling, not priority and fairness, request: GET:https://172.20.0.1:443/apis/storage.k8s.io/v1beta1?timeout=32s
{"level":"warn","ts":"2024-02-06T13:37:04Z","msg":"Unknown build number: this might affect your scan results. Please ensure that you are running the latest version."}
{"level":"info","ts":"2024-02-06T13:37:06Z","msg":"Initialized scanner"}
{"level":"info","ts":"2024-02-06T13:37:06Z","msg":"Loading policies..."}
{"level":"info","ts":"2024-02-06T13:37:06Z","msg":"Loaded policies"}
{"level":"info","ts":"2024-02-06T13:37:06Z","msg":"Loading exceptions..."}
{"level":"info","ts":"2024-02-06T13:37:06Z","msg":"Loaded exceptions"}
{"level":"info","ts":"2024-02-06T13:37:06Z","msg":"Loading account configurations..."}
{"level":"info","ts":"2024-02-06T13:37:06Z","msg":"Loaded account configurations"}
{"level":"info","ts":"2024-02-06T13:37:06Z","msg":"Accessing Kubernetes objects..."}
{"level":"info","ts":"2024-02-06T13:37:11Z","msg":"Accessed Kubernetes objects"}
{"level":"info","ts":"2024-02-06T13:37:11Z","msg":"Collecting RBAC resources..."}
{"level":"info","ts":"2024-02-06T13:37:15Z","msg":"Collected RBAC resources"}
{"level":"info","ts":"2024-02-06T13:37:15Z","msg":"Downloading cloud resources..."}
panic: runtime error: slice bounds out of range [:6] with capacity 4 [recovered]
	panic: runtime error: slice bounds out of range [:6] with capacity 4 [recovered]
	panic: runtime error: slice bounds out of range [:6] with capacity 4

goroutine 42 [running]:
go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End.func1()
	/go/pkg/mod/go.opentelemetry.io/otel/sdk@v1.18.0/trace/span.go:383 +0x25
go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End(0xc001312000, {0x0, 0x0, 0xcbdca2e176faa27e?})
	/go/pkg/mod/go.opentelemetry.io/otel/sdk@v1.18.0/trace/span.go:421 +0x9fb
panic({0x3d38b00?, 0xc004a14ff0?})
	/usr/local/go/src/runtime/panic.go:914 +0x21f
go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End.func1()
	/go/pkg/mod/go.opentelemetry.io/otel/sdk@v1.18.0/trace/span.go:383 +0x25
go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End(0xc000da0600, {0x0, 0x0, 0xc00456ae08?})
	/go/pkg/mod/go.opentelemetry.io/otel/sdk@v1.18.0/trace/span.go:421 +0x9fb
panic({0x3d38b00?, 0xc004a14ff0?})
	/usr/local/go/src/runtime/panic.go:914 +0x21f
github.com/kubescape/k8s-interface/cloudsupport/v1.(*EKSSupport).GetRegion(0xc0006e41c0?, {0xc0011dac00, 0x15})
	/go/pkg/mod/github.com/kubescape/k8s-interface@v0.0.156/cloudsupport/v1/ekssupport.go:129 +0x14e
github.com/kubescape/k8s-interface/cloudsupport.GetDescriptiveInfoFromCloudProvider({0xc0011dac00, 0x15}, {0x3fa369e?, 0xc004a48ed0?})
	/go/pkg/mod/github.com/kubescape/k8s-interface@v0.0.156/cloudsupport/cloudproviderconfiguration.go:52 +0xf2
github.com/kubescape/kubescape/v3/core/pkg/resourcehandler.(*K8sResourceHandler).collectCloudResources(0xc001a68fc0, {0x4c3bd30, 0xc0020f2b10}, 0xc0000f6960, 0xc002183b70?, 0x3d84540?, {0xc0097456c0, 0x3, 0xc0000a8800?}, {0x4c2b600, ...})
	/work/core/pkg/resourcehandler/k8sresources.go:229 +0x574
github.com/kubescape/kubescape/v3/core/pkg/resourcehandler.(*K8sResourceHandler).GetResources(0xc001a68fc0, {0x4c3bd30, 0xc0020f2b10}, 0xc0000f6960, {0x4c2b600, 0xc001895f38}, 0xc0014d4480)
	/work/core/pkg/resourcehandler/k8sresources.go:146 +0xb39
github.com/kubescape/kubescape/v3/core/pkg/resourcehandler.CollectResources({0x4c3bd30, 0xc0020f2ae0}, {0x4c2b570, 0xc001a68fc0}, {0x0?, 0xc0010b9f01?, 0xc000eca500?}, 0xc0000f6960, {0x4c2b600, 0xc001895f38}, ...)
	/work/core/pkg/resourcehandler/handlerpullresources.go:29 +0x1b5
github.com/kubescape/kubescape/v3/core/core.(*Kubescape).Scan(0xc0010c2440?, {0x4c3bd30?, 0xc0010a62a0}, 0xc0014d4480)
	/work/core/core/scan.go:166 +0x825
github.com/kubescape/kubescape/v3/httphandler/handlerequests/v1.scan({0x4c3bd30, 0xc00163b3e0}, 0xc0014d4480, {0xc00012e7b0, 0x24})
	/work/httphandler/handlerequests/v1/requestshandlerutils.go:76 +0xf85
github.com/kubescape/kubescape/v3/httphandler/handlerequests/v1.(*HTTPHandler).executeScan(0xc000f7f320, 0xc00163af00)
	/work/httphandler/handlerequests/v1/requestshandlerutils.go:31 +0x16a
github.com/kubescape/kubescape/v3/httphandler/handlerequests/v1.(*HTTPHandler).watchForScan(0xc000f7f320)
	/work/httphandler/handlerequests/v1/requestshandlerutils.go:56 +0x53
created by github.com/kubescape/kubescape/v3/httphandler/handlerequests/v1.NewHTTPHandler in goroutine 1
	/work/httphandler/handlerequests/v1/requestshandler.go:44 +0x12f

Type

bug_fix, enhancement


Description

  • Enhanced the logic for parsing the AWS region from EKS cluster names, supporting a wider range of cluster name formats.
  • Improved error handling in cases where the region cannot be determined from the cluster name.
  • Added comprehensive test cases to validate the parsing of AWS regions from various EKS cluster name formats, including handling of environment variables.

Changes walkthrough

Relevant files
Enhancement
ekssupport.go
Enhanced EKS Region Parsing Logic                                               

cloudsupport/v1/ekssupport.go

  • Improved logic for extracting region from EKS cluster name.
  • Added support for cluster names with different formats.
  • Enhanced error handling for cases where the region cannot be
    determined.
  • +3/-1     
    Tests
    ekssupport_test.go
    Comprehensive Tests for EKS Region Parsing                             

    cloudsupport/v1/ekssupport_test.go

  • Introduced comprehensive test cases for EKS region parsing.
  • Added support for setting region via environment variable in tests.
  • Improved test structure for better clarity and coverage.
  • +56/-9   

    PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Signed-off-by: David Wertenteil <dwertent@armosec.io>
    @codiumai-pr-agent codiumai-pr-agent bot added enhancement New feature or request bug_fix labels Feb 22, 2024
    Copy link

    PR Description updated to latest commit (23cdfaa)

    Copy link

    PR Review

         PR feedback                    
    ⏱️ Estimated effort to review [1-5]

    2, because the changes are localized to a specific functionality (EKS region parsing) and include both implementation and tests. The logic is straightforward, and the tests are comprehensive.

    🧪 Relevant tests

    Yes

    🔍 Possible issues
    • The condition len(splittedClusterContext) >= 6 in ekssupport.go might be too restrictive for future or custom EKS cluster naming conventions. Consider if there's a more flexible way to determine the region without hardcoding the expected number of segments.
    • The test case "Region is extracted from cluster name with ':' separator" expects an error (expectErr: true), but the description suggests it's testing successful region extraction. This might be a misunderstanding or a copy-paste error in the test case description.
    🔒 Security concerns

    No


    ✨ Review tool usage guide:

    Overview:
    The review tool scans the PR code changes, and generates a PR review. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.
    When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:

    /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...
    

    With a configuration file, use the following template:

    [pr_reviewer]
    some_config1=...
    some_config2=...
    
    Utilizing extra instructions

    The review tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize.

    Examples for extra instructions:

    [pr_reviewer] # /review #
    extra_instructions="""
    In the 'possible issues' section, emphasize the following:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    How to enable\disable automation
    • When you first install PR-Agent app, the default mode for the review tool is:
    pr_commands = ["/review", ...]
    

    meaning the review tool will run automatically on every PR, with the default configuration.
    Edit this field to enable/disable the tool, or to change the used configurations

    Auto-labels

    The review tool can auto-generate two specific types of labels for a PR:

    • a possible security issue label, that detects possible security issues (enable_review_labels_security flag)
    • a Review effort [1-5]: x label, where x is the estimated effort to review the PR (enable_review_labels_effort flag)
    Extra sub-tools

    The review tool provides a collection of possible feedbacks about a PR.
    It is recommended to review the possible options, and choose the ones relevant for your use case.
    Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example:
    require_score_review, require_soc2_ticket, and more.

    Auto-approve PRs

    By invoking:

    /review auto_approve
    

    The tool will automatically approve the PR, and add a comment with the approval.

    To ensure safety, the auto-approval feature is disabled by default. To enable auto-approval, you need to actively set in a pre-defined configuration file the following:

    [pr_reviewer]
    enable_auto_approval = true
    

    (this specific flag cannot be set with a command line argument, only in the configuration file, committed to the repository)

    You can also enable auto-approval only if the PR meets certain requirements, such as that the estimated_review_effort is equal or below a certain threshold, by adjusting the flag:

    [pr_reviewer]
    maximal_review_effort = 5
    
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

    See the review usage page for a comprehensive guide on using this tool.

    Copy link

    codiumai-pr-agent bot commented Feb 22, 2024

    PR Code Suggestions

    Suggestions                                                                                                                                                     
    maintainability
    Simplify conditional logic by removing unnecessary else keywords.

    Consider simplifying the conditional logic by removing the else keyword since the if block
    ends with a return statement. This will enhance readability and maintainability.

    cloudsupport/v1/ekssupport.go [128]

    -} else if len(splittedClusterContext) >= 6 {
    +if len(splittedClusterContext) >= 6 {
     
    best practice
    Replace magic numbers with named constants for clarity and maintainability.  

    To ensure consistency and avoid magic numbers, consider defining a constant for the magic
    number 6 used in the condition check. This will make the code more readable and easier to
    maintain.

    cloudsupport/v1/ekssupport.go [128]

    -} else if len(splittedClusterContext) >= 6 {
    +const expectedParts = 6
    +if len(splittedClusterContext) >= expectedParts {
     
    Ensure environment variables are cleaned up in tests by deferring their unset at the start.

    It is a good practice to clean up environment variables in tests by deferring their unset
    at the beginning of the test function. This ensures that even if the test fails or panics,
    the environment variable will be cleaned up, maintaining test isolation.

    cloudsupport/v1/ekssupport_test.go [72-73]

    +defer os.Unsetenv(KS_CLOUD_REGION_ENV_VAR)
     os.Setenv(KS_CLOUD_REGION_ENV_VAR, tt.envRegion)
    -defer os.Unsetenv(KS_CLOUD_REGION_ENV_VAR)
     
    possible issue
    Correct the expected error flag for a test case to match its description.    

    For the test case where the region is expected to be extracted from the cluster name with
    a ':' separator, the expectErr field is set to true. This seems to be a mistake since the
    test case description and expected behavior suggest that the region extraction should
    succeed. Consider setting expectErr to false.

    cloudsupport/v1/ekssupport_test.go [57-60]

     {
       name:           "Region is extracted from cluster name with ':' separator",
       cluster:        "cluster:us-west-2:eks",
       expectedRegion: "us-west-2",
    -  expectErr:      true,
    +  expectErr:      false,
     }
     
    enhancement
    Add a test case for unexpected cluster name formats to verify error handling.

    To improve the robustness of your tests, consider adding a case to explicitly test the
    behavior when the cluster name does not follow the expected format. This will help ensure
    that your error handling works as expected.

    cloudsupport/v1/ekssupport_test.go [63-65]

     {
    -  name:      "Failed to get region",
    -  cluster:   "cluster",
    +  name:      "Failed to get region due to unexpected format",
    +  cluster:   "unexpected-format-cluster",
       expectErr: true,
     }
     

    ✨ Improve tool usage guide:

    Overview:
    The improve tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.
    When commenting, to edit configurations related to the improve tool (pr_code_suggestions section), use the following template:

    /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=...
    

    With a configuration file, use the following template:

    [pr_code_suggestions]
    some_config1=...
    some_config2=...
    
    Enabling\disabling automation

    When you first install the app, the default mode for the improve tool is:

    pr_commands = ["/improve --pr_code_suggestions.summarize=true", ...]
    

    meaning the improve tool will run automatically on every PR, with summarization enabled. Delete this line to disable the tool from running automatically.

    Utilizing extra instructions

    Extra instructions are very important for the improve tool, since they enable to guide the model to suggestions that are more relevant to the specific needs of the project.

    Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on.

    Examples for extra instructions:

    [pr_code_suggestions] # /improve #
    extra_instructions="""
    Emphasize the following aspects:
    - Does the code logic cover relevant edge cases?
    - Is the code logic clear and easy to understand?
    - Is the code logic efficient?
    ...
    """
    

    Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

    A note on code suggestions quality
    • While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically.
    • Suggestions are not meant to be simplistic. Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base.
    • Recommended to use the 'extra_instructions' field to guide the model to suggestions that are more relevant to the specific needs of the project, or use the custom suggestions 💎 tool
    • With large PRs, best quality will be obtained by using 'improve --extended' mode.
    More PR-Agent commands

    To invoke the PR-Agent, add a comment using one of the following commands:

    • /review: Request a review of your Pull Request.
    • /describe: Update the PR title and description based on the contents of the PR.
    • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
    • /ask <QUESTION>: Ask a question about the PR.
    • /update_changelog: Update the changelog based on the PR's contents.
    • /add_docs 💎: Generate docstring for new components introduced in the PR.
    • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
    • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

    See the tools guide for more details.
    To list the possible configuration parameters, add a /config comment.

    See the improve usage page for a more comprehensive guide on using this tool.

    Copy link

    Summary:

    • License scan: failure
    • Credentials scan: failure
    • Vulnerabilities scan: failure
    • Unit test: success
    • Go linting: success

    1 similar comment
    Copy link

    Summary:

    • License scan: failure
    • Credentials scan: failure
    • Vulnerabilities scan: failure
    • Unit test: success
    • Go linting: success

    @@ -125,8 +125,10 @@ func (eksSupport *EKSSupport) GetRegion(cluster string) (string, error) {
    splittedClusterContext := strings.Split(cluster, "-")
    if len(splittedClusterContext) < 4 {
    return "", fmt.Errorf("failed to get region")
    } else {
    } else if len(splittedClusterContext) >= 6 {
    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    holy ****

    @dwertent dwertent merged commit 9309d64 into main Feb 22, 2024
    10 of 11 checks passed
    @dwertent dwertent deleted the fix/eks-region-parser branch February 22, 2024 15:54
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    None yet

    2 participants