Skip to content

Conversation

@FAUST-BENCHOU
Copy link
Contributor

Link to #88

Signed-off-by: zhoujinyu <2319109590@qq.com>
@volcano-sh-bot
Copy link
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @FAUST-BENCHOU, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request focuses on enhancing the test coverage for the pkg/picod package by introducing several new unit tests. These tests specifically target a file mode parsing utility, error handling within the authentication manager's bootstrap key loading mechanism, and various error scenarios for the ExecuteHandler API endpoint. The changes aim to improve the robustness and reliability of these components by validating their behavior under both expected and erroneous inputs. This PR is linked to issue #88.

Highlights

  • New File Mode Parsing Tests: Added TestParseFileMode to validate the utility function responsible for parsing file mode strings, covering valid octal inputs, empty strings, invalid formats, and values exceeding 0777.
  • Auth Key Loading Error Tests: Introduced TestLoadBootstrapKey to thoroughly test error paths for the LoadBootstrapKey function in the authentication manager, ensuring it correctly handles empty or invalid PEM formatted key data.
  • Execute Handler Error Path Tests: Implemented TestExecuteHandler_ErrorPaths to verify the ExecuteHandler's behavior under various error conditions, such as empty commands, malformed JSON requests, and invalid timeout formats, ensuring appropriate HTTP status codes are returned.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds several tests for the pkg/picod package, covering file mode parsing, bootstrap key loading, and error paths for the execute handler. The tests for TestParseFileMode and TestLoadBootstrapKey are well-structured unit tests. However, TestExecuteHandler_ErrorPaths tests the handler in isolation, bypassing the authentication middleware. This could lead to a false sense of security, as a real-world request would be blocked before reaching the handler logic being tested. I've suggested refactoring this test to be a proper integration test that initializes the server and sends authenticated requests through the full HTTP stack, ensuring the entire request lifecycle is tested.

Comment on lines 549 to 600
func TestExecuteHandler_ErrorPaths(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "picod_execute_test")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)

_, bootstrapPubStr := generateRSAKeys(t)
server := NewServer(Config{
BootstrapKey: []byte(bootstrapPubStr),
Workspace: tmpDir,
})

tests := []struct {
name string
request string
statusCode int
desc string
}{
{
name: "Empty command",
request: `{"command": []}`,
statusCode: http.StatusBadRequest,
desc: "Should reject empty command",
},
{
name: "Invalid JSON",
request: `{"command": invalid}`,
statusCode: http.StatusBadRequest,
desc: "Should reject invalid JSON",
},
{
name: "Invalid timeout format",
request: `{"command": ["echo", "test"], "timeout": "invalid"}`,
statusCode: http.StatusBadRequest,
desc: "Should reject invalid timeout",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/api/execute", bytes.NewBufferString(tt.request))
req.Header.Set("Content-Type", "application/json")

ctx, _ := gin.CreateTestContext(w)
ctx.Request = req

server.ExecuteHandler(ctx)

assert.Equal(t, tt.statusCode, w.Code, tt.desc)
})
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The current implementation of TestExecuteHandler_ErrorPaths tests the handler in isolation by calling server.ExecuteHandler(ctx) directly. This bypasses the authentication middleware, which is a critical part of the request lifecycle for this endpoint.

A real request to /api/execute on an uninitialized server would be rejected by the AuthMiddleware with a 403 Forbidden status, and would never reach the handler to produce the 400 Bad Request that this test expects. This means the test could pass even if the endpoint is not correctly configured or is inaccessible.

To make this test more robust and representative of real-world usage, it should be structured as an integration test that goes through the full HTTP stack. This involves:

  1. Setting up a test server using httptest.NewServer.
  2. Initializing the server by making a request to the /init endpoint.
  3. Sending authenticated requests with invalid bodies to the /api/execute endpoint.

This approach ensures that the middleware, routing, and handler logic are all tested together. I've provided a suggestion to refactor the test accordingly.

func TestExecuteHandler_ErrorPaths(t *testing.T) {
	tmpDir, err := os.MkdirTemp("", "picod_execute_test")
	require.NoError(t, err)
	defer os.RemoveAll(tmpDir)

	bootstrapPriv, bootstrapPubStr := generateRSAKeys(t)
	sessionPriv, sessionPubStr := generateRSAKeys(t)

	server := NewServer(Config{
		BootstrapKey: []byte(bootstrapPubStr),
		Workspace:    tmpDir,
	})
	ts := httptest.NewServer(server.engine)
	defer ts.Close()
	client := ts.Client()

	// Initialize server to allow access to authenticated endpoints
	sessionPubB64 := base64.RawStdEncoding.EncodeToString([]byte(sessionPubStr))
	initClaims := jwt.MapClaims{
		"session_public_key": sessionPubB64,
		"iat":                time.Now().Unix(),
		"exp":                time.Now().Add(time.Hour).Unix(),
	}
	initToken := createToken(t, bootstrapPriv, initClaims)
	initReq, err := http.NewRequest("POST", ts.URL+"/init", nil)
	require.NoError(t, err)
	initReq.Header.Set("Authorization", "Bearer "+initToken)
	initResp, err := client.Do(initReq)
	require.NoError(t, err)
	require.Equal(t, http.StatusOK, initResp.StatusCode)
	initResp.Body.Close()

	tests := []struct {
		name       string
		request    string
		statusCode int
		desc       string
	}{
		{
			name:       "Empty command",
			request:    `{"command": []}`,
			statusCode: http.StatusBadRequest,
			desc:       "Should reject empty command",
		},
		{
			name:       "Invalid JSON",
			request:    `{"command": invalid}`,
			statusCode: http.StatusBadRequest,
			desc:       "Should reject invalid JSON",
		},
		{
			name:       "Invalid timeout format",
			request:    `{"command": ["echo", "test"], "timeout": "invalid"}`,
			statusCode: http.StatusBadRequest,
			desc:       "Should reject invalid timeout",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			reqBody := []byte(tt.request)
			hash := sha256.Sum256(reqBody)
			claims := jwt.MapClaims{
				"body_sha256": fmt.Sprintf("%x", hash),
				"iat":         time.Now().Unix(),
				"exp":         time.Now().Add(time.Hour).Unix(),
			}
			token := createToken(t, sessionPriv, claims)

			req, err := http.NewRequest("POST", ts.URL+"/api/execute", bytes.NewBuffer(reqBody))
			require.NoError(t, err)
			req.Header.Set("Content-Type", "application/json")
			req.Header.Set("Authorization", "Bearer "+token)

			resp, err := client.Do(req)
			require.NoError(t, err)
			defer resp.Body.Close()

			assert.Equal(t, tt.statusCode, resp.StatusCode, tt.desc)
		})
	}
}

}

// TestExecuteHandler_ErrorPaths tests execution pipeline error paths
func TestExecuteHandler_ErrorPaths(t *testing.T) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there no test case for the normal command?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

Signed-off-by: zhoujinyu <2319109590@qq.com>
Signed-off-by: zhoujinyu <2319109590@qq.com>
@FAUST-BENCHOU
Copy link
Contributor Author

@LiZhenCheng9527 Thanks for your review, I added some other tests, and now the picod test coverage has reached 77%.🙃

@FAUST-BENCHOU
Copy link
Contributor Author

Hi @LiZhenCheng9527, just wanted to check if there’s any feedback on the PR I submitted. Appreciate your time!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants