-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
169 lines (140 loc) · 4.82 KB
/
main.go
File metadata and controls
169 lines (140 loc) · 4.82 KB
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
package main
import (
"context"
"embed"
"fmt"
"html/template"
"log"
"net/http"
"regexp"
"runtime/debug"
"strings"
"github.com/UnitVectorY-Labs/lockboxkms/internal/config"
"github.com/UnitVectorY-Labs/lockboxkms/internal/kms"
)
// Version is the application version, injected at build time via ldflags
var Version = "dev"
//go:embed templates/*
var templatesFS embed.FS
const (
maxKeyNameLength = 63
maxPlaintextSize = 64 * 1024 // 64 KiB
)
func main() {
// Set the build version from the build info if not set by the build system
if Version == "dev" || Version == "" {
if bi, ok := debug.ReadBuildInfo(); ok {
if bi.Main.Version != "" && bi.Main.Version != "(devel)" {
Version = bi.Main.Version
}
}
}
// Load configuration
cfg := config.LoadConfig()
if cfg.ProjectID == "" {
log.Fatal("GOOGLE_CLOUD_PROJECT environment variable must be set")
}
// Initialize KMS client
ctx := context.Background()
kmsClient, err := kms.NewClient(ctx, kms.Config{
ProjectID: cfg.ProjectID,
Location: cfg.Location,
KeyRing: cfg.KeyRing,
})
if err != nil {
log.Fatalf("Failed to initialize KMS client: %v", err)
}
defer kmsClient.Close()
// Verify essential configurations
if cfg.ProjectID == "" || cfg.KeyRing == "" {
log.Fatal("GOOGLE_CLOUD_PROJECT and KMS_KEY_RING environment variables must be set")
}
// Regular expression for validating key names
keyNameRegex := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
log.Printf("Starting lockboxkms version %s", Version)
// Load the HTML template from embedded filesystem with version function
tpl := template.Must(template.New("index.html").Funcs(template.FuncMap{
"version": func() string { return Version },
}).ParseFS(templatesFS, "templates/index.html"))
// Set up HTTP handlers
http.HandleFunc("/", getHomeHandler(cfg, tpl))
http.HandleFunc("/keys", getKeysHandler(kmsClient))
http.HandleFunc("/encrypt", encryptHandler(cfg, kmsClient, keyNameRegex))
// Start the server
log.Printf("Server starting on port %s", cfg.Port)
if err := http.ListenAndServe(":"+cfg.Port, nil); err != nil {
log.Fatalf("Could not start server: %v", err)
}
}
// serveHome renders the main HTML page
func getHomeHandler(cfg config.Config, tpl *template.Template) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
err := tpl.Execute(w, cfg)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
log.Printf("Template execution error: %v", err)
}
}
}
// getKeysHandler returns an HTTP handler function for listing keys
func getKeysHandler(client *kms.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
keys, err := client.ListKeys(context.Background())
if err != nil {
http.Error(w, "Failed to list keys", http.StatusInternalServerError)
log.Printf("ListKeys error: %v", err)
return
}
// Generate HTML options for the dropdown
var options strings.Builder
options.WriteString("<option value=\"\" disabled selected>Select key</option>")
for name, shortName := range keys {
options.WriteString(fmt.Sprintf("<option value=\"%s\">%s</option>", name, shortName))
}
// Return the options as HTML fragment
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(options.String()))
}
}
// encryptHandler returns an HTTP handler function for encrypting text
func encryptHandler(cfg config.Config, client *kms.Client, keyNameRegex *regexp.Regexp) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
keyName := r.FormValue("key")
plaintext := r.FormValue("text")
if keyName == "" || plaintext == "" {
http.Error(w, "Key and text are required", http.StatusBadRequest)
return
}
expectedPrefix := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/", cfg.ProjectID, cfg.Location, cfg.KeyRing)
if !strings.HasPrefix(keyName, expectedPrefix) {
http.Error(w, "Invalid keyName format", http.StatusBadRequest)
return
}
shortName := keyName[strings.LastIndex(keyName, "/")+1:]
if !keyNameRegex.MatchString(shortName) {
http.Error(w, "Invalid keyName format", http.StatusBadRequest)
return
}
if len(shortName) > maxKeyNameLength {
http.Error(w, fmt.Sprintf("keyName exceeds maximum length of %d characters", maxKeyNameLength), http.StatusBadRequest)
return
}
if len(plaintext) >= maxPlaintextSize {
http.Error(w, fmt.Sprintf("plaintext exceeds maximum size of %d bytes", maxPlaintextSize), http.StatusBadRequest)
return
}
encryptedText, err := client.Encrypt(context.Background(), keyName, plaintext)
if err != nil {
http.Error(w, "Encryption failed", http.StatusInternalServerError)
log.Printf("Encryption error: %v", err)
return
}
// Return the encrypted text
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(encryptedText))
}
}