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

[csr] add private_server certificate type #2

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

capcom6
Copy link
Member

@capcom6 capcom6 commented Mar 7, 2025

Summary by CodeRabbit

  • New Features

    • Certificate request endpoints now accept an additional "type" attribute (e.g., "private_server") for more precise categorization.
  • Enhancements

    • Improved processing and clarity in certificate request responses for a more consistent user experience.
    • Underlying updates boost the reliability and performance of certificate request handling.
    • New mappings for CSR types enhance the handling of certificate requests.
  • Tests

    • Added unit tests to validate the creation and behavior of CSR and CSR status objects.

Copy link

coderabbitai bot commented Mar 7, 2025

Walkthrough

The changes update the dependency version in the go.mod file and modify the CSR handling flow. In the API layer, a helper function is added to convert CSR status into response objects, and the submit/status methods now use this helper. In the CSR domain, a new field for CSR type is introduced with corresponding changes to the constructor and status functions. The repository and service layers are updated to accept and process CSR types, with serial number generation adjusted to use a new typed prefix. Additionally, an obsolete constant file is removed and the HTTP request payload is updated.

Changes

File / Group Change Summary
go.mod Updated dependency version of github.com/android-sms-gateway/client-go from v1.5.0 to v1.5.5-0.20250307091924-1076d115eb88. Added new dependency github.com/go-playground/assert/v2 version v2.2.0.
internal/api (converters.go, csr.go) Added new function csrStatusToResponse to generate response objects. Updated csrHandler.submit and .status to use the helper function, and modified the call to csr.NewCSR to include the new req.Type parameter.
internal/csr (const.go, domain.go, repository.go, service.go, types.go) Deleted const.go containing the obsolete constant. In domain.go, added a new csrType field to CSR, updated constructor functions (NewCSR, NewCSRStatus), and added a new method Type(). In repository.go and service.go, adjusted calls to include the CSR type. Introduced a new file (types.go) that defines SerialNumberPrefix with constants and a mapping from CSR types to prefixes; updated newSerialNumber to use the new type.
requests.http Added a "type": "private_server" field to the POST request payload and updated the CSR id in the GET request.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant H as CSR Handler (API)
    participant D as CSR Domain
    participant S as Service
    participant R as Repository

    C->>H: POST /csr (payload with "type", content, metadata)
    H->>D: Call csr.NewCSR(csrType, content, metadata)
    D-->>H: New CSR instance
    H->>S: Call Service.Create(new CSR)
    S->>S: Process CSR
    S->>S: Retrieve prefix using csrTypeToPrefix mapping
    S->>S: Call newSerialNumber(prefix) to generate serial number
    S->>D: Call NewCSRStatus(id, csrType, content, metadata, status, certificate, reason)
    D-->>S: Return CSR status
    S-->>H: Return CSR status
    H->>H: Convert status via csrStatusToResponse
    H-->>C: Return JSON response
Loading
sequenceDiagram
    participant C as Client
    participant H as CSR Handler (API)
    participant R as Repository

    C->>H: GET /csr/{id}
    H->>R: Call Repository.Get(id)
    R->>R: Retrieve record and call NewCSRStatus (with csrType)
    R-->>H: Return CSR status object
    H->>H: Convert status via csrStatusToResponse
    H-->>C: Return JSON response
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@capcom6 capcom6 marked this pull request as draft March 7, 2025 23:19
Copy link
Member Author

Choose a reason for hiding this comment

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

@coderabbitai generate unit testing code for this file.

Copy link

Choose a reason for hiding this comment

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

@capcom6 Here's a comprehensive unit test file for internal/csr/domain.go:

package csr

import (
	"encoding/json"
	"testing"

	"github.com/android-sms-gateway/client-go/ca"
	"github.com/stretchr/testify/assert"
)

