Auth token functionality
This commit is contained in:
@@ -19,6 +19,7 @@ type AppConfig struct {
|
|||||||
Daemon struct {
|
Daemon struct {
|
||||||
ListenAddress string `json:"listen_address"`
|
ListenAddress string `json:"listen_address"`
|
||||||
Port int `json:"port"`
|
Port int `json:"port"`
|
||||||
|
AuthToken string `json:"auth_token"`
|
||||||
} `json:"daemon"`
|
} `json:"daemon"`
|
||||||
|
|
||||||
Instances map[string]InstanceMetadata `json:"instances"`
|
Instances map[string]InstanceMetadata `json:"instances"`
|
||||||
|
|||||||
21
daemon.go
21
daemon.go
@@ -55,13 +55,32 @@ func StartDaemon(cfg *AppConfig, configPath string) error {
|
|||||||
corsWrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
corsWrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
|
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
|
||||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||||
|
|
||||||
if r.Method == http.MethodOptions {
|
if r.Method == http.MethodOptions {
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
authCheck := func() bool {
|
||||||
|
ds.RLock()
|
||||||
|
defer ds.RUnlock()
|
||||||
|
if ds.cfg.Daemon.AuthToken != "" {
|
||||||
|
authHeader := r.Header.Get("Authorization")
|
||||||
|
expected := "Bearer " + ds.cfg.Daemon.AuthToken
|
||||||
|
if authHeader != expected {
|
||||||
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}()
|
||||||
|
|
||||||
|
if !authCheck {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
mux.ServeHTTP(w, r)
|
mux.ServeHTTP(w, r)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
94
main.go
94
main.go
@@ -2,6 +2,8 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -13,6 +15,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"text/tabwriter"
|
"text/tabwriter"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -71,11 +74,42 @@ func main() {
|
|||||||
switch subCommand {
|
switch subCommand {
|
||||||
|
|
||||||
case "daemon":
|
case "daemon":
|
||||||
|
if isDaemonRunning(cfg) {
|
||||||
|
log.Fatalf("Cannot start daemon as it is already running. Stop it first (`pkill vssm`).")
|
||||||
|
}
|
||||||
|
|
||||||
fmt.Printf("Initializing VSSM Daemon [Config: %s]...\n", absConfigPath)
|
fmt.Printf("Initializing VSSM Daemon [Config: %s]...\n", absConfigPath)
|
||||||
if err := StartDaemon(cfg, absConfigPath); err != nil {
|
if err := StartDaemon(cfg, absConfigPath); err != nil {
|
||||||
log.Fatalf("Daemon runtime fatal error: %v", err)
|
log.Fatalf("Daemon runtime fatal error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case "generate-token":
|
||||||
|
if isDaemonRunning(cfg) {
|
||||||
|
log.Fatalf("Cannot generate a new token while the daemon is running. Stop it first (`pkill vssm`).")
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := generateToken()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to generate token: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
overwritten := cfg.Daemon.AuthToken != ""
|
||||||
|
cfg.Daemon.AuthToken = token
|
||||||
|
|
||||||
|
data, err := json.MarshalIndent(cfg, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to marshal config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.WriteFile(absConfigPath, data, 0644); err != nil {
|
||||||
|
log.Fatalf("Failed to write config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if overwritten {
|
||||||
|
fmt.Println("Existing auth token was overwritten.")
|
||||||
|
}
|
||||||
|
fmt.Printf("New auth token: %s\n", token)
|
||||||
|
|
||||||
case "create":
|
case "create":
|
||||||
if len(args) < 4 {
|
if len(args) < 4 {
|
||||||
log.Fatalf("Usage: vssm create <instance_name> <version> <port>")
|
log.Fatalf("Usage: vssm create <instance_name> <version> <port>")
|
||||||
@@ -156,6 +190,10 @@ func sendIPCRequest(cfg *AppConfig, method string, path string, body io.Reader)
|
|||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if cfg.Daemon.AuthToken != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+cfg.Daemon.AuthToken)
|
||||||
|
}
|
||||||
|
|
||||||
resp, err := http.DefaultClient.Do(req)
|
resp, err := http.DefaultClient.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("IPC connection failed. Is the VSSM daemon running? Error: %v", err)
|
log.Fatalf("IPC connection failed. Is the VSSM daemon running? Error: %v", err)
|
||||||
@@ -174,7 +212,17 @@ func sendIPCRequest(cfg *AppConfig, method string, path string, body io.Reader)
|
|||||||
func fetchAndPrintStatus(cfg *AppConfig) {
|
func fetchAndPrintStatus(cfg *AppConfig) {
|
||||||
listenAddress := cfg.Daemon.ListenAddress + ":" + strconv.Itoa(cfg.Daemon.Port)
|
listenAddress := cfg.Daemon.ListenAddress + ":" + strconv.Itoa(cfg.Daemon.Port)
|
||||||
targetUrl := fmt.Sprintf("http://%s/instances/list", listenAddress)
|
targetUrl := fmt.Sprintf("http://%s/instances/list", listenAddress)
|
||||||
resp, err := http.Get(targetUrl)
|
|
||||||
|
req, err := http.NewRequest("GET", targetUrl, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to construct status request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Daemon.AuthToken != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+cfg.Daemon.AuthToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("IPC connection failed. Is the VSSM daemon running? Error: %v", err)
|
log.Fatalf("IPC connection failed. Is the VSSM daemon running? Error: %v", err)
|
||||||
}
|
}
|
||||||
@@ -205,16 +253,44 @@ func fetchAndPrintStatus(cfg *AppConfig) {
|
|||||||
w.Flush()
|
w.Flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func generateToken() (string, error) {
|
||||||
|
bytes := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(bytes); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(bytes), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDaemonRunning(cfg *AppConfig) bool {
|
||||||
|
listenAddress := cfg.Daemon.ListenAddress + ":" + strconv.Itoa(cfg.Daemon.Port)
|
||||||
|
client := http.Client{Timeout: 500 * time.Millisecond}
|
||||||
|
resp, err := client.Get(fmt.Sprintf("http://%s/instances/list", listenAddress))
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func printUsage() {
|
func printUsage() {
|
||||||
fmt.Println("VintageStory Server Manager")
|
fmt.Println("VintageStory Server Manager")
|
||||||
fmt.Println("\nGlobal Options:")
|
fmt.Println("\nGlobal Options:")
|
||||||
fmt.Println(" --config <path> Explicitly target a non-default config structure file location")
|
|
||||||
|
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
|
||||||
|
fmt.Fprintln(w, " --config <path>\tExplicitly target a non-default config structure file location")
|
||||||
|
w.Flush()
|
||||||
|
|
||||||
fmt.Println("\nUsage Commands:")
|
fmt.Println("\nUsage Commands:")
|
||||||
fmt.Println(" vssm daemon Starts the daemon")
|
|
||||||
fmt.Println(" vssm create <name> <version> Creates the instance configuration and profile")
|
w = tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
|
||||||
fmt.Println(" vssm delete <name> <options> Deletes an instance profile, optionally deletes all files with the `--purge` flag")
|
fmt.Fprintln(w, " vssm daemon\tStarts the daemon")
|
||||||
fmt.Println(" vssm start <name> Launches an existing server instance from a stored profile")
|
fmt.Fprintln(w, " vssm generate-token\tGenerates a new auth token and stores it in the config")
|
||||||
fmt.Println(" vssm stop <name> Gracefully shuts down a server instance")
|
fmt.Fprintln(w, " vssm create <name> <version> <port>\tCreates the instance configuration and profile")
|
||||||
fmt.Println(" vssm cmd <name> \"<command>\" Sends a command to an instance")
|
fmt.Fprintln(w, " vssm delete <name> [--purge]\tDeletes an instance profile, optionally deleting all files")
|
||||||
fmt.Println(" vssm list Displays a list of all instances and their status")
|
fmt.Fprintln(w, " vssm start <name>\tLaunches an existing server instance from a stored profile")
|
||||||
|
fmt.Fprintln(w, " vssm stop <name>\tGracefully shuts down a server instance")
|
||||||
|
fmt.Fprintln(w, " vssm cmd <name> \"<command>\"\tSends a command to an instance")
|
||||||
|
fmt.Fprintln(w, " vssm modify <name> <new_name> <new_port>\tRenames an instance and/or changes its port")
|
||||||
|
fmt.Fprintln(w, " vssm list\tDisplays a list of all instances and their status")
|
||||||
|
w.Flush()
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user