main.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "time"
  8. "github.com/smallstep/certificates/ca"
  9. )
  10. func main() {
  11. if len(os.Args) != 2 {
  12. fmt.Fprintf(os.Stderr, "Usage: %s <token>\n", os.Args[0])
  13. os.Exit(1)
  14. }
  15. token := os.Args[1]
  16. // make sure to cancel the renew goroutine
  17. ctx, cancel := context.WithCancel(context.Background())
  18. defer cancel()
  19. srv, err := ca.BootstrapServer(ctx, token, &http.Server{
  20. Addr: ":8443",
  21. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  22. name := "nobody"
  23. issuer := "none"
  24. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  25. name = r.TLS.PeerCertificates[0].Subject.CommonName
  26. issuer = r.TLS.PeerCertificates[len(r.TLS.PeerCertificates)-1].Issuer.CommonName
  27. }
  28. w.Write([]byte(fmt.Sprintf("Hello %s (cert issued by '%s') at %s", name, issuer, time.Now().UTC())))
  29. }),
  30. }, ca.AddFederationToRootCAs(), ListTrustedRoots())
  31. if err != nil {
  32. panic(err)
  33. }
  34. fmt.Println("Listening on :8443 ...")
  35. if err := srv.ListenAndServeTLS("", ""); err != nil {
  36. panic(err)
  37. }
  38. }
  39. // ListTrustedRoots prints list of trusted roots for illustration purposes
  40. func ListTrustedRoots() ca.TLSOption {
  41. fn := func(ctx *ca.TLSOptionCtx) error {
  42. certs, err := ctx.Client.Federation()
  43. if err != nil {
  44. return err
  45. }
  46. roots, err := ctx.Client.Roots()
  47. if err != nil {
  48. return err
  49. }
  50. if len(certs.Certificates) > len(roots.Certificates) {
  51. fmt.Println("Server is using federated root certificates")
  52. }
  53. for _, cert := range certs.Certificates {
  54. fmt.Printf("Accepting certs anchored in %s\n", cert.Certificate.Subject)
  55. }
  56. return nil
  57. }
  58. return func(ctx *ca.TLSOptionCtx) error {
  59. ctx.OnRenewFunc = append(ctx.OnRenewFunc, fn)
  60. return fn(ctx)
  61. }
  62. }