package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "log" "net/http" "net/url" "os" "strconv" "git.coolaj86.com/coolaj86/go-mockid/mockid" _ "github.com/joho/godotenv/autoload" ) func main() { done := make(chan bool) var port int var host string portFlag := flag.Int("port", 0, "Port on which the HTTP server should run") urlFlag := flag.String("url", "", "Outward-facing address, such as https://example.com") prefixFlag := flag.String("jwkspath", "", "The path to the JWKs storage directory") flag.Parse() if nil != portFlag && *portFlag > 0 { port = *portFlag } else { portStr := os.Getenv("PORT") port, _ = strconv.Atoi(portStr) } if port < 1 { fmt.Fprintf(os.Stderr, "You must specify --port or PORT\n") os.Exit(1) } jwkpath := "./default.jwk.json" jwkb, err := ioutil.ReadFile(jwkpath) if nil != err { panic(fmt.Errorf("read default jwk %v: %w", jwkpath, err)) return } jwkm := map[string]string{} err = json.Unmarshal(jwkb, &jwkm) if nil != err { // TODO delete the bad file? panic(fmt.Errorf("unmarshal jwk %v: %w", string(jwkb), err)) return } jwk := &mockid.PrivateJWK{ PublicJWK: mockid.PublicJWK{ Crv: jwkm["crv"], X: jwkm["x"], Y: jwkm["y"], }, D: jwkm["d"], } priv := mockid.ParseKey(jwk) if nil != urlFlag && "" != *urlFlag { host = *urlFlag } else { host = "http://localhost:" + strconv.Itoa(port) } var jwksPrefix string if nil != prefixFlag && "" != *prefixFlag { jwksPrefix = *prefixFlag } else { jwksPrefix = "public-jwks" } err = os.MkdirAll(jwksPrefix, 0755) if nil != err { fmt.Fprintf(os.Stderr, "couldn't write %q: %s", jwksPrefix, err) os.Exit(1) } mockid.Route(jwksPrefix, priv, jwk) fs := http.FileServer(http.Dir("./public")) http.Handle("/", fs) /* http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { log.Printf(r.Method, r.URL.Path) http.Error(w, "Not Found", http.StatusNotFound) }) */ fmt.Printf("Serving on port %d\n", port) go func() { log.Fatal(http.ListenAndServe(":"+strconv.Itoa(port), nil)) done <- true }() b, _ := json.Marshal(jwk) fmt.Printf("Private Key:\n\t%s\n", string(b)) b, _ = json.Marshal(jwk.PublicJWK) fmt.Printf("Public Key:\n\t%s\n", string(b)) protected, payload, token := mockid.GenToken(host, priv, url.Values{}) fmt.Printf("Protected (Header):\n\t%s\n", protected) fmt.Printf("Payload (Claims):\n\t%s\n", payload) fmt.Printf("Access Token:\n\t%s\n", token) <-done }