func TestNewCSR(t *testing.T) {
	tests := []struct {
		name     string
		csrType  ca.CSRType
		content  string
		metadata map[string]string
		want     CSR
	}{
		{
			name:     "With type provided",
			csrType:  ca.CSRType("private_server"),
			content:  "test-content",
			metadata: map[string]string{"key": "value"},
			want: CSR{
				csrType:  ca.CSRType("private_server"),
				content:  "test-content",
				metadata: map[string]string{"key": "value"},
			},
		},
		{
			name:     "With empty type",
			csrType:  "",
			content:  "test-content",
			metadata: map[string]string{"key": "value"},
			want: CSR{
				csrType:  ca.CSRTypeWebhook,
				content:  "test-content",
				metadata: map[string]string{"key": "value"},
			},
		},
		{
			name:     "With empty metadata",
			csrType:  ca.CSRType("private_server"),
			content:  "test-content",
			metadata: nil,
			want: CSR{
				csrType:  ca.CSRType("private_server"),
				content:  "test-content",
				metadata: nil,
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := NewCSR(tt.csrType, tt.content, tt.metadata)
			assert.Equal(t, tt.want, got)
		})
	}
}

func TestCSR_Type(t *testing.T) {
	csr := CSR{
		csrType: ca.CSRType("private_server"),
	}
	assert.Equal(t, ca.CSRType("private_server"), csr.Type())
}

func TestCSR_Content(t *testing.T) {
	csr := CSR{
		content: "test-content",
	}
	assert.Equal(t, "test-content", csr.Content())
}

func TestCSR_Metadata(t *testing.T) {
	metadata := map[string]string{"key": "value"}
	csr := CSR{
		metadata: metadata,
	}
	assert.Equal(t, metadata, csr.Metadata())
}

func TestCSR_toMap(t *testing.T) {
	tests := []struct {
		name     string
		csr      CSR
		expected map[string]string
	}{
		{
			name: "With metadata",
			csr: CSR{
				csrType:  ca.CSRType("private_server"),
				content:  "test-content",
				metadata: map[string]string{"key": "value"},
			},
			expected: map[string]string{
				"type":     "private_server",
				"content":  "test-content",
				"metadata": `{"key":"value"}`,
			},
		},
		{
			name: "Without metadata",
			csr: CSR{
				csrType:  ca.CSRType("private_server"),
				content:  "test-content",
				metadata: map[string]string{},
			},
			expected: map[string]string{
				"type":     "private_server",
				"content":  "test-content",
				"metadata": "{}",
			},
		},
		{
			name: "With nil metadata",
			csr: CSR{
				csrType:  ca.CSRType("private_server"),
				content:  "test-content",
				metadata: nil,
			},
			expected: map[string]string{
				"type":     "private_server",
				"content":  "test-content",
				"metadata": "{}",
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := tt.csr.toMap()

			// Check that maps have the same keys and values
			assert.Equal(t, tt.expected, result)

			// For metadata, verify it's valid JSON
			if metadataJSON, exists := result["metadata"]; exists {
				var metadataMap map[string]string
				err := json.Unmarshal([]byte(metadataJSON), &metadataMap)
				assert.NoError(t, err, "Metadata should be valid JSON")

				// If the original metadata was not nil or empty, verify the unmarshaled content
				if tt.csr.metadata != nil && len(tt.csr.metadata) > 0 {
					assert.Equal(t, tt.csr.metadata, metadataMap)
				}
			}
		})
	}
}

func TestNewCSRStatus(t *testing.T) {
	id := "test-id"
	csrType := ca.CSRType("private_server")
	content := "test-content"
	metadata := map[string]string{"key": "value"}
	status := ca.CSRStatus("pending")
	certificate := "test-certificate"
	reason := "test-reason"

	csrStatus := NewCSRStatus(id, csrType, content, metadata, status, certificate, reason)

	assert.Equal(t, id, csrStatus.id)
	assert.Equal(t, csrType, csrStatus.csrType)
	assert.Equal(t, content, csrStatus.content)
	assert.Equal(t, metadata, csrStatus.metadata)
	assert.Equal(t, status, csrStatus.status)
	assert.Equal(t, certificate, csrStatus.certificate)
	assert.Equal(t, reason, csrStatus.reason)
}

func TestCSRStatus_ID(t *testing.T) {
	csrStatus := CSRStatus{id: "test-id"}
	assert.Equal(t, "test-id", csrStatus.ID())
}

func TestCSRStatus_Status(t *testing.T) {
	csrStatus := CSRStatus{status: ca.CSRStatus("approved")}
	assert.Equal(t, ca.CSRStatus("approved"), csrStatus.Status())
}

func TestCSRStatus_Certificate(t *testing.T) {
	csrStatus := CSRStatus{certificate: "test-certificate"}
	assert.Equal(t, "test-certificate", csrStatus.Certificate())
}

