From 76e5d8e77c1636d2cadbb48cb6176d8231aa69bf Mon Sep 17 00:00:00 2001
From: Moritz Marquardt <git@momar.de>
Date: Thu, 2 Dec 2021 19:12:45 +0100
Subject: [PATCH] Add TODOs

---
 certificates.go         | 9 ++++++---
 handler.go              | 3 +++
 haproxy-sni/haproxy.cfg | 1 +
 main.go                 | 4 +++-
 4 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/certificates.go b/certificates.go
index db51020..73b4793 100644
--- a/certificates.go
+++ b/certificates.go
@@ -130,6 +130,7 @@ var tlsConfig = &tls.Config{
 	},
 }
 
+// TODO: clean up & move to init
 var keyCache = mcache.New()
 var keyDatabase, keyDatabaseErr = pogreb.Open("key-database.pogreb", &pogreb.Options{
 	BackgroundSyncInterval:       30 * time.Second,
@@ -218,6 +219,7 @@ func retrieveCertFromDB(sni []byte) (tls.Certificate, bool) {
 		panic(err)
 	}
 
+	// TODO: document & put into own function
 	if !bytes.Equal(sni, MainDomainSuffix) {
 		tlsCertificate.Leaf, err = x509.ParseCertificate(tlsCertificate.Certificate[0])
 		if err != nil {
@@ -226,6 +228,7 @@ func retrieveCertFromDB(sni []byte) (tls.Certificate, bool) {
 
 		// renew certificates 7 days before they expire
 		if !tlsCertificate.Leaf.NotAfter.After(time.Now().Add(-7 * 24 * time.Hour)) {
+			// TODO: add ValidUntil to custom res struct
 			if res.CSR != nil && len(res.CSR) > 0 {
 				// CSR stores the time when the renewal shall be tried again
 				nextTryUnix, err := strconv.ParseInt(string(res.CSR), 10, 64)
@@ -315,9 +318,8 @@ func obtainCert(acmeClient *lego.Client, domains []string, renew *certificate.Re
 				PogrebPut(keyDatabase, []byte(name), renew)
 				return tlsCertificate, nil
 			}
-		} else {
-			return mockCert(domains[0], err.Error()), err
 		}
+		return mockCert(domains[0], err.Error()), err
 	}
 	log.Printf("Obtained certificate for %v", domains)
 
@@ -531,9 +533,10 @@ func setupCertificates() {
 		for {
 			err := keyDatabase.Sync()
 			if err != nil {
-				log.Printf("[ERROR] Syncinc key database failed: %s", err)
+				log.Printf("[ERROR] Syncing key database failed: %s", err)
 			}
 			time.Sleep(5 * time.Minute)
+			// TODO: graceful exit
 		}
 	})()
 	go (func() {
diff --git a/handler.go b/handler.go
index 626385d..4e9efbf 100644
--- a/handler.go
+++ b/handler.go
@@ -301,6 +301,7 @@ func returnErrorPage(ctx *fasthttp.RequestCtx, code int) {
 	if code == fasthttp.StatusFailedDependency {
 		message += " - target repo/branch doesn't exist or is private"
 	}
+	// TODO: use template engine?
 	ctx.Response.SetBody(bytes.ReplaceAll(NotFoundPage, []byte("%status"), []byte(strconv.Itoa(code)+" "+message)))
 }
 
@@ -351,6 +352,7 @@ func getBranchTimestamp(owner, repo, branch string) *branchTimestamp {
 	if branch == "" {
 		// Get default branch
 		var body = make([]byte, 0)
+		// TODO: use header for API key?
 		status, body, err := fasthttp.GetTimeout(body, string(GiteaRoot)+"/api/v1/repos/"+owner+"/"+repo+"?access_token="+GiteaApiToken, 5*time.Second)
 		if err != nil || status != 200 {
 			_ = branchTimestampCache.Set(owner+"/"+repo+"/"+branch, nil, DefaultBranchCacheTimeout)
@@ -509,6 +511,7 @@ func upstream(ctx *fasthttp.RequestCtx, targetOwner string, targetRepo string, t
 		if res.Header.ContentLength() > FileCacheSizeLimit {
 			err = res.BodyWriteTo(ctx.Response.BodyWriter())
 		} else {
+			// TODO: cache is half-empty if request is cancelled - does the ctx.Err() below do the trick?
 			err = res.BodyWriteTo(io.MultiWriter(ctx.Response.BodyWriter(), &cacheBodyWriter))
 		}
 	} else {
diff --git a/haproxy-sni/haproxy.cfg b/haproxy-sni/haproxy.cfg
index 869bae3..c8f3610 100644
--- a/haproxy-sni/haproxy.cfg
+++ b/haproxy-sni/haproxy.cfg
@@ -51,6 +51,7 @@ frontend https_sni_frontend
   ###################################################
   acl use_http_backend req.ssl_sni -i "codeberg.org"
   acl use_http_backend req.ssl_sni -i "join.codeberg.org"
+  # TODO: use this if no SNI exists
   use_backend https_termination_backend if use_http_backend
 
   ############################
diff --git a/main.go b/main.go
index 44cec0f..1a4cb65 100644
--- a/main.go
+++ b/main.go
@@ -71,6 +71,7 @@ var IndexPages = []string{
 
 // main sets up and starts the web server.
 func main() {
+	// TODO: CLI Library
 	if len(os.Args) > 1 && os.Args[1] == "--remove-certificate" {
 		if len(os.Args) < 2 {
 			println("--remove-certificate requires at least one domain as an argument")
@@ -105,7 +106,7 @@ func main() {
 
 	server := &fasthttp.Server{
 		Handler:                      compressedHandler,
-		DisablePreParseMultipartForm: false,
+		DisablePreParseMultipartForm: true,
 		MaxRequestBodySize:           0,
 		NoDefaultServerHeader:        true,
 		NoDefaultDate:                true,
@@ -151,6 +152,7 @@ func main() {
 }
 
 // envOr reads an environment variable and returns a default value if it's empty.
+// TODO: to helpers.go or use CLI framework
 func envOr(env string, or string) string {
 	if v := os.Getenv(env); v != "" {
 		return v