Home

tailpolicy @main - refs - log -
-
https://git.jolheiser.com/tailpolicy.git
Tailscale policy editor on your tailnet
tailpolicy / index.go
- raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main

import (
	_ "embed"
	"errors"
	"html/template"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing/object"
	"github.com/google/go-jsonnet/formatter"
)

var (
	//go:embed static/index.tmpl
	index string
	tmpl  = template.Must(template.New("").Parse(index))
)

func Index(repoURL, repoLocation string) http.HandlerFunc {
	policyLocation := filepath.Join(repoLocation, "policy.jsonnet")
	policyOutLocation := filepath.Join(repoLocation, "policy.hujson")
	return func(w http.ResponseWriter, r *http.Request) {
		fn := func(w http.ResponseWriter, r *http.Request) error {
			repo, err := git.PlainOpen(repoLocation)
			if err != nil {
				return err
			}

			switch r.Method {
			case http.MethodGet:
				policyData, err := os.ReadFile(policyLocation)
				if err != nil {
					return err
				}
				content := string(policyData)
				return tmpl.Execute(w, map[any]any{
					"content": content,
					"error":   "",
				})
			case http.MethodPost:
				formContent := r.FormValue("content")
				formContent, err = formatter.Format("policy.jsonnet", formContent, formatter.DefaultOptions())
				if err != nil {
					return err
				}
				out, err := Transpile(strings.NewReader(formContent), repoURL)
				if err != nil {
					return err
				}
				if err := os.WriteFile(policyLocation, []byte(formContent), os.ModePerm); err != nil {
					return err
				}
				if err := os.WriteFile(policyOutLocation, []byte(out), os.ModePerm); err != nil {
					return err
				}
				tree, err := repo.Worktree()
				if err != nil {
					return err
				}
				if err := tree.AddGlob("policy.*"); err != nil {
					return err
				}
				if _, err := tree.Commit("update policy via tailpolicy", &git.CommitOptions{
					Author: &object.Signature{
						Name:  "tailpolicy",
						Email: "tailpolicy@example.com",
						When:  time.Now(),
					},
				}); err != nil {
					return err
				}
				if err := repo.Push(&git.PushOptions{}); err != nil {
					return err
				}
				http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
				return nil
			default:
				return errors.New("method not allowed")
			}
		}
		if err := fn(w, r); err != nil {
			log.Printf("error during processing: %v", err)
			tmpl.Execute(w, map[any]any{
				"content": "",
				"error":   err.Error(),
			})
		}
	}
}