server.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package authmanagement
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "github.com/joeshaw/envdecode"
  8. "github.com/bufbuild/connect-go"
  9. otelconnect "github.com/bufbuild/connect-opentelemetry-go"
  10. "github.com/porter-dev/api-contracts/generated/go/porter/v1/porterv1connect"
  11. "golang.org/x/net/http2"
  12. "golang.org/x/net/http2/h2c"
  13. )
  14. // Config contains all configuration options for the AuthManagementService
  15. type Config struct {
  16. // Port is the port that the AuthManagementService listens on
  17. Port int `env:"AUTH_MANAGEMENT_SERVICE_PORT,default=8090"`
  18. // TokenGeneratorSecret is the secret used to generate JWT tokens
  19. TokenGeneratorSecret string `env:"TOKEN_GENERATOR_SECRET,default=secret"`
  20. }
  21. // AuthManagementService stores the service config and implements the gRPC server's interface
  22. type AuthManagementService struct {
  23. Config Config
  24. }
  25. // NewService loads the authmanagement.Config from the environment and returns an initialized AuthManagementService
  26. func NewService() (AuthManagementService, error) {
  27. var server AuthManagementService
  28. var config Config
  29. if err := envdecode.StrictDecode(&config); err != nil {
  30. return server, fmt.Errorf("Failed to decode server conf: %s", err)
  31. }
  32. server.Config = config
  33. return server, nil
  34. }
  35. // ListenAndServe starts the AuthManagementService
  36. func (a AuthManagementService) ListenAndServe(ctx context.Context) error {
  37. ctx, cancel := context.WithCancel(ctx)
  38. defer cancel()
  39. mux := http.NewServeMux()
  40. mux.Handle(porterv1connect.NewAuthManagementServiceHandler(a,
  41. connect.WithInterceptors(
  42. otelconnect.NewInterceptor(otelconnect.WithTrustRemote()),
  43. ),
  44. ))
  45. srv := &http.Server{
  46. Addr: fmt.Sprintf("0.0.0.0:%d", a.Config.Port),
  47. ReadTimeout: 5 * time.Second,
  48. // TODO: remove this. Use h2c so we can serve HTTP/2 without TLS.
  49. Handler: h2c.NewHandler(mux, &http2.Server{}),
  50. }
  51. defer srv.Shutdown(ctx) // nolint:errcheck
  52. errChan := make(chan error)
  53. go func() {
  54. err := srv.ListenAndServe()
  55. if err != nil {
  56. errChan <- err
  57. }
  58. }()
  59. select {
  60. case err := <-errChan:
  61. return err
  62. case <-ctx.Done():
  63. }
  64. return nil
  65. }