func TestCsrID_Bytes(t *testing.T) {
	id := csrID("test-id")
	expected := []byte("test-id")
	assert.Equal(t, expected, id.Bytes())
}

This test file provides complete coverage for all the structs and functions in the domain.go file, including:

  • Testing the CSR constructor with various inputs
  • Testing all getter methods
  • Testing the toMap method with different metadata scenarios
  • Testing the CSRStatus constructor and its methods
  • Testing the csrID type's Bytes method

Copy link
Member Author

Choose a reason for hiding this comment

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

@coderabbitai, please use csr_test package and test only public methods and fields

Copy link

Choose a reason for hiding this comment

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

@capcom6 Here's the updated unit test code using the csr_test package and testing only public methods:

package csr_test

import (
	"testing"

	"github.com/android-sms-gateway/ca-backend/internal/csr"
	"github.com/android-sms-gateway/client-go/ca"
	"github.com/stretchr/testify/assert"
)

func TestNewCSR(t *testing.T) {
	tests := []struct {
		name     string
		csrType  ca.CSRType
		content  string
		metadata map[string]string
	}{
		{
			name:     "With type provided",
			csrType:  ca.CSRType("private_server"),
			content:  "test-content",
			metadata: map[string]string{"key": "value"},
		},
		{
			name:     "With empty type",
			csrType:  "",
			content:  "test-content",
			metadata: map[string]string{"key": "value"},
		},
		{
			name:     "With empty metadata",
			csrType:  ca.CSRType("private_server"),
			content:  "test-content",
			metadata: nil,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := csr.NewCSR(tt.csrType, tt.content, tt.metadata)
			
			// Check type (should default to webhook if empty)
			expectedType := tt.csrType
			if expectedType == "" {
				expectedType = ca.CSRTypeWebhook
			}
			assert.Equal(t, expectedType, got.Type())
			
			// Check content and metadata
			assert.Equal(t, tt.content, got.Content())
			assert.Equal(t, tt.metadata, got.Metadata())
		})
	}
}

func TestCSR_Getters(t *testing.T) {
	csrType := ca.CSRType("private_server")
	content := "test-content"
	metadata := map[string]string{"key": "value"}
	
	testCSR := csr.NewCSR(csrType, content, metadata)
	
	assert.Equal(t, csrType, testCSR.Type())
	assert.Equal(t, content, testCSR.Content())
	assert.Equal(t, metadata, testCSR.Metadata())
}

func TestNewCSRStatus(t *testing.T) {
	id := "test-id"
	csrType := ca.CSRType("private_server")
	content := "test-content"
	metadata := map[string]string{"key": "value"}
	status := ca.CSRStatus("pending")
	certificate := "test-certificate"
	reason := "test-reason"

	csrStatus := csr.NewCSRStatus(id, csrType, content, metadata, status, certificate, reason)

	// Verify through public getters
	assert.Equal(t, id, csrStatus.ID())
	assert.Equal(t, csrType, csrStatus.Type())
	assert.Equal(t, content, csrStatus.Content())
	assert.Equal(t, metadata, csrStatus.Metadata())
	assert.Equal(t, status, csrStatus.Status())
	assert.Equal(t, certificate, csrStatus.Certificate())
}

func TestCSRStatus_Getters(t *testing.T) {
	id := "test-id"
	csrType := ca.CSRType("private_server")
	content := "test-content"
	metadata := map[string]string{"key": "value"}
	status := ca.CSRStatus("approved")
	certificate := "test-certificate"
	reason := "test-reason"

	csrStatus := csr.NewCSRStatus(id, csrType, content, metadata, status, certificate, reason)
	
	assert.Equal(t, id, csrStatus.ID())
	assert.Equal(t, status, csrStatus.Status())
	assert.Equal(t, certificate, csrStatus.Certificate())
}

This test file adheres to black-box testing principles by using the csr_test package and only testing public methods. We verify the functionality by calling public constructors and getter methods rather than accessing internal fields directly.


✏️ Learnings added
Learnt from: capcom6
PR: android-sms-gateway/ca-backend#2
File: internal/csr/domain.go:1-1
Timestamp: 2025-03-07T23:33:54.409Z
Learning: When writing unit tests for Go packages, use a `package_test` naming convention for black-box testing where only public (exported) methods and fields can be tested. This provides better validation of the public API's behavior.

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.

