navid/veinsforge / 63285f2f5d2a393973991e37c053cc38309039a403f8ab54ee76b01499670c0e / internal/web/ci.go

ci.go

← internal/web · 12660 bytes · raw · download

package web

import (
	"context"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"

	"veinsforge/internal/auth"
	"veinsforge/internal/data"
)

func (s *Server) watchPushes(ctx context.Context) {
	ticker := time.NewTicker(2 * time.Second)
	defer ticker.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
			s.scanPushes(ctx)
		}
	}
}

func (s *Server) scanPushes(ctx context.Context) {
	repos, err := s.data.ListPushWatchRepos(ctx)
	if err != nil {
		s.logger.Printf("scan pushes: %v", err)
		return
	}
	for _, repo := range repos {
		config, _ := s.ciConfigForRepo(ctx, repo.ID)
		central := s.vn.RepoPath(repo.OwnerName, repo.Name)
		branches, err := s.vn.Bookmarks(ctx, central)
		if err != nil {
			s.logger.Printf("scan bookmarks %s/%s: %v", repo.OwnerName, repo.Name, err)
			continue
		}
		current := make(map[string]string, len(branches))
		for _, branch := range branches {
			current[branch.Name] = branch.Hash
		}

		s.scanRepoTags(ctx, repo, config, central)

		s.pushMu.Lock()
		previous, seen := s.pushSeen[repo.ID]
		s.pushSeen[repo.ID] = current
		s.pushMu.Unlock()
		if !seen {
			continue
		}

		for name, newHash := range current {
			oldHash, existed := previous[name]
			if existed && oldHash == newHash {
				continue
			}
			newCommit := newHash
			if newHash != "" {
				if full, err := s.vn.ResolveRef(ctx, central, newHash); err == nil {
					newCommit = full
				}
			}
			oldCommit := oldHash
			if oldHash != "" {
				if full, err := s.vn.ResolveRef(ctx, central, oldHash); err == nil {
					oldCommit = full
				}
			}
			s.dispatchWebhook(repo, nil, "push", map[string]any{
				"bookmark":   name,
				"old_commit": oldCommit,
				"new_commit": newCommit,
			})
			if newCommit != "" && config != nil && config.Enabled && s.ciMgr != nil {
				go s.ciMgr.Trigger(ctx, config, repo, name, newCommit)
			}
		}
		for name, oldHash := range previous {
			if _, ok := current[name]; ok {
				continue
			}
			oldCommit := oldHash
			if oldHash != "" {
				if full, err := s.vn.ResolveRef(ctx, central, oldHash); err == nil {
					oldCommit = full
				}
			}
			s.dispatchWebhook(repo, nil, "push", map[string]any{
				"bookmark":   name,
				"old_commit": oldCommit,
				"new_commit": "",
				"deleted":    true,
			})
		}
	}
}

func (s *Server) scanRepoTags(ctx context.Context, repo *data.Repo, config *data.CIConfig,
	central string) {
	tags, err := s.vn.TagsCentral(ctx, central)
	if err != nil {
		s.logger.Printf("scan tags %s/%s: %v", repo.OwnerName, repo.Name, err)
		return
	}
	current := make(map[string]string, len(tags))
	for _, tag := range tags {
		current[tag.Name] = tag.Hash
	}
	s.pushMu.Lock()
	previous, seen := s.tagSeen[repo.ID]
	s.tagSeen[repo.ID] = current
	s.pushMu.Unlock()
	if !seen {
		return
	}
	for name, newHash := range current {
		oldHash, existed := previous[name]
		if existed && oldHash == newHash {
			continue
		}
		if !strings.HasPrefix(name, "v") {
			continue
		}
		newCommit := newHash
		if full, err := s.vn.ResolveRef(ctx, central, newHash); err == nil {
			newCommit = full
		}
		oldCommit := oldHash
		if oldHash != "" {
			if full, err := s.vn.ResolveRef(ctx, central, oldHash); err == nil {
				oldCommit = full
			}
		}
		s.dispatchWebhook(repo, nil, "release", map[string]any{
			"tag":        name,
			"old_commit": oldCommit,
			"new_commit": newCommit,
		})
		if newCommit != "" && config != nil && config.Enabled && s.ciMgr != nil {
			go s.ciMgr.TriggerTag(ctx, config, repo, name, newCommit)
		}
	}
}

