| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- package authmanagement
- import (
- "context"
- "fmt"
- "net/http"
- "time"
- "github.com/joeshaw/envdecode"
- "github.com/bufbuild/connect-go"
- otelconnect "github.com/bufbuild/connect-opentelemetry-go"
- "github.com/porter-dev/api-contracts/generated/go/porter/v1/porterv1connect"
- "golang.org/x/net/http2"
- "golang.org/x/net/http2/h2c"
- )
- // Config contains all configuration options for the AuthManagementService
- type Config struct {
- // Port is the port that the AuthManagementService listens on
- Port int `env:"AUTH_MANAGEMENT_SERVICE_PORT,default=8090"`
- // TokenGeneratorSecret is the secret used to generate JWT tokens
- TokenGeneratorSecret string `env:"TOKEN_GENERATOR_SECRET,default=secret"`
- }
- // AuthManagementService stores the service config and implements the gRPC server's interface
- type AuthManagementService struct {
- Config Config
- }
- // NewService loads the authmanagement.Config from the environment and returns an initialized AuthManagementService
- func NewService() (AuthManagementService, error) {
- var server AuthManagementService
- var config Config
- if err := envdecode.StrictDecode(&config); err != nil {
- return server, fmt.Errorf("Failed to decode server conf: %s", err)
- }
- server.Config = config
- return server, nil
- }
- // ListenAndServe starts the AuthManagementService
- func (a AuthManagementService) ListenAndServe(ctx context.Context) error {
- ctx, cancel := context.WithCancel(ctx)
- defer cancel()
- mux := http.NewServeMux()
- mux.Handle(porterv1connect.NewAuthManagementServiceHandler(a,
- connect.WithInterceptors(
- otelconnect.NewInterceptor(otelconnect.WithTrustRemote()),
- ),
- ))
- srv := &http.Server{
- Addr: fmt.Sprintf("0.0.0.0:%d", a.Config.Port),
- ReadTimeout: 5 * time.Second,
- // TODO: remove this. Use h2c so we can serve HTTP/2 without TLS.
- Handler: h2c.NewHandler(mux, &http2.Server{}),
- }
- defer srv.Shutdown(ctx) // nolint:errcheck
- errChan := make(chan error)
- go func() {
- err := srv.ListenAndServe()
- if err != nil {
- errChan <- err
- }
- }()
- select {
- case err := <-errChan:
- return err
- case <-ctx.Done():
- }
- return nil
- }
|