Files
opencloud/ocis-pkg/service/http/service.go
Ralf Haferkamp b24d126b30 Introduce TLS Settings for go-micro based http services
TLS for the services can be configure by setting the "OCIS_HTTP_TLS_ENABLED",
"OCIS_HTTP_TLS_CERTIFICATE" and "OCIS_HTTP_TLS_KEY" environment variables.
Currently the ocis proxy is this only service that directly accesses backend
services. It determines whether to use TLS or not by looking a the new registry
metadata "use_tls". As specific CA Cert for certificate verification
can be set with the "PROXY_HTTPS_CACERT" environment variable.
2022-11-03 11:58:53 +01:00

76 lines
2.2 KiB
Go

package http
import (
"crypto/tls"
"fmt"
"strings"
"time"
"github.com/owncloud/ocis/v2/ocis-pkg/broker"
"github.com/owncloud/ocis/v2/ocis-pkg/registry"
mhttps "github.com/go-micro/plugins/v4/server/http"
ociscrypto "github.com/owncloud/ocis/v2/ocis-pkg/crypto"
"go-micro.dev/v4"
"go-micro.dev/v4/server"
)
// Service simply wraps the go-micro web service.
type Service struct {
micro.Service
}
// NewService initializes a new http service.
func NewService(opts ...Option) (Service, error) {
noopBroker := broker.NoOp{}
sopts := newOptions(opts...)
var mServer server.Server
if sopts.TLSConfig.Enabled {
var cert tls.Certificate
var err error
if sopts.TLSConfig.Cert != "" {
cert, err = tls.LoadX509KeyPair(sopts.TLSConfig.Cert, sopts.TLSConfig.Key)
if err != nil {
sopts.Logger.Error().Err(err).
Str("cert", sopts.TLSConfig.Cert).
Str("key", sopts.TLSConfig.Key).
Msg("error loading server certifcate and key")
return Service{}, fmt.Errorf("error loading server certificate and key: %w", err)
}
} else {
// Generate a self-signed server certificate on the fly. This requires the clients
// to connect with InsecureSkipVerify.
sopts.Logger.Warn().Str("address", sopts.Address).
Msg("No server certificate configured. Generating a temporary self-signed certificate")
cert, err = ociscrypto.GenTempCertForAddr(sopts.Address)
if err != nil {
return Service{}, fmt.Errorf("error creating temporary self-signed certificate: %w", err)
}
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
}
mServer = mhttps.NewServer(server.TLSConfig(tlsConfig))
} else {
mServer = mhttps.NewServer()
}
wopts := []micro.Option{
micro.Server(mServer),
micro.Broker(noopBroker),
micro.Address(sopts.Address),
micro.Name(strings.Join([]string{sopts.Namespace, sopts.Name}, ".")),
micro.Version(sopts.Version),
micro.Context(sopts.Context),
micro.Flags(sopts.Flags...),
micro.Registry(registry.GetRegistry()),
micro.RegisterTTL(time.Second * 30),
micro.RegisterInterval(time.Second * 10),
}
if sopts.TLSConfig.Enabled {
wopts = append(wopts, micro.Metadata(map[string]string{"use_tls": "true"}))
}
return Service{micro.NewService(wopts...)}, nil
}