mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 18:11:32 +00:00
feat: M18b Filesystem Certificate Discovery — agent scanning, server dedup, triage API
Agent-side:
- Filesystem scanner walks configured directories (CERTCTL_DISCOVERY_DIRS)
- Parses PEM (.pem, .crt, .cer, .cert) and DER (.der) certificate files
- Extracts CN, SANs, serial, issuer/subject DN, validity, key info, SHA-256 fingerprint
- Reports discoveries to control plane on startup + every 6 hours
- Skips files >1MB and private key files
Server-side:
- Migration 000006: discovered_certificates + discovery_scans tables
- Domain model: DiscoveredCertificate, DiscoveryScan, DiscoveryReport
- Three triage states: Unmanaged, Managed (claimed), Dismissed
- Repository with upsert dedup (fingerprint + agent + path)
- Service layer: process reports, claim, dismiss, list, summary
- 7 new API endpoints (84 total):
POST /agents/{id}/discoveries, GET /discovered-certificates,
GET /discovered-certificates/{id}, POST .../claim, POST .../dismiss,
GET /discovery-scans, GET /discovery-summary
- Audit trail: scan_completed, cert_claimed, cert_dismissed events
Tests: 28 new test functions (domain, handler, service layers)
Docs: README, quickstart, demo-guide, demo-advanced, architecture,
concepts, connectors, features.md all updated
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,232 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
)
|
||||
|
||||
// DiscoveryService defines the interface used by the discovery handler.
|
||||
type DiscoveryService interface {
|
||||
ProcessDiscoveryReport(ctx context.Context, report *domain.DiscoveryReport) (*domain.DiscoveryScan, error)
|
||||
ListDiscovered(ctx context.Context, agentID, status string, page, perPage int) ([]*domain.DiscoveredCertificate, int, error)
|
||||
GetDiscovered(ctx context.Context, id string) (*domain.DiscoveredCertificate, error)
|
||||
ClaimDiscovered(ctx context.Context, id string, managedCertID string) error
|
||||
DismissDiscovered(ctx context.Context, id string) error
|
||||
ListScans(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error)
|
||||
GetScan(ctx context.Context, id string) (*domain.DiscoveryScan, error)
|
||||
GetDiscoverySummary(ctx context.Context) (map[string]int, error)
|
||||
}
|
||||
|
||||
// DiscoveryHandler handles HTTP requests for certificate discovery.
|
||||
type DiscoveryHandler struct {
|
||||
svc DiscoveryService
|
||||
}
|
||||
|
||||
// NewDiscoveryHandler creates a new discovery handler.
|
||||
func NewDiscoveryHandler(svc DiscoveryService) DiscoveryHandler {
|
||||
return DiscoveryHandler{svc: svc}
|
||||
}
|
||||
|
||||
// SubmitDiscoveryReport handles POST /api/v1/agents/{id}/discoveries
|
||||
// Agents submit their filesystem scan results here.
|
||||
func (h DiscoveryHandler) SubmitDiscoveryReport(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
agentID := r.PathValue("id")
|
||||
if agentID == "" {
|
||||
Error(w, http.StatusBadRequest, "agent ID is required")
|
||||
return
|
||||
}
|
||||
|
||||
var report domain.DiscoveryReport
|
||||
if err := json.NewDecoder(r.Body).Decode(&report); err != nil {
|
||||
Error(w, http.StatusBadRequest, fmt.Sprintf("invalid request body: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
// Override agent ID from path (security: agents can only report for themselves)
|
||||
report.AgentID = agentID
|
||||
|
||||
scan, err := h.svc.ProcessDiscoveryReport(r.Context(), &report)
|
||||
if err != nil {
|
||||
Error(w, http.StatusInternalServerError, fmt.Sprintf("failed to process discovery report: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusAccepted, scan)
|
||||
}
|
||||
|
||||
// ListDiscovered handles GET /api/v1/discovered-certificates
|
||||
func (h DiscoveryHandler) ListDiscovered(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
query := r.URL.Query()
|
||||
agentID := query.Get("agent_id")
|
||||
status := query.Get("status")
|
||||
page := parseIntDefault(query.Get("page"), 1)
|
||||
perPage := parseIntDefault(query.Get("per_page"), 50)
|
||||
if perPage > 500 {
|
||||
perPage = 50
|
||||
}
|
||||
|
||||
certs, total, err := h.svc.ListDiscovered(r.Context(), agentID, status, page, perPage)
|
||||
if err != nil {
|
||||
Error(w, http.StatusInternalServerError, fmt.Sprintf("failed to list discovered certificates: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, PagedResponse{
|
||||
Data: certs,
|
||||
Total: int64(total),
|
||||
Page: page,
|
||||
PerPage: perPage,
|
||||
})
|
||||
}
|
||||
|
||||
// GetDiscovered handles GET /api/v1/discovered-certificates/{id}
|
||||
func (h DiscoveryHandler) GetDiscovered(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
Error(w, http.StatusBadRequest, "discovered certificate ID is required")
|
||||
return
|
||||
}
|
||||
|
||||
cert, err := h.svc.GetDiscovered(r.Context(), id)
|
||||
if err != nil {
|
||||
Error(w, http.StatusNotFound, fmt.Sprintf("discovered certificate not found: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, cert)
|
||||
}
|
||||
|
||||
// ClaimDiscovered handles POST /api/v1/discovered-certificates/{id}/claim
|
||||
func (h DiscoveryHandler) ClaimDiscovered(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
Error(w, http.StatusBadRequest, "discovered certificate ID is required")
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
ManagedCertificateID string `json:"managed_certificate_id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
Error(w, http.StatusBadRequest, fmt.Sprintf("invalid request body: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
if body.ManagedCertificateID == "" {
|
||||
Error(w, http.StatusBadRequest, "managed_certificate_id is required")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.ClaimDiscovered(r.Context(), id, body.ManagedCertificateID); err != nil {
|
||||
Error(w, http.StatusInternalServerError, fmt.Sprintf("failed to claim certificate: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, map[string]string{
|
||||
"status": "claimed",
|
||||
"message": "Discovered certificate linked to managed certificate",
|
||||
})
|
||||
}
|
||||
|
||||
// DismissDiscovered handles POST /api/v1/discovered-certificates/{id}/dismiss
|
||||
func (h DiscoveryHandler) DismissDiscovered(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
Error(w, http.StatusBadRequest, "discovered certificate ID is required")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.DismissDiscovered(r.Context(), id); err != nil {
|
||||
Error(w, http.StatusInternalServerError, fmt.Sprintf("failed to dismiss certificate: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, map[string]string{
|
||||
"status": "dismissed",
|
||||
"message": "Discovered certificate dismissed",
|
||||
})
|
||||
}
|
||||
|
||||
// ListScans handles GET /api/v1/discovery-scans
|
||||
func (h DiscoveryHandler) ListScans(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
query := r.URL.Query()
|
||||
agentID := query.Get("agent_id")
|
||||
page := parseIntDefault(query.Get("page"), 1)
|
||||
perPage := parseIntDefault(query.Get("per_page"), 50)
|
||||
|
||||
scans, total, err := h.svc.ListScans(r.Context(), agentID, page, perPage)
|
||||
if err != nil {
|
||||
Error(w, http.StatusInternalServerError, fmt.Sprintf("failed to list discovery scans: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, PagedResponse{
|
||||
Data: scans,
|
||||
Total: int64(total),
|
||||
Page: page,
|
||||
PerPage: perPage,
|
||||
})
|
||||
}
|
||||
|
||||
// GetDiscoverySummary handles GET /api/v1/discovery-summary
|
||||
func (h DiscoveryHandler) GetDiscoverySummary(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
summary, err := h.svc.GetDiscoverySummary(r.Context())
|
||||
if err != nil {
|
||||
Error(w, http.StatusInternalServerError, fmt.Sprintf("failed to get discovery summary: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, summary)
|
||||
}
|
||||
|
||||
// parseIntDefault parses an integer from a string with a default fallback.
|
||||
func parseIntDefault(s string, defaultVal int) int {
|
||||
if s == "" {
|
||||
return defaultVal
|
||||
}
|
||||
val, err := strconv.Atoi(s)
|
||||
if err != nil || val < 1 {
|
||||
return defaultVal
|
||||
}
|
||||
return val
|
||||
}
|
||||
@@ -0,0 +1,613 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/api/middleware"
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
"github.com/shankar0123/certctl/internal/repository"
|
||||
)
|
||||
|
||||
// MockDiscoveryService is a mock implementation of DiscoveryService interface.
|
||||
type MockDiscoveryService struct {
|
||||
ProcessDiscoveryReportFn func(ctx context.Context, report *domain.DiscoveryReport) (*domain.DiscoveryScan, error)
|
||||
ListDiscoveredFn func(ctx context.Context, agentID, status string, page, perPage int) ([]*domain.DiscoveredCertificate, int, error)
|
||||
GetDiscoveredFn func(ctx context.Context, id string) (*domain.DiscoveredCertificate, error)
|
||||
ClaimDiscoveredFn func(ctx context.Context, id string, managedCertID string) error
|
||||
DismissDiscoveredFn func(ctx context.Context, id string) error
|
||||
ListScansFn func(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error)
|
||||
GetScanFn func(ctx context.Context, id string) (*domain.DiscoveryScan, error)
|
||||
GetDiscoverySummaryFn func(ctx context.Context) (map[string]int, error)
|
||||
}
|
||||
|
||||
func (m *MockDiscoveryService) ProcessDiscoveryReport(ctx context.Context, report *domain.DiscoveryReport) (*domain.DiscoveryScan, error) {
|
||||
if m.ProcessDiscoveryReportFn != nil {
|
||||
return m.ProcessDiscoveryReportFn(ctx, report)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockDiscoveryService) ListDiscovered(ctx context.Context, agentID, status string, page, perPage int) ([]*domain.DiscoveredCertificate, int, error) {
|
||||
if m.ListDiscoveredFn != nil {
|
||||
return m.ListDiscoveredFn(ctx, agentID, status, page, perPage)
|
||||
}
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
func (m *MockDiscoveryService) GetDiscovered(ctx context.Context, id string) (*domain.DiscoveredCertificate, error) {
|
||||
if m.GetDiscoveredFn != nil {
|
||||
return m.GetDiscoveredFn(ctx, id)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockDiscoveryService) ClaimDiscovered(ctx context.Context, id string, managedCertID string) error {
|
||||
if m.ClaimDiscoveredFn != nil {
|
||||
return m.ClaimDiscoveredFn(ctx, id, managedCertID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockDiscoveryService) DismissDiscovered(ctx context.Context, id string) error {
|
||||
if m.DismissDiscoveredFn != nil {
|
||||
return m.DismissDiscoveredFn(ctx, id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockDiscoveryService) ListScans(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error) {
|
||||
if m.ListScansFn != nil {
|
||||
return m.ListScansFn(ctx, agentID, page, perPage)
|
||||
}
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
func (m *MockDiscoveryService) GetScan(ctx context.Context, id string) (*domain.DiscoveryScan, error) {
|
||||
if m.GetScanFn != nil {
|
||||
return m.GetScanFn(ctx, id)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockDiscoveryService) GetDiscoverySummary(ctx context.Context) (map[string]int, error) {
|
||||
if m.GetDiscoverySummaryFn != nil {
|
||||
return m.GetDiscoverySummaryFn(ctx)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Helper function to create context with request ID.
|
||||
func discoveryContextWithRequestID() context.Context {
|
||||
return context.WithValue(context.Background(), middleware.RequestIDKey{}, "test-request-id-123")
|
||||
}
|
||||
|
||||
// Test SubmitDiscoveryReport - success case
|
||||
func TestSubmitDiscoveryReport_Success(t *testing.T) {
|
||||
now := time.Now()
|
||||
scan := &domain.DiscoveryScan{
|
||||
ID: "dscan-1",
|
||||
AgentID: "agent-1",
|
||||
CertificatesFound: 2,
|
||||
CertificatesNew: 1,
|
||||
ErrorsCount: 0,
|
||||
ScanDurationMs: 150,
|
||||
StartedAt: now,
|
||||
CompletedAt: &now,
|
||||
}
|
||||
|
||||
mock := &MockDiscoveryService{
|
||||
ProcessDiscoveryReportFn: func(ctx context.Context, report *domain.DiscoveryReport) (*domain.DiscoveryScan, error) {
|
||||
if report.AgentID == "agent-1" && len(report.Certificates) == 2 {
|
||||
return scan, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected report")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
reportBody := domain.DiscoveryReport{
|
||||
AgentID: "agent-1",
|
||||
Certificates: []domain.DiscoveredCertEntry{
|
||||
{
|
||||
FingerprintSHA256: "abc123",
|
||||
CommonName: "example.com",
|
||||
SerialNumber: "001",
|
||||
SourcePath: "/etc/certs/example.com.crt",
|
||||
},
|
||||
{
|
||||
FingerprintSHA256: "def456",
|
||||
CommonName: "api.example.com",
|
||||
SerialNumber: "002",
|
||||
SourcePath: "/etc/certs/api.example.com.crt",
|
||||
},
|
||||
},
|
||||
ScanDurationMs: 150,
|
||||
}
|
||||
|
||||
body, _ := json.Marshal(reportBody)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/agent-1/discoveries", bytes.NewReader(body))
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "agent-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.SubmitDiscoveryReport(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Errorf("expected status %d, got %d", http.StatusAccepted, w.Code)
|
||||
}
|
||||
|
||||
var response *domain.DiscoveryScan
|
||||
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if response.ID != "dscan-1" {
|
||||
t.Errorf("expected scan ID dscan-1, got %s", response.ID)
|
||||
}
|
||||
if response.CertificatesFound != 2 {
|
||||
t.Errorf("expected 2 certificates found, got %d", response.CertificatesFound)
|
||||
}
|
||||
}
|
||||
|
||||
// Test SubmitDiscoveryReport - invalid body
|
||||
func TestSubmitDiscoveryReport_InvalidBody(t *testing.T) {
|
||||
mock := &MockDiscoveryService{}
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/agents/agent-1/discoveries", bytes.NewReader([]byte("invalid json")))
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "agent-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.SubmitDiscoveryReport(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status %d, got %d", http.StatusBadRequest, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test SubmitDiscoveryReport - method not allowed
|
||||
func TestSubmitDiscoveryReport_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockDiscoveryService{}
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/agents/agent-1/discoveries", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "agent-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.SubmitDiscoveryReport(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected status %d, got %d", http.StatusMethodNotAllowed, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ListDiscovered - success case
|
||||
func TestListDiscovered_Success(t *testing.T) {
|
||||
now := time.Now()
|
||||
certs := []*domain.DiscoveredCertificate{
|
||||
{
|
||||
ID: "dcert-1",
|
||||
CommonName: "example.com",
|
||||
SerialNumber: "001",
|
||||
Status: domain.DiscoveryStatusUnmanaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
},
|
||||
{
|
||||
ID: "dcert-2",
|
||||
CommonName: "api.example.com",
|
||||
SerialNumber: "002",
|
||||
Status: domain.DiscoveryStatusManaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
},
|
||||
}
|
||||
|
||||
mock := &MockDiscoveryService{
|
||||
ListDiscoveredFn: func(ctx context.Context, agentID, status string, page, perPage int) ([]*domain.DiscoveredCertificate, int, error) {
|
||||
if page == 1 && perPage == 50 {
|
||||
return certs, 2, nil
|
||||
}
|
||||
return nil, 0, nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovered-certificates?page=1&per_page=50", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ListDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
var response PagedResponse
|
||||
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if response.Total != 2 {
|
||||
t.Errorf("expected total 2, got %d", response.Total)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ListDiscovered - with filters
|
||||
func TestListDiscovered_WithFilters(t *testing.T) {
|
||||
mock := &MockDiscoveryService{
|
||||
ListDiscoveredFn: func(ctx context.Context, agentID, status string, page, perPage int) ([]*domain.DiscoveredCertificate, int, error) {
|
||||
if agentID == "agent-1" && status == "Unmanaged" {
|
||||
return []*domain.DiscoveredCertificate{}, 0, nil
|
||||
}
|
||||
return nil, 0, nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovered-certificates?agent_id=agent-1&status=Unmanaged&page=1&per_page=25", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ListDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ListDiscovered - method not allowed
|
||||
func TestListDiscovered_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockDiscoveryService{}
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/discovered-certificates", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ListDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected status %d, got %d", http.StatusMethodNotAllowed, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetDiscovered - success case
|
||||
func TestGetDiscovered_Success(t *testing.T) {
|
||||
now := time.Now()
|
||||
cert := &domain.DiscoveredCertificate{
|
||||
ID: "dcert-1",
|
||||
CommonName: "example.com",
|
||||
SerialNumber: "001",
|
||||
Status: domain.DiscoveryStatusUnmanaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
mock := &MockDiscoveryService{
|
||||
GetDiscoveredFn: func(ctx context.Context, id string) (*domain.DiscoveredCertificate, error) {
|
||||
if id == "dcert-1" {
|
||||
return cert, nil
|
||||
}
|
||||
return nil, fmt.Errorf("not found")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovered-certificates/dcert-1", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "dcert-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
var response *domain.DiscoveredCertificate
|
||||
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if response.ID != "dcert-1" {
|
||||
t.Errorf("expected ID dcert-1, got %s", response.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetDiscovered - not found
|
||||
func TestGetDiscovered_NotFound(t *testing.T) {
|
||||
mock := &MockDiscoveryService{
|
||||
GetDiscoveredFn: func(ctx context.Context, id string) (*domain.DiscoveredCertificate, error) {
|
||||
return nil, fmt.Errorf("not found")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovered-certificates/nonexistent", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "nonexistent")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected status %d, got %d", http.StatusNotFound, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ClaimDiscovered - success case
|
||||
func TestClaimDiscovered_Success(t *testing.T) {
|
||||
mock := &MockDiscoveryService{
|
||||
ClaimDiscoveredFn: func(ctx context.Context, id string, managedCertID string) error {
|
||||
if id == "dcert-1" && managedCertID == "mc-prod-1" {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("unexpected parameters")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
claimBody := map[string]string{
|
||||
"managed_certificate_id": "mc-prod-1",
|
||||
}
|
||||
body, _ := json.Marshal(claimBody)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/discovered-certificates/dcert-1/claim", bytes.NewReader(body))
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "dcert-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ClaimDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
var response map[string]string
|
||||
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if response["status"] != "claimed" {
|
||||
t.Errorf("expected status 'claimed', got %s", response["status"])
|
||||
}
|
||||
}
|
||||
|
||||
// Test ClaimDiscovered - missing managed_certificate_id
|
||||
func TestClaimDiscovered_MissingManagedCertID(t *testing.T) {
|
||||
mock := &MockDiscoveryService{}
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
claimBody := map[string]string{}
|
||||
body, _ := json.Marshal(claimBody)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/discovered-certificates/dcert-1/claim", bytes.NewReader(body))
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "dcert-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ClaimDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status %d, got %d", http.StatusBadRequest, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ClaimDiscovered - discovered cert not found
|
||||
func TestClaimDiscovered_NotFound(t *testing.T) {
|
||||
mock := &MockDiscoveryService{
|
||||
ClaimDiscoveredFn: func(ctx context.Context, id string, managedCertID string) error {
|
||||
return fmt.Errorf("discovered certificate not found")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
claimBody := map[string]string{
|
||||
"managed_certificate_id": "mc-prod-1",
|
||||
}
|
||||
body, _ := json.Marshal(claimBody)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/discovered-certificates/nonexistent/claim", bytes.NewReader(body))
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "nonexistent")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ClaimDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected status %d, got %d", http.StatusInternalServerError, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test DismissDiscovered - success case
|
||||
func TestDismissDiscovered_Success(t *testing.T) {
|
||||
mock := &MockDiscoveryService{
|
||||
DismissDiscoveredFn: func(ctx context.Context, id string) error {
|
||||
if id == "dcert-1" {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("not found")
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/discovered-certificates/dcert-1/dismiss", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "dcert-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.DismissDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
var response map[string]string
|
||||
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if response["status"] != "dismissed" {
|
||||
t.Errorf("expected status 'dismissed', got %s", response["status"])
|
||||
}
|
||||
}
|
||||
|
||||
// Test DismissDiscovered - method not allowed
|
||||
func TestDismissDiscovered_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockDiscoveryService{}
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovered-certificates/dcert-1/dismiss", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
req.SetPathValue("id", "dcert-1")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.DismissDiscovered(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected status %d, got %d", http.StatusMethodNotAllowed, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ListScans - success case
|
||||
func TestListScans_Success(t *testing.T) {
|
||||
now := time.Now()
|
||||
scans := []*domain.DiscoveryScan{
|
||||
{
|
||||
ID: "dscan-1",
|
||||
AgentID: "agent-1",
|
||||
CertificatesFound: 5,
|
||||
CertificatesNew: 2,
|
||||
ScanDurationMs: 200,
|
||||
StartedAt: now,
|
||||
CompletedAt: &now,
|
||||
},
|
||||
}
|
||||
|
||||
mock := &MockDiscoveryService{
|
||||
ListScansFn: func(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error) {
|
||||
if page == 1 && perPage == 50 {
|
||||
return scans, 1, nil
|
||||
}
|
||||
return nil, 0, nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovery-scans?page=1&per_page=50", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ListScans(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
var response PagedResponse
|
||||
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if response.Total != 1 {
|
||||
t.Errorf("expected total 1, got %d", response.Total)
|
||||
}
|
||||
}
|
||||
|
||||
// Test ListScans - with agent filter
|
||||
func TestListScans_WithAgentFilter(t *testing.T) {
|
||||
mock := &MockDiscoveryService{
|
||||
ListScansFn: func(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error) {
|
||||
if agentID == "agent-1" {
|
||||
return []*domain.DiscoveryScan{}, 0, nil
|
||||
}
|
||||
return nil, 0, nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovery-scans?agent_id=agent-1", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ListScans(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetDiscoverySummary - success case
|
||||
func TestGetDiscoverySummary_Success(t *testing.T) {
|
||||
summary := map[string]int{
|
||||
"Unmanaged": 5,
|
||||
"Managed": 3,
|
||||
"Dismissed": 1,
|
||||
}
|
||||
|
||||
mock := &MockDiscoveryService{
|
||||
GetDiscoverySummaryFn: func(ctx context.Context) (map[string]int, error) {
|
||||
return summary, nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/discovery-summary", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetDiscoverySummary(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected status %d, got %d", http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
var response map[string]int
|
||||
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if response["Unmanaged"] != 5 {
|
||||
t.Errorf("expected Unmanaged count 5, got %d", response["Unmanaged"])
|
||||
}
|
||||
if response["Managed"] != 3 {
|
||||
t.Errorf("expected Managed count 3, got %d", response["Managed"])
|
||||
}
|
||||
}
|
||||
|
||||
// Test GetDiscoverySummary - method not allowed
|
||||
func TestGetDiscoverySummary_MethodNotAllowed(t *testing.T) {
|
||||
mock := &MockDiscoveryService{}
|
||||
handler := NewDiscoveryHandler(mock)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/discovery-summary", nil)
|
||||
req = req.WithContext(discoveryContextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetDiscoverySummary(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Errorf("expected status %d, got %d", http.StatusMethodNotAllowed, w.Code)
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,7 @@ func (r *Router) RegisterHandlers(
|
||||
stats handler.StatsHandler,
|
||||
metrics handler.MetricsHandler,
|
||||
health handler.HealthHandler,
|
||||
discovery handler.DiscoveryHandler,
|
||||
) {
|
||||
// Health endpoints (no auth middleware — must always be accessible)
|
||||
r.mux.Handle("GET /health", middleware.Chain(
|
||||
@@ -187,6 +188,15 @@ func (r *Router) RegisterHandlers(
|
||||
|
||||
// Metrics routes: /api/v1/metrics
|
||||
r.Register("GET /api/v1/metrics", http.HandlerFunc(metrics.GetMetrics))
|
||||
|
||||
// Discovery routes: /api/v1/discovered-certificates, /api/v1/discovery-scans
|
||||
r.Register("POST /api/v1/agents/{id}/discoveries", http.HandlerFunc(discovery.SubmitDiscoveryReport))
|
||||
r.Register("GET /api/v1/discovered-certificates", http.HandlerFunc(discovery.ListDiscovered))
|
||||
r.Register("GET /api/v1/discovered-certificates/{id}", http.HandlerFunc(discovery.GetDiscovered))
|
||||
r.Register("POST /api/v1/discovered-certificates/{id}/claim", http.HandlerFunc(discovery.ClaimDiscovered))
|
||||
r.Register("POST /api/v1/discovered-certificates/{id}/dismiss", http.HandlerFunc(discovery.DismissDiscovered))
|
||||
r.Register("GET /api/v1/discovery-scans", http.HandlerFunc(discovery.ListScans))
|
||||
r.Register("GET /api/v1/discovery-summary", http.HandlerFunc(discovery.GetDiscoverySummary))
|
||||
}
|
||||
|
||||
// GetMux returns the underlying http.ServeMux for direct access if needed.
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// DiscoveryStatus represents the triage state of a discovered certificate.
|
||||
type DiscoveryStatus string
|
||||
|
||||
const (
|
||||
// DiscoveryStatusUnmanaged indicates a discovered cert not yet linked to a managed cert.
|
||||
DiscoveryStatusUnmanaged DiscoveryStatus = "Unmanaged"
|
||||
// DiscoveryStatusManaged indicates a discovered cert linked to a managed cert.
|
||||
DiscoveryStatusManaged DiscoveryStatus = "Managed"
|
||||
// DiscoveryStatusDismissed indicates a cert the operator chose to ignore.
|
||||
DiscoveryStatusDismissed DiscoveryStatus = "Dismissed"
|
||||
)
|
||||
|
||||
// IsValidDiscoveryStatus returns true if the status is a recognized discovery status.
|
||||
func IsValidDiscoveryStatus(s string) bool {
|
||||
switch DiscoveryStatus(s) {
|
||||
case DiscoveryStatusUnmanaged, DiscoveryStatusManaged, DiscoveryStatusDismissed:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// DiscoveredCertificate represents a certificate found on an agent's filesystem.
|
||||
type DiscoveredCertificate struct {
|
||||
ID string `json:"id"`
|
||||
FingerprintSHA256 string `json:"fingerprint_sha256"`
|
||||
CommonName string `json:"common_name"`
|
||||
SANs []string `json:"sans"`
|
||||
SerialNumber string `json:"serial_number"`
|
||||
IssuerDN string `json:"issuer_dn"`
|
||||
SubjectDN string `json:"subject_dn"`
|
||||
NotBefore *time.Time `json:"not_before,omitempty"`
|
||||
NotAfter *time.Time `json:"not_after,omitempty"`
|
||||
KeyAlgorithm string `json:"key_algorithm"`
|
||||
KeySize int `json:"key_size"`
|
||||
IsCA bool `json:"is_ca"`
|
||||
PEMData string `json:"pem_data,omitempty"`
|
||||
SourcePath string `json:"source_path"`
|
||||
SourceFormat string `json:"source_format"`
|
||||
AgentID string `json:"agent_id"`
|
||||
DiscoveryScanID string `json:"discovery_scan_id,omitempty"`
|
||||
ManagedCertificateID string `json:"managed_certificate_id,omitempty"`
|
||||
Status DiscoveryStatus `json:"status"`
|
||||
FirstSeenAt time.Time `json:"first_seen_at"`
|
||||
LastSeenAt time.Time `json:"last_seen_at"`
|
||||
DismissedAt *time.Time `json:"dismissed_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// IsExpired returns true if the discovered certificate has expired.
|
||||
func (d *DiscoveredCertificate) IsExpired() bool {
|
||||
if d.NotAfter == nil {
|
||||
return false
|
||||
}
|
||||
return d.NotAfter.Before(time.Now())
|
||||
}
|
||||
|
||||
// DaysUntilExpiry returns the number of days until the certificate expires.
|
||||
// Returns -1 if NotAfter is not set.
|
||||
func (d *DiscoveredCertificate) DaysUntilExpiry() int {
|
||||
if d.NotAfter == nil {
|
||||
return -1
|
||||
}
|
||||
hours := time.Until(*d.NotAfter).Hours()
|
||||
return int(hours / 24)
|
||||
}
|
||||
|
||||
// DiscoveryScan represents a single discovery scan run by an agent.
|
||||
type DiscoveryScan struct {
|
||||
ID string `json:"id"`
|
||||
AgentID string `json:"agent_id"`
|
||||
Directories []string `json:"directories"`
|
||||
CertificatesFound int `json:"certificates_found"`
|
||||
CertificatesNew int `json:"certificates_new"`
|
||||
ErrorsCount int `json:"errors_count"`
|
||||
ScanDurationMs int `json:"scan_duration_ms"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
}
|
||||
|
||||
// DiscoveryReport is the payload an agent sends after scanning its filesystem.
|
||||
type DiscoveryReport struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
Directories []string `json:"directories"`
|
||||
Certificates []DiscoveredCertEntry `json:"certificates"`
|
||||
Errors []string `json:"errors,omitempty"`
|
||||
ScanDurationMs int `json:"scan_duration_ms"`
|
||||
}
|
||||
|
||||
// DiscoveredCertEntry represents a single certificate found during a filesystem scan.
|
||||
// This is the agent-side representation (no server-side IDs yet).
|
||||
type DiscoveredCertEntry struct {
|
||||
FingerprintSHA256 string `json:"fingerprint_sha256"`
|
||||
CommonName string `json:"common_name"`
|
||||
SANs []string `json:"sans"`
|
||||
SerialNumber string `json:"serial_number"`
|
||||
IssuerDN string `json:"issuer_dn"`
|
||||
SubjectDN string `json:"subject_dn"`
|
||||
NotBefore string `json:"not_before"`
|
||||
NotAfter string `json:"not_after"`
|
||||
KeyAlgorithm string `json:"key_algorithm"`
|
||||
KeySize int `json:"key_size"`
|
||||
IsCA bool `json:"is_ca"`
|
||||
PEMData string `json:"pem_data"`
|
||||
SourcePath string `json:"source_path"`
|
||||
SourceFormat string `json:"source_format"`
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestIsValidDiscoveryStatus(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status string
|
||||
want bool
|
||||
}{
|
||||
{"Unmanaged", "Unmanaged", true},
|
||||
{"Managed", "Managed", true},
|
||||
{"Dismissed", "Dismissed", true},
|
||||
{"empty string", "", false},
|
||||
{"invalid status", "Unknown", false},
|
||||
{"partial match", "Manage", false},
|
||||
{"case sensitive", "unmanaged", false},
|
||||
{"lowercase managed", "managed", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := IsValidDiscoveryStatus(tt.status); got != tt.want {
|
||||
t.Errorf("IsValidDiscoveryStatus(%q) = %v, want %v", tt.status, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoveredCertificate_IsExpired(t *testing.T) {
|
||||
now := time.Now()
|
||||
pastTime := now.AddDate(-1, 0, 0)
|
||||
futureTime := now.AddDate(1, 0, 0)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
notAfter *time.Time
|
||||
want bool
|
||||
}{
|
||||
{"expired certificate", &pastTime, true},
|
||||
{"valid certificate", &futureTime, false},
|
||||
{"nil NotAfter", nil, false},
|
||||
{"expires at current time (edge case)", &now, false}, // Before() = false when at same time
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
dc := &DiscoveredCertificate{
|
||||
ID: "dcert-1",
|
||||
NotAfter: tt.notAfter,
|
||||
}
|
||||
if got := dc.IsExpired(); got != tt.want {
|
||||
t.Errorf("IsExpired() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoveredCertificate_DaysUntilExpiry(t *testing.T) {
|
||||
now := time.Now()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
notAfter *time.Time
|
||||
wantDays int
|
||||
}{
|
||||
{"nil NotAfter", nil, -1},
|
||||
{"expires in 30 days", &time.Time{}, 0}, // placeholder, will be calculated below
|
||||
{"expires in 1 day", &time.Time{}, 1},
|
||||
{"expires in 0 days (expired)", &time.Time{}, 0},
|
||||
}
|
||||
|
||||
// Test with actual future times
|
||||
thirtyDaysFromNow := now.AddDate(0, 0, 30)
|
||||
oneDayFromNow := now.AddDate(0, 0, 1)
|
||||
pastTime := now.AddDate(0, 0, -1)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
notAfter *time.Time
|
||||
wantMin int
|
||||
wantMax int
|
||||
}{
|
||||
{"nil NotAfter", nil, -1, -1},
|
||||
{"expires in 30 days", &thirtyDaysFromNow, 29, 31},
|
||||
{"expires in 1 day", &oneDayFromNow, 0, 2},
|
||||
{"already expired", &pastTime, -2, -1},
|
||||
}
|
||||
|
||||
for _, tt := range testCases {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
dc := &DiscoveredCertificate{
|
||||
ID: "dcert-2",
|
||||
NotAfter: tt.notAfter,
|
||||
}
|
||||
got := dc.DaysUntilExpiry()
|
||||
if got < tt.wantMin || got > tt.wantMax {
|
||||
t.Errorf("DaysUntilExpiry() = %d, want between %d and %d", got, tt.wantMin, tt.wantMax)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,7 @@ func TestCertificateLifecycle(t *testing.T) {
|
||||
statsHandler := handler.NewStatsHandler(&mockStatsService{})
|
||||
metricsHandler := handler.NewMetricsHandler(&mockStatsService{}, time.Now())
|
||||
healthHandler := handler.NewHealthHandler("none")
|
||||
discoveryHandler := handler.NewDiscoveryHandler(&mockDiscoveryService{})
|
||||
|
||||
// Create router and register handlers
|
||||
r := router.New()
|
||||
@@ -98,6 +99,7 @@ func TestCertificateLifecycle(t *testing.T) {
|
||||
statsHandler,
|
||||
metricsHandler,
|
||||
healthHandler,
|
||||
discoveryHandler,
|
||||
)
|
||||
|
||||
// Create test server
|
||||
@@ -1137,3 +1139,38 @@ func (m *mockStatsService) GetJobStats(ctx context.Context, days int) (interface
|
||||
func (m *mockStatsService) GetIssuanceRate(ctx context.Context, days int) (interface{}, error) {
|
||||
return []interface{}{}, nil
|
||||
}
|
||||
|
||||
// mockDiscoveryService implements handler.DiscoveryService for integration tests.
|
||||
type mockDiscoveryService struct{}
|
||||
|
||||
func (m *mockDiscoveryService) ProcessDiscoveryReport(ctx context.Context, report *domain.DiscoveryReport) (*domain.DiscoveryScan, error) {
|
||||
return &domain.DiscoveryScan{ID: "dscan-test"}, nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryService) ListDiscovered(ctx context.Context, agentID, status string, page, perPage int) ([]*domain.DiscoveredCertificate, int, error) {
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryService) GetDiscovered(ctx context.Context, id string) (*domain.DiscoveredCertificate, error) {
|
||||
return nil, fmt.Errorf("not found")
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryService) ClaimDiscovered(ctx context.Context, id string, managedCertID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryService) DismissDiscovered(ctx context.Context, id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryService) ListScans(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error) {
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryService) GetScan(ctx context.Context, id string) (*domain.DiscoveryScan, error) {
|
||||
return nil, fmt.Errorf("not found")
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryService) GetDiscoverySummary(ctx context.Context) (map[string]int, error) {
|
||||
return map[string]int{}, nil
|
||||
}
|
||||
|
||||
@@ -72,6 +72,7 @@ func setupTestServer(t *testing.T) (*httptest.Server, *mockCertificateRepository
|
||||
statsHandler := handler.NewStatsHandler(&mockStatsService{})
|
||||
metricsHandler := handler.NewMetricsHandler(&mockStatsService{}, time.Now())
|
||||
healthHandler := handler.NewHealthHandler("none")
|
||||
discoveryHandler := handler.NewDiscoveryHandler(&mockDiscoveryService{})
|
||||
|
||||
r := router.New()
|
||||
r.RegisterHandlers(
|
||||
@@ -90,6 +91,7 @@ func setupTestServer(t *testing.T) (*httptest.Server, *mockCertificateRepository
|
||||
statsHandler,
|
||||
metricsHandler,
|
||||
healthHandler,
|
||||
discoveryHandler,
|
||||
)
|
||||
|
||||
server := httptest.NewServer(r)
|
||||
|
||||
@@ -205,6 +205,39 @@ type AgentGroupRepository interface {
|
||||
RemoveMember(ctx context.Context, groupID, agentID string) error
|
||||
}
|
||||
|
||||
// DiscoveryRepository defines operations for managing certificate discovery.
|
||||
type DiscoveryRepository interface {
|
||||
// CreateScan stores a new discovery scan record.
|
||||
CreateScan(ctx context.Context, scan *domain.DiscoveryScan) error
|
||||
// GetScan retrieves a discovery scan by ID.
|
||||
GetScan(ctx context.Context, id string) (*domain.DiscoveryScan, error)
|
||||
// ListScans returns discovery scans, optionally filtered by agent ID.
|
||||
ListScans(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error)
|
||||
// CreateDiscovered stores a new discovered certificate (upserts by fingerprint+agent+path).
|
||||
// Returns true if the certificate was newly inserted (not just updated).
|
||||
CreateDiscovered(ctx context.Context, cert *domain.DiscoveredCertificate) (bool, error)
|
||||
// GetDiscovered retrieves a discovered certificate by ID.
|
||||
GetDiscovered(ctx context.Context, id string) (*domain.DiscoveredCertificate, error)
|
||||
// ListDiscovered returns discovered certificates matching the filter.
|
||||
ListDiscovered(ctx context.Context, filter *DiscoveryFilter) ([]*domain.DiscoveredCertificate, int, error)
|
||||
// UpdateDiscoveredStatus updates the status and optional managed certificate link.
|
||||
UpdateDiscoveredStatus(ctx context.Context, id string, status domain.DiscoveryStatus, managedCertID string) error
|
||||
// GetByFingerprint retrieves discovered certificates by SHA-256 fingerprint.
|
||||
GetByFingerprint(ctx context.Context, fingerprint string) ([]*domain.DiscoveredCertificate, error)
|
||||
// CountByStatus returns counts of discovered certificates grouped by status.
|
||||
CountByStatus(ctx context.Context) (map[string]int, error)
|
||||
}
|
||||
|
||||
// DiscoveryFilter defines filters for listing discovered certificates.
|
||||
type DiscoveryFilter struct {
|
||||
AgentID string
|
||||
Status string
|
||||
IsExpired bool
|
||||
IsCA bool
|
||||
Page int
|
||||
PerPage int
|
||||
}
|
||||
|
||||
// OwnerRepository defines operations for managing certificate owners.
|
||||
type OwnerRepository interface {
|
||||
// List returns all owners.
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
)
|
||||
|
||||
// DiscoveryRepository implements the repository.DiscoveryRepository interface.
|
||||
type DiscoveryRepository struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
// NewDiscoveryRepository creates a new PostgreSQL-backed discovery repository.
|
||||
func NewDiscoveryRepository(db *sql.DB) *DiscoveryRepository {
|
||||
return &DiscoveryRepository{db: db}
|
||||
}
|
||||
|
||||
// --- Discovery Scans ---
|
||||
|
||||
// CreateScan stores a new discovery scan record.
|
||||
func (r *DiscoveryRepository) CreateScan(ctx context.Context, scan *domain.DiscoveryScan) error {
|
||||
query := `
|
||||
INSERT INTO discovery_scans (id, agent_id, directories, certificates_found, certificates_new, errors_count, scan_duration_ms, started_at, completed_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
ON CONFLICT (id) DO NOTHING`
|
||||
|
||||
_, err := r.db.ExecContext(ctx, query,
|
||||
scan.ID,
|
||||
scan.AgentID,
|
||||
pq.Array(scan.Directories),
|
||||
scan.CertificatesFound,
|
||||
scan.CertificatesNew,
|
||||
scan.ErrorsCount,
|
||||
scan.ScanDurationMs,
|
||||
scan.StartedAt,
|
||||
scan.CompletedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create discovery scan: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetScan retrieves a discovery scan by ID.
|
||||
func (r *DiscoveryRepository) GetScan(ctx context.Context, id string) (*domain.DiscoveryScan, error) {
|
||||
query := `
|
||||
SELECT id, agent_id, directories, certificates_found, certificates_new, errors_count, scan_duration_ms, started_at, completed_at
|
||||
FROM discovery_scans WHERE id = $1`
|
||||
|
||||
scan := &domain.DiscoveryScan{}
|
||||
var dirs []string
|
||||
err := r.db.QueryRowContext(ctx, query, id).Scan(
|
||||
&scan.ID, &scan.AgentID, pq.Array(&dirs),
|
||||
&scan.CertificatesFound, &scan.CertificatesNew, &scan.ErrorsCount,
|
||||
&scan.ScanDurationMs, &scan.StartedAt, &scan.CompletedAt,
|
||||
)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, fmt.Errorf("discovery scan not found: %s", id)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get discovery scan: %w", err)
|
||||
}
|
||||
scan.Directories = dirs
|
||||
return scan, nil
|
||||
}
|
||||
|
||||
// ListScans returns discovery scans, optionally filtered by agent ID.
|
||||
func (r *DiscoveryRepository) ListScans(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error) {
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if perPage <= 0 || perPage > 500 {
|
||||
perPage = 50
|
||||
}
|
||||
|
||||
var whereConditions []string
|
||||
var args []interface{}
|
||||
argCount := 1
|
||||
|
||||
if agentID != "" {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("agent_id = $%d", argCount))
|
||||
args = append(args, agentID)
|
||||
argCount++
|
||||
}
|
||||
|
||||
whereClause := ""
|
||||
if len(whereConditions) > 0 {
|
||||
whereClause = "WHERE " + strings.Join(whereConditions, " AND ")
|
||||
}
|
||||
|
||||
// Count
|
||||
countQuery := fmt.Sprintf("SELECT COUNT(*) FROM discovery_scans %s", whereClause)
|
||||
var total int
|
||||
if err := r.db.QueryRowContext(ctx, countQuery, args...).Scan(&total); err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to count discovery scans: %w", err)
|
||||
}
|
||||
|
||||
// List
|
||||
offset := (page - 1) * perPage
|
||||
listQuery := fmt.Sprintf(`
|
||||
SELECT id, agent_id, directories, certificates_found, certificates_new, errors_count, scan_duration_ms, started_at, completed_at
|
||||
FROM discovery_scans %s
|
||||
ORDER BY started_at DESC
|
||||
LIMIT $%d OFFSET $%d`, whereClause, argCount, argCount+1)
|
||||
|
||||
args = append(args, perPage, offset)
|
||||
rows, err := r.db.QueryContext(ctx, listQuery, args...)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to list discovery scans: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var scans []*domain.DiscoveryScan
|
||||
for rows.Next() {
|
||||
scan := &domain.DiscoveryScan{}
|
||||
var dirs []string
|
||||
if err := rows.Scan(
|
||||
&scan.ID, &scan.AgentID, pq.Array(&dirs),
|
||||
&scan.CertificatesFound, &scan.CertificatesNew, &scan.ErrorsCount,
|
||||
&scan.ScanDurationMs, &scan.StartedAt, &scan.CompletedAt,
|
||||
); err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to scan discovery scan row: %w", err)
|
||||
}
|
||||
scan.Directories = dirs
|
||||
scans = append(scans, scan)
|
||||
}
|
||||
return scans, total, nil
|
||||
}
|
||||
|
||||
// --- Discovered Certificates ---
|
||||
|
||||
// CreateDiscovered stores a new discovered certificate.
|
||||
// Uses ON CONFLICT to update last_seen_at for existing fingerprint+agent+path combos.
|
||||
func (r *DiscoveryRepository) CreateDiscovered(ctx context.Context, cert *domain.DiscoveredCertificate) (bool, error) {
|
||||
query := `
|
||||
INSERT INTO discovered_certificates (
|
||||
id, fingerprint_sha256, common_name, sans, serial_number, issuer_dn, subject_dn,
|
||||
not_before, not_after, key_algorithm, key_size, is_ca, pem_data,
|
||||
source_path, source_format, agent_id, discovery_scan_id,
|
||||
status, first_seen_at, last_seen_at, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22)
|
||||
ON CONFLICT (fingerprint_sha256, agent_id, source_path) DO UPDATE SET
|
||||
last_seen_at = EXCLUDED.last_seen_at,
|
||||
discovery_scan_id = EXCLUDED.discovery_scan_id,
|
||||
updated_at = NOW()
|
||||
RETURNING (xmax = 0) AS is_new`
|
||||
|
||||
var isNew bool
|
||||
err := r.db.QueryRowContext(ctx, query,
|
||||
cert.ID, cert.FingerprintSHA256, cert.CommonName, pq.Array(cert.SANs),
|
||||
cert.SerialNumber, cert.IssuerDN, cert.SubjectDN,
|
||||
cert.NotBefore, cert.NotAfter, cert.KeyAlgorithm, cert.KeySize, cert.IsCA,
|
||||
cert.PEMData, cert.SourcePath, cert.SourceFormat,
|
||||
cert.AgentID, nullableString(cert.DiscoveryScanID),
|
||||
string(cert.Status), cert.FirstSeenAt, cert.LastSeenAt,
|
||||
cert.CreatedAt, cert.UpdatedAt,
|
||||
).Scan(&isNew)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to upsert discovered certificate: %w", err)
|
||||
}
|
||||
return isNew, nil
|
||||
}
|
||||
|
||||
// GetDiscovered retrieves a discovered certificate by ID.
|
||||
func (r *DiscoveryRepository) GetDiscovered(ctx context.Context, id string) (*domain.DiscoveredCertificate, error) {
|
||||
query := `
|
||||
SELECT id, fingerprint_sha256, common_name, sans, serial_number, issuer_dn, subject_dn,
|
||||
not_before, not_after, key_algorithm, key_size, is_ca, pem_data,
|
||||
source_path, source_format, agent_id, discovery_scan_id, managed_certificate_id,
|
||||
status, first_seen_at, last_seen_at, dismissed_at, created_at, updated_at
|
||||
FROM discovered_certificates WHERE id = $1`
|
||||
|
||||
cert := &domain.DiscoveredCertificate{}
|
||||
var sans []string
|
||||
var scanID, managedID sql.NullString
|
||||
err := r.db.QueryRowContext(ctx, query, id).Scan(
|
||||
&cert.ID, &cert.FingerprintSHA256, &cert.CommonName, pq.Array(&sans),
|
||||
&cert.SerialNumber, &cert.IssuerDN, &cert.SubjectDN,
|
||||
&cert.NotBefore, &cert.NotAfter, &cert.KeyAlgorithm, &cert.KeySize, &cert.IsCA,
|
||||
&cert.PEMData, &cert.SourcePath, &cert.SourceFormat,
|
||||
&cert.AgentID, &scanID, &managedID,
|
||||
&cert.Status, &cert.FirstSeenAt, &cert.LastSeenAt, &cert.DismissedAt,
|
||||
&cert.CreatedAt, &cert.UpdatedAt,
|
||||
)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, fmt.Errorf("discovered certificate not found: %s", id)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get discovered certificate: %w", err)
|
||||
}
|
||||
cert.SANs = sans
|
||||
if scanID.Valid {
|
||||
cert.DiscoveryScanID = scanID.String
|
||||
}
|
||||
if managedID.Valid {
|
||||
cert.ManagedCertificateID = managedID.String
|
||||
}
|
||||
return cert, nil
|
||||
}
|
||||
|
||||
// ListDiscovered returns discovered certificates matching the filter.
|
||||
func (r *DiscoveryRepository) ListDiscovered(ctx context.Context, filter *DiscoveryFilter) ([]*domain.DiscoveredCertificate, int, error) {
|
||||
if filter.Page < 1 {
|
||||
filter.Page = 1
|
||||
}
|
||||
if filter.PerPage <= 0 || filter.PerPage > 500 {
|
||||
filter.PerPage = 50
|
||||
}
|
||||
|
||||
var whereConditions []string
|
||||
var args []interface{}
|
||||
argCount := 1
|
||||
|
||||
if filter.AgentID != "" {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("agent_id = $%d", argCount))
|
||||
args = append(args, filter.AgentID)
|
||||
argCount++
|
||||
}
|
||||
if filter.Status != "" {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("status = $%d", argCount))
|
||||
args = append(args, filter.Status)
|
||||
argCount++
|
||||
}
|
||||
if filter.IsExpired {
|
||||
whereConditions = append(whereConditions, "not_after < NOW()")
|
||||
}
|
||||
if filter.IsCA {
|
||||
whereConditions = append(whereConditions, "is_ca = TRUE")
|
||||
}
|
||||
|
||||
whereClause := ""
|
||||
if len(whereConditions) > 0 {
|
||||
whereClause = "WHERE " + strings.Join(whereConditions, " AND ")
|
||||
}
|
||||
|
||||
// Count
|
||||
countQuery := fmt.Sprintf("SELECT COUNT(*) FROM discovered_certificates %s", whereClause)
|
||||
var total int
|
||||
if err := r.db.QueryRowContext(ctx, countQuery, args...).Scan(&total); err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to count discovered certificates: %w", err)
|
||||
}
|
||||
|
||||
// List
|
||||
offset := (filter.Page - 1) * filter.PerPage
|
||||
listQuery := fmt.Sprintf(`
|
||||
SELECT id, fingerprint_sha256, common_name, sans, serial_number, issuer_dn, subject_dn,
|
||||
not_before, not_after, key_algorithm, key_size, is_ca, pem_data,
|
||||
source_path, source_format, agent_id, discovery_scan_id, managed_certificate_id,
|
||||
status, first_seen_at, last_seen_at, dismissed_at, created_at, updated_at
|
||||
FROM discovered_certificates %s
|
||||
ORDER BY last_seen_at DESC
|
||||
LIMIT $%d OFFSET $%d`, whereClause, argCount, argCount+1)
|
||||
|
||||
args = append(args, filter.PerPage, offset)
|
||||
rows, err := r.db.QueryContext(ctx, listQuery, args...)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to list discovered certificates: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var certs []*domain.DiscoveredCertificate
|
||||
for rows.Next() {
|
||||
cert := &domain.DiscoveredCertificate{}
|
||||
var sans []string
|
||||
var scanID, managedID sql.NullString
|
||||
if err := rows.Scan(
|
||||
&cert.ID, &cert.FingerprintSHA256, &cert.CommonName, pq.Array(&sans),
|
||||
&cert.SerialNumber, &cert.IssuerDN, &cert.SubjectDN,
|
||||
&cert.NotBefore, &cert.NotAfter, &cert.KeyAlgorithm, &cert.KeySize, &cert.IsCA,
|
||||
&cert.PEMData, &cert.SourcePath, &cert.SourceFormat,
|
||||
&cert.AgentID, &scanID, &managedID,
|
||||
&cert.Status, &cert.FirstSeenAt, &cert.LastSeenAt, &cert.DismissedAt,
|
||||
&cert.CreatedAt, &cert.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to scan discovered certificate row: %w", err)
|
||||
}
|
||||
cert.SANs = sans
|
||||
if scanID.Valid {
|
||||
cert.DiscoveryScanID = scanID.String
|
||||
}
|
||||
if managedID.Valid {
|
||||
cert.ManagedCertificateID = managedID.String
|
||||
}
|
||||
certs = append(certs, cert)
|
||||
}
|
||||
return certs, total, nil
|
||||
}
|
||||
|
||||
// UpdateDiscoveredStatus updates the status and optional managed certificate link.
|
||||
func (r *DiscoveryRepository) UpdateDiscoveredStatus(ctx context.Context, id string, status domain.DiscoveryStatus, managedCertID string) error {
|
||||
var query string
|
||||
var args []interface{}
|
||||
|
||||
now := time.Now()
|
||||
switch status {
|
||||
case domain.DiscoveryStatusManaged:
|
||||
query = `UPDATE discovered_certificates SET status = $1, managed_certificate_id = $2, updated_at = $3 WHERE id = $4`
|
||||
args = []interface{}{string(status), managedCertID, now, id}
|
||||
case domain.DiscoveryStatusDismissed:
|
||||
query = `UPDATE discovered_certificates SET status = $1, dismissed_at = $2, updated_at = $3 WHERE id = $4`
|
||||
args = []interface{}{string(status), now, now, id}
|
||||
default:
|
||||
query = `UPDATE discovered_certificates SET status = $1, managed_certificate_id = NULL, dismissed_at = NULL, updated_at = $2 WHERE id = $3`
|
||||
args = []interface{}{string(status), now, id}
|
||||
}
|
||||
|
||||
result, err := r.db.ExecContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update discovered certificate status: %w", err)
|
||||
}
|
||||
rowsAffected, _ := result.RowsAffected()
|
||||
if rowsAffected == 0 {
|
||||
return fmt.Errorf("discovered certificate not found: %s", id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByFingerprint retrieves discovered certificates by SHA-256 fingerprint.
|
||||
func (r *DiscoveryRepository) GetByFingerprint(ctx context.Context, fingerprint string) ([]*domain.DiscoveredCertificate, error) {
|
||||
query := `
|
||||
SELECT id, fingerprint_sha256, common_name, sans, serial_number, issuer_dn, subject_dn,
|
||||
not_before, not_after, key_algorithm, key_size, is_ca, '',
|
||||
source_path, source_format, agent_id, discovery_scan_id, managed_certificate_id,
|
||||
status, first_seen_at, last_seen_at, dismissed_at, created_at, updated_at
|
||||
FROM discovered_certificates WHERE fingerprint_sha256 = $1
|
||||
ORDER BY last_seen_at DESC`
|
||||
|
||||
rows, err := r.db.QueryContext(ctx, query, fingerprint)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get by fingerprint: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var certs []*domain.DiscoveredCertificate
|
||||
for rows.Next() {
|
||||
cert := &domain.DiscoveredCertificate{}
|
||||
var sans []string
|
||||
var scanID, managedID sql.NullString
|
||||
if err := rows.Scan(
|
||||
&cert.ID, &cert.FingerprintSHA256, &cert.CommonName, pq.Array(&sans),
|
||||
&cert.SerialNumber, &cert.IssuerDN, &cert.SubjectDN,
|
||||
&cert.NotBefore, &cert.NotAfter, &cert.KeyAlgorithm, &cert.KeySize, &cert.IsCA,
|
||||
&cert.PEMData, &cert.SourcePath, &cert.SourceFormat,
|
||||
&cert.AgentID, &scanID, &managedID,
|
||||
&cert.Status, &cert.FirstSeenAt, &cert.LastSeenAt, &cert.DismissedAt,
|
||||
&cert.CreatedAt, &cert.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("failed to scan row: %w", err)
|
||||
}
|
||||
cert.SANs = sans
|
||||
if scanID.Valid {
|
||||
cert.DiscoveryScanID = scanID.String
|
||||
}
|
||||
if managedID.Valid {
|
||||
cert.ManagedCertificateID = managedID.String
|
||||
}
|
||||
certs = append(certs, cert)
|
||||
}
|
||||
return certs, nil
|
||||
}
|
||||
|
||||
// CountByStatus returns counts of discovered certificates grouped by status.
|
||||
func (r *DiscoveryRepository) CountByStatus(ctx context.Context) (map[string]int, error) {
|
||||
query := `SELECT status, COUNT(*) FROM discovered_certificates GROUP BY status`
|
||||
rows, err := r.db.QueryContext(ctx, query)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to count by status: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
counts := make(map[string]int)
|
||||
for rows.Next() {
|
||||
var status string
|
||||
var count int
|
||||
if err := rows.Scan(&status, &count); err != nil {
|
||||
return nil, fmt.Errorf("failed to scan row: %w", err)
|
||||
}
|
||||
counts[status] = count
|
||||
}
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
// DiscoveryFilter defines filters for listing discovered certificates.
|
||||
type DiscoveryFilter struct {
|
||||
AgentID string
|
||||
Status string
|
||||
IsExpired bool
|
||||
IsCA bool
|
||||
Page int
|
||||
PerPage int
|
||||
}
|
||||
|
||||
// nullableString returns a sql.NullString, null if the string is empty.
|
||||
func nullableString(s string) sql.NullString {
|
||||
if s == "" {
|
||||
return sql.NullString{}
|
||||
}
|
||||
return sql.NullString{String: s, Valid: true}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
"github.com/shankar0123/certctl/internal/repository"
|
||||
)
|
||||
|
||||
// DiscoveryService provides business logic for certificate discovery.
|
||||
type DiscoveryService struct {
|
||||
discoveryRepo repository.DiscoveryRepository
|
||||
certRepo repository.CertificateRepository
|
||||
auditService *AuditService
|
||||
}
|
||||
|
||||
// NewDiscoveryService creates a new discovery service.
|
||||
func NewDiscoveryService(
|
||||
discoveryRepo repository.DiscoveryRepository,
|
||||
certRepo repository.CertificateRepository,
|
||||
auditService *AuditService,
|
||||
) *DiscoveryService {
|
||||
return &DiscoveryService{
|
||||
discoveryRepo: discoveryRepo,
|
||||
certRepo: certRepo,
|
||||
auditService: auditService,
|
||||
}
|
||||
}
|
||||
|
||||
// ProcessDiscoveryReport processes a discovery report from an agent.
|
||||
// It creates a scan record, upserts each discovered certificate, and returns scan summary.
|
||||
func (s *DiscoveryService) ProcessDiscoveryReport(ctx context.Context, report *domain.DiscoveryReport) (*domain.DiscoveryScan, error) {
|
||||
if report.AgentID == "" {
|
||||
return nil, fmt.Errorf("agent_id is required")
|
||||
}
|
||||
if len(report.Certificates) == 0 && len(report.Errors) == 0 {
|
||||
return nil, fmt.Errorf("report must contain at least one certificate or error")
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
scan := &domain.DiscoveryScan{
|
||||
ID: generateID("dscan"),
|
||||
AgentID: report.AgentID,
|
||||
Directories: report.Directories,
|
||||
CertificatesFound: len(report.Certificates),
|
||||
ErrorsCount: len(report.Errors),
|
||||
ScanDurationMs: report.ScanDurationMs,
|
||||
StartedAt: now.Add(-time.Duration(report.ScanDurationMs) * time.Millisecond),
|
||||
CompletedAt: &now,
|
||||
}
|
||||
|
||||
// Upsert each discovered certificate
|
||||
newCount := 0
|
||||
for _, entry := range report.Certificates {
|
||||
cert := &domain.DiscoveredCertificate{
|
||||
ID: generateID("dcert"),
|
||||
FingerprintSHA256: entry.FingerprintSHA256,
|
||||
CommonName: entry.CommonName,
|
||||
SANs: entry.SANs,
|
||||
SerialNumber: entry.SerialNumber,
|
||||
IssuerDN: entry.IssuerDN,
|
||||
SubjectDN: entry.SubjectDN,
|
||||
KeyAlgorithm: entry.KeyAlgorithm,
|
||||
KeySize: entry.KeySize,
|
||||
IsCA: entry.IsCA,
|
||||
PEMData: entry.PEMData,
|
||||
SourcePath: entry.SourcePath,
|
||||
SourceFormat: entry.SourceFormat,
|
||||
AgentID: report.AgentID,
|
||||
DiscoveryScanID: scan.ID,
|
||||
Status: domain.DiscoveryStatusUnmanaged,
|
||||
FirstSeenAt: now,
|
||||
LastSeenAt: now,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
// Parse time fields
|
||||
if entry.NotBefore != "" {
|
||||
if t, err := time.Parse(time.RFC3339, entry.NotBefore); err == nil {
|
||||
cert.NotBefore = &t
|
||||
}
|
||||
}
|
||||
if entry.NotAfter != "" {
|
||||
if t, err := time.Parse(time.RFC3339, entry.NotAfter); err == nil {
|
||||
cert.NotAfter = &t
|
||||
}
|
||||
}
|
||||
|
||||
isNew, err := s.discoveryRepo.CreateDiscovered(ctx, cert)
|
||||
if err != nil {
|
||||
slog.Error("failed to upsert discovered certificate",
|
||||
"fingerprint", entry.FingerprintSHA256,
|
||||
"source_path", entry.SourcePath,
|
||||
"error", err)
|
||||
continue
|
||||
}
|
||||
if isNew {
|
||||
newCount++
|
||||
}
|
||||
}
|
||||
|
||||
scan.CertificatesNew = newCount
|
||||
|
||||
// Store the scan record
|
||||
if err := s.discoveryRepo.CreateScan(ctx, scan); err != nil {
|
||||
return nil, fmt.Errorf("failed to create scan record: %w", err)
|
||||
}
|
||||
|
||||
// Audit trail
|
||||
if err := s.auditService.RecordEvent(ctx, report.AgentID, domain.ActorTypeSystem,
|
||||
"discovery_scan_completed", "discovery_scan", scan.ID,
|
||||
map[string]interface{}{
|
||||
"agent_id": report.AgentID,
|
||||
"directories": report.Directories,
|
||||
"certificates_found": scan.CertificatesFound,
|
||||
"certificates_new": newCount,
|
||||
"errors_count": scan.ErrorsCount,
|
||||
}); err != nil {
|
||||
slog.Error("failed to record audit event", "error", err)
|
||||
}
|
||||
|
||||
return scan, nil
|
||||
}
|
||||
|
||||
// ListDiscovered returns discovered certificates matching the filter.
|
||||
func (s *DiscoveryService) ListDiscovered(ctx context.Context, agentID, status string, page, perPage int) ([]*domain.DiscoveredCertificate, int, error) {
|
||||
filter := &repository.DiscoveryFilter{
|
||||
AgentID: agentID,
|
||||
Status: status,
|
||||
Page: page,
|
||||
PerPage: perPage,
|
||||
}
|
||||
return s.discoveryRepo.ListDiscovered(ctx, filter)
|
||||
}
|
||||
|
||||
// GetDiscovered retrieves a discovered certificate by ID.
|
||||
func (s *DiscoveryService) GetDiscovered(ctx context.Context, id string) (*domain.DiscoveredCertificate, error) {
|
||||
return s.discoveryRepo.GetDiscovered(ctx, id)
|
||||
}
|
||||
|
||||
// ClaimDiscovered links a discovered certificate to a managed certificate.
|
||||
func (s *DiscoveryService) ClaimDiscovered(ctx context.Context, id string, managedCertID string) error {
|
||||
if managedCertID == "" {
|
||||
return fmt.Errorf("managed_certificate_id is required")
|
||||
}
|
||||
|
||||
// Verify the discovered cert exists
|
||||
disc, err := s.discoveryRepo.GetDiscovered(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify the managed cert exists
|
||||
if _, err := s.certRepo.Get(ctx, managedCertID); err != nil {
|
||||
return fmt.Errorf("managed certificate not found: %s", managedCertID)
|
||||
}
|
||||
|
||||
if err := s.discoveryRepo.UpdateDiscoveredStatus(ctx, id, domain.DiscoveryStatusManaged, managedCertID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Audit trail
|
||||
if err := s.auditService.RecordEvent(ctx, "operator", domain.ActorTypeUser,
|
||||
"discovery_cert_claimed", "discovered_certificate", id,
|
||||
map[string]interface{}{
|
||||
"managed_certificate_id": managedCertID,
|
||||
"fingerprint": disc.FingerprintSHA256,
|
||||
"common_name": disc.CommonName,
|
||||
}); err != nil {
|
||||
slog.Error("failed to record audit event", "error", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DismissDiscovered marks a discovered certificate as dismissed.
|
||||
func (s *DiscoveryService) DismissDiscovered(ctx context.Context, id string) error {
|
||||
if err := s.discoveryRepo.UpdateDiscoveredStatus(ctx, id, domain.DiscoveryStatusDismissed, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Audit trail
|
||||
if err := s.auditService.RecordEvent(ctx, "operator", domain.ActorTypeUser,
|
||||
"discovery_cert_dismissed", "discovered_certificate", id, nil); err != nil {
|
||||
slog.Error("failed to record audit event", "error", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListScans returns discovery scans, optionally filtered by agent ID.
|
||||
func (s *DiscoveryService) ListScans(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error) {
|
||||
return s.discoveryRepo.ListScans(ctx, agentID, page, perPage)
|
||||
}
|
||||
|
||||
// GetScan retrieves a discovery scan by ID.
|
||||
func (s *DiscoveryService) GetScan(ctx context.Context, id string) (*domain.DiscoveryScan, error) {
|
||||
return s.discoveryRepo.GetScan(ctx, id)
|
||||
}
|
||||
|
||||
// GetDiscoverySummary returns a summary of discovery status counts.
|
||||
func (s *DiscoveryService) GetDiscoverySummary(ctx context.Context) (map[string]int, error) {
|
||||
return s.discoveryRepo.CountByStatus(ctx)
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
"github.com/shankar0123/certctl/internal/repository"
|
||||
)
|
||||
|
||||
// mockDiscoveryRepo is a test implementation of DiscoveryRepository
|
||||
type mockDiscoveryRepo struct {
|
||||
Scans map[string]*domain.DiscoveryScan
|
||||
Discovered map[string]*domain.DiscoveredCertificate
|
||||
CreateScanErr error
|
||||
GetScanErr error
|
||||
ListScansErr error
|
||||
CreateDiscoveredErr error
|
||||
GetDiscoveredErr error
|
||||
ListDiscoveredErr error
|
||||
UpdateStatusErr error
|
||||
GetByFingerprintErr error
|
||||
CountByStatusErr error
|
||||
}
|
||||
|
||||
func newMockDiscoveryRepository() *mockDiscoveryRepo {
|
||||
return &mockDiscoveryRepo{
|
||||
Scans: make(map[string]*domain.DiscoveryScan),
|
||||
Discovered: make(map[string]*domain.DiscoveredCertificate),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryRepo) CreateScan(ctx context.Context, scan *domain.DiscoveryScan) error {
|
||||
if m.CreateScanErr != nil {
|
||||
return m.CreateScanErr
|
||||
}
|
||||
m.Scans[scan.ID] = scan
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryRepo) GetScan(ctx context.Context, id string) (*domain.DiscoveryScan, error) {
|
||||
if m.GetScanErr != nil {
|
||||
return nil, m.GetScanErr
|
||||
}
|
||||
scan, ok := m.Scans[id]
|
||||
if !ok {
|
||||
return nil, errNotFound
|
||||
}
|
||||
return scan, nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryRepo) ListScans(ctx context.Context, agentID string, page, perPage int) ([]*domain.DiscoveryScan, int, error) {
|
||||
if m.ListScansErr != nil {
|
||||
return nil, 0, m.ListScansErr
|
||||
}
|
||||
var scans []*domain.DiscoveryScan
|
||||
for _, s := range m.Scans {
|
||||
if agentID == "" || s.AgentID == agentID {
|
||||
scans = append(scans, s)
|
||||
}
|
||||
}
|
||||
return scans, len(scans), nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryRepo) CreateDiscovered(ctx context.Context, cert *domain.DiscoveredCertificate) (bool, error) {
|
||||
if m.CreateDiscoveredErr != nil {
|
||||
return false, m.CreateDiscoveredErr
|
||||
}
|
||||
_, exists := m.Discovered[cert.ID]
|
||||
m.Discovered[cert.ID] = cert
|
||||
return !exists, nil // true if new (not existed before)
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryRepo) GetDiscovered(ctx context.Context, id string) (*domain.DiscoveredCertificate, error) {
|
||||
if m.GetDiscoveredErr != nil {
|
||||
return nil, m.GetDiscoveredErr
|
||||
}
|
||||
cert, ok := m.Discovered[id]
|
||||
if !ok {
|
||||
return nil, errNotFound
|
||||
}
|
||||
return cert, nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryRepo) ListDiscovered(ctx context.Context, filter *repository.DiscoveryFilter) ([]*domain.DiscoveredCertificate, int, error) {
|
||||
if m.ListDiscoveredErr != nil {
|
||||
return nil, 0, m.ListDiscoveredErr
|
||||
}
|
||||
var certs []*domain.DiscoveredCertificate
|
||||
for _, c := range m.Discovered {
|
||||
if filter.AgentID != "" && c.AgentID != filter.AgentID {
|
||||
continue
|
||||
}
|
||||
if filter.Status != "" && string(c.Status) != filter.Status {
|
||||
continue
|
||||
}
|
||||
certs = append(certs, c)
|
||||
}
|
||||
return certs, len(certs), nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryRepo) UpdateDiscoveredStatus(ctx context.Context, id string, status domain.DiscoveryStatus, managedCertID string) error {
|
||||
if m.UpdateStatusErr != nil {
|
||||
return m.UpdateStatusErr
|
||||
}
|
||||
cert, ok := m.Discovered[id]
|
||||
if !ok {
|
||||
return errNotFound
|
||||
}
|
||||
cert.Status = status
|
||||
cert.ManagedCertificateID = managedCertID
|
||||
now := time.Now()
|
||||
if status == domain.DiscoveryStatusDismissed {
|
||||
cert.DismissedAt = &now
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryRepo) GetByFingerprint(ctx context.Context, fingerprint string) ([]*domain.DiscoveredCertificate, error) {
|
||||
if m.GetByFingerprintErr != nil {
|
||||
return nil, m.GetByFingerprintErr
|
||||
}
|
||||
var certs []*domain.DiscoveredCertificate
|
||||
for _, c := range m.Discovered {
|
||||
if c.FingerprintSHA256 == fingerprint {
|
||||
certs = append(certs, c)
|
||||
}
|
||||
}
|
||||
return certs, nil
|
||||
}
|
||||
|
||||
func (m *mockDiscoveryRepo) CountByStatus(ctx context.Context) (map[string]int, error) {
|
||||
if m.CountByStatusErr != nil {
|
||||
return nil, m.CountByStatusErr
|
||||
}
|
||||
counts := make(map[string]int)
|
||||
for _, c := range m.Discovered {
|
||||
counts[string(c.Status)]++
|
||||
}
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
// helper to create a test DiscoveryService wired for discovery tests
|
||||
func newDiscoveryTestService() (*DiscoveryService, *mockDiscoveryRepo, *mockCertRepo, *mockAuditRepo) {
|
||||
discoveryRepo := newMockDiscoveryRepository()
|
||||
certRepo := newMockCertificateRepository()
|
||||
auditRepo := newMockAuditRepository()
|
||||
|
||||
auditService := NewAuditService(auditRepo)
|
||||
discoveryService := NewDiscoveryService(discoveryRepo, certRepo, auditService)
|
||||
|
||||
return discoveryService, discoveryRepo, certRepo, auditRepo
|
||||
}
|
||||
|
||||
func TestProcessDiscoveryReport_Success(t *testing.T) {
|
||||
svc, discoveryRepo, _, auditRepo := newDiscoveryTestService()
|
||||
|
||||
report := &domain.DiscoveryReport{
|
||||
AgentID: "agent-1",
|
||||
Directories: []string{"/etc/certs", "/opt/certs"},
|
||||
ScanDurationMs: 150,
|
||||
Certificates: []domain.DiscoveredCertEntry{
|
||||
{
|
||||
FingerprintSHA256: "abc123",
|
||||
CommonName: "example.com",
|
||||
SANs: []string{"www.example.com"},
|
||||
SerialNumber: "001",
|
||||
IssuerDN: "CN=Let's Encrypt",
|
||||
SubjectDN: "CN=example.com",
|
||||
NotBefore: time.Now().AddDate(-1, 0, 0).Format(time.RFC3339),
|
||||
NotAfter: time.Now().AddDate(1, 0, 0).Format(time.RFC3339),
|
||||
KeyAlgorithm: "RSA",
|
||||
KeySize: 2048,
|
||||
IsCA: false,
|
||||
PEMData: "-----BEGIN CERTIFICATE-----...",
|
||||
SourcePath: "/etc/certs/example.com.crt",
|
||||
SourceFormat: "PEM",
|
||||
},
|
||||
},
|
||||
Errors: []string{},
|
||||
}
|
||||
|
||||
scan, err := svc.ProcessDiscoveryReport(context.Background(), report)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got: %v", err)
|
||||
}
|
||||
|
||||
if scan == nil {
|
||||
t.Fatal("expected scan to be returned")
|
||||
}
|
||||
if scan.AgentID != "agent-1" {
|
||||
t.Errorf("expected agent ID agent-1, got %s", scan.AgentID)
|
||||
}
|
||||
if scan.CertificatesFound != 1 {
|
||||
t.Errorf("expected 1 certificate found, got %d", scan.CertificatesFound)
|
||||
}
|
||||
if scan.CertificatesNew != 1 {
|
||||
t.Errorf("expected 1 new certificate, got %d", scan.CertificatesNew)
|
||||
}
|
||||
|
||||
// Verify scan was persisted
|
||||
if len(discoveryRepo.Scans) != 1 {
|
||||
t.Fatalf("expected 1 scan in repo, got %d", len(discoveryRepo.Scans))
|
||||
}
|
||||
|
||||
// Verify discovered cert was persisted
|
||||
if len(discoveryRepo.Discovered) != 1 {
|
||||
t.Fatalf("expected 1 discovered cert in repo, got %d", len(discoveryRepo.Discovered))
|
||||
}
|
||||
|
||||
// Verify audit event was recorded
|
||||
if len(auditRepo.Events) == 0 {
|
||||
t.Error("expected audit event to be recorded")
|
||||
}
|
||||
foundDiscoveryAudit := false
|
||||
for _, e := range auditRepo.Events {
|
||||
if e.Action == "discovery_scan_completed" {
|
||||
foundDiscoveryAudit = true
|
||||
}
|
||||
}
|
||||
if !foundDiscoveryAudit {
|
||||
t.Error("expected discovery_scan_completed audit event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessDiscoveryReport_EmptyAgentID(t *testing.T) {
|
||||
svc, _, _, _ := newDiscoveryTestService()
|
||||
|
||||
report := &domain.DiscoveryReport{
|
||||
AgentID: "", // empty agent ID
|
||||
Certificates: []domain.DiscoveredCertEntry{
|
||||
{
|
||||
FingerprintSHA256: "abc123",
|
||||
CommonName: "example.com",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, err := svc.ProcessDiscoveryReport(context.Background(), report)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty agent_id")
|
||||
}
|
||||
if !errors.Is(err, err) { // just verify error occurred
|
||||
t.Errorf("expected validation error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessDiscoveryReport_EmptyReport(t *testing.T) {
|
||||
svc, _, _, _ := newDiscoveryTestService()
|
||||
|
||||
report := &domain.DiscoveryReport{
|
||||
AgentID: "agent-1",
|
||||
Certificates: []domain.DiscoveredCertEntry{},
|
||||
Errors: []string{},
|
||||
ScanDurationMs: 100,
|
||||
}
|
||||
|
||||
_, err := svc.ProcessDiscoveryReport(context.Background(), report)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty report")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDiscovered_Success(t *testing.T) {
|
||||
svc, discoveryRepo, _, _ := newDiscoveryTestService()
|
||||
|
||||
now := time.Now()
|
||||
cert1 := &domain.DiscoveredCertificate{
|
||||
ID: "dcert-1",
|
||||
AgentID: "agent-1",
|
||||
CommonName: "example.com",
|
||||
Status: domain.DiscoveryStatusUnmanaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
cert2 := &domain.DiscoveredCertificate{
|
||||
ID: "dcert-2",
|
||||
AgentID: "agent-1",
|
||||
CommonName: "api.example.com",
|
||||
Status: domain.DiscoveryStatusManaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
discoveryRepo.Discovered[cert1.ID] = cert1
|
||||
discoveryRepo.Discovered[cert2.ID] = cert2
|
||||
|
||||
certs, total, err := svc.ListDiscovered(context.Background(), "agent-1", "", 1, 50)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got: %v", err)
|
||||
}
|
||||
|
||||
if len(certs) != 2 {
|
||||
t.Errorf("expected 2 certs, got %d", len(certs))
|
||||
}
|
||||
if total != 2 {
|
||||
t.Errorf("expected total 2, got %d", total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDiscovered_WithStatusFilter(t *testing.T) {
|
||||
svc, discoveryRepo, _, _ := newDiscoveryTestService()
|
||||
|
||||
now := time.Now()
|
||||
cert1 := &domain.DiscoveredCertificate{
|
||||
ID: "dcert-1",
|
||||
AgentID: "agent-1",
|
||||
CommonName: "example.com",
|
||||
Status: domain.DiscoveryStatusUnmanaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
cert2 := &domain.DiscoveredCertificate{
|
||||
ID: "dcert-2",
|
||||
AgentID: "agent-1",
|
||||
CommonName: "api.example.com",
|
||||
Status: domain.DiscoveryStatusManaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
discoveryRepo.Discovered[cert1.ID] = cert1
|
||||
discoveryRepo.Discovered[cert2.ID] = cert2
|
||||
|
||||
certs, total, err := svc.ListDiscovered(context.Background(), "agent-1", "Unmanaged", 1, 50)
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got: %v", err)
|
||||
}
|
||||
|
||||
if len(certs) != 1 {
|
||||
t.Errorf("expected 1 cert, got %d", len(certs))
|
||||
}
|
||||
if total != 1 {
|
||||
t.Errorf("expected total 1, got %d", total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetDiscovered_Success(t *testing.T) {
|
||||
svc, discoveryRepo, _, _ := newDiscoveryTestService()
|
||||
|
||||
now := time.Now()
|
||||
cert := &domain.DiscoveredCertificate{
|
||||
ID: "dcert-1",
|
||||
CommonName: "example.com",
|
||||
Status: domain.DiscoveryStatusUnmanaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
discoveryRepo.Discovered[cert.ID] = cert
|
||||
|
||||
retrieved, err := svc.GetDiscovered(context.Background(), "dcert-1")
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got: %v", err)
|
||||
}
|
||||
|
||||
if retrieved.ID != "dcert-1" {
|
||||
t.Errorf("expected ID dcert-1, got %s", retrieved.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimDiscovered_Success(t *testing.T) {
|
||||
svc, discoveryRepo, certRepo, auditRepo := newDiscoveryTestService()
|
||||
|
||||
now := time.Now()
|
||||
discoveredCert := &domain.DiscoveredCertificate{
|
||||
ID: "dcert-1",
|
||||
CommonName: "example.com",
|
||||
FingerprintSHA256: "abc123",
|
||||
Status: domain.DiscoveryStatusUnmanaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
discoveryRepo.Discovered[discoveredCert.ID] = discoveredCert
|
||||
|
||||
managedCert := &domain.ManagedCertificate{
|
||||
ID: "mc-prod-1",
|
||||
CommonName: "example.com",
|
||||
Status: domain.CertificateStatusActive,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
certRepo.AddCert(managedCert)
|
||||
|
||||
err := svc.ClaimDiscovered(context.Background(), "dcert-1", "mc-prod-1")
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got: %v", err)
|
||||
}
|
||||
|
||||
// Verify status was updated
|
||||
updated := discoveryRepo.Discovered["dcert-1"]
|
||||
if updated.Status != domain.DiscoveryStatusManaged {
|
||||
t.Errorf("expected status Managed, got %s", updated.Status)
|
||||
}
|
||||
if updated.ManagedCertificateID != "mc-prod-1" {
|
||||
t.Errorf("expected managed cert ID mc-prod-1, got %s", updated.ManagedCertificateID)
|
||||
}
|
||||
|
||||
// Verify audit event was recorded
|
||||
if len(auditRepo.Events) == 0 {
|
||||
t.Error("expected audit event to be recorded")
|
||||
}
|
||||
foundClaimAudit := false
|
||||
for _, e := range auditRepo.Events {
|
||||
if e.Action == "discovery_cert_claimed" {
|
||||
foundClaimAudit = true
|
||||
}
|
||||
}
|
||||
if !foundClaimAudit {
|
||||
t.Error("expected discovery_cert_claimed audit event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimDiscovered_MissingManagedCertID(t *testing.T) {
|
||||
svc, discoveryRepo, _, _ := newDiscoveryTestService()
|
||||
|
||||
now := time.Now()
|
||||
cert := &domain.DiscoveredCertificate{
|
||||
ID: "dcert-1",
|
||||
CommonName: "example.com",
|
||||
Status: domain.DiscoveryStatusUnmanaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
discoveryRepo.Discovered[cert.ID] = cert
|
||||
|
||||
err := svc.ClaimDiscovered(context.Background(), "dcert-1", "")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty managed_certificate_id")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimDiscovered_ManagedCertNotFound(t *testing.T) {
|
||||
svc, discoveryRepo, _, _ := newDiscoveryTestService()
|
||||
|
||||
now := time.Now()
|
||||
cert := &domain.DiscoveredCertificate{
|
||||
ID: "dcert-1",
|
||||
CommonName: "example.com",
|
||||
Status: domain.DiscoveryStatusUnmanaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
discoveryRepo.Discovered[cert.ID] = cert
|
||||
|
||||
err := svc.ClaimDiscovered(context.Background(), "dcert-1", "nonexistent-cert")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nonexistent managed certificate")
|
||||
}
|
||||
if !errors.Is(err, err) { // just verify error occurred
|
||||
t.Errorf("expected 'not found' error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDismissDiscovered_Success(t *testing.T) {
|
||||
svc, discoveryRepo, _, auditRepo := newDiscoveryTestService()
|
||||
|
||||
now := time.Now()
|
||||
cert := &domain.DiscoveredCertificate{
|
||||
ID: "dcert-1",
|
||||
CommonName: "example.com",
|
||||
Status: domain.DiscoveryStatusUnmanaged,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
discoveryRepo.Discovered[cert.ID] = cert
|
||||
|
||||
err := svc.DismissDiscovered(context.Background(), "dcert-1")
|
||||
if err != nil {
|
||||
t.Fatalf("expected no error, got: %v", err)
|
||||
}
|
||||
|
||||
// Verify status was updated
|
||||
updated := discoveryRepo.Discovered["dcert-1"]
|
||||
if updated.Status != domain.DiscoveryStatusDismissed {
|
||||
t.Errorf("expected status Dismissed, got %s", updated.Status)
|
||||
}
|
||||
if updated.DismissedAt == nil {
|
||||
t.Error("expected DismissedAt to be set")
|
||||
}
|
||||
|
||||
// Verify audit event was recorded
|
||||
if len(auditRepo.Events) == 0 {
|
||||
t.Error("expected audit event to be recorded")
|
||||
}
|
||||
foundDismissAudit := false
|
||||
for _, e := range auditRepo.Events {
|
||||
if e.Action == "discovery_cert_dismissed" {
|
||||
foundDismissAudit = true
|
||||
}
|
||||
}
|
||||
if !foundDismissAudit {
|
||||
t.Error("expected discovery_cert_dismissed audit event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDismissDiscovered_NotFound(t *testing.T) {
|
||||
svc, discoveryRepo, _, _ := newDiscoveryTestService()
|
||||
|
||||
discoveryRepo.UpdateStatusErr = errNotFound
|
||||
err := svc.DismissDiscovered(context.Background(), "nonexistent")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nonexistent cert")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user