Commit a809457

mo khan <mo@mokhan.ca>
2022-04-22 20:51:16
embed insecure private key in main package
1 parent fb04519
Changed files (4)
pkg/web/templates/insecure.pem → cmd/server/insecure.pem
File renamed without changes
cmd/server/main.go
@@ -1,6 +1,7 @@
 package main
 
 import (
+	_ "embed"
 	"log"
 	"net/http"
 	"os"
@@ -8,6 +9,9 @@ import (
 	"mokhan.ca/xlgmokha/oauth/pkg/web"
 )
 
+//go:embed insecure.pem
+var privateKey []byte
+
 func main() {
 	log.Println("Starting server, listening on port 8282.")
 	issuer, ok := os.LookupEnv("ISSUER")
@@ -16,7 +20,7 @@ func main() {
 	}
 	server := &http.Server{
 		Addr:         ":8282",
-		Handler:      web.NewHandler(issuer),
+		Handler:      web.NewHandler(issuer, privateKey),
 		ReadTimeout:  0,
 		WriteTimeout: 0,
 		IdleTimeout:  0,
pkg/web/http_mux.go
@@ -1,53 +1,17 @@
 package web
 
 import (
-	_ "embed"
 	"log"
 	"net/http"
-	"time"
-
-	"github.com/golang-jwt/jwt"
-	"github.com/hashicorp/uuid"
 )
 
-//go:embed templates/insecure.pem
-var privateKey string
-
-var (
-	tokens = map[string]string{}
-)
-
-type IdTokenFactory func(clientId string) string
-
-func (h *HttpContext) createIdToken(clientId string) string {
-	now := time.Now()
-	if clientId == "" {
-		clientId = "clientId"
-	}
-	expiresAt := now.Add(time.Hour * time.Duration(1))
-	idToken := jwt.NewWithClaims(jwt.SigningMethodRS256, &jwt.StandardClaims{
-		Issuer:    h.issuer,
-		Subject:   "1",
-		Audience:  clientId,
-		ExpiresAt: expiresAt.Unix(),
-		NotBefore: now.Unix(),
-		IssuedAt:  now.Unix(),
-		Id:        uuid.GenerateUUID(),
-	})
-
-	key, _ := jwt.ParseRSAPrivateKeyFromPEM(h.keyData)
-	signedIdToken, _ := idToken.SignedString(key)
-	return signedIdToken
-}
-
 type HttpContext struct {
 	issuer  string
 	keyData []byte
 	log     *log.Logger
 }
 
-func NewHandler(issuer string) http.Handler {
-	keyData := []byte(privateKey)
+func NewHandler(issuer string, keyData []byte) http.Handler {
 	h := &HttpContext{
 		issuer:  issuer,
 		keyData: keyData,
pkg/web/token.go
@@ -3,6 +3,14 @@ package web
 import (
 	"fmt"
 	"net/http"
+	"time"
+
+	"github.com/golang-jwt/jwt"
+	"github.com/hashicorp/uuid"
+)
+
+var (
+	tokens = map[string]string{}
 )
 
 type TokenRequest struct {
@@ -46,3 +54,24 @@ func (h *HttpContext) Token(w http.ResponseWriter, r *http.Request) {
 		}
 	}
 }
+
+func (h *HttpContext) createIdToken(clientId string) string {
+	now := time.Now()
+	if clientId == "" {
+		clientId = "clientId"
+	}
+	expiresAt := now.Add(time.Hour * time.Duration(1))
+	idToken := jwt.NewWithClaims(jwt.SigningMethodRS256, &jwt.StandardClaims{
+		Issuer:    h.issuer,
+		Subject:   "1",
+		Audience:  clientId,
+		ExpiresAt: expiresAt.Unix(),
+		NotBefore: now.Unix(),
+		IssuedAt:  now.Unix(),
+		Id:        uuid.GenerateUUID(),
+	})
+
+	key, _ := jwt.ParseRSAPrivateKeyFromPEM(h.keyData)
+	signedIdToken, _ := idToken.SignedString(key)
+	return signedIdToken
+}