Home

jsonnetpecker @76f1583259e585a41ba8552e7501aaba50281530 - refs - log -
-
https://git.jolheiser.com/jsonnetpecker.git
Woodpecker config service for jsonnet
jsonnetpecker / main.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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package main

import (
	"bytes"
	"crypto/ed25519"
	"crypto/x509"
	"encoding/json"
	"encoding/pem"
	"errors"
	"flag"
	"fmt"
	"log/slog"
	"net/http"
	"os"
	"strings"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/google/go-jsonnet"
	"github.com/peterbourgon/ff/v3"
	"github.com/peterbourgon/ff/v3/ffyaml"
	"github.com/yaronf/httpsign"
	"gopkg.in/yaml.v3"
)

type args struct {
	port       int
	pubKey     string
	pubKeyFile string

	logLevel slog.Level
	logJSON  bool
}

const magicKey = "woodpcecker-ci-extensions"

func maine() error {
	var args args
	fs := flag.NewFlagSet("jsonnetpecker", flag.ExitOnError)
	fs.String("config", ".config.yaml", "Path to config file")
	fs.IntVar(&args.port, "port", args.port, "Port to listen on")
	fs.IntVar(&args.port, "p", args.port, "--port")
	fs.StringVar(&args.pubKey, "public-key", args.pubKey, "Woodpecker public key for verification")
	fs.StringVar(&args.pubKey, "k", args.pubKey, "--public-key")
	fs.StringVar(&args.pubKeyFile, "public-key-file", args.pubKeyFile, "Path to file containing woodpecker public key for verification")
	fs.StringVar(&args.pubKeyFile, "K", args.pubKeyFile, "--public-key-file")
	logLevelFunc := func(s string) error {
		switch strings.ToLower(s) {
		case "debug":
			args.logLevel = slog.LevelDebug
		case "info":
			args.logLevel = slog.LevelInfo
		case "warn", "warning":
			args.logLevel = slog.LevelWarn
		case "error":
			args.logLevel = slog.LevelError
		default:
			return fmt.Errorf("unknown log level %q: [debug, info, warn, error]", s)
		}
		return nil
	}
	fs.Func("log-level", "Log level", logLevelFunc)
	fs.Func("l", "--log-level", logLevelFunc)
	fs.BoolVar(&args.logJSON, "json", args.logJSON, "JSON logging")
	fs.BoolVar(&args.logJSON, "j", args.logJSON, "--json")
	if err := ff.Parse(fs, os.Args[1:],
		ff.WithConfigFileFlag("config"),
		ff.WithAllowMissingConfigFile(true),
		ff.WithConfigFileParser(ffyaml.Parser),
		ff.WithEnvVarPrefix("JSONNETPECKER"),
	); err != nil {
		return err
	}

	if args.pubKeyFile != "" {
		data, err := os.ReadFile(args.pubKeyFile)
		if err != nil {
			return err
		}
		args.pubKey = string(bytes.TrimSpace(data))
	}

	pubKey, err := publicKey(args.pubKey)
	if err != nil {
		return err
	}

	addr := fmt.Sprintf(":%d", args.port)
	fmt.Printf("Listening at http://localhost%s\n", addr)
	return http.ListenAndServe(addr, mux(pubKey))
}

func mux(pubKey ed25519.PublicKey) http.Handler {
	mux := chi.NewMux()

	mux.Use(middleware.Logger)
	mux.Use(middleware.Recoverer)

	mux.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`send me some jsonnet`))
	})
	mux.With(verifyMiddleware(pubKey)).Post("/", func(w http.ResponseWriter, r *http.Request) {
		var req Request
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			w.WriteHeader(http.StatusBadRequest)
			json.NewEncoder(w).Encode(map[string]string{"error": "could not decode JSON"})
			return
		}

		configs := make([]Config, 0, len(req.Configs))
		for _, cfg := range req.Configs {
			if strings.HasSuffix(cfg.Name, "jsonnet") {
				vm := jsonnet.MakeVM()
				jsonData, err := vm.EvaluateAnonymousSnippet(cfg.Name, cfg.Data)
				if err != nil {
					slog.Error("could not evaluate jsonnet", slog.Any("err", err))
					continue
				}
				var data map[string]any
				if err := json.Unmarshal([]byte(jsonData), &data); err != nil {
					slog.Error("could not unmarshal jsonnet into intermediary map", slog.Any("err", err))
					continue
				}
				yamlData, err := yaml.Marshal(data)
				if err != nil {
					slog.Error("could not marshal YAML", slog.Any("err", err))
					continue
				}
				cfg.Data = string(yamlData)
			}
			configs = append(configs, cfg)
		}
		json.NewEncoder(w).Encode(Request{Configs: configs})
	})

	return mux
}

func publicKey(raw string) (ed25519.PublicKey, error) {
	pemblock, _ := pem.Decode([]byte(raw))
	if pemblock == nil {
		return nil, errors.New("failed to decode PEM block")
	}

	b, err := x509.ParsePKIXPublicKey(pemblock.Bytes)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse public key file: %w", err)
	}

	pubKey, ok := b.(ed25519.PublicKey)
	if !ok {
		return nil, errors.New("Failed to parse public key file")
	}

	return pubKey, nil
}

func verify(pubKey ed25519.PublicKey, r *http.Request) error {
	verifier, err := httpsign.NewEd25519Verifier(pubKey, httpsign.NewVerifyConfig(), httpsign.Headers("@request-target", "content-digest"))
	if err != nil {
		return fmt.Errorf("could not create new http signing verifier: %w", err)
	}

	err = httpsign.VerifyRequest(magicKey, *verifier, r)
	if err != nil {
		return fmt.Errorf("could not verify request: %w", err)
	}

	return nil
}

func verifyMiddleware(pubKey ed25519.PublicKey) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if err := verify(pubKey, r); err != nil {
				w.WriteHeader(http.StatusUnauthorized)
				json.NewEncoder(w).Encode(map[string]string{"error": "Failed to verify request"})
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}

type Request struct {
	Configs []Config `json:"configs"`
}

type Config struct {
	Name string `json:"name"`
	Data string `json:"data"`
}

func main() {
	if err := maine(); err != nil {
		panic(err)
	}
}