Build and Push Image / build (push) Successful in 40s
Add GET /oauth/atproto-client-metadata.json next to the existing OAuth relay routes so AT Protocol authorization servers can resolve the latha-auth public client (client_id is this URL).
388 lines
12 KiB
Go
388 lines
12 KiB
Go
package server
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"embed"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.site.latha.org/experiments/gitea-k3s-deployer/internal/config"
|
|
"git.site.latha.org/experiments/gitea-k3s-deployer/internal/deployer"
|
|
"git.site.latha.org/experiments/gitea-k3s-deployer/internal/gitea"
|
|
"git.site.latha.org/experiments/gitea-k3s-deployer/internal/k8s"
|
|
"git.site.latha.org/experiments/gitea-k3s-deployer/internal/store"
|
|
)
|
|
|
|
//go:embed web/index.html
|
|
var webFS embed.FS
|
|
|
|
type Server struct {
|
|
cfg config.Config
|
|
store *store.Store
|
|
svc *deployer.Service
|
|
k8s k8s.Applier
|
|
oauth *oauthRelayStore
|
|
mux *http.ServeMux
|
|
}
|
|
|
|
func New(cfg config.Config, st *store.Store, svc *deployer.Service, ka k8s.Applier) *Server {
|
|
s := &Server{
|
|
cfg: cfg,
|
|
store: st,
|
|
svc: svc,
|
|
k8s: ka,
|
|
oauth: newOAuthRelayStore(),
|
|
mux: http.NewServeMux(),
|
|
}
|
|
s.routes()
|
|
return s
|
|
}
|
|
|
|
func (s *Server) Handler() http.Handler {
|
|
return s.mux
|
|
}
|
|
|
|
func (s *Server) routes() {
|
|
s.mux.HandleFunc("GET /", s.handleIndex)
|
|
s.mux.HandleFunc("GET /healthz", s.handleHealthz)
|
|
s.mux.HandleFunc("GET /readyz", s.handleReadyz)
|
|
s.mux.HandleFunc("GET /metrics", s.handleMetrics)
|
|
|
|
s.mux.HandleFunc("GET /oauth/callback", s.handleOAuthCallback)
|
|
s.mux.HandleFunc("GET /oauth/atproto-client-metadata.json", s.handleAtprotoClientMetadata)
|
|
s.mux.HandleFunc("GET /api/oauth/poll", s.handleOAuthPoll)
|
|
|
|
s.mux.HandleFunc("POST /webhook/gitea", s.handleGiteaWebhook)
|
|
|
|
s.mux.HandleFunc("GET /api/apps", s.handleListApps)
|
|
s.mux.HandleFunc("POST /api/apps", s.handleUpsertApp)
|
|
s.mux.HandleFunc("GET /api/deployments", s.handleListDeployments)
|
|
s.mux.HandleFunc("GET /api/deployments/{id}", s.handleGetDeployment)
|
|
s.mux.HandleFunc("POST /api/deploy", s.handleDeploy)
|
|
s.mux.HandleFunc("POST /api/deployments/{id}/rollback", s.handleRollback)
|
|
s.mux.HandleFunc("GET /api/webhooks", s.handleListWebhooks)
|
|
}
|
|
|
|
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/" {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
b, err := webFS.ReadFile("web/index.html")
|
|
if err != nil {
|
|
http.Error(w, "dashboard unavailable", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
_, _ = w.Write(b)
|
|
}
|
|
|
|
func (s *Server) handleHealthz(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"kube_mode": s.k8s.Mode(),
|
|
"gitea_url": s.cfg.GiteaURL,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleReadyz(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ready",
|
|
"kube_mode": s.k8s.Mode(),
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
|
|
fmt.Fprintf(w, "# TYPE deployer_webhooks_total counter\n")
|
|
fmt.Fprintf(w, "deployer_webhooks_total %d\n", s.svc.Metrics.WebhooksTotal.Load())
|
|
fmt.Fprintf(w, "# TYPE deployer_webhooks_rejected_total counter\n")
|
|
fmt.Fprintf(w, "deployer_webhooks_rejected_total %d\n", s.svc.Metrics.WebhooksRejected.Load())
|
|
fmt.Fprintf(w, "# TYPE deployer_deployments_total counter\n")
|
|
fmt.Fprintf(w, "deployer_deployments_total %d\n", s.svc.Metrics.DeploymentsTotal.Load())
|
|
fmt.Fprintf(w, "# TYPE deployer_deployments_succeeded_total counter\n")
|
|
fmt.Fprintf(w, "deployer_deployments_succeeded_total %d\n", s.svc.Metrics.DeploymentsSuccess.Load())
|
|
fmt.Fprintf(w, "# TYPE deployer_deployments_failed_total counter\n")
|
|
fmt.Fprintf(w, "deployer_deployments_failed_total %d\n", s.svc.Metrics.DeploymentsFailed.Load())
|
|
}
|
|
|
|
func (s *Server) handleGiteaWebhook(w http.ResponseWriter, r *http.Request) {
|
|
s.svc.Metrics.WebhooksTotal.Add(1)
|
|
|
|
body, err := io.ReadAll(io.LimitReader(r.Body, 2<<20))
|
|
if err != nil {
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "failed to read body"})
|
|
return
|
|
}
|
|
|
|
event := r.Header.Get("X-Gitea-Event")
|
|
if event == "" {
|
|
event = r.Header.Get("X-GitHub-Event")
|
|
}
|
|
sig := r.Header.Get("X-Gitea-Signature")
|
|
sigOK := gitea.VerifySignature(s.cfg.GiteaWebhookSecret, body, sig)
|
|
|
|
delivery := store.WebhookDelivery{
|
|
ID: shortID(),
|
|
Event: event,
|
|
SignatureOK: sigOK,
|
|
ReceivedAt: time.Now().UTC(),
|
|
}
|
|
|
|
if !sigOK {
|
|
s.svc.Metrics.WebhooksRejected.Add(1)
|
|
delivery.Accepted = false
|
|
delivery.Message = "invalid X-Gitea-Signature"
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid signature"})
|
|
return
|
|
}
|
|
|
|
if event == "ping" {
|
|
delivery.Accepted = true
|
|
delivery.Message = "pong"
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "pong"})
|
|
return
|
|
}
|
|
|
|
var req deployer.DeployRequest
|
|
switch event {
|
|
case "push":
|
|
var p gitea.PushEvent
|
|
if err := json.Unmarshal(body, &p); err != nil {
|
|
delivery.Message = "invalid push payload"
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": delivery.Message})
|
|
return
|
|
}
|
|
branch := gitea.BranchFromRef(p.Ref)
|
|
delivery.Repo = p.Repository.FullName
|
|
delivery.Ref = branch
|
|
delivery.CommitSHA = p.After
|
|
|
|
// Ignore tag pushes on push event (handled by release) or branch deletions
|
|
if strings.HasPrefix(p.Ref, "refs/tags/") || p.After == "0000000000000000000000000000000000000000" {
|
|
delivery.Accepted = false
|
|
delivery.Message = "ignored tag/delete push"
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ignored", "reason": delivery.Message})
|
|
return
|
|
}
|
|
|
|
// Check target branch if app is already registered
|
|
targetBranch := p.Repository.DefaultBranch
|
|
if targetBranch == "" {
|
|
targetBranch = "main"
|
|
}
|
|
if app, ok := s.store.GetApp(p.Repository.FullName); ok && app.Branch != "" {
|
|
targetBranch = app.Branch
|
|
}
|
|
if branch != targetBranch {
|
|
delivery.Accepted = false
|
|
delivery.Message = fmt.Sprintf("branch %q != target %q", branch, targetBranch)
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ignored", "reason": delivery.Message})
|
|
return
|
|
}
|
|
|
|
actor := p.Pusher.Username
|
|
if actor == "" {
|
|
actor = p.Sender.Username
|
|
}
|
|
req = deployer.DeployRequest{
|
|
Repo: p.Repository.FullName,
|
|
Ref: branch,
|
|
CommitSHA: p.After,
|
|
Trigger: "webhook:push",
|
|
Actor: actor,
|
|
}
|
|
|
|
case "release":
|
|
var rel gitea.ReleaseEvent
|
|
if err := json.Unmarshal(body, &rel); err != nil {
|
|
delivery.Message = "invalid release payload"
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": delivery.Message})
|
|
return
|
|
}
|
|
delivery.Repo = rel.Repository.FullName
|
|
delivery.Ref = rel.Release.TagName
|
|
if rel.Action != "published" && rel.Action != "released" {
|
|
delivery.Accepted = false
|
|
delivery.Message = fmt.Sprintf("ignored release action %q", rel.Action)
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ignored", "reason": delivery.Message})
|
|
return
|
|
}
|
|
req = deployer.DeployRequest{
|
|
Repo: rel.Repository.FullName,
|
|
Ref: rel.Release.TagName,
|
|
ImageTag: rel.Release.TagName,
|
|
Trigger: "webhook:release",
|
|
Actor: rel.Sender.Username,
|
|
}
|
|
|
|
case "workflow_run":
|
|
var wf gitea.WorkflowRunEvent
|
|
if err := json.Unmarshal(body, &wf); err != nil {
|
|
delivery.Message = "invalid workflow_run payload"
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": delivery.Message})
|
|
return
|
|
}
|
|
delivery.Repo = wf.Repository.FullName
|
|
delivery.Ref = wf.WorkflowRun.HeadBranch
|
|
delivery.CommitSHA = wf.WorkflowRun.HeadSHA
|
|
if wf.Action != "completed" || wf.WorkflowRun.Conclusion != "success" {
|
|
delivery.Accepted = false
|
|
delivery.Message = fmt.Sprintf("ignored workflow_run (%s/%s)", wf.Action, wf.WorkflowRun.Conclusion)
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ignored", "reason": delivery.Message})
|
|
return
|
|
}
|
|
req = deployer.DeployRequest{
|
|
Repo: wf.Repository.FullName,
|
|
Ref: wf.WorkflowRun.HeadBranch,
|
|
CommitSHA: wf.WorkflowRun.HeadSHA,
|
|
Trigger: "webhook:workflow_run",
|
|
Actor: wf.Sender.Username,
|
|
}
|
|
|
|
default:
|
|
delivery.Accepted = false
|
|
delivery.Message = fmt.Sprintf("unsupported event %q", event)
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ignored", "reason": delivery.Message})
|
|
return
|
|
}
|
|
|
|
dep, err := s.svc.DeployRepo(r.Context(), req)
|
|
if err != nil {
|
|
delivery.Accepted = false
|
|
delivery.DeploymentID = dep.ID
|
|
delivery.Message = err.Error()
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusUnprocessableEntity, map[string]any{
|
|
"status": "failed",
|
|
"deployment_id": dep.ID,
|
|
"error": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
delivery.Accepted = true
|
|
delivery.DeploymentID = dep.ID
|
|
delivery.Message = fmt.Sprintf("deployed %s (%d resources)", dep.AppName, len(dep.AppliedResources))
|
|
s.store.AddWebhook(delivery)
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "deployed",
|
|
"deployment_id": dep.ID,
|
|
"app": dep.AppName,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleListApps(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"apps": s.store.ListApps()})
|
|
}
|
|
|
|
func (s *Server) handleUpsertApp(w http.ResponseWriter, r *http.Request) {
|
|
var app store.App
|
|
if err := json.NewDecoder(r.Body).Decode(&app); err != nil {
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
|
return
|
|
}
|
|
if app.Repo == "" {
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "repo is required"})
|
|
return
|
|
}
|
|
if app.Branch == "" {
|
|
app.Branch = "main"
|
|
}
|
|
if app.Namespace == "" {
|
|
app.Namespace = "default"
|
|
}
|
|
s.store.UpsertApp(app)
|
|
writeJSON(w, http.StatusOK, app)
|
|
}
|
|
|
|
func (s *Server) handleListDeployments(w http.ResponseWriter, r *http.Request) {
|
|
limit := 50
|
|
if v := r.URL.Query().Get("limit"); v != "" {
|
|
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
|
limit = n
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"deployments": s.store.ListDeployments(limit)})
|
|
}
|
|
|
|
func (s *Server) handleGetDeployment(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
dep, ok := s.store.GetDeployment(id)
|
|
if !ok {
|
|
writeJSON(w, http.StatusNotFound, map[string]string{"error": "deployment not found"})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, dep)
|
|
}
|
|
|
|
func (s *Server) handleDeploy(w http.ResponseWriter, r *http.Request) {
|
|
var req deployer.DeployRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
|
return
|
|
}
|
|
if req.Repo == "" {
|
|
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "repo is required"})
|
|
return
|
|
}
|
|
dep, err := s.svc.DeployRepo(r.Context(), req)
|
|
if err != nil {
|
|
writeJSON(w, http.StatusUnprocessableEntity, map[string]any{
|
|
"id": dep.ID,
|
|
"status": dep.Status,
|
|
"error": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, dep)
|
|
}
|
|
|
|
func (s *Server) handleRollback(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
dep, err := s.svc.RollbackDeployment(r.Context(), id, "dashboard")
|
|
if err != nil {
|
|
writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, dep)
|
|
}
|
|
|
|
func (s *Server) handleListWebhooks(w http.ResponseWriter, r *http.Request) {
|
|
limit := 50
|
|
if v := r.URL.Query().Get("limit"); v != "" {
|
|
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
|
limit = n
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]any{"webhooks": s.store.ListWebhooks(limit)})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
func shortID() string {
|
|
var b [4]byte
|
|
_, _ = rand.Read(b[:])
|
|
return hex.EncodeToString(b[:])
|
|
}
|