Files
tiny-forge/internal/api/projects.go
T
alexei.dolgolyov 0405ecd9ce
Build / build (push) Successful in 10m36s
feat(notify): HMAC-signed outgoing webhooks with per-tier secrets and test sender
Outgoing notifications were bare POSTs with no auth and no way to verify
they came from Tinyforge. They also went out from one global URL only,
even though stages had a notification_url field, and static-site sync
emitted no events at all.

Schema: add notification_url + notification_secret (lazy-generated) to
settings, projects, stages and static_sites. Migrations are additive.

Notifier: SendSigned computes HMAC-SHA256 over the exact body bytes and
sends X-Hub-Signature-256 (GitHub-compatible — receivers built for
GitHub/Gitea/Forgejo verify out of the box). Aux headers
X-Tinyforge-Event/Delivery/Timestamp/Tier are advisory and not signed.
Empty secret => unsigned send for back-compat.

Resolution: deploys fall through stage > project > settings, sites fall
through site > settings. The secret travels with the URL that sourced
it, so any tier can sign even when its parents are unsigned. Site sync
events now actually emit (site_sync_success / site_sync_failure).

API: 12 new endpoints — {GET secret, POST regenerate, POST disable,
POST test} for each of the 4 tiers. SendSyncForTest returns
status_code/latency_ms/signature_sent/delivery_id/response_snippet so
the UI surfaces receiver feedback inline.

UI: shared OutgoingWebhookPanel.svelte fits the existing card aesthetic.
Signing-state pill, secret reveal-on-demand, regenerate/disable behind
ConfirmDialog modals (not inline strips — too easy to misclick), send-
test result card with colour-coded status. Wired into Settings →
Integrations, project edit form, per-stage edit, and per-site detail.
EN + RU i18n.

Tests: round-trip (sender signs, receiver verifies), tampered-body and
wrong-secret rejection, unsigned-send omits header, send-test surfaces
4xx, concurrent fan-out via Drain. Resolver precedence locked for both
deploy and site paths.

Docs: docs/webhooks.md with header reference, verifier snippets in
Node/Python/Go, and a recipe for the service-to-notification-bridge
generic webhook provider.
2026-05-07 02:03:32 +03:00

226 lines
5.9 KiB
Go

package api
import (
"errors"
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/alexei/tinyforge/internal/events"
"github.com/alexei/tinyforge/internal/store"
)
// projectRequest is the expected JSON body for creating/updating a project.
type projectRequest struct {
Name string `json:"name"`
Registry string `json:"registry"`
Image string `json:"image"`
Port int `json:"port"`
Healthcheck string `json:"healthcheck"`
Env string `json:"env"`
Volumes string `json:"volumes"`
NpmAccessListID *int `json:"npm_access_list_id,omitempty"`
NotificationURL *string `json:"notification_url,omitempty"`
}
// listProjects handles GET /api/projects.
func (s *Server) listProjects(w http.ResponseWriter, r *http.Request) {
projects, err := s.store.GetAllProjects()
if err != nil {
slog.Error("failed to list projects", "error", err)
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
respondJSON(w, http.StatusOK, projects)
}
// createProject handles POST /api/projects.
func (s *Server) createProject(w http.ResponseWriter, r *http.Request) {
var req projectRequest
if !decodeJSON(w, r, &req) {
return
}
if req.Name == "" {
respondError(w, http.StatusBadRequest, "name is required")
return
}
if req.Image == "" {
respondError(w, http.StatusBadRequest, "image is required")
return
}
if req.Env == "" {
req.Env = "{}"
}
if req.Volumes == "" {
req.Volumes = "{}"
}
npmAccessListID := 0
if req.NpmAccessListID != nil {
npmAccessListID = *req.NpmAccessListID
}
project, err := s.store.CreateProject(store.Project{
Name: req.Name,
Registry: req.Registry,
Image: req.Image,
Port: req.Port,
Healthcheck: req.Healthcheck,
Env: req.Env,
Volumes: req.Volumes,
NpmAccessListID: npmAccessListID,
})
if err != nil {
slog.Error("failed to create project", "error", err)
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
s.eventBus.Publish(events.Event{
Type: events.EventLog,
Payload: events.EventLogPayload{
Source: "admin",
Severity: "info",
Message: "project created: " + project.Name,
},
})
respondJSON(w, http.StatusCreated, project)
}
// getProject handles GET /api/projects/{id}.
func (s *Server) getProject(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
project, err := s.store.GetProjectByID(id)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
respondNotFound(w, "project")
return
}
slog.Error("failed to get project", "error", err)
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
// Also fetch stages for this project.
stages, err := s.store.GetStagesByProjectID(id)
if err != nil {
slog.Error("failed to get stages", "error", err)
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
respondJSON(w, http.StatusOK, map[string]any{
"project": project,
"stages": stages,
})
}
// updateProject handles PUT /api/projects/{id}.
func (s *Server) updateProject(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
existing, err := s.store.GetProjectByID(id)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
respondNotFound(w, "project")
return
}
slog.Error("failed to get project", "error", err)
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
var req projectRequest
if !decodeJSON(w, r, &req) {
return
}
// Apply updates to existing project, preserving fields not provided.
updated := existing
if req.Name != "" {
updated.Name = req.Name
}
if req.Image != "" {
updated.Image = req.Image
}
updated.Registry = req.Registry
updated.Port = req.Port
updated.Healthcheck = req.Healthcheck
if req.Env != "" {
updated.Env = req.Env
}
if req.Volumes != "" {
updated.Volumes = req.Volumes
}
if req.NpmAccessListID != nil {
updated.NpmAccessListID = *req.NpmAccessListID
}
if req.NotificationURL != nil {
updated.NotificationURL = *req.NotificationURL
}
if err := s.store.UpdateProject(updated); err != nil {
slog.Error("failed to update project", "error", err)
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
s.eventBus.Publish(events.Event{
Type: events.EventLog,
Payload: events.EventLogPayload{
Source: "admin",
Severity: "info",
Message: "project updated: " + updated.Name,
},
})
respondJSON(w, http.StatusOK, updated)
}
// deleteProject handles DELETE /api/projects/{id}.
func (s *Server) deleteProject(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
// Clean up Docker containers and proxy routes before deleting the project.
ctx := r.Context()
stages, _ := s.store.GetStagesByProjectID(id)
for _, stage := range stages {
instances, _ := s.store.GetInstancesByStageID(stage.ID)
for _, inst := range instances {
if inst.ContainerID != "" {
if err := s.docker.RemoveContainer(ctx, inst.ContainerID, true); err != nil {
slog.Warn("delete project: remove container", "container", inst.ContainerID, "error", err)
}
}
if inst.ProxyRouteID != "" {
if err := s.proxyProvider.DeleteRoute(ctx, inst.ProxyRouteID); err != nil {
slog.Warn("delete project: delete proxy route", "route", inst.ProxyRouteID, "error", err)
}
}
}
}
if err := s.store.DeleteProject(id); err != nil {
if errors.Is(err, store.ErrNotFound) {
respondNotFound(w, "project")
return
}
slog.Error("failed to delete project", "error", err)
respondError(w, http.StatusInternalServerError, "internal server error")
return
}
s.eventBus.Publish(events.Event{
Type: events.EventLog,
Payload: events.EventLogPayload{
Source: "admin",
Severity: "info",
Message: "project deleted: " + id,
},
})
respondJSON(w, http.StatusOK, map[string]string{"deleted": id})
}