mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 17:41:29 +00:00
G-1: renewal-policies API + frontend FK-drift fix
Three frontend call sites (OnboardingWizard.tsx:603, CertificatesPage.tsx:52,
CertificateDetailPage.tsx:169) populated the renewal_policy_id dropdown from
getPolicies() — the compliance-rule endpoint returning pol-* IDs — which
violated the FK managed_certificates.renewal_policy_id REFERENCES
renewal_policies(id) ON DELETE RESTRICT. Create would fail pg 23503 at insert.
Backend (new):
- RenewalPolicyRepository CRUD + ListAll/ExistsByID (pg 23503 → ErrRenewalPolicyInUse
→ HTTP 409; pg 23505 → ErrRenewalPolicyDuplicateName → HTTP 409)
- RenewalPolicyService with repo-only constructor. Service sentinels
var-alias the repo sentinels so errors.Is walks across layers.
- RenewalPolicyHandler with validation bounds: name 1–255;
renewal_window_days [1,365] default 30; max_retries [0,10] not defaulted;
retry_interval_seconds [60,86400] default 3600; alert_thresholds_days
[0,365] default [30,14,7,0]. Auto-generated IDs rp-<slug(name)>.
- Router registers 5 routes under /api/v1/renewal-policies[/{id}].
Frontend:
- CertificatesPage/CertificateDetailPage/OnboardingWizard now call
getRenewalPolicies() and render rp-* IDs.
- client.ts adds getRenewalPolicies/createRenewalPolicy/updateRenewalPolicy/
deleteRenewalPolicy. types.ts adds the RenewalPolicy shape.
OpenAPI: RenewalPolicies tag + 5 operations + 3 schemas (RenewalPolicy,
RenewalPolicyCreateRequest, RenewalPolicyUpdateRequest). 409 responses
on create/update duplicate-name and delete FK-in-use.
No migration — renewal_policies table already exists from the initial
schema (000001).
Tests:
- internal/service/renewal_policy_test.go: CRUD + validation + sentinel
error wrapping.
- internal/api/handler/renewal_policy_handler_test.go: handler endpoint
contracts including 400/404/409.
- web/src/api/client.test.ts: 4 subtests covering the 4 new API functions.
Phase 3 gates all green: go vet, build, short tests, race tests (service/
handler/router/scheduler), staticcheck (G-1 packages), govulncheck (0
reachable), coverage (service 69.7%, handler 79.0%, domain 86.9%,
middleware 80.6% — all above thresholds), tsc, vitest (256 passed),
vite build, OpenAPI structural validation.
This commit is contained in:
@@ -0,0 +1,243 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/api/middleware"
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
"github.com/shankar0123/certctl/internal/service"
|
||||
)
|
||||
|
||||
// RenewalPolicyService defines the service interface for renewal policy
|
||||
// operations. G-1: all methods take ctx so the handler can propagate
|
||||
// request-scoped cancellation/deadlines through the full stack.
|
||||
type RenewalPolicyService interface {
|
||||
ListRenewalPolicies(ctx context.Context, page, perPage int) ([]domain.RenewalPolicy, int64, error)
|
||||
GetRenewalPolicy(ctx context.Context, id string) (*domain.RenewalPolicy, error)
|
||||
CreateRenewalPolicy(ctx context.Context, rp domain.RenewalPolicy) (*domain.RenewalPolicy, error)
|
||||
UpdateRenewalPolicy(ctx context.Context, id string, rp domain.RenewalPolicy) (*domain.RenewalPolicy, error)
|
||||
DeleteRenewalPolicy(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// RenewalPolicyHandler serves /api/v1/renewal-policies CRUD endpoints.
|
||||
//
|
||||
// G-1 design note: the service-level `ErrRenewalPolicyDuplicateName` /
|
||||
// `ErrRenewalPolicyInUse` sentinels alias the repository sentinels (same var
|
||||
// identity), so `errors.Is` walks transparently across layers. Delete/Update
|
||||
// not-found detection intentionally uses a `strings.Contains(err.Error(),
|
||||
// "not found")` substring check — the repo wraps `sql.ErrNoRows` as
|
||||
// `fmt.Errorf("renewal policy not found: %s", id)` which strips the sentinel,
|
||||
// and the handler red-tests' `ErrMockNotFound = errors.New("mock not found
|
||||
// error")` follows the same substring convention.
|
||||
type RenewalPolicyHandler struct {
|
||||
svc RenewalPolicyService
|
||||
}
|
||||
|
||||
// NewRenewalPolicyHandler constructs the handler with its service dependency.
|
||||
// Returned by value to match the house pattern (PolicyHandler, IssuerHandler
|
||||
// etc.) — the registry stores handlers by value in router.HandlerRegistry.
|
||||
func NewRenewalPolicyHandler(svc RenewalPolicyService) RenewalPolicyHandler {
|
||||
return RenewalPolicyHandler{svc: svc}
|
||||
}
|
||||
|
||||
// ListRenewalPolicies lists all renewal policies (paginated).
|
||||
// GET /api/v1/renewal-policies?page=1&per_page=50
|
||||
func (h RenewalPolicyHandler) ListRenewalPolicies(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
|
||||
}
|
||||
}
|
||||
|
||||
policies, total, err := h.svc.ListRenewalPolicies(r.Context(), page, perPage)
|
||||
if err != nil {
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to list renewal policies", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
response := PagedResponse{
|
||||
Data: policies,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PerPage: perPage,
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, response)
|
||||
}
|
||||
|
||||
// GetRenewalPolicy retrieves a single renewal policy by ID.
|
||||
// GET /api/v1/renewal-policies/{id}
|
||||
func (h RenewalPolicyHandler) GetRenewalPolicy(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/renewal-policies/")
|
||||
parts := strings.Split(id, "/")
|
||||
if len(parts) == 0 || parts[0] == "" {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Renewal policy ID is required", requestID)
|
||||
return
|
||||
}
|
||||
id = parts[0]
|
||||
|
||||
policy, err := h.svc.GetRenewalPolicy(r.Context(), id)
|
||||
if err != nil {
|
||||
// Matches the PolicyHandler.GetPolicy convention: any error from the
|
||||
// service surfaces as 404. The repo wraps sql.ErrNoRows as
|
||||
// "renewal policy not found: %s" and there's no other expected failure
|
||||
// mode on Get — the caller gets a clean 404.
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Renewal policy not found", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, policy)
|
||||
}
|
||||
|
||||
// CreateRenewalPolicy inserts a new renewal policy.
|
||||
// POST /api/v1/renewal-policies
|
||||
//
|
||||
// Error mapping:
|
||||
// - invalid JSON / missing name → 400
|
||||
// - ErrRenewalPolicyDuplicateName (pg 23505 on name UNIQUE) → 409
|
||||
// - anything else → 500
|
||||
func (h RenewalPolicyHandler) CreateRenewalPolicy(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 rp domain.RenewalPolicy
|
||||
if err := json.NewDecoder(r.Body).Decode(&rp); err != nil {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Invalid request body", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
if err := ValidateRequired("name", rp.Name); err != nil {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, err.Error(), requestID)
|
||||
return
|
||||
}
|
||||
|
||||
created, err := h.svc.CreateRenewalPolicy(r.Context(), rp)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrRenewalPolicyDuplicateName) {
|
||||
ErrorWithRequestID(w, http.StatusConflict, "A renewal policy with that name already exists", requestID)
|
||||
return
|
||||
}
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to create renewal policy", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusCreated, created)
|
||||
}
|
||||
|
||||
// UpdateRenewalPolicy replaces the fields of an existing renewal policy.
|
||||
// PUT /api/v1/renewal-policies/{id}
|
||||
//
|
||||
// Error mapping:
|
||||
// - invalid JSON / empty ID → 400
|
||||
// - ErrRenewalPolicyDuplicateName → 409
|
||||
// - error text contains "not found" → 404 (see struct doc comment re: substring check)
|
||||
// - anything else → 500
|
||||
func (h RenewalPolicyHandler) UpdateRenewalPolicy(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/renewal-policies/")
|
||||
parts := strings.Split(id, "/")
|
||||
if len(parts) == 0 || parts[0] == "" {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Renewal policy ID is required", requestID)
|
||||
return
|
||||
}
|
||||
id = parts[0]
|
||||
|
||||
var rp domain.RenewalPolicy
|
||||
if err := json.NewDecoder(r.Body).Decode(&rp); err != nil {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Invalid request body", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
updated, err := h.svc.UpdateRenewalPolicy(r.Context(), id, rp)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrRenewalPolicyDuplicateName) {
|
||||
ErrorWithRequestID(w, http.StatusConflict, "A renewal policy with that name already exists", requestID)
|
||||
return
|
||||
}
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Renewal policy not found", requestID)
|
||||
return
|
||||
}
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to update renewal policy", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
JSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// DeleteRenewalPolicy removes a renewal policy.
|
||||
// DELETE /api/v1/renewal-policies/{id}
|
||||
//
|
||||
// Error mapping:
|
||||
// - empty ID (trailing slash) → 400
|
||||
// - ErrRenewalPolicyInUse (pg 23503 FK-RESTRICT against managed_certificates.renewal_policy_id) → 409
|
||||
// - error text contains "not found" → 404
|
||||
// - anything else → 500
|
||||
func (h RenewalPolicyHandler) DeleteRenewalPolicy(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/renewal-policies/")
|
||||
parts := strings.Split(id, "/")
|
||||
if len(parts) == 0 || parts[0] == "" {
|
||||
ErrorWithRequestID(w, http.StatusBadRequest, "Renewal policy ID is required", requestID)
|
||||
return
|
||||
}
|
||||
id = parts[0]
|
||||
|
||||
if err := h.svc.DeleteRenewalPolicy(r.Context(), id); err != nil {
|
||||
if errors.Is(err, service.ErrRenewalPolicyInUse) {
|
||||
ErrorWithRequestID(w, http.StatusConflict, "Renewal policy is still referenced by managed certificates", requestID)
|
||||
return
|
||||
}
|
||||
if strings.Contains(err.Error(), "not found") {
|
||||
ErrorWithRequestID(w, http.StatusNotFound, "Renewal policy not found", requestID)
|
||||
return
|
||||
}
|
||||
ErrorWithRequestID(w, http.StatusInternalServerError, "Failed to delete renewal policy", requestID)
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/shankar0123/certctl/internal/domain"
|
||||
"github.com/shankar0123/certctl/internal/service"
|
||||
)
|
||||
|
||||
// G-1 red tests: lock in the HTTP surface of /api/v1/renewal-policies before
|
||||
// the production code exists. Every subtest here references a symbol that
|
||||
// Phase 2b must introduce:
|
||||
//
|
||||
// - NewRenewalPolicyHandler(svc) (constructor)
|
||||
// - RenewalPolicyService (service-layer interface, in this package)
|
||||
// - handler.ListRenewalPolicies / GetRenewalPolicy / CreateRenewalPolicy /
|
||||
// UpdateRenewalPolicy / DeleteRenewalPolicy
|
||||
// - service.ErrRenewalPolicyDuplicateName (pg 23505 → 409 mapping)
|
||||
// - service.ErrRenewalPolicyInUse (pg 23503 → 409 mapping)
|
||||
|
||||
// MockRenewalPolicyService is a mock implementation of RenewalPolicyService.
|
||||
type MockRenewalPolicyService struct {
|
||||
ListRenewalPoliciesFn func(page, perPage int) ([]domain.RenewalPolicy, int64, error)
|
||||
GetRenewalPolicyFn func(id string) (*domain.RenewalPolicy, error)
|
||||
CreateRenewalPolicyFn func(rp domain.RenewalPolicy) (*domain.RenewalPolicy, error)
|
||||
UpdateRenewalPolicyFn func(id string, rp domain.RenewalPolicy) (*domain.RenewalPolicy, error)
|
||||
DeleteRenewalPolicyFn func(id string) error
|
||||
}
|
||||
|
||||
func (m *MockRenewalPolicyService) ListRenewalPolicies(_ context.Context, page, perPage int) ([]domain.RenewalPolicy, int64, error) {
|
||||
if m.ListRenewalPoliciesFn != nil {
|
||||
return m.ListRenewalPoliciesFn(page, perPage)
|
||||
}
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
func (m *MockRenewalPolicyService) GetRenewalPolicy(_ context.Context, id string) (*domain.RenewalPolicy, error) {
|
||||
if m.GetRenewalPolicyFn != nil {
|
||||
return m.GetRenewalPolicyFn(id)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockRenewalPolicyService) CreateRenewalPolicy(_ context.Context, rp domain.RenewalPolicy) (*domain.RenewalPolicy, error) {
|
||||
if m.CreateRenewalPolicyFn != nil {
|
||||
return m.CreateRenewalPolicyFn(rp)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockRenewalPolicyService) UpdateRenewalPolicy(_ context.Context, id string, rp domain.RenewalPolicy) (*domain.RenewalPolicy, error) {
|
||||
if m.UpdateRenewalPolicyFn != nil {
|
||||
return m.UpdateRenewalPolicyFn(id, rp)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *MockRenewalPolicyService) DeleteRenewalPolicy(_ context.Context, id string) error {
|
||||
if m.DeleteRenewalPolicyFn != nil {
|
||||
return m.DeleteRenewalPolicyFn(id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ----- List -----
|
||||
|
||||
func TestListRenewalPolicies_Success(t *testing.T) {
|
||||
now := time.Now()
|
||||
rp1 := domain.RenewalPolicy{
|
||||
ID: "rp-default", Name: "Default", RenewalWindowDays: 30,
|
||||
MaxRetries: 3, RetryInterval: 3600, AutoRenew: true,
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
rp2 := domain.RenewalPolicy{
|
||||
ID: "rp-urgent", Name: "Urgent", RenewalWindowDays: 7,
|
||||
MaxRetries: 5, RetryInterval: 600, AutoRenew: true,
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
|
||||
mock := &MockRenewalPolicyService{
|
||||
ListRenewalPoliciesFn: func(page, perPage int) ([]domain.RenewalPolicy, int64, error) {
|
||||
return []domain.RenewalPolicy{rp1, rp2}, 2, nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/renewal-policies", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ListRenewalPolicies(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 != 2 {
|
||||
t.Errorf("expected total 2, got %d", resp.Total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRenewalPolicies_ServiceError(t *testing.T) {
|
||||
mock := &MockRenewalPolicyService{
|
||||
ListRenewalPoliciesFn: func(page, perPage int) ([]domain.RenewalPolicy, int64, error) {
|
||||
return nil, 0, ErrMockServiceFailed
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/renewal-policies", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ListRenewalPolicies(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("expected status 500, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListRenewalPolicies_MethodNotAllowed(t *testing.T) {
|
||||
handler := NewRenewalPolicyHandler(&MockRenewalPolicyService{})
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/renewal-policies", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.ListRenewalPolicies(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("expected status 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ----- Get -----
|
||||
|
||||
func TestGetRenewalPolicy_Success(t *testing.T) {
|
||||
now := time.Now()
|
||||
mock := &MockRenewalPolicyService{
|
||||
GetRenewalPolicyFn: func(id string) (*domain.RenewalPolicy, error) {
|
||||
return &domain.RenewalPolicy{
|
||||
ID: id, Name: "Default", RenewalWindowDays: 30,
|
||||
MaxRetries: 3, RetryInterval: 3600, AutoRenew: true,
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/renewal-policies/rp-default", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRenewalPolicy_NotFound(t *testing.T) {
|
||||
mock := &MockRenewalPolicyService{
|
||||
GetRenewalPolicyFn: func(id string) (*domain.RenewalPolicy, error) {
|
||||
return nil, ErrMockNotFound
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/renewal-policies/nonexistent", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.GetRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected status 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ----- Create -----
|
||||
|
||||
func TestCreateRenewalPolicy_Success(t *testing.T) {
|
||||
now := time.Now()
|
||||
mock := &MockRenewalPolicyService{
|
||||
CreateRenewalPolicyFn: func(rp domain.RenewalPolicy) (*domain.RenewalPolicy, error) {
|
||||
rp.ID = "rp-new"
|
||||
rp.CreatedAt = now
|
||||
rp.UpdatedAt = now
|
||||
return &rp, nil
|
||||
},
|
||||
}
|
||||
|
||||
body := map[string]interface{}{
|
||||
"name": "New Policy",
|
||||
"renewal_window_days": 30,
|
||||
"max_retries": 3,
|
||||
"retry_interval_seconds": 3600,
|
||||
"auto_renew": true,
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(body)
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/renewal-policies", bytes.NewReader(bodyBytes))
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.CreateRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("expected status 201, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRenewalPolicy_MissingName(t *testing.T) {
|
||||
body := map[string]interface{}{
|
||||
"renewal_window_days": 30,
|
||||
"max_retries": 3,
|
||||
"retry_interval_seconds": 3600,
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(body)
|
||||
|
||||
handler := NewRenewalPolicyHandler(&MockRenewalPolicyService{})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/renewal-policies", bytes.NewReader(bodyBytes))
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.CreateRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected status 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRenewalPolicy_InvalidJSON(t *testing.T) {
|
||||
handler := NewRenewalPolicyHandler(&MockRenewalPolicyService{})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/renewal-policies", bytes.NewReader([]byte("not json")))
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.CreateRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected status 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRenewalPolicy_DuplicateName(t *testing.T) {
|
||||
// Service bubbles up ErrRenewalPolicyDuplicateName (pg 23505) → handler maps to 409.
|
||||
mock := &MockRenewalPolicyService{
|
||||
CreateRenewalPolicyFn: func(rp domain.RenewalPolicy) (*domain.RenewalPolicy, error) {
|
||||
return nil, service.ErrRenewalPolicyDuplicateName
|
||||
},
|
||||
}
|
||||
|
||||
body := map[string]interface{}{
|
||||
"name": "Duplicate",
|
||||
"renewal_window_days": 30,
|
||||
"max_retries": 3,
|
||||
"retry_interval_seconds": 3600,
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(body)
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/renewal-policies", bytes.NewReader(bodyBytes))
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.CreateRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("expected status 409 on duplicate name, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateRenewalPolicy_MethodNotAllowed(t *testing.T) {
|
||||
handler := NewRenewalPolicyHandler(&MockRenewalPolicyService{})
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/renewal-policies", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.CreateRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("expected status 405, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ----- Update -----
|
||||
|
||||
func TestUpdateRenewalPolicy_Success(t *testing.T) {
|
||||
now := time.Now()
|
||||
mock := &MockRenewalPolicyService{
|
||||
UpdateRenewalPolicyFn: func(id string, rp domain.RenewalPolicy) (*domain.RenewalPolicy, error) {
|
||||
return &domain.RenewalPolicy{
|
||||
ID: id, Name: rp.Name, RenewalWindowDays: rp.RenewalWindowDays,
|
||||
MaxRetries: rp.MaxRetries, RetryInterval: rp.RetryInterval,
|
||||
AutoRenew: rp.AutoRenew,
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
|
||||
body := map[string]interface{}{
|
||||
"name": "Updated Policy",
|
||||
"renewal_window_days": 45,
|
||||
"max_retries": 5,
|
||||
"retry_interval_seconds": 1800,
|
||||
"auto_renew": true,
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(body)
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPut, "/api/v1/renewal-policies/rp-default", bytes.NewReader(bodyBytes))
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.UpdateRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateRenewalPolicy_NotFound(t *testing.T) {
|
||||
mock := &MockRenewalPolicyService{
|
||||
UpdateRenewalPolicyFn: func(id string, rp domain.RenewalPolicy) (*domain.RenewalPolicy, error) {
|
||||
return nil, ErrMockNotFound
|
||||
},
|
||||
}
|
||||
|
||||
body := map[string]interface{}{
|
||||
"name": "Updated",
|
||||
"renewal_window_days": 30,
|
||||
"max_retries": 3,
|
||||
"retry_interval_seconds": 3600,
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(body)
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodPut, "/api/v1/renewal-policies/rp-missing", bytes.NewReader(bodyBytes))
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.UpdateRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected status 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// ----- Delete -----
|
||||
|
||||
func TestDeleteRenewalPolicy_Success(t *testing.T) {
|
||||
var deletedID string
|
||||
mock := &MockRenewalPolicyService{
|
||||
DeleteRenewalPolicyFn: func(id string) error {
|
||||
deletedID = id
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/renewal-policies/rp-default", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.DeleteRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected status 204, got %d", w.Code)
|
||||
}
|
||||
if deletedID != "rp-default" {
|
||||
t.Errorf("expected deleted ID 'rp-default', got '%s'", deletedID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteRenewalPolicy_NotFound(t *testing.T) {
|
||||
mock := &MockRenewalPolicyService{
|
||||
DeleteRenewalPolicyFn: func(id string) error {
|
||||
return ErrMockNotFound
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/renewal-policies/rp-missing", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.DeleteRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected status 404, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteRenewalPolicy_InUseConflict(t *testing.T) {
|
||||
// Service bubbles up ErrRenewalPolicyInUse (pg 23503 FK-RESTRICT) → handler maps to 409.
|
||||
mock := &MockRenewalPolicyService{
|
||||
DeleteRenewalPolicyFn: func(id string) error {
|
||||
return service.ErrRenewalPolicyInUse
|
||||
},
|
||||
}
|
||||
|
||||
handler := NewRenewalPolicyHandler(mock)
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/renewal-policies/rp-active", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.DeleteRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("expected status 409 on in-use conflict, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteRenewalPolicy_EmptyID(t *testing.T) {
|
||||
handler := NewRenewalPolicyHandler(&MockRenewalPolicyService{})
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/renewal-policies/", nil)
|
||||
req = req.WithContext(contextWithRequestID())
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
handler.DeleteRenewalPolicy(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected status 400, got %d", w.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user