type ciStatusRequest struct {
	Commit      string `json:"commit"`
	Bookmark    string `json:"bookmark"`
	State       string `json:"state"`
	Context     string `json:"context"`
	Description string `json:"description"`
	URL         string `json:"url"`
	ExternalID  string `json:"external_id"`
}

func (s *Server) ciStatusAPI(w http.ResponseWriter, r *http.Request) {
	token := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
	if token == "" {
		token = strings.TrimSpace(r.Header.Get("X-Veinsforge-Token"))
	}
	if token == "" {
		writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "missing CI token"})
		return
	}
	config, err := s.data.CIConfigByToken(r.Context(), token)
	if err != nil {
		writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "invalid CI token"})
		return
	}
	repo, err := s.data.GetRepoByID(r.Context(), config.RepoID)
	if err != nil {
		writeJSON(w, http.StatusNotFound, map[string]any{"error": "repository not found"})
		return
	}
	var request ciStatusRequest
	decoder := json.NewDecoder(io.LimitReader(r.Body, 64<<10))
	decoder.DisallowUnknownFields()
	if err := decoder.Decode(&request); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": "invalid JSON body"})
		return
	}
	state := strings.ToLower(strings.TrimSpace(request.State))
	switch state {
	case "pending", "queued", "running", "passed", "failed", "canceled", "cancelled", "error":
		if state == "cancelled" {
			state = "canceled"
		}
	default:
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": "invalid CI state"})
		return
	}
	commit := strings.TrimSpace(request.Commit)
	if commit == "" {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": "commit is required"})
		return
	}
	if s.vn != nil {
		central := s.vn.RepoPath(repo.OwnerName, repo.Name)
		if full, err := s.vn.CommitHash(r.Context(), repo.ID, central, commit); err == nil {
			commit = full
		}
	}
	contextName := strings.TrimSpace(request.Context)
	if contextName == "" {
		contextName = "ci"
	}
	if len(contextName) > 100 || len(request.Description) > 1000 || len(request.URL) > 2000 ||
		len(request.ExternalID) > 500 {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": "CI status field is too long"})
		return
	}
	run, err := s.data.RecordCIRun(r.Context(), &data.CIRun{
		RepoID:      repo.ID,
		ConfigID:    config.ID,
		Provider:    config.Provider,
		Commit:      commit,
		Bookmark:    strings.TrimSpace(request.Bookmark),
		Context:     contextName,
		State:       state,
		Description: strings.TrimSpace(request.Description),
		URL:         strings.TrimSpace(request.URL),
		ExternalID:  strings.TrimSpace(request.ExternalID),
	})
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "could not record CI status"})
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"ok":       true,
		"run_id":   run.ID,
		"commit":   run.Commit,
		"state":    run.State,
		"context":  run.Context,
		"provider": run.Provider,
	})
}

type ciReleaseRequest struct {
	Tag       string                 `json:"tag"`
	Commit    string                 `json:"commit"`
	Provider  string                 `json:"provider"`
	BuildURL  string                 `json:"build_url"`
	Artifacts []data.ReleaseArtifact `json:"artifacts"`
}

func (s *Server) ciReleaseAPI(w http.ResponseWriter, r *http.Request) {
	token := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
	if token == "" {
		token = strings.TrimSpace(r.Header.Get("X-Veinsforge-Token"))
	}
	if token == "" {
		writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "missing CI token"})
		return
	}
	config, err := s.data.CIConfigByToken(r.Context(), token)
	if err != nil {
		writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "invalid CI token"})
		return
	}
	repo, err := s.data.GetRepoByID(r.Context(), config.RepoID)
	if err != nil {
		writeJSON(w, http.StatusNotFound, map[string]any{"error": "repository not found"})
		return
	}
	var request ciReleaseRequest
	decoder := json.NewDecoder(io.LimitReader(r.Body, 64<<10))
	decoder.DisallowUnknownFields()
	if err := decoder.Decode(&request); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": "invalid JSON body"})
		return
	}
	tag := strings.TrimSpace(request.Tag)
	if !strings.HasPrefix(tag, "v") || len(tag) > 200 {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": "release tag must start with v"})
		return
	}
	commit := strings.TrimSpace(request.Commit)
	if commit == "" {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": "commit is required"})
		return
	}
	if s.vn != nil {
		central := s.vn.RepoPath(repo.OwnerName, repo.Name)
		if full, err := s.vn.CommitHash(r.Context(), repo.ID, central, commit); err == nil {
			commit = full
		}
	}
	if len(request.BuildURL) > 2000 || len(request.Artifacts) > 32 {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": "release metadata is too large"})
		return
	}
	artifacts := make([]data.ReleaseArtifact, 0, len(request.Artifacts))
	for _, artifact := range request.Artifacts {
		artifact.Name = strings.TrimSpace(artifact.Name)
		artifact.URL = strings.TrimSpace(artifact.URL)
		if artifact.Name == "" || len(artifact.Name) > 300 || len(artifact.URL) > 2000 {
			writeJSON(w, http.StatusBadRequest, map[string]any{"error": "invalid release artifact"})
			return
		}
		parsed, err := url.Parse(artifact.URL)
		if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
			writeJSON(w, http.StatusBadRequest, map[string]any{"error": "artifact URL must be http or https"})
			return
		}
		artifacts = append(artifacts, artifact)
	}
	release, err := s.data.UpsertRelease(r.Context(), &data.Release{
		RepoID: repo.ID, Tag: tag, Commit: commit, Provider: config.Provider,
		BuildURL: strings.TrimSpace(request.BuildURL), Artifacts: artifacts,
	})
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "could not save release"})
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{
		"ok": true, "id": release.ID, "tag": release.Tag, "commit": release.Commit,
	})
}

