Files
aeternalis/server/internal/gitops/worlds.go
T

188 lines
6.6 KiB
Go

package gitops
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"regexp"
"strings"
"time"
"go.yaml.in/yaml/v3"
)
type Config struct{ Repository, Branch, File, Token, PublicURL string }
type Client struct {
config Config
endpoint string
http *http.Client
}
var identifier = regexp.MustCompile(`^[a-z][a-z0-9-]{0,30}$`)
var seedPattern = regexp.MustCompile(`^[0-9]{1,15}$`)
func New(c Config) (*Client, error) {
if c.Repository == "" && c.Token == "" {
return nil, nil
}
u, err := url.Parse(c.Repository)
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return nil, errors.New("CONTROL_GITOPS_REPOSITORY must be an HTTPS repository URL without credentials")
}
parts := strings.Split(strings.Trim(strings.TrimSuffix(u.Path, ".git"), "/"), "/")
if len(parts) != 2 {
return nil, errors.New("GitOps repository must have owner/repository path")
}
for _, p := range parts {
if p == "." || p == ".." || !regexp.MustCompile(`^[A-Za-z0-9_.-]+$`).MatchString(p) {
return nil, errors.New("invalid repository path")
}
}
if c.Token == "" || c.Branch == "" || c.File == "" || path.Clean(c.File) != c.File || strings.HasPrefix(c.File, "/") || strings.Contains(c.File, "\\") || strings.HasPrefix(c.File, "..") || !strings.HasSuffix(c.File, ".yaml") {
return nil, errors.New("GitOps requires token, branch, and repository-relative .yaml file")
}
public, err := url.Parse(c.PublicURL)
if err != nil || public.Scheme != "https" || public.Host == "" || public.Path != "" || public.RawQuery != "" || public.User != nil {
return nil, errors.New("GitOps requires an HTTPS public origin")
}
endpoint := u.Scheme + "://" + u.Host + "/api/v1/repos/" + url.PathEscape(parts[0]) + "/" + url.PathEscape(parts[1]) + "/contents/"
for i, p := range strings.Split(c.File, "/") {
if i > 0 {
endpoint += "/"
}
endpoint += url.PathEscape(p)
}
return &Client{c, endpoint, &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
}
func (c *Client) request(ctx context.Context, method string, body any) ([]byte, int, error) {
var r io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, 0, err
}
r = bytes.NewReader(data)
}
u := c.endpoint
if method == http.MethodGet {
u += "?ref=" + url.QueryEscape(c.config.Branch)
}
req, err := http.NewRequestWithContext(ctx, method, u, r)
if err != nil {
return nil, 0, err
}
req.Header.Set("Authorization", "token "+c.config.Token)
req.Header.Set("Content-Type", "application/json")
res, err := c.http.Do(req)
if err != nil {
return nil, 0, errors.New("GitOps service unavailable")
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 2<<20))
if err != nil {
return nil, res.StatusCode, errors.New("GitOps response unavailable")
}
return raw, res.StatusCode, nil
}
func mapping(n *yaml.Node, key string) *yaml.Node {
if n.Kind != yaml.MappingNode {
return nil
}
for i := 0; i < len(n.Content); i += 2 {
if n.Content[i].Value == key {
return n.Content[i+1]
}
}
return nil
}
func scalar(v string) *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: v} }
// Only the worlds sequence is changed; image pins, comments and runtime settings
// stay intact. Gitea's content SHA rejects concurrent image-promotion overwrites.
func (c *Client) CreateWorld(ctx context.Context, id, seed string) (string, error) {
return c.CreateInstance(ctx, id, seed, "survival")
}
func (c *Client) CreateInstance(ctx context.Context, id, seed, kind string) (string, error) {
if kind != "hub" && kind != "survival" {
return "", errors.New("invalid world kind")
}
if !identifier.MatchString(id) || !seedPattern.MatchString(seed) {
return "", errors.New("invalid world ID or seed")
}
for attempt := 0; attempt < 3; attempt++ {
raw, status, err := c.request(ctx, http.MethodGet, nil)
if err != nil {
return "", err
}
if status != 200 {
return "", fmt.Errorf("GitOps values could not be read (HTTP %d)", status)
}
var file struct {
SHA string `json:"sha"`
Content string `json:"content"`
}
if json.Unmarshal(raw, &file) != nil || file.SHA == "" {
return "", errors.New("invalid GitOps file response")
}
data, err := base64.StdEncoding.DecodeString(strings.ReplaceAll(file.Content, "\n", ""))
if err != nil {
return "", errors.New("invalid GitOps file encoding")
}
var doc yaml.Node
if yaml.Unmarshal(data, &doc) != nil || len(doc.Content) != 1 {
return "", errors.New("invalid GitOps YAML")
}
root := doc.Content[0]
worlds := mapping(root, "worlds")
portal := mapping(root, "portal")
public, _ := url.Parse(c.config.PublicURL)
if portal == nil || mapping(portal, "host") == nil || mapping(portal, "host").Value != public.Host {
return "", errors.New("GitOps portal.host must match PUBLIC_URL before provisioning")
}
if worlds == nil || worlds.Kind != yaml.SequenceNode {
return "", errors.New("GitOps values must contain a worlds list")
}
for _, world := range worlds.Content {
key := mapping(world, "id")
if key != nil && key.Value == id {
existing := mapping(world, "seed")
existingKind := "survival"
if k := mapping(world, "kind"); k != nil {
existingKind = k.Value
}
if existing != nil && existing.Value == seed && existingKind == kind {
return "World definition already committed; waiting for ArgoCD readiness.", nil
}
return "", errors.New("world ID already exists with a different seed or kind")
}
}
if len(worlds.Content) >= 50 {
return "", errors.New("operator world limit reached (50)")
}
worlds.Content = append(worlds.Content, &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{scalar("id"), scalar(id), scalar("seed"), scalar(seed), scalar("host"), scalar(public.Host), scalar("kind"), scalar(kind)}})
encoded, err := yaml.Marshal(&doc)
if err != nil {
return "", err
}
body := map[string]string{"branch": c.config.Branch, "sha": file.SHA, "content": base64.StdEncoding.EncodeToString(encoded), "message": "Provision Aeternalis world " + id}
_, status, err = c.request(ctx, http.MethodPut, body)
if err != nil {
return "", err
}
if status == 200 || status == 201 {
return "World definition committed; waiting for ArgoCD readiness.", nil
}
if status != 409 && status != 422 {
return "", fmt.Errorf("GitOps commit rejected (HTTP %d)", status)
}
}
return "", errors.New("GitOps changed concurrently; retry the request")
}