feat: M11b — ownership tracking, agent groups, interactive renewal approval

Ownership: owners/teams GUI pages, notification email resolution via
resolveRecipient (owner_id → owner.email lookup). Agent groups: dynamic
device grouping by OS/arch/IP CIDR/version with manual include/exclude
membership, migration 000004, full CRUD stack (domain → repo → service →
handler → frontend). Interactive approval: AwaitingApproval job state,
approve/reject API endpoints with reason tracking. Tests: 12 agent group
handler tests, 8 approve/reject job handler tests, integration tests
updated for 13-param RegisterHandlers. Docs updated across architecture,
concepts, and seed data.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Shankar
2026-03-20 21:02:35 -04:00
parent 1ef16984eb
commit e445cbef22
27 changed files with 1774 additions and 21 deletions
@@ -0,0 +1,324 @@
package handler
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/shankar0123/certctl/internal/domain"
)
// MockAgentGroupService is a mock implementation of AgentGroupService interface.
type MockAgentGroupService struct {
ListAgentGroupsFn func(page, perPage int) ([]domain.AgentGroup, int64, error)
GetAgentGroupFn func(id string) (*domain.AgentGroup, error)
CreateAgentGroupFn func(group domain.AgentGroup) (*domain.AgentGroup, error)
UpdateAgentGroupFn func(id string, group domain.AgentGroup) (*domain.AgentGroup, error)
DeleteAgentGroupFn func(id string) error
ListMembersFn func(id string) ([]domain.Agent, int64, error)
}
func (m *MockAgentGroupService) ListAgentGroups(page, perPage int) ([]domain.AgentGroup, int64, error) {
if m.ListAgentGroupsFn != nil {
return m.ListAgentGroupsFn(page, perPage)
}
return []domain.AgentGroup{}, 0, nil
}
func (m *MockAgentGroupService) GetAgentGroup(id string) (*domain.AgentGroup, error) {
if m.GetAgentGroupFn != nil {
return m.GetAgentGroupFn(id)
}
return nil, fmt.Errorf("not found")
}
func (m *MockAgentGroupService) CreateAgentGroup(group domain.AgentGroup) (*domain.AgentGroup, error) {
if m.CreateAgentGroupFn != nil {
return m.CreateAgentGroupFn(group)
}
return &group, nil
}
func (m *MockAgentGroupService) UpdateAgentGroup(id string, group domain.AgentGroup) (*domain.AgentGroup, error) {
if m.UpdateAgentGroupFn != nil {
return m.UpdateAgentGroupFn(id, group)
}
group.ID = id
return &group, nil
}
func (m *MockAgentGroupService) DeleteAgentGroup(id string) error {
if m.DeleteAgentGroupFn != nil {
return m.DeleteAgentGroupFn(id)
}
return nil
}
func (m *MockAgentGroupService) ListMembers(id string) ([]domain.Agent, int64, error) {
if m.ListMembersFn != nil {
return m.ListMembersFn(id)
}
return []domain.Agent{}, 0, nil
}
func TestListAgentGroups_Success(t *testing.T) {
group := domain.AgentGroup{
ID: "ag-linux",
Name: "Linux Agents",
Description: "All Linux-based agents",
MatchOS: "linux",
Enabled: true,
}
mock := &MockAgentGroupService{
ListAgentGroupsFn: func(page, perPage int) ([]domain.AgentGroup, int64, error) {
return []domain.AgentGroup{group}, 1, nil
},
}
h := NewAgentGroupHandler(mock)
req := httptest.NewRequest(http.MethodGet, "/api/v1/agent-groups", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.ListAgentGroups(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
var resp PagedResponse
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if resp.Total != 1 {
t.Errorf("expected total 1, got %d", resp.Total)
}
}
func TestListAgentGroups_ServiceError(t *testing.T) {
mock := &MockAgentGroupService{
ListAgentGroupsFn: func(page, perPage int) ([]domain.AgentGroup, int64, error) {
return nil, 0, ErrMockServiceFailed
},
}
h := NewAgentGroupHandler(mock)
req := httptest.NewRequest(http.MethodGet, "/api/v1/agent-groups", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.ListAgentGroups(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("expected status 500, got %d", w.Code)
}
}
func TestListAgentGroups_MethodNotAllowed(t *testing.T) {
h := NewAgentGroupHandler(&MockAgentGroupService{})
req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-groups", nil)
w := httptest.NewRecorder()
h.ListAgentGroups(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Fatalf("expected status 405, got %d", w.Code)
}
}
func TestGetAgentGroup_Success(t *testing.T) {
mock := &MockAgentGroupService{
GetAgentGroupFn: func(id string) (*domain.AgentGroup, error) {
return &domain.AgentGroup{
ID: id,
Name: "Linux Agents",
MatchOS: "linux",
Enabled: true,
}, nil
},
}
h := NewAgentGroupHandler(mock)
req := httptest.NewRequest(http.MethodGet, "/api/v1/agent-groups/ag-linux", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.GetAgentGroup(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
}
func TestGetAgentGroup_NotFound(t *testing.T) {
mock := &MockAgentGroupService{
GetAgentGroupFn: func(id string) (*domain.AgentGroup, error) {
return nil, ErrMockNotFound
},
}
h := NewAgentGroupHandler(mock)
req := httptest.NewRequest(http.MethodGet, "/api/v1/agent-groups/ag-ghost", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.GetAgentGroup(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("expected status 404, got %d", w.Code)
}
}
func TestCreateAgentGroup_Success(t *testing.T) {
mock := &MockAgentGroupService{
CreateAgentGroupFn: func(group domain.AgentGroup) (*domain.AgentGroup, error) {
group.ID = "ag-new"
return &group, nil
},
}
body := map[string]interface{}{
"name": "Ubuntu Agents",
"match_os": "linux",
"enabled": true,
}
bodyBytes, _ := json.Marshal(body)
h := NewAgentGroupHandler(mock)
req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-groups", bytes.NewReader(bodyBytes))
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.CreateAgentGroup(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("expected status 201, got %d. Body: %s", w.Code, w.Body.String())
}
}
func TestCreateAgentGroup_MissingName(t *testing.T) {
body := map[string]interface{}{
"match_os": "linux",
}
bodyBytes, _ := json.Marshal(body)
h := NewAgentGroupHandler(&MockAgentGroupService{})
req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-groups", bytes.NewReader(bodyBytes))
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.CreateAgentGroup(w, req)
// Handler may or may not validate name — service does. Either 400 or 500 acceptable.
if w.Code == http.StatusCreated || w.Code == http.StatusOK {
t.Fatalf("expected error for missing name, got %d", w.Code)
}
}
func TestCreateAgentGroup_InvalidJSON(t *testing.T) {
h := NewAgentGroupHandler(&MockAgentGroupService{})
req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-groups", bytes.NewReader([]byte("not json")))
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.CreateAgentGroup(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected status 400, got %d", w.Code)
}
}
func TestDeleteAgentGroup_Success(t *testing.T) {
var deletedID string
mock := &MockAgentGroupService{
DeleteAgentGroupFn: func(id string) error {
deletedID = id
return nil
},
}
h := NewAgentGroupHandler(mock)
req := httptest.NewRequest(http.MethodDelete, "/api/v1/agent-groups/ag-linux", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.DeleteAgentGroup(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
if deletedID != "ag-linux" {
t.Errorf("expected deleted ID 'ag-linux', got '%s'", deletedID)
}
}
func TestDeleteAgentGroup_ServiceError(t *testing.T) {
mock := &MockAgentGroupService{
DeleteAgentGroupFn: func(id string) error {
return ErrMockServiceFailed
},
}
h := NewAgentGroupHandler(mock)
req := httptest.NewRequest(http.MethodDelete, "/api/v1/agent-groups/ag-linux", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.DeleteAgentGroup(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("expected status 500, got %d", w.Code)
}
}
func TestListAgentGroupMembers_Success(t *testing.T) {
mock := &MockAgentGroupService{
ListMembersFn: func(id string) ([]domain.Agent, int64, error) {
return []domain.Agent{
{ID: "agent-001", Name: "web-1", Hostname: "web-1.prod"},
}, 1, nil
},
}
h := NewAgentGroupHandler(mock)
req := httptest.NewRequest(http.MethodGet, "/api/v1/agent-groups/ag-linux/members", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.ListAgentGroupMembers(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
var resp PagedResponse
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if resp.Total != 1 {
t.Errorf("expected total 1, got %d", resp.Total)
}
}
func TestListAgentGroupMembers_ServiceError(t *testing.T) {
mock := &MockAgentGroupService{
ListMembersFn: func(id string) ([]domain.Agent, int64, error) {
return nil, 0, ErrMockServiceFailed
},
}
h := NewAgentGroupHandler(mock)
req := httptest.NewRequest(http.MethodGet, "/api/v1/agent-groups/ag-linux/members", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.ListAgentGroupMembers(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("expected status 500, got %d", w.Code)
}
}
+234
View File
@@ -0,0 +1,234 @@
package handler
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"github.com/shankar0123/certctl/internal/api/middleware"
"github.com/shankar0123/certctl/internal/domain"
)
// AgentGroupService defines the service interface for agent group operations.
type AgentGroupService interface {
ListAgentGroups(page, perPage int) ([]domain.AgentGroup, int64, error)
GetAgentGroup(id string) (*domain.AgentGroup, error)
CreateAgentGroup(group domain.AgentGroup) (*domain.AgentGroup, error)
UpdateAgentGroup(id string, group domain.AgentGroup) (*domain.AgentGroup, error)
DeleteAgentGroup(id string) error
ListMembers(id string) ([]domain.Agent, int64, error)
}
// AgentGroupHandler handles HTTP requests for agent group operations.
type AgentGroupHandler struct {
svc AgentGroupService
}
// NewAgentGroupHandler creates a new AgentGroupHandler with a service dependency.
func NewAgentGroupHandler(svc AgentGroupService) AgentGroupHandler {
return AgentGroupHandler{svc: svc}
}
// ListAgentGroups lists all agent groups.
// GET /api/v1/agent-groups?page=1&per_page=50
func (h AgentGroupHandler) ListAgentGroups(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
return
}
requestID := middleware.GetRequestID(r.Context())
page := 1
perPage := 50
query := r.URL.Query()
if p := query.Get("page"); p != "" {
if parsed, err := strconv.Atoi(p); err == nil && parsed > 0 {
page = parsed
}
}
if pp := query.Get("per_page"); pp != "" {
if parsed, err := strconv.Atoi(pp); err == nil && parsed > 0 && parsed <= 500 {
perPage = parsed
}
}
groups, total, err := h.svc.ListAgentGroups(page, perPage)
if err != nil {
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to list agent groups", requestID)
return
}
response := PagedResponse{
Data: groups,
Total: total,
Page: page,
PerPage: perPage,
}
JSON(w, http.StatusOK, response)
}
// GetAgentGroup retrieves a single agent group by ID.
// GET /api/v1/agent-groups/{id}
func (h AgentGroupHandler) GetAgentGroup(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
return
}
requestID := middleware.GetRequestID(r.Context())
id := strings.TrimPrefix(r.URL.Path, "/api/v1/agent-groups/")
if id == "" || strings.Contains(id, "/") {
ErrorWithRequestID(w, http.StatusBadRequest, "Agent group ID is required", requestID)
return
}
group, err := h.svc.GetAgentGroup(id)
if err != nil {
ErrorWithRequestID(w, http.StatusNotFound, "Agent group not found", requestID)
return
}
JSON(w, http.StatusOK, group)
}
// CreateAgentGroup creates a new agent group.
// POST /api/v1/agent-groups
func (h AgentGroupHandler) CreateAgentGroup(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
return
}
requestID := middleware.GetRequestID(r.Context())
var group domain.AgentGroup
if err := json.NewDecoder(r.Body).Decode(&group); err != nil {
ErrorWithRequestID(w, http.StatusBadRequest, "Invalid request body", requestID)
return
}
if err := ValidateRequired("name", group.Name); err != nil {
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
return
}
if err := ValidateStringLength("name", group.Name, 255); err != nil {
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
return
}
created, err := h.svc.CreateAgentGroup(group)
if err != nil {
if strings.Contains(err.Error(), "invalid") || strings.Contains(err.Error(), "required") {
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
return
}
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to create agent group", requestID)
return
}
JSON(w, http.StatusCreated, created)
}
// UpdateAgentGroup updates an existing agent group.
// PUT /api/v1/agent-groups/{id}
func (h AgentGroupHandler) UpdateAgentGroup(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
return
}
requestID := middleware.GetRequestID(r.Context())
id := strings.TrimPrefix(r.URL.Path, "/api/v1/agent-groups/")
parts := strings.Split(id, "/")
if len(parts) == 0 || parts[0] == "" {
ErrorWithRequestID(w, http.StatusBadRequest, "Agent group ID is required", requestID)
return
}
id = parts[0]
var group domain.AgentGroup
if err := json.NewDecoder(r.Body).Decode(&group); err != nil {
ErrorWithRequestID(w, http.StatusBadRequest, "Invalid request body", requestID)
return
}
updated, err := h.svc.UpdateAgentGroup(id, group)
if err != nil {
if strings.Contains(err.Error(), "not found") {
ErrorWithRequestID(w, http.StatusNotFound, "Agent group not found", requestID)
return
}
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to update agent group", requestID)
return
}
JSON(w, http.StatusOK, updated)
}
// DeleteAgentGroup deletes an agent group.
// DELETE /api/v1/agent-groups/{id}
func (h AgentGroupHandler) DeleteAgentGroup(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
return
}
requestID := middleware.GetRequestID(r.Context())
id := strings.TrimPrefix(r.URL.Path, "/api/v1/agent-groups/")
if id == "" || strings.Contains(id, "/") {
ErrorWithRequestID(w, http.StatusBadRequest, "Agent group ID is required", requestID)
return
}
if err := h.svc.DeleteAgentGroup(id); err != nil {
if strings.Contains(err.Error(), "not found") {
ErrorWithRequestID(w, http.StatusNotFound, "Agent group not found", requestID)
return
}
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to delete agent group", requestID)
return
}
w.WriteHeader(http.StatusNoContent)
}
// ListAgentGroupMembers lists agents in a group.
// GET /api/v1/agent-groups/{id}/members
func (h AgentGroupHandler) ListAgentGroupMembers(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
return
}
requestID := middleware.GetRequestID(r.Context())
// Parse ID from: /api/v1/agent-groups/{id}/members
path := strings.TrimPrefix(r.URL.Path, "/api/v1/agent-groups/")
parts := strings.Split(path, "/")
if len(parts) < 2 || parts[0] == "" {
ErrorWithRequestID(w, http.StatusBadRequest, "Agent group ID is required", requestID)
return
}
id := parts[0]
members, total, err := h.svc.ListMembers(id)
if err != nil {
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to list group members", requestID)
return
}
response := PagedResponse{
Data: members,
Total: total,
Page: 1,
PerPage: int(total),
}
JSON(w, http.StatusOK, response)
}
+182 -3
View File
@@ -2,8 +2,10 @@ package handler
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
@@ -12,9 +14,11 @@ import (
// MockJobService is a mock implementation of JobService interface.
type MockJobService struct {
ListJobsFn func(status, jobType string, page, perPage int) ([]domain.Job, int64, error)
GetJobFn func(id string) (*domain.Job, error)
CancelJobFn func(id string) error
ListJobsFn func(status, jobType string, page, perPage int) ([]domain.Job, int64, error)
GetJobFn func(id string) (*domain.Job, error)
CancelJobFn func(id string) error
ApproveJobFn func(id string) error
RejectJobFn func(id string, reason string) error
}
func (m *MockJobService) ListJobs(status, jobType string, page, perPage int) ([]domain.Job, int64, error) {
@@ -38,6 +42,20 @@ func (m *MockJobService) CancelJob(id string) error {
return nil
}
func (m *MockJobService) ApproveJob(id string) error {
if m.ApproveJobFn != nil {
return m.ApproveJobFn(id)
}
return nil
}
func (m *MockJobService) RejectJob(id string, reason string) error {
if m.RejectJobFn != nil {
return m.RejectJobFn(id, reason)
}
return nil
}
func TestListJobs_Success(t *testing.T) {
now := time.Now()
job1 := domain.Job{
@@ -325,3 +343,164 @@ func TestCancelJob_EmptyID(t *testing.T) {
t.Fatalf("expected status 400, got %d", w.Code)
}
}
func TestApproveJob_Success(t *testing.T) {
var approvedID string
mock := &MockJobService{
ApproveJobFn: func(id string) error {
approvedID = id
return nil
},
}
h := NewJobHandler(mock)
req := httptest.NewRequest(http.MethodPost, "/api/v1/jobs/job-001/approve", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.ApproveJob(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
if approvedID != "job-001" {
t.Errorf("expected approved ID 'job-001', got '%s'", approvedID)
}
var resp map[string]string
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if resp["status"] != "job_approved" {
t.Errorf("expected status 'job_approved', got '%s'", resp["status"])
}
}
func TestApproveJob_NotFound(t *testing.T) {
mock := &MockJobService{
ApproveJobFn: func(id string) error {
return fmt.Errorf("job not found: no rows")
},
}
h := NewJobHandler(mock)
req := httptest.NewRequest(http.MethodPost, "/api/v1/jobs/job-ghost/approve", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.ApproveJob(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("expected status 404, got %d", w.Code)
}
}
func TestApproveJob_BadStatus(t *testing.T) {
mock := &MockJobService{
ApproveJobFn: func(id string) error {
return fmt.Errorf("cannot approve job with status Running")
},
}
h := NewJobHandler(mock)
req := httptest.NewRequest(http.MethodPost, "/api/v1/jobs/job-001/approve", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.ApproveJob(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected status 400, got %d", w.Code)
}
}
func TestApproveJob_MethodNotAllowed(t *testing.T) {
h := NewJobHandler(&MockJobService{})
req := httptest.NewRequest(http.MethodGet, "/api/v1/jobs/job-001/approve", nil)
w := httptest.NewRecorder()
h.ApproveJob(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Fatalf("expected status 405, got %d", w.Code)
}
}
func TestRejectJob_Success(t *testing.T) {
var rejectedID, capturedReason string
mock := &MockJobService{
RejectJobFn: func(id string, reason string) error {
rejectedID = id
capturedReason = reason
return nil
},
}
body := `{"reason":"Certificate no longer needed"}`
h := NewJobHandler(mock)
req := httptest.NewRequest(http.MethodPost, "/api/v1/jobs/job-002/reject", strings.NewReader(body))
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.RejectJob(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
if rejectedID != "job-002" {
t.Errorf("expected rejected ID 'job-002', got '%s'", rejectedID)
}
if capturedReason != "Certificate no longer needed" {
t.Errorf("expected reason 'Certificate no longer needed', got '%s'", capturedReason)
}
}
func TestRejectJob_NoReason(t *testing.T) {
mock := &MockJobService{
RejectJobFn: func(id string, reason string) error {
return nil
},
}
h := NewJobHandler(mock)
req := httptest.NewRequest(http.MethodPost, "/api/v1/jobs/job-002/reject", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.RejectJob(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d", w.Code)
}
}
func TestRejectJob_NotFound(t *testing.T) {
mock := &MockJobService{
RejectJobFn: func(id string, reason string) error {
return fmt.Errorf("job not found: no rows")
},
}
h := NewJobHandler(mock)
req := httptest.NewRequest(http.MethodPost, "/api/v1/jobs/job-ghost/reject", nil)
req = req.WithContext(contextWithRequestID())
w := httptest.NewRecorder()
h.RejectJob(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("expected status 404, got %d", w.Code)
}
}
func TestRejectJob_MethodNotAllowed(t *testing.T) {
h := NewJobHandler(&MockJobService{})
req := httptest.NewRequest(http.MethodGet, "/api/v1/jobs/job-001/reject", nil)
w := httptest.NewRecorder()
h.RejectJob(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Fatalf("expected status 405, got %d", w.Code)
}
}
+78
View File
@@ -1,6 +1,7 @@
package handler
import (
"encoding/json"
"net/http"
"strconv"
"strings"
@@ -14,6 +15,8 @@ type JobService interface {
ListJobs(status, jobType string, page, perPage int) ([]domain.Job, int64, error)
GetJob(id string) (*domain.Job, error)
CancelJob(id string) error
ApproveJob(id string) error
RejectJob(id string, reason string) error
}
// JobHandler handles HTTP requests for job operations.
@@ -126,3 +129,78 @@ func (h JobHandler) CancelJob(w http.ResponseWriter, r *http.Request) {
JSON(w, http.StatusOK, response)
}
// ApproveJob approves a renewal job awaiting approval.
// POST /api/v1/jobs/{id}/approve
func (h JobHandler) ApproveJob(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
return
}
requestID := middleware.GetRequestID(r.Context())
path := strings.TrimPrefix(r.URL.Path, "/api/v1/jobs/")
parts := strings.Split(path, "/")
if len(parts) < 2 || parts[0] == "" {
ErrorWithRequestID(w, http.StatusBadRequest, "Job ID is required", requestID)
return
}
jobID := parts[0]
if err := h.svc.ApproveJob(jobID); err != nil {
if strings.Contains(err.Error(), "not found") {
ErrorWithRequestID(w, http.StatusNotFound, "Job not found", requestID)
return
}
if strings.Contains(err.Error(), "cannot approve") {
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
return
}
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to approve job", requestID)
return
}
JSON(w, http.StatusOK, map[string]string{"status": "job_approved"})
}
// RejectJob rejects a renewal job awaiting approval.
// POST /api/v1/jobs/{id}/reject
func (h JobHandler) RejectJob(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
Error(w, http.StatusMethodNotAllowed, "Method not allowed")
return
}
requestID := middleware.GetRequestID(r.Context())
path := strings.TrimPrefix(r.URL.Path, "/api/v1/jobs/")
parts := strings.Split(path, "/")
if len(parts) < 2 || parts[0] == "" {
ErrorWithRequestID(w, http.StatusBadRequest, "Job ID is required", requestID)
return
}
jobID := parts[0]
var body struct {
Reason string `json:"reason"`
}
if r.Body != nil {
json.NewDecoder(r.Body).Decode(&body)
}
if err := h.svc.RejectJob(jobID, body.Reason); err != nil {
if strings.Contains(err.Error(), "not found") {
ErrorWithRequestID(w, http.StatusNotFound, "Job not found", requestID)
return
}
if strings.Contains(err.Error(), "cannot reject") {
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
return
}
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to reject job", requestID)
return
}
JSON(w, http.StatusOK, map[string]string{"status": "job_rejected"})
}
+11
View File
@@ -54,6 +54,7 @@ func (r *Router) RegisterHandlers(
profiles handler.ProfileHandler,
teams handler.TeamHandler,
owners handler.OwnerHandler,
agentGroups handler.AgentGroupHandler,
audit handler.AuditHandler,
notifications handler.NotificationHandler,
health handler.HealthHandler,
@@ -117,6 +118,8 @@ func (r *Router) RegisterHandlers(
r.Register("GET /api/v1/jobs", http.HandlerFunc(jobs.ListJobs))
r.Register("GET /api/v1/jobs/{id}", http.HandlerFunc(jobs.GetJob))
r.Register("POST /api/v1/jobs/{id}/cancel", http.HandlerFunc(jobs.CancelJob))
r.Register("POST /api/v1/jobs/{id}/approve", http.HandlerFunc(jobs.ApproveJob))
r.Register("POST /api/v1/jobs/{id}/reject", http.HandlerFunc(jobs.RejectJob))
// Policies routes: /api/v1/policies
r.Register("GET /api/v1/policies", http.HandlerFunc(policies.ListPolicies))
@@ -147,6 +150,14 @@ func (r *Router) RegisterHandlers(
r.Register("PUT /api/v1/owners/{id}", http.HandlerFunc(owners.UpdateOwner))
r.Register("DELETE /api/v1/owners/{id}", http.HandlerFunc(owners.DeleteOwner))
// Agent Groups routes: /api/v1/agent-groups
r.Register("GET /api/v1/agent-groups", http.HandlerFunc(agentGroups.ListAgentGroups))
r.Register("POST /api/v1/agent-groups", http.HandlerFunc(agentGroups.CreateAgentGroup))
r.Register("GET /api/v1/agent-groups/{id}", http.HandlerFunc(agentGroups.GetAgentGroup))
r.Register("PUT /api/v1/agent-groups/{id}", http.HandlerFunc(agentGroups.UpdateAgentGroup))
r.Register("DELETE /api/v1/agent-groups/{id}", http.HandlerFunc(agentGroups.DeleteAgentGroup))
r.Register("GET /api/v1/agent-groups/{id}/members", http.HandlerFunc(agentGroups.ListAgentGroupMembers))
// Audit routes: /api/v1/audit
r.Register("GET /api/v1/audit", http.HandlerFunc(audit.ListAuditEvents))
r.Register("GET /api/v1/audit/{id}", http.HandlerFunc(audit.GetAuditEvent))
+53
View File
@@ -0,0 +1,53 @@
package domain
import (
"time"
)
// AgentGroup defines a logical grouping of agents based on metadata criteria
// and/or manual membership. Used for policy scoping and fleet management.
type AgentGroup struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
MatchOS string `json:"match_os"`
MatchArchitecture string `json:"match_architecture"`
MatchIPCIDR string `json:"match_ip_cidr"`
MatchVersion string `json:"match_version"`
Enabled bool `json:"enabled"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// AgentGroupMembership represents an explicit (manual) agent-to-group mapping.
type AgentGroupMembership struct {
AgentGroupID string `json:"agent_group_id"`
AgentID string `json:"agent_id"`
MembershipType string `json:"membership_type"` // "include" or "exclude"
CreatedAt time.Time `json:"created_at"`
}
// HasDynamicCriteria returns true if this group defines at least one metadata match rule.
func (g *AgentGroup) HasDynamicCriteria() bool {
return g.MatchOS != "" || g.MatchArchitecture != "" || g.MatchIPCIDR != "" || g.MatchVersion != ""
}
// MatchesAgent checks whether an agent's metadata matches all non-empty criteria.
// Empty criteria fields are treated as wildcards (match anything).
func (g *AgentGroup) MatchesAgent(agent *Agent) bool {
if g.MatchOS != "" && agent.OS != g.MatchOS {
return false
}
if g.MatchArchitecture != "" && agent.Architecture != g.MatchArchitecture {
return false
}
if g.MatchVersion != "" && agent.Version != g.MatchVersion {
return false
}
// IP CIDR matching is more complex — for now, do exact match on the field.
// Full CIDR parsing (net.ParseCIDR + Contains) deferred to when we have real use cases.
if g.MatchIPCIDR != "" && agent.IPAddress != g.MatchIPCIDR {
return false
}
return true
}
+7 -6
View File
@@ -35,12 +35,13 @@ const (
type JobStatus string
const (
JobStatusPending JobStatus = "Pending"
JobStatusAwaitingCSR JobStatus = "AwaitingCSR"
JobStatusRunning JobStatus = "Running"
JobStatusCompleted JobStatus = "Completed"
JobStatusFailed JobStatus = "Failed"
JobStatusCancelled JobStatus = "Cancelled"
JobStatusPending JobStatus = "Pending"
JobStatusAwaitingCSR JobStatus = "AwaitingCSR"
JobStatusAwaitingApproval JobStatus = "AwaitingApproval"
JobStatusRunning JobStatus = "Running"
JobStatusCompleted JobStatus = "Completed"
JobStatusFailed JobStatus = "Failed"
JobStatusCancelled JobStatus = "Cancelled"
)
// DeploymentJob represents a job that deploys a certificate to a target via an agent.
+29
View File
@@ -68,6 +68,7 @@ func TestCertificateLifecycle(t *testing.T) {
profileHandler := handler.NewProfileHandler(&mockProfileService{})
teamHandler := handler.NewTeamHandler(&mockTeamService{})
ownerHandler := handler.NewOwnerHandler(&mockOwnerService{})
agentGroupHandler := handler.NewAgentGroupHandler(&mockAgentGroupService{})
auditHandler := handler.NewAuditHandler(auditService)
notificationHandler := handler.NewNotificationHandler(notificationService)
healthHandler := handler.NewHealthHandler("none")
@@ -84,6 +85,7 @@ func TestCertificateLifecycle(t *testing.T) {
profileHandler,
teamHandler,
ownerHandler,
agentGroupHandler,
auditHandler,
notificationHandler,
healthHandler,
@@ -1019,3 +1021,30 @@ func (m *mockProfileService) UpdateProfile(id string, profile domain.Certificate
func (m *mockProfileService) DeleteProfile(id string) error {
return nil
}
type mockAgentGroupService struct{}
func (m *mockAgentGroupService) ListAgentGroups(page, perPage int) ([]domain.AgentGroup, int64, error) {
return []domain.AgentGroup{}, 0, nil
}
func (m *mockAgentGroupService) GetAgentGroup(id string) (*domain.AgentGroup, error) {
return nil, fmt.Errorf("agent group not found")
}
func (m *mockAgentGroupService) CreateAgentGroup(group domain.AgentGroup) (*domain.AgentGroup, error) {
return &group, nil
}
func (m *mockAgentGroupService) UpdateAgentGroup(id string, group domain.AgentGroup) (*domain.AgentGroup, error) {
group.ID = id
return &group, nil
}
func (m *mockAgentGroupService) DeleteAgentGroup(id string) error {
return nil
}
func (m *mockAgentGroupService) ListMembers(id string) ([]domain.Agent, int64, error) {
return []domain.Agent{}, 0, nil
}
+2
View File
@@ -58,6 +58,7 @@ func setupTestServer(t *testing.T) (*httptest.Server, *mockCertificateRepository
profileHandler := handler.NewProfileHandler(&mockProfileService{})
teamHandler := handler.NewTeamHandler(&mockTeamService{})
ownerHandler := handler.NewOwnerHandler(&mockOwnerService{})
agentGroupHandler := handler.NewAgentGroupHandler(&mockAgentGroupService{})
auditHandler := handler.NewAuditHandler(auditService)
notificationHandler := handler.NewNotificationHandler(notificationService)
healthHandler := handler.NewHealthHandler("none")
@@ -73,6 +74,7 @@ func setupTestServer(t *testing.T) (*httptest.Server, *mockCertificateRepository
profileHandler,
teamHandler,
ownerHandler,
agentGroupHandler,
auditHandler,
notificationHandler,
healthHandler,
+20
View File
@@ -169,6 +169,26 @@ type CertificateProfileRepository interface {
Delete(ctx context.Context, id string) error
}
// AgentGroupRepository defines operations for managing agent groups.
type AgentGroupRepository interface {
// List returns all agent groups.
List(ctx context.Context) ([]*domain.AgentGroup, error)
// Get retrieves an agent group by ID.
Get(ctx context.Context, id string) (*domain.AgentGroup, error)
// Create stores a new agent group.
Create(ctx context.Context, group *domain.AgentGroup) error
// Update modifies an existing agent group.
Update(ctx context.Context, group *domain.AgentGroup) error
// Delete removes an agent group.
Delete(ctx context.Context, id string) error
// ListMembers returns agents in a group (both dynamic matches and manual includes).
ListMembers(ctx context.Context, groupID string) ([]*domain.Agent, error)
// AddMember adds a manual membership.
AddMember(ctx context.Context, groupID, agentID, membershipType string) error
// RemoveMember removes a manual membership.
RemoveMember(ctx context.Context, groupID, agentID string) error
}
// OwnerRepository defines operations for managing certificate owners.
type OwnerRepository interface {
// List returns all owners.
+168
View File
@@ -0,0 +1,168 @@
package postgres
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/shankar0123/certctl/internal/domain"
)
// AgentGroupRepository implements agent group CRUD with PostgreSQL.
type AgentGroupRepository struct {
db *sql.DB
}
// NewAgentGroupRepository creates a new PostgreSQL-backed agent group repository.
func NewAgentGroupRepository(db *sql.DB) *AgentGroupRepository {
return &AgentGroupRepository{db: db}
}
// List returns all agent groups.
func (r *AgentGroupRepository) List(ctx context.Context) ([]*domain.AgentGroup, error) {
rows, err := r.db.QueryContext(ctx,
`SELECT id, name, description, match_os, match_architecture, match_ip_cidr, match_version, enabled, created_at, updated_at
FROM agent_groups ORDER BY name`)
if err != nil {
return nil, fmt.Errorf("failed to query agent groups: %w", err)
}
defer rows.Close()
var groups []*domain.AgentGroup
for rows.Next() {
g, err := scanAgentGroup(rows)
if err != nil {
return nil, err
}
groups = append(groups, g)
}
return groups, rows.Err()
}
// Get retrieves an agent group by ID.
func (r *AgentGroupRepository) Get(ctx context.Context, id string) (*domain.AgentGroup, error) {
row := r.db.QueryRowContext(ctx,
`SELECT id, name, description, match_os, match_architecture, match_ip_cidr, match_version, enabled, created_at, updated_at
FROM agent_groups WHERE id = $1`, id)
g := &domain.AgentGroup{}
err := row.Scan(&g.ID, &g.Name, &g.Description, &g.MatchOS, &g.MatchArchitecture,
&g.MatchIPCIDR, &g.MatchVersion, &g.Enabled, &g.CreatedAt, &g.UpdatedAt)
if err == sql.ErrNoRows {
return nil, fmt.Errorf("agent group not found: %s", id)
}
if err != nil {
return nil, fmt.Errorf("failed to get agent group: %w", err)
}
return g, nil
}
// Create stores a new agent group.
func (r *AgentGroupRepository) Create(ctx context.Context, group *domain.AgentGroup) error {
_, err := r.db.ExecContext(ctx,
`INSERT INTO agent_groups (id, name, description, match_os, match_architecture, match_ip_cidr, match_version, enabled, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
group.ID, group.Name, group.Description, group.MatchOS, group.MatchArchitecture,
group.MatchIPCIDR, group.MatchVersion, group.Enabled, group.CreatedAt, group.UpdatedAt)
if err != nil {
return fmt.Errorf("failed to create agent group: %w", err)
}
return nil
}
// Update modifies an existing agent group.
func (r *AgentGroupRepository) Update(ctx context.Context, group *domain.AgentGroup) error {
group.UpdatedAt = time.Now()
result, err := r.db.ExecContext(ctx,
`UPDATE agent_groups SET name=$1, description=$2, match_os=$3, match_architecture=$4, match_ip_cidr=$5, match_version=$6, enabled=$7, updated_at=$8
WHERE id=$9`,
group.Name, group.Description, group.MatchOS, group.MatchArchitecture,
group.MatchIPCIDR, group.MatchVersion, group.Enabled, group.UpdatedAt, group.ID)
if err != nil {
return fmt.Errorf("failed to update agent group: %w", err)
}
rows, _ := result.RowsAffected()
if rows == 0 {
return fmt.Errorf("agent group not found: %s", group.ID)
}
return nil
}
// Delete removes an agent group.
func (r *AgentGroupRepository) Delete(ctx context.Context, id string) error {
result, err := r.db.ExecContext(ctx, `DELETE FROM agent_groups WHERE id = $1`, id)
if err != nil {
return fmt.Errorf("failed to delete agent group: %w", err)
}
rows, _ := result.RowsAffected()
if rows == 0 {
return fmt.Errorf("agent group not found: %s", id)
}
return nil
}
// ListMembers returns agents that belong to a group (manual includes only for now).
func (r *AgentGroupRepository) ListMembers(ctx context.Context, groupID string) ([]*domain.Agent, error) {
rows, err := r.db.QueryContext(ctx,
`SELECT a.id, a.name, a.hostname, a.status, a.last_heartbeat_at, a.registered_at, a.api_key_hash, a.os, a.architecture, a.ip_address, a.version
FROM agents a
INNER JOIN agent_group_members m ON a.id = m.agent_id
WHERE m.agent_group_id = $1 AND m.membership_type = 'include'
ORDER BY a.name`, groupID)
if err != nil {
return nil, fmt.Errorf("failed to list group members: %w", err)
}
defer rows.Close()
var agents []*domain.Agent
for rows.Next() {
a := &domain.Agent{}
var lastHeartbeat sql.NullTime
err := rows.Scan(&a.ID, &a.Name, &a.Hostname, &a.Status, &lastHeartbeat,
&a.RegisteredAt, &a.APIKeyHash, &a.OS, &a.Architecture, &a.IPAddress, &a.Version)
if err != nil {
return nil, fmt.Errorf("failed to scan agent: %w", err)
}
if lastHeartbeat.Valid {
a.LastHeartbeatAt = &lastHeartbeat.Time
}
agents = append(agents, a)
}
return agents, rows.Err()
}
// AddMember adds a manual membership.
func (r *AgentGroupRepository) AddMember(ctx context.Context, groupID, agentID, membershipType string) error {
_, err := r.db.ExecContext(ctx,
`INSERT INTO agent_group_members (agent_group_id, agent_id, membership_type, created_at)
VALUES ($1, $2, $3, $4)
ON CONFLICT (agent_group_id, agent_id) DO UPDATE SET membership_type = $3`,
groupID, agentID, membershipType, time.Now())
if err != nil {
return fmt.Errorf("failed to add group member: %w", err)
}
return nil
}
// RemoveMember removes a manual membership.
func (r *AgentGroupRepository) RemoveMember(ctx context.Context, groupID, agentID string) error {
_, err := r.db.ExecContext(ctx,
`DELETE FROM agent_group_members WHERE agent_group_id = $1 AND agent_id = $2`,
groupID, agentID)
if err != nil {
return fmt.Errorf("failed to remove group member: %w", err)
}
return nil
}
// scanAgentGroup scans a single agent group row.
func scanAgentGroup(rows *sql.Rows) (*domain.AgentGroup, error) {
g := &domain.AgentGroup{}
err := rows.Scan(&g.ID, &g.Name, &g.Description, &g.MatchOS, &g.MatchArchitecture,
&g.MatchIPCIDR, &g.MatchVersion, &g.Enabled, &g.CreatedAt, &g.UpdatedAt)
if err != nil {
return nil, fmt.Errorf("failed to scan agent group: %w", err)
}
return g, nil
}
+154
View File
@@ -0,0 +1,154 @@
package service
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/shankar0123/certctl/internal/domain"
"github.com/shankar0123/certctl/internal/repository"
)
// AgentGroupService provides business logic for agent group management.
type AgentGroupService struct {
groupRepo repository.AgentGroupRepository
auditService *AuditService
}
// NewAgentGroupService creates a new agent group service.
func NewAgentGroupService(
groupRepo repository.AgentGroupRepository,
auditService *AuditService,
) *AgentGroupService {
return &AgentGroupService{
groupRepo: groupRepo,
auditService: auditService,
}
}
// ListAgentGroups returns paginated agent groups (handler interface method).
func (s *AgentGroupService) ListAgentGroups(page, perPage int) ([]domain.AgentGroup, int64, error) {
if page < 1 {
page = 1
}
if perPage < 1 {
perPage = 50
}
groups, err := s.groupRepo.List(context.Background())
if err != nil {
return nil, 0, fmt.Errorf("failed to list agent groups: %w", err)
}
total := int64(len(groups))
var result []domain.AgentGroup
for _, g := range groups {
if g != nil {
result = append(result, *g)
}
}
return result, total, nil
}
// GetAgentGroup returns a single agent group (handler interface method).
func (s *AgentGroupService) GetAgentGroup(id string) (*domain.AgentGroup, error) {
return s.groupRepo.Get(context.Background(), id)
}
// CreateAgentGroup creates a new agent group with validation (handler interface method).
func (s *AgentGroupService) CreateAgentGroup(group domain.AgentGroup) (*domain.AgentGroup, error) {
if err := validateAgentGroup(&group); err != nil {
return nil, err
}
if group.ID == "" {
group.ID = generateID("ag")
}
now := time.Now()
if group.CreatedAt.IsZero() {
group.CreatedAt = now
}
if group.UpdatedAt.IsZero() {
group.UpdatedAt = now
}
if err := s.groupRepo.Create(context.Background(), &group); err != nil {
return nil, fmt.Errorf("failed to create agent group: %w", err)
}
if s.auditService != nil {
if auditErr := s.auditService.RecordEvent(context.Background(), "api", domain.ActorTypeUser,
"create_agent_group", "agent_group", group.ID, nil); auditErr != nil {
slog.Error("failed to record audit event", "error", auditErr)
}
}
return &group, nil
}
// UpdateAgentGroup modifies an existing agent group (handler interface method).
func (s *AgentGroupService) UpdateAgentGroup(id string, group domain.AgentGroup) (*domain.AgentGroup, error) {
if err := validateAgentGroup(&group); err != nil {
return nil, err
}
group.ID = id
if err := s.groupRepo.Update(context.Background(), &group); err != nil {
return nil, fmt.Errorf("failed to update agent group: %w", err)
}
if s.auditService != nil {
if auditErr := s.auditService.RecordEvent(context.Background(), "api", domain.ActorTypeUser,
"update_agent_group", "agent_group", id, nil); auditErr != nil {
slog.Error("failed to record audit event", "error", auditErr)
}
}
return &group, nil
}
// DeleteAgentGroup removes an agent group (handler interface method).
func (s *AgentGroupService) DeleteAgentGroup(id string) error {
if err := s.groupRepo.Delete(context.Background(), id); err != nil {
return fmt.Errorf("failed to delete agent group: %w", err)
}
if s.auditService != nil {
if auditErr := s.auditService.RecordEvent(context.Background(), "api", domain.ActorTypeUser,
"delete_agent_group", "agent_group", id, nil); auditErr != nil {
slog.Error("failed to record audit event", "error", auditErr)
}
}
return nil
}
// ListMembers returns agents in a group.
func (s *AgentGroupService) ListMembers(id string) ([]domain.Agent, int64, error) {
agents, err := s.groupRepo.ListMembers(context.Background(), id)
if err != nil {
return nil, 0, fmt.Errorf("failed to list group members: %w", err)
}
var result []domain.Agent
for _, a := range agents {
if a != nil {
result = append(result, *a)
}
}
return result, int64(len(result)), nil
}
// validateAgentGroup checks that an agent group's configuration is valid.
func validateAgentGroup(g *domain.AgentGroup) error {
if g.Name == "" {
return fmt.Errorf("agent group name is required")
}
if len(g.Name) > 255 {
return fmt.Errorf("agent group name exceeds 255 characters")
}
return nil
}
+47
View File
@@ -249,3 +249,50 @@ func (s *JobService) ListJobs(status, jobType string, page, perPage int) ([]doma
func (s *JobService) GetJob(id string) (*domain.Job, error) {
return s.jobRepo.Get(context.Background(), id)
}
// ApproveJob approves a renewal job that is awaiting approval.
// Transitions the job from AwaitingApproval to Pending so the scheduler picks it up.
func (s *JobService) ApproveJob(id string) error {
ctx := context.Background()
job, err := s.jobRepo.Get(ctx, id)
if err != nil {
return fmt.Errorf("job not found: %w", err)
}
if job.Status != domain.JobStatusAwaitingApproval {
return fmt.Errorf("cannot approve job with status %s (must be AwaitingApproval)", job.Status)
}
if err := s.jobRepo.UpdateStatus(ctx, id, domain.JobStatusPending, ""); err != nil {
return fmt.Errorf("failed to approve job: %w", err)
}
s.logger.Info("renewal job approved", "job_id", id, "certificate_id", job.CertificateID)
return nil
}
// RejectJob rejects a renewal job that is awaiting approval.
// Transitions the job to Cancelled with a rejection reason.
func (s *JobService) RejectJob(id string, reason string) error {
ctx := context.Background()
job, err := s.jobRepo.Get(ctx, id)
if err != nil {
return fmt.Errorf("job not found: %w", err)
}
if job.Status != domain.JobStatusAwaitingApproval {
return fmt.Errorf("cannot reject job with status %s (must be AwaitingApproval)", job.Status)
}
msg := "rejected by user"
if reason != "" {
msg = "rejected: " + reason
}
if err := s.jobRepo.UpdateStatus(ctx, id, domain.JobStatusCancelled, msg); err != nil {
return fmt.Errorf("failed to reject job: %w", err)
}
s.logger.Info("renewal job rejected", "job_id", id, "certificate_id", job.CertificateID, "reason", reason)
return nil
}
+24 -4
View File
@@ -13,6 +13,7 @@ import (
// NotificationService provides business logic for managing notifications.
type NotificationService struct {
notifRepo repository.NotificationRepository
ownerRepo repository.OwnerRepository
notifierRegistry map[string]Notifier
}
@@ -35,6 +36,25 @@ func NewNotificationService(
}
}
// SetOwnerRepo sets the owner repository for email resolution.
// Called after construction to avoid circular dependency during initialization.
func (s *NotificationService) SetOwnerRepo(ownerRepo repository.OwnerRepository) {
s.ownerRepo = ownerRepo
}
// resolveRecipient resolves an owner ID to an email address.
// Falls back to the raw owner ID if the owner repo is not set or lookup fails.
func (s *NotificationService) resolveRecipient(ctx context.Context, ownerID string) string {
if s.ownerRepo == nil || ownerID == "" {
return ownerID
}
owner, err := s.ownerRepo.Get(ctx, ownerID)
if err != nil || owner == nil || owner.Email == "" {
return ownerID
}
return owner.Email
}
// SendExpirationWarning sends a certificate expiration warning for a specific threshold.
func (s *NotificationService) SendExpirationWarning(ctx context.Context, cert *domain.ManagedCertificate, daysUntilExpiry int) error {
return s.SendThresholdAlert(ctx, cert, daysUntilExpiry, daysUntilExpiry)
@@ -56,13 +76,13 @@ func (s *NotificationService) SendThresholdAlert(ctx context.Context, cert *doma
)
}
// Create notification record
// Create notification record — resolve owner email if possible
notif := &domain.NotificationEvent{
ID: generateID("notif"),
CertificateID: &cert.ID,
Type: domain.NotificationTypeExpirationWarning,
Channel: domain.NotificationChannelEmail,
Recipient: cert.OwnerID,
Recipient: s.resolveRecipient(ctx, cert.OwnerID),
Message: body,
Status: "pending",
CreatedAt: time.Now(),
@@ -121,7 +141,7 @@ func (s *NotificationService) SendRenewalNotification(ctx context.Context, cert
CertificateID: &cert.ID,
Type: notifType,
Channel: domain.NotificationChannelEmail,
Recipient: cert.OwnerID,
Recipient: s.resolveRecipient(ctx, cert.OwnerID),
Message: body,
Status: "pending",
CreatedAt: time.Now(),
@@ -160,7 +180,7 @@ func (s *NotificationService) SendDeploymentNotification(ctx context.Context, ce
CertificateID: &cert.ID,
Type: notifType,
Channel: domain.NotificationChannelEmail,
Recipient: cert.OwnerID,
Recipient: s.resolveRecipient(ctx, cert.OwnerID),
Message: body,
Status: "pending",
CreatedAt: time.Now(),