func writeJSON(w http.ResponseWriter, status int, value any) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(value)
}

func (s *Server) repoCISettingsPost(w http.ResponseWriter, r *http.Request) {
	repo, perms, ok := s.repoFromPath(w, r)
	if !ok {
		return
	}
	if !perms.CanAdmin {
		s.renderError(w, r, http.StatusForbidden, "Repository administrator access required.")
		return
	}
	u := userFrom(r)
	provider := strings.ToLower(strings.TrimSpace(r.FormValue("provider")))
	switch provider {
	case "", "generic":
		provider = "generic"
	case "buildkite", "circleci", "jenkins":
	default:
		redirect(w, r, repoURL(repo)+"/settings", "", "Unsupported CI provider.")
		return
	}
	endpoint := strings.TrimSpace(r.FormValue("endpoint"))
	if endpoint != "" {
		parsed, err := url.Parse(endpoint)
		if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
			redirect(w, r, repoURL(repo)+"/settings", "", "CI endpoint must be an http or https URL.")
			return
		}
	}
	enabled := r.FormValue("enabled") == "on"
	if enabled && endpoint == "" {
		redirect(w, r, repoURL(repo)+"/settings", "", "An enabled CI configuration needs an endpoint.")
		return
	}
	existing, _ := s.data.GetCIConfig(r.Context(), repo.ID)
	token := strings.TrimSpace(r.FormValue("token"))
	if token == "" && existing != nil {
		token = existing.Token
	}
	if len(token) > 1000 {
		redirect(w, r, repoURL(repo)+"/settings", "", "CI token is too long.")
		return
	}
	reportToken := ""
	if existing != nil && r.FormValue("rotate_token") != "on" {
		reportToken = existing.ReportToken
	}
	if reportToken == "" {
		reportToken, _ = auth.RandomToken(32)
	}
	config, err := s.data.UpsertCIConfig(r.Context(), &data.CIConfig{
		RepoID:      repo.ID,
		Provider:    provider,
		Endpoint:    endpoint,
		Token:       token,
		Project:     strings.TrimSpace(r.FormValue("project")),
		Enabled:     enabled,
		Required:    r.FormValue("required") == "on",
		ReportToken: reportToken,
	})
	if err != nil {
		redirect(w, r, repoURL(repo)+"/settings", "", "Could not save CI settings.")
		return
	}
	if u != nil {
		s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "ci.settings", repo.OwnerName+"/"+repo.Name+" "+config.Provider, r.UserAgent())
	}
	redirect(w, r, repoURL(repo)+"/settings", "CI settings saved.", "")
}

func (s *Server) ciConfigForRepo(ctx context.Context, repoID int64) (*data.CIConfig, error) {
	config, err := s.data.GetCIConfig(ctx, repoID)
	if errors.Is(err, data.ErrNotFound) {
		return nil, nil
	}
	return config, err
}

func (s *Server) allCIPassed(ctx context.Context, repoID int64, commit string) bool {
	if commit == "" {
		return false
	}
	runs, err := s.data.ListCIRuns(ctx, repoID, commit)
	if err != nil || len(runs) == 0 {
		return false
	}
	for _, run := range runs {
		if run.State != "passed" {
			return false
		}
	}
	return true
}