From 95a63133de5444715ea9264b8066c65e5a6f0ac1 Mon Sep 17 00:00:00 2001 From: Kelvin Ly Date: Sun, 25 Aug 2024 02:11:47 -0400 Subject: [PATCH] Add octoprint proxy stub --- main.go | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index ace7d4c..0286253 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "context" "crypto/hmac" "crypto/sha1" + "crypto/sha256" "encoding/hex" "flag" "fmt" @@ -140,8 +141,32 @@ func main() { log.Println("server terminated") } +type auth struct { + username, password []byte +} + +func readAuth() []auth { + ret := make([]auth, 0) + b, err := os.ReadFile("auth_secret") + if err != nil { + log.Printf("[ERR] auth keys not found, authentication will not work!") + return ret + } + lines := bytes.Split(b, []byte("\n")) + for _, l := range lines { + parts := bytes.Split(l, []byte(",")) + if len(parts) == 2 { + user := sha256.Sum256(parts[0]) + password := sha256.Sum256(parts[1]) + ret = append(ret, auth{user[:], password[:]}) + } + } + + return ret +} + func readWebhookKey() []byte { - b, err := ioutil.ReadFile("webhook_secret") + b, err := os.ReadFile("webhook_secret") if err != nil { log.Printf("[ERR] webhook key not found, webhook updates will not work!") return nil @@ -186,6 +211,38 @@ func startServer(srv *http.Server) { } serveMux.Handle("shrooms."+DOMAIN_NAME+"/", httputil.NewSingleHostReverseProxy(shroomsUrl)) + octoUrl, err := url.Parse("http://localhost:9000") + if err != nil { + log.Fatalf("unable to parse reverse proxy path: %v", err) + return + } + + auths := readAuth() + + octoProxy := httputil.NewSingleHostReverseProxy(octoUrl) + serveMux.HandleFunc("octo."+DOMAIN_NAME+"/", func(w http.ResponseWriter, r *http.Request) { + username, password, ok := r.BasicAuth() + if ok { + userHash := sha256.Sum256([]byte(username)) + passwordHash := sha256.Sum256([]byte(password)) + match := false + for _, a := range auths { + userMatch := bytes.Compare(userHash[:], a.username) + passwordMatch := bytes.Compare(passwordHash[:], a.password) + if userMatch == 0 && passwordMatch == 0 { + match = true + } + } + + if match { + octoProxy.ServeHTTP(w, r) + return + } + } + w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8"`) + http.Error(w, "Unauthorized", http.StatusUnauthorized) + }) + serveMux.HandleFunc("/", rootHandler) //serveMux.Handle("/certbot/", http.StripPrefix("/certbot/", http.FileServer(http.Dir("./certbot-tmp")))) serveMux.Handle("/gfm/", http.StripPrefix("/gfm", http.FileServer(gfmstyle.Assets)))