Copy link

@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: 0

🧹 Nitpick comments (4)
internal/csr/domain_test.go (4)

88-102: TestCSRStatus_Getters is incomplete

This test only verifies a subset of the getters (ID, status, and certificate) but omits validation for Type(), Content(), Metadata(), and possibly Reason(). Consider extending this test to cover all getters or explain why only some are being tested.

 func TestCSRStatus_Getters(t *testing.T) {
 	id := "test-id"
 	csrType := ca.CSRType("private_server")
 	content := "test-content"
 	metadata := map[string]string{"key": "value"}
 	status := ca.CSRStatus("approved")
 	certificate := "test-certificate"
 	reason := "test-reason"

 	csrStatus := csr.NewCSRStatus(id, csrType, content, metadata, status, certificate, reason)

 	assert.Equal(t, id, csrStatus.ID())
+	assert.Equal(t, csrType, csrStatus.Type())
+	assert.Equal(t, content, csrStatus.Content())
+	assert.Equal(t, metadata, csrStatus.Metadata())
 	assert.Equal(t, status, csrStatus.Status())
 	assert.Equal(t, certificate, csrStatus.Certificate())
+	// If Reason getter exists
+	// assert.Equal(t, reason, csrStatus.Reason())
 }

11-54: Add negative test cases to TestNewCSR

The current tests only cover valid inputs. Consider adding tests for potential error cases or edge cases such as invalid CSR types to ensure robust validation.

 func TestNewCSR(t *testing.T) {
 	tests := []struct {
 		name     string
 		csrType  ca.CSRType
 		content  string
 		metadata map[string]string
 	}{
 		{
 			name:     "With type provided",
 			csrType:  ca.CSRTypePrivateServer,
 			content:  "test-content",
 			metadata: map[string]string{"key": "value"},
 		},
 		{
 			name:     "With empty type",
 			csrType:  "",
 			content:  "test-content",
 			metadata: map[string]string{"key": "value"},
 		},
 		{
 			name:     "With empty metadata",
 			csrType:  ca.CSRTypePrivateServer,
 			content:  "test-content",
 			metadata: nil,
 		},
+		{
+			name:     "With empty content",
+			csrType:  ca.CSRTypePrivateServer,
+			content:  "",
+			metadata: map[string]string{"key": "value"},
+		},
+		{
+			name:     "With invalid CSR type",
+			csrType:  "invalid_type",
+			content:  "test-content",
+			metadata: map[string]string{"key": "value"},
+		},
 	}

1-9: Consider using testify for more assertion options

The current tests use github.com/go-playground/assert/v2, but github.com/stretchr/testify/assert offers a wider range of assertion functions and is more commonly used in Go projects. Consider standardizing the assertion library across the project.


56-66: TestCSR_Getters duplicates functionality already tested in TestNewCSR

This test largely duplicates what's already being tested in TestNewCSR. Consider either merging them or making this test focus on different aspects not covered by the table-driven tests.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c0944e9 and be66001.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (2)
  • go.mod (1 hunks)
  • internal/csr/domain_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • go.mod
🔇 Additional comments (1)
internal/csr/domain_test.go (1)

68-86:

❓ Verification inconclusive

TestNewCSRStatus doesn't validate the reason getter

The test creates a CSRStatus with a reason parameter but doesn't verify it with an assertion. Consider adding an assertion to validate that the reason is properly stored and retrieved.


🏁 Script executed:

#!/bin/bash
# Check if CSRStatus has a Reason getter method
rg -A 1 -B 1 "func \(\w+ \*CSRStatus\) Reason\(\) string" internal/csr/domain.go

Length of output: 82


Attention: Verify and Validate the "reason" Field in CSRStatus

The test currently creates a CSRStatus with a "reason" parameter but does not assert its retrieval. Our initial search in internal/csr/domain.go did not reveal a public Reason() getter for CSRStatus. Please verify whether:

  • The CSRStatus type is intended to expose a "reason" field through a public getter.
  • If the getter is missing, either add the Reason() string method to CSRStatus or remove the unused "reason" parameter from NewCSRStatus.
  • If the getter exists (perhaps under a different pattern or in another part of the code), update TestNewCSRStatus to include an assertion for it.

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