From eb3f8e956f25cda11aa2642a1c9efe9f9782847a Mon Sep 17 00:00:00 2001 From: Aleksandr Tarasov Date: Wed, 22 Nov 2023 15:30:19 +0300 Subject: [PATCH] Add TLS and static token authentication. Add kratos for managing app (#9) * Add TLS and static token authentication. Add kratos for managing app * fix registry image --- .github/workflows/release.yml | 1 + .gitignore | 4 + Makefile | 15 + README.md | 11 +- buf.gen.yaml | 4 +- cmd/main.go | 101 ++- docker-compose.dev.yml | 2 +- docker-compose.yml | 14 +- gen/pbuf-registry/v1/registry.pb.gw.go | 768 ----------------------- gen/pbuf-registry/v1/registry_http.pb.go | 356 +++++++++++ go.mod | 10 +- go.sum | 34 +- internal/config/config.go | 44 +- internal/config/config.yaml | 15 +- internal/data/common_test.go | 3 +- internal/data/registry.go | 26 +- internal/middleware/auth.go | 60 ++ internal/middleware/auth_test.go | 152 +++++ internal/middleware/config.go | 29 + internal/mocks/auth_middleware.go | 43 ++ internal/mocks/registry_repository.go | 2 +- internal/server/debug.go | 44 ++ internal/server/grpc.go | 62 ++ internal/server/http.go | 33 + internal/server/registry.go | 24 +- internal/server/registry_test.go | 2 +- pbuf.yaml | 5 +- scripts/cert-gen.sh | 17 + 28 files changed, 986 insertions(+), 895 deletions(-) delete mode 100644 gen/pbuf-registry/v1/registry.pb.gw.go create mode 100644 gen/pbuf-registry/v1/registry_http.pb.go create mode 100644 internal/middleware/auth.go create mode 100644 internal/middleware/auth_test.go create mode 100644 internal/middleware/config.go create mode 100644 internal/mocks/auth_middleware.go create mode 100644 internal/server/debug.go create mode 100644 internal/server/grpc.go create mode 100644 internal/server/http.go create mode 100755 scripts/cert-gen.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 19bdf19..8d87031 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,6 +4,7 @@ on: push: tags: - "v[0-9]+.[0-9]+.[0-9]+" + - "v[0-9]+.[0-9]+.[0-9]+-rc.[0-9]+" permissions: contents: write diff --git a/.gitignore b/.gitignore index 836e825..4c6ddbe 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ bin/ # Output of the go coverage tool, specifically when used with LiteIDE *.out +*.DS_store # Dependency directories (remove the comment below to include it) # vendor/ @@ -24,3 +25,6 @@ go.work # IDE .idea + +# SSL Certificates +gen/certs/ diff --git a/Makefile b/Makefile index f8dbeb6..a711818 100644 --- a/Makefile +++ b/Makefile @@ -72,6 +72,21 @@ run: stop: docker-compose -f docker-compose.dev.yml down +.PHONY: cert-gen +# generate cert +cert-gen: + ./scripts/cert-gen.sh + +.PHONY: run-prod +# run prod +run-prod: + docker-compose -f docker-compose.yml up --force-recreate -d + +.PHONY: stop-prod +# stop prod +stop-prod: + docker-compose -f docker-compose.yml down + # show help help: @echo '' diff --git a/README.md b/README.md index 50a4c8b..e6b22d3 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,14 @@ The registry solves this problem by providing a central place to store and manag #### Steps 1. Clone the repository -2. Run `docker-compose up -d` +2. Generate certificates with `make certs-gen` command (they will appear in `gen/certs` folder) or put your own certificates in the folder +3. Export `SERVER_STATIC_TOKEN` with static authorization token +4. Run `make run-prod` to start the registry +5. Run `make stop-prod` to stop the running registry + +#### Configuration + +The registry can be configured with environment variables that overrides values in the `config/config.yaml` file. For instance, to change the database DSN you can set `DATA_DATABASE_DSN` environment variable that is reflect to `data.database.dsn` yaml property. ### Helm Chart @@ -63,7 +70,7 @@ The registry provides a REST API (`:8080` port by default). You can find the swa #### gRPC -The registry provides a gRPC API (`:8081` port by default). You can find the protobuf definition [here](https://github.com/pbufio/pbuf-registry/blob/main/api/v1/registry.proto) +The registry provides a gRPC API (`:6777` port by default). You can find the protobuf definition [here](https://github.com/pbufio/pbuf-registry/blob/main/api/v1/registry.proto) ## Development and Contributing diff --git a/buf.gen.yaml b/buf.gen.yaml index 27f4425..ba5334a 100644 --- a/buf.gen.yaml +++ b/buf.gen.yaml @@ -6,8 +6,8 @@ plugins: - plugin: go-grpc out: gen opt: paths=source_relative - - plugin: grpc-gateway + - plugin: go-http out: gen - opt: paths=source_relative,generate_unbound_methods=true + opt: paths=source_relative - plugin: openapiv2 out: gen \ No newline at end of file diff --git a/cmd/main.go b/cmd/main.go index de4014b..d56c3c7 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,88 +2,57 @@ package main import ( "context" - "log" - "net" - "net/http" + "os" - "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" + "github.com/go-kratos/kratos/v2" + "github.com/go-kratos/kratos/v2/log" "github.com/jackc/pgx/v5/pgxpool" - v1 "github.com/pbufio/pbuf-registry/gen/pbuf-registry/v1" "github.com/pbufio/pbuf-registry/internal/config" "github.com/pbufio/pbuf-registry/internal/data" "github.com/pbufio/pbuf-registry/internal/server" - "google.golang.org/grpc" - "google.golang.org/grpc/reflection" ) -func startGRPCServer(address string, grpcServer *grpc.Server) error { - listen, err := net.Listen("tcp", address) - if err != nil { - return err - } - return grpcServer.Serve(listen) -} - -func startHTTPServer(address string, grpcServer *server.RegistryServer) error { - ctx := context.Background() - ctx, cancel := context.WithCancel(ctx) - defer cancel() - - mux := runtime.NewServeMux() - err := v1.RegisterRegistryHandlerServer(ctx, mux, grpcServer) - if err != nil { - return err - } - - return http.ListenAndServe(address, mux) -} - -func startDebugServer(address string) error { - // add /healthz endpoint - mux := runtime.NewServeMux() +// go build -ldflags "-X main.Version=x.y.z" +var ( + // Name is the name of the compiled software. + Name string + // Version is the version of the compiled software. + Version string - err := mux.HandlePath("GET", "/healthz", func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) { - w.WriteHeader(http.StatusOK) - }) - - if err != nil { - log.Fatalf("failed to register debug server: %v", err) - } - - return http.ListenAndServe(address, mux) -} + id, _ = os.Hostname() +) func main() { config.NewLoader().MustLoad() - grpcServer := grpc.NewServer() + logger := log.DefaultLogger + logHelper := log.NewHelper(logger) pool, err := pgxpool.New(context.Background(), config.Cfg.Data.Database.DSN) if err != nil { - log.Fatalf("failed to connect to database: %v", err) + logHelper.Errorf("failed to connect to database: %v", err) + return } - - registryRepository := data.NewRegistryRepository(pool) - registryServer := server.NewRegistryServer(registryRepository) - v1.RegisterRegistryServer(grpcServer, registryServer) - reflection.Register(grpcServer) - - go func() { - err := startGRPCServer(config.Cfg.Server.GRPC.Addr, grpcServer) - if err != nil { - log.Fatalf("failed to start grpc server: %v", err) - } - }() - - go func() { - err = startHTTPServer(config.Cfg.Server.HTTP.Addr, registryServer) - if err != nil { - log.Fatalf("failed to start http server: %v", err) - } - }() - - err = startDebugServer(config.Cfg.Server.Debug.Addr) + defer pool.Close() + + registryRepository := data.NewRegistryRepository(pool, logger) + registryServer := server.NewRegistryServer(registryRepository, logger) + + app := kratos.New( + kratos.ID(id), + kratos.Name(Name), + kratos.Version(Version), + kratos.Metadata(map[string]string{}), + kratos.Logger(logger), + kratos.Server( + server.NewGRPCServer(&config.Cfg.Server, registryServer, logger), + server.NewHTTPServer(&config.Cfg.Server, registryServer, logger), + server.NewDebugServer(&config.Cfg.Server, logger), + ), + ) + + err = app.Run() if err != nil { - log.Fatalf("failed to start debug server: %v", err) + logHelper.Errorf("failed to run application: %v", err) } } diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 20941d8..ba847ae 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -22,7 +22,7 @@ services: - db ports: - "8080:8080" - - "8081:8081" + - "6777:6777" - "8082:8082" healthcheck: test: wget -O - http://localhost:8082/healthz || exit 1 diff --git a/docker-compose.yml b/docker-compose.yml index b438d1d..7f2cc77 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,20 +17,30 @@ services: timeout: 10s retries: 5 pbuf-registry: - image: ghcr.io/pbufio/registry:v0.1.2 + image: ghcr.io/pbufio/registry:v0.3.0-rc.1 restart: always depends_on: - db ports: - "8080:8080" - - "8081:8081" + - "6777:6777" - "8082:8082" healthcheck: test: wget -O - http://localhost:8082/healthz || exit 1 interval: 5s timeout: 10s retries: 5 + volumes: + - ./gen/certs:/app/certs environment: DATA_DATABASE_DSN: "postgres://pbuf:pbuf@db:5432/pbuf_registry?sslmode=disable" + SERVER_GRPC_TLS_ENABLED: true + SERVER_GRPC_TLS_CERTFILE: /app/certs/server-cert.pem + SERVER_GRPC_TLS_KEYFILE: /app/certs/server-key.pem + SERVER_GRPC_AUTH_ENABLED: true + SERVER_GRPC_AUTH_TYPE: static-token + SERVER_HTTP_AUTH_ENABLED: true + SERVER_HTTP_AUTH_TYPE: static-token + SERVER_STATIC_TOKEN: ${SERVER_STATIC_TOKEN} command: > sh -c "/app/pbuf-migrations && /app/pbuf-registry" \ No newline at end of file diff --git a/gen/pbuf-registry/v1/registry.pb.gw.go b/gen/pbuf-registry/v1/registry.pb.gw.go deleted file mode 100644 index 07cd2e5..0000000 --- a/gen/pbuf-registry/v1/registry.pb.gw.go +++ /dev/null @@ -1,768 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: pbuf-registry/v1/registry.proto - -/* -Package v1 is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package v1 - -import ( - "context" - "io" - "net/http" - - "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" - "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" - "google.golang.org/protobuf/proto" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = metadata.Join - -var ( - filter_Registry_ListModules_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Registry_ListModules_0(ctx context.Context, marshaler runtime.Marshaler, client RegistryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ListModulesRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Registry_ListModules_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.ListModules(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Registry_ListModules_0(ctx context.Context, marshaler runtime.Marshaler, server RegistryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ListModulesRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Registry_ListModules_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.ListModules(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Registry_GetModule_0(ctx context.Context, marshaler runtime.Marshaler, client RegistryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq GetModuleRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.GetModule(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Registry_GetModule_0(ctx context.Context, marshaler runtime.Marshaler, server RegistryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq GetModuleRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.GetModule(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Registry_RegisterModule_0(ctx context.Context, marshaler runtime.Marshaler, client RegistryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq RegisterModuleRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.RegisterModule(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Registry_RegisterModule_0(ctx context.Context, marshaler runtime.Marshaler, server RegistryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq RegisterModuleRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.RegisterModule(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Registry_PullModule_0(ctx context.Context, marshaler runtime.Marshaler, client RegistryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq PullModuleRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.PullModule(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Registry_PullModule_0(ctx context.Context, marshaler runtime.Marshaler, server RegistryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq PullModuleRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.PullModule(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Registry_PushModule_0(ctx context.Context, marshaler runtime.Marshaler, client RegistryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq PushModuleRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.PushModule(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Registry_PushModule_0(ctx context.Context, marshaler runtime.Marshaler, server RegistryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq PushModuleRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.PushModule(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Registry_DeleteModule_0(ctx context.Context, marshaler runtime.Marshaler, client RegistryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq DeleteModuleRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.DeleteModule(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Registry_DeleteModule_0(ctx context.Context, marshaler runtime.Marshaler, server RegistryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq DeleteModuleRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.DeleteModule(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Registry_DeleteModuleTag_0(ctx context.Context, marshaler runtime.Marshaler, client RegistryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq DeleteModuleTagRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.DeleteModuleTag(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Registry_DeleteModuleTag_0(ctx context.Context, marshaler runtime.Marshaler, server RegistryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq DeleteModuleTagRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.DeleteModuleTag(ctx, &protoReq) - return msg, metadata, err - -} - -func request_Registry_GetModuleDependencies_0(ctx context.Context, marshaler runtime.Marshaler, client RegistryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq GetModuleDependenciesRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.GetModuleDependencies(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Registry_GetModuleDependencies_0(ctx context.Context, marshaler runtime.Marshaler, server RegistryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq GetModuleDependenciesRequest - var metadata runtime.ServerMetadata - - newReader, berr := utilities.IOReaderFactory(req.Body) - if berr != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr) - } - if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.GetModuleDependencies(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterRegistryHandlerServer registers the http handlers for service Registry to "mux". -// UnaryRPC :call RegistryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterRegistryHandlerFromEndpoint instead. -func RegisterRegistryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server RegistryServer) error { - - mux.Handle("GET", pattern_Registry_ListModules_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbufregistry.v1.Registry/ListModules", runtime.WithHTTPPathPattern("/v1/modules")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Registry_ListModules_0(annotatedContext, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_ListModules_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_GetModule_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbufregistry.v1.Registry/GetModule", runtime.WithHTTPPathPattern("/v1/modules/get")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Registry_GetModule_0(annotatedContext, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_GetModule_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_RegisterModule_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbufregistry.v1.Registry/RegisterModule", runtime.WithHTTPPathPattern("/v1/modules")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Registry_RegisterModule_0(annotatedContext, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_RegisterModule_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_PullModule_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbufregistry.v1.Registry/PullModule", runtime.WithHTTPPathPattern("/v1/modules/pull")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Registry_PullModule_0(annotatedContext, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_PullModule_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_PushModule_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbufregistry.v1.Registry/PushModule", runtime.WithHTTPPathPattern("/v1/modules/push")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Registry_PushModule_0(annotatedContext, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_PushModule_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_DeleteModule_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbufregistry.v1.Registry/DeleteModule", runtime.WithHTTPPathPattern("/v1/modules/delete")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Registry_DeleteModule_0(annotatedContext, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_DeleteModule_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_DeleteModuleTag_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbufregistry.v1.Registry/DeleteModuleTag", runtime.WithHTTPPathPattern("/v1/modules/tags/delete")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Registry_DeleteModuleTag_0(annotatedContext, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_DeleteModuleTag_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_GetModuleDependencies_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/pbufregistry.v1.Registry/GetModuleDependencies", runtime.WithHTTPPathPattern("/v1/modules/dependencies")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Registry_GetModuleDependencies_0(annotatedContext, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_GetModuleDependencies_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterRegistryHandlerFromEndpoint is same as RegisterRegistryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterRegistryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.DialContext(ctx, endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterRegistryHandler(ctx, mux, conn) -} - -// RegisterRegistryHandler registers the http handlers for service Registry to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterRegistryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterRegistryHandlerClient(ctx, mux, NewRegistryClient(conn)) -} - -// RegisterRegistryHandlerClient registers the http handlers for service Registry -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "RegistryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "RegistryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "RegistryClient" to call the correct interceptors. -func RegisterRegistryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client RegistryClient) error { - - mux.Handle("GET", pattern_Registry_ListModules_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pbufregistry.v1.Registry/ListModules", runtime.WithHTTPPathPattern("/v1/modules")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Registry_ListModules_0(annotatedContext, inboundMarshaler, client, req, pathParams) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_ListModules_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_GetModule_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pbufregistry.v1.Registry/GetModule", runtime.WithHTTPPathPattern("/v1/modules/get")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Registry_GetModule_0(annotatedContext, inboundMarshaler, client, req, pathParams) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_GetModule_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_RegisterModule_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pbufregistry.v1.Registry/RegisterModule", runtime.WithHTTPPathPattern("/v1/modules")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Registry_RegisterModule_0(annotatedContext, inboundMarshaler, client, req, pathParams) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_RegisterModule_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_PullModule_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pbufregistry.v1.Registry/PullModule", runtime.WithHTTPPathPattern("/v1/modules/pull")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Registry_PullModule_0(annotatedContext, inboundMarshaler, client, req, pathParams) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_PullModule_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_PushModule_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pbufregistry.v1.Registry/PushModule", runtime.WithHTTPPathPattern("/v1/modules/push")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Registry_PushModule_0(annotatedContext, inboundMarshaler, client, req, pathParams) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_PushModule_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_DeleteModule_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pbufregistry.v1.Registry/DeleteModule", runtime.WithHTTPPathPattern("/v1/modules/delete")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Registry_DeleteModule_0(annotatedContext, inboundMarshaler, client, req, pathParams) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_DeleteModule_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_DeleteModuleTag_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pbufregistry.v1.Registry/DeleteModuleTag", runtime.WithHTTPPathPattern("/v1/modules/tags/delete")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Registry_DeleteModuleTag_0(annotatedContext, inboundMarshaler, client, req, pathParams) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_DeleteModuleTag_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - mux.Handle("POST", pattern_Registry_GetModuleDependencies_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/pbufregistry.v1.Registry/GetModuleDependencies", runtime.WithHTTPPathPattern("/v1/modules/dependencies")) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Registry_GetModuleDependencies_0(annotatedContext, inboundMarshaler, client, req, pathParams) - annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) - if err != nil { - runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) - return - } - - forward_Registry_GetModuleDependencies_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Registry_ListModules_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "modules"}, "")) - - pattern_Registry_GetModule_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "modules", "get"}, "")) - - pattern_Registry_RegisterModule_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "modules"}, "")) - - pattern_Registry_PullModule_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "modules", "pull"}, "")) - - pattern_Registry_PushModule_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "modules", "push"}, "")) - - pattern_Registry_DeleteModule_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "modules", "delete"}, "")) - - pattern_Registry_DeleteModuleTag_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "modules", "tags", "delete"}, "")) - - pattern_Registry_GetModuleDependencies_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "modules", "dependencies"}, "")) -) - -var ( - forward_Registry_ListModules_0 = runtime.ForwardResponseMessage - - forward_Registry_GetModule_0 = runtime.ForwardResponseMessage - - forward_Registry_RegisterModule_0 = runtime.ForwardResponseMessage - - forward_Registry_PullModule_0 = runtime.ForwardResponseMessage - - forward_Registry_PushModule_0 = runtime.ForwardResponseMessage - - forward_Registry_DeleteModule_0 = runtime.ForwardResponseMessage - - forward_Registry_DeleteModuleTag_0 = runtime.ForwardResponseMessage - - forward_Registry_GetModuleDependencies_0 = runtime.ForwardResponseMessage -) diff --git a/gen/pbuf-registry/v1/registry_http.pb.go b/gen/pbuf-registry/v1/registry_http.pb.go new file mode 100644 index 0000000..5d924e6 --- /dev/null +++ b/gen/pbuf-registry/v1/registry_http.pb.go @@ -0,0 +1,356 @@ +// Code generated by protoc-gen-go-http. DO NOT EDIT. +// versions: +// - protoc-gen-go-http v2.7.1 +// - protoc (unknown) +// source: pbuf-registry/v1/registry.proto + +package v1 + +import ( + context "context" + http "github.com/go-kratos/kratos/v2/transport/http" + binding "github.com/go-kratos/kratos/v2/transport/http/binding" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the kratos package it is being compiled against. +var _ = new(context.Context) +var _ = binding.EncodeURL + +const _ = http.SupportPackageIsVersion1 + +const OperationRegistryDeleteModule = "/pbufregistry.v1.Registry/DeleteModule" +const OperationRegistryDeleteModuleTag = "/pbufregistry.v1.Registry/DeleteModuleTag" +const OperationRegistryGetModule = "/pbufregistry.v1.Registry/GetModule" +const OperationRegistryGetModuleDependencies = "/pbufregistry.v1.Registry/GetModuleDependencies" +const OperationRegistryListModules = "/pbufregistry.v1.Registry/ListModules" +const OperationRegistryPullModule = "/pbufregistry.v1.Registry/PullModule" +const OperationRegistryPushModule = "/pbufregistry.v1.Registry/PushModule" +const OperationRegistryRegisterModule = "/pbufregistry.v1.Registry/RegisterModule" + +type RegistryHTTPServer interface { + // DeleteModule Delete a module by name + DeleteModule(context.Context, *DeleteModuleRequest) (*DeleteModuleResponse, error) + // DeleteModuleTag Delete a specific module tag + DeleteModuleTag(context.Context, *DeleteModuleTagRequest) (*DeleteModuleTagResponse, error) + // GetModule Get a module by name + GetModule(context.Context, *GetModuleRequest) (*Module, error) + // GetModuleDependencies Get Module Dependencies + GetModuleDependencies(context.Context, *GetModuleDependenciesRequest) (*GetModuleDependenciesResponse, error) + // ListModules List all registered modules + ListModules(context.Context, *ListModulesRequest) (*ListModulesResponse, error) + // PullModule Pull a module tag + PullModule(context.Context, *PullModuleRequest) (*PullModuleResponse, error) + // PushModule Push a module + PushModule(context.Context, *PushModuleRequest) (*Module, error) + // RegisterModule Register a module + RegisterModule(context.Context, *RegisterModuleRequest) (*Module, error) +} + +func RegisterRegistryHTTPServer(s *http.Server, srv RegistryHTTPServer) { + r := s.Route("/") + r.GET("/v1/modules", _Registry_ListModules0_HTTP_Handler(srv)) + r.POST("/v1/modules/get", _Registry_GetModule0_HTTP_Handler(srv)) + r.POST("/v1/modules", _Registry_RegisterModule0_HTTP_Handler(srv)) + r.POST("/v1/modules/pull", _Registry_PullModule0_HTTP_Handler(srv)) + r.POST("/v1/modules/push", _Registry_PushModule0_HTTP_Handler(srv)) + r.POST("/v1/modules/delete", _Registry_DeleteModule0_HTTP_Handler(srv)) + r.POST("/v1/modules/tags/delete", _Registry_DeleteModuleTag0_HTTP_Handler(srv)) + r.POST("/v1/modules/dependencies", _Registry_GetModuleDependencies0_HTTP_Handler(srv)) +} + +func _Registry_ListModules0_HTTP_Handler(srv RegistryHTTPServer) func(ctx http.Context) error { + return func(ctx http.Context) error { + var in ListModulesRequest + if err := ctx.BindQuery(&in); err != nil { + return err + } + http.SetOperation(ctx, OperationRegistryListModules) + h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.ListModules(ctx, req.(*ListModulesRequest)) + }) + out, err := h(ctx, &in) + if err != nil { + return err + } + reply := out.(*ListModulesResponse) + return ctx.Result(200, reply) + } +} + +func _Registry_GetModule0_HTTP_Handler(srv RegistryHTTPServer) func(ctx http.Context) error { + return func(ctx http.Context) error { + var in GetModuleRequest + if err := ctx.Bind(&in); err != nil { + return err + } + if err := ctx.BindQuery(&in); err != nil { + return err + } + http.SetOperation(ctx, OperationRegistryGetModule) + h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.GetModule(ctx, req.(*GetModuleRequest)) + }) + out, err := h(ctx, &in) + if err != nil { + return err + } + reply := out.(*Module) + return ctx.Result(200, reply) + } +} + +func _Registry_RegisterModule0_HTTP_Handler(srv RegistryHTTPServer) func(ctx http.Context) error { + return func(ctx http.Context) error { + var in RegisterModuleRequest + if err := ctx.Bind(&in); err != nil { + return err + } + if err := ctx.BindQuery(&in); err != nil { + return err + } + http.SetOperation(ctx, OperationRegistryRegisterModule) + h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.RegisterModule(ctx, req.(*RegisterModuleRequest)) + }) + out, err := h(ctx, &in) + if err != nil { + return err + } + reply := out.(*Module) + return ctx.Result(200, reply) + } +} + +func _Registry_PullModule0_HTTP_Handler(srv RegistryHTTPServer) func(ctx http.Context) error { + return func(ctx http.Context) error { + var in PullModuleRequest + if err := ctx.Bind(&in); err != nil { + return err + } + if err := ctx.BindQuery(&in); err != nil { + return err + } + http.SetOperation(ctx, OperationRegistryPullModule) + h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.PullModule(ctx, req.(*PullModuleRequest)) + }) + out, err := h(ctx, &in) + if err != nil { + return err + } + reply := out.(*PullModuleResponse) + return ctx.Result(200, reply) + } +} + +func _Registry_PushModule0_HTTP_Handler(srv RegistryHTTPServer) func(ctx http.Context) error { + return func(ctx http.Context) error { + var in PushModuleRequest + if err := ctx.Bind(&in); err != nil { + return err + } + if err := ctx.BindQuery(&in); err != nil { + return err + } + http.SetOperation(ctx, OperationRegistryPushModule) + h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.PushModule(ctx, req.(*PushModuleRequest)) + }) + out, err := h(ctx, &in) + if err != nil { + return err + } + reply := out.(*Module) + return ctx.Result(200, reply) + } +} + +func _Registry_DeleteModule0_HTTP_Handler(srv RegistryHTTPServer) func(ctx http.Context) error { + return func(ctx http.Context) error { + var in DeleteModuleRequest + if err := ctx.Bind(&in); err != nil { + return err + } + if err := ctx.BindQuery(&in); err != nil { + return err + } + http.SetOperation(ctx, OperationRegistryDeleteModule) + h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.DeleteModule(ctx, req.(*DeleteModuleRequest)) + }) + out, err := h(ctx, &in) + if err != nil { + return err + } + reply := out.(*DeleteModuleResponse) + return ctx.Result(200, reply) + } +} + +func _Registry_DeleteModuleTag0_HTTP_Handler(srv RegistryHTTPServer) func(ctx http.Context) error { + return func(ctx http.Context) error { + var in DeleteModuleTagRequest + if err := ctx.Bind(&in); err != nil { + return err + } + if err := ctx.BindQuery(&in); err != nil { + return err + } + http.SetOperation(ctx, OperationRegistryDeleteModuleTag) + h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.DeleteModuleTag(ctx, req.(*DeleteModuleTagRequest)) + }) + out, err := h(ctx, &in) + if err != nil { + return err + } + reply := out.(*DeleteModuleTagResponse) + return ctx.Result(200, reply) + } +} + +func _Registry_GetModuleDependencies0_HTTP_Handler(srv RegistryHTTPServer) func(ctx http.Context) error { + return func(ctx http.Context) error { + var in GetModuleDependenciesRequest + if err := ctx.Bind(&in); err != nil { + return err + } + if err := ctx.BindQuery(&in); err != nil { + return err + } + http.SetOperation(ctx, OperationRegistryGetModuleDependencies) + h := ctx.Middleware(func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.GetModuleDependencies(ctx, req.(*GetModuleDependenciesRequest)) + }) + out, err := h(ctx, &in) + if err != nil { + return err + } + reply := out.(*GetModuleDependenciesResponse) + return ctx.Result(200, reply) + } +} + +type RegistryHTTPClient interface { + DeleteModule(ctx context.Context, req *DeleteModuleRequest, opts ...http.CallOption) (rsp *DeleteModuleResponse, err error) + DeleteModuleTag(ctx context.Context, req *DeleteModuleTagRequest, opts ...http.CallOption) (rsp *DeleteModuleTagResponse, err error) + GetModule(ctx context.Context, req *GetModuleRequest, opts ...http.CallOption) (rsp *Module, err error) + GetModuleDependencies(ctx context.Context, req *GetModuleDependenciesRequest, opts ...http.CallOption) (rsp *GetModuleDependenciesResponse, err error) + ListModules(ctx context.Context, req *ListModulesRequest, opts ...http.CallOption) (rsp *ListModulesResponse, err error) + PullModule(ctx context.Context, req *PullModuleRequest, opts ...http.CallOption) (rsp *PullModuleResponse, err error) + PushModule(ctx context.Context, req *PushModuleRequest, opts ...http.CallOption) (rsp *Module, err error) + RegisterModule(ctx context.Context, req *RegisterModuleRequest, opts ...http.CallOption) (rsp *Module, err error) +} + +type RegistryHTTPClientImpl struct { + cc *http.Client +} + +func NewRegistryHTTPClient(client *http.Client) RegistryHTTPClient { + return &RegistryHTTPClientImpl{client} +} + +func (c *RegistryHTTPClientImpl) DeleteModule(ctx context.Context, in *DeleteModuleRequest, opts ...http.CallOption) (*DeleteModuleResponse, error) { + var out DeleteModuleResponse + pattern := "/v1/modules/delete" + path := binding.EncodeURL(pattern, in, false) + opts = append(opts, http.Operation(OperationRegistryDeleteModule)) + opts = append(opts, http.PathTemplate(pattern)) + err := c.cc.Invoke(ctx, "POST", path, in, &out, opts...) + if err != nil { + return nil, err + } + return &out, err +} + +func (c *RegistryHTTPClientImpl) DeleteModuleTag(ctx context.Context, in *DeleteModuleTagRequest, opts ...http.CallOption) (*DeleteModuleTagResponse, error) { + var out DeleteModuleTagResponse + pattern := "/v1/modules/tags/delete" + path := binding.EncodeURL(pattern, in, false) + opts = append(opts, http.Operation(OperationRegistryDeleteModuleTag)) + opts = append(opts, http.PathTemplate(pattern)) + err := c.cc.Invoke(ctx, "POST", path, in, &out, opts...) + if err != nil { + return nil, err + } + return &out, err +} + +func (c *RegistryHTTPClientImpl) GetModule(ctx context.Context, in *GetModuleRequest, opts ...http.CallOption) (*Module, error) { + var out Module + pattern := "/v1/modules/get" + path := binding.EncodeURL(pattern, in, false) + opts = append(opts, http.Operation(OperationRegistryGetModule)) + opts = append(opts, http.PathTemplate(pattern)) + err := c.cc.Invoke(ctx, "POST", path, in, &out, opts...) + if err != nil { + return nil, err + } + return &out, err +} + +func (c *RegistryHTTPClientImpl) GetModuleDependencies(ctx context.Context, in *GetModuleDependenciesRequest, opts ...http.CallOption) (*GetModuleDependenciesResponse, error) { + var out GetModuleDependenciesResponse + pattern := "/v1/modules/dependencies" + path := binding.EncodeURL(pattern, in, false) + opts = append(opts, http.Operation(OperationRegistryGetModuleDependencies)) + opts = append(opts, http.PathTemplate(pattern)) + err := c.cc.Invoke(ctx, "POST", path, in, &out, opts...) + if err != nil { + return nil, err + } + return &out, err +} + +func (c *RegistryHTTPClientImpl) ListModules(ctx context.Context, in *ListModulesRequest, opts ...http.CallOption) (*ListModulesResponse, error) { + var out ListModulesResponse + pattern := "/v1/modules" + path := binding.EncodeURL(pattern, in, true) + opts = append(opts, http.Operation(OperationRegistryListModules)) + opts = append(opts, http.PathTemplate(pattern)) + err := c.cc.Invoke(ctx, "GET", path, nil, &out, opts...) + if err != nil { + return nil, err + } + return &out, err +} + +func (c *RegistryHTTPClientImpl) PullModule(ctx context.Context, in *PullModuleRequest, opts ...http.CallOption) (*PullModuleResponse, error) { + var out PullModuleResponse + pattern := "/v1/modules/pull" + path := binding.EncodeURL(pattern, in, false) + opts = append(opts, http.Operation(OperationRegistryPullModule)) + opts = append(opts, http.PathTemplate(pattern)) + err := c.cc.Invoke(ctx, "POST", path, in, &out, opts...) + if err != nil { + return nil, err + } + return &out, err +} + +func (c *RegistryHTTPClientImpl) PushModule(ctx context.Context, in *PushModuleRequest, opts ...http.CallOption) (*Module, error) { + var out Module + pattern := "/v1/modules/push" + path := binding.EncodeURL(pattern, in, false) + opts = append(opts, http.Operation(OperationRegistryPushModule)) + opts = append(opts, http.PathTemplate(pattern)) + err := c.cc.Invoke(ctx, "POST", path, in, &out, opts...) + if err != nil { + return nil, err + } + return &out, err +} + +func (c *RegistryHTTPClientImpl) RegisterModule(ctx context.Context, in *RegisterModuleRequest, opts ...http.CallOption) (*Module, error) { + var out Module + pattern := "/v1/modules" + path := binding.EncodeURL(pattern, in, false) + opts = append(opts, http.Operation(OperationRegistryRegisterModule)) + opts = append(opts, http.PathTemplate(pattern)) + err := c.cc.Invoke(ctx, "POST", path, in, &out, opts...) + if err != nil { + return nil, err + } + return &out, err +} diff --git a/go.mod b/go.mod index e618343..8114884 100644 --- a/go.mod +++ b/go.mod @@ -4,8 +4,8 @@ go 1.21 require ( github.com/docker/go-connections v0.4.0 + github.com/go-kratos/kratos/v2 v2.7.1 github.com/google/martian v2.1.0+incompatible - github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0 github.com/jackc/pgx/v5 v5.4.3 github.com/lib/pq v1.10.9 github.com/pressly/goose/v3 v3.15.1 @@ -32,16 +32,20 @@ require ( github.com/docker/docker v24.0.6+incompatible // indirect github.com/docker/go-units v0.5.0 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/go-kratos/aegis v0.2.0 // indirect github.com/go-ole/go-ole v1.2.6 // indirect + github.com/go-playground/form/v4 v4.2.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang-jwt/jwt/v4 v4.5.0 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/uuid v1.3.1 // indirect + github.com/gorilla/mux v1.8.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/puddle/v2 v2.2.1 // indirect github.com/klauspost/compress v1.17.0 // indirect - github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect + github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/moby/patternmatcher v0.6.0 // indirect @@ -54,7 +58,7 @@ require ( github.com/pelletier/go-toml/v2 v2.1.0 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect + github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b // indirect github.com/sagikazarmark/locafero v0.3.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect github.com/shirou/gopsutil/v3 v3.23.9 // indirect diff --git a/go.sum b/go.sum index 5812880..631f9d0 100644 --- a/go.sum +++ b/go.sum @@ -51,6 +51,8 @@ github.com/Microsoft/hcsshim v0.11.1/go.mod h1:nFJmaO4Zr5Y7eADdFOpYswDDlNVbvcIJJ github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/census-instrumentation/opencensus-proto v0.4.1 h1:iKLQ0xPNFxR/2hzXZMrBo8f1j86j5WHzznCCQxV/b8g= +github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= @@ -58,6 +60,8 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/xds/go v0.0.0-20230607035331-e9ce68804cb4 h1:/inchEIKaYC1Akx+H+gqO04wryn5h75LSazbRlnya1k= +github.com/cncf/xds/go v0.0.0-20230607035331-e9ce68804cb4/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/containerd/containerd v1.7.7 h1:QOC2K4A42RQpcrZyptP6z9EJZnlHfHJUfZrAAHe15q4= github.com/containerd/containerd v1.7.7/go.mod h1:3c4XZv6VeT9qgf9GMTxNTMFxGJrGpI2vz1yk4ye+YY8= github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= @@ -85,7 +89,11 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.11.2-0.20230627204322-7d0032219fcb h1:kxNVXsNro/lpR5WD+P1FI/yUHn2G03Glber3k8cQL2Y= +github.com/envoyproxy/go-control-plane v0.11.2-0.20230627204322-7d0032219fcb/go.mod h1:GxGqnjWzl1Gz8WfAfMJSfhvsi4EPZayRb25nLHDWXyA= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/envoyproxy/protoc-gen-validate v1.0.2 h1:QkIBuU5k+x7/QXPvPPnWXWlCdaBFApVqftFV6k087DA= +github.com/envoyproxy/protoc-gen-validate v1.0.2/go.mod h1:GpiZQP3dDbg4JouG/NNS7QWXpgx6x8QiMKdmN72jogE= github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= @@ -93,13 +101,21 @@ github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbS github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-kratos/aegis v0.2.0 h1:dObzCDWn3XVjUkgxyBp6ZeWtx/do0DPZ7LY3yNSJLUQ= +github.com/go-kratos/aegis v0.2.0/go.mod h1:v0R2m73WgEEYB3XYu6aE2WcMwsZkJ/Rzuf5eVccm7bI= +github.com/go-kratos/kratos/v2 v2.7.1 h1:PNMUaWxS5ZGDp1EyID5ZosJb1OA/YiHnBxB0yUmocnc= +github.com/go-kratos/kratos/v2 v2.7.1/go.mod h1:CPn82O93OLHjtnbuyOKhAG5TkSvw+mFnL32c4lZFDwU= github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/form/v4 v4.2.0 h1:N1wh+Goz61e6w66vo8vJkQt+uwZSoLz50kZPJWR8eic= +github.com/go-playground/form/v4 v4.2.0/go.mod h1:q1a2BY+AQUUzhl6xA/6hBetay6dEIhMHjgvJiGo6K7U= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= +github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.1.2 h1:DVjP2PbBOzHyzA+dn3WhHIq4NdVu3Q+pvivFICf/7fo= -github.com/golang/glog v1.1.2/go.mod h1:zR+okUeTbrL6EL3xHUDxZuEtGv04p5shwip1+mL/rLQ= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -163,8 +179,8 @@ github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0 h1:RtRsiaGvWxcwd8y3BiRZxsylPT8hLWZ5SPcfI+3IDNk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0/go.mod h1:TzP6duP4Py2pHLVPPQp42aoYI92+PCrVotyR5e8Vqlk= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= @@ -197,8 +213,9 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= +github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a h1:N9zuLhTvBSRt0gWSiJswwQ2HqDmtX/ZCDJURnKUt1Ik= +github.com/lufia/plan9stats v0.0.0-20230326075908-cb1d2100619a/go.mod h1:JKx41uQRwqlTZabZc+kILPrO/3jlKnQ2Z8b7YiVw5cE= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= @@ -227,16 +244,17 @@ github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qR github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw= github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= +github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b h1:0LFwY6Q3gMACTjAbMZBjXAqTOzOwFaj2Ld6cjeQ7Rig= +github.com/power-devops/perfstat v0.0.0-20221212215047-62379fc7944b/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/pressly/goose/v3 v3.15.1 h1:dKaJ1SdLvS/+HtS8PzFT0KBEtICC1jewLXM+b3emlv8= github.com/pressly/goose/v3 v3.15.1/go.mod h1:0E3Yg/+EwYzO6Rz2P98MlClFgIcoujbVRs575yi3iIM= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= -github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/sagikazarmark/locafero v0.3.0 h1:zT7VEGWC2DTflmccN/5T1etyKvxSxpHsjb9cJvm4SvQ= github.com/sagikazarmark/locafero v0.3.0/go.mod h1:w+v7UsPNFwzF1cHuOajOOzoq4U7v/ig1mpRjqV+Bu1U= github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= diff --git a/internal/config/config.go b/internal/config/config.go index 02d55b0..3cdb501 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,6 +4,7 @@ import ( "bytes" _ "embed" "strings" + "time" "github.com/spf13/viper" ) @@ -11,24 +12,41 @@ import ( //go:embed config.yaml var embeddedConfigBytes []byte +type Auth struct { + Enabled bool `mapstructure:"enabled"` + Type string `mapstructure:"type"` +} + +type Server struct { + HTTP struct { + Addr string `mapstructure:"addr"` + Timeout time.Duration `mapstructure:"timeout"` + Auth Auth `mapstructure:"auth"` + } `mapstructure:"http"` + GRPC struct { + Addr string `mapstructure:"addr"` + Timeout time.Duration `mapstructure:"timeout"` + TLS struct { + Enabled bool `mapstructure:"enabled"` + CertFile string `mapstructure:"certFile"` + KeyFile string `mapstructure:"keyFile"` + } `mapstructure:"tls"` + Auth Auth `mapstructure:"auth"` + } `mapstructure:"grpc"` + Debug struct { + Addr string `mapstructure:"addr"` + Timeout time.Duration `mapstructure:"timeout"` + } `mapstructure:"debug"` +} + type Config struct { - Server struct { - HTTP struct { - Addr string `mapstructure:"addr"` - } - GRPC struct { - Addr string `mapstructure:"addr"` - } - Debug struct { - Addr string `mapstructure:"addr"` - } - } + Server Server `mapstructure:"server"` Data struct { Database struct { DSN string `mapstructure:"dsn"` - } - } + } `mapstructure:"database"` + } `mapstructure:"data"` } // Cfg is the global config diff --git a/internal/config/config.yaml b/internal/config/config.yaml index a98701c..9584f55 100644 --- a/internal/config/config.yaml +++ b/internal/config/config.yaml @@ -1,10 +1,23 @@ server: http: addr: 0.0.0.0:8080 + timeout: 30s + auth: + enabled: false + type: grpc: - addr: 0.0.0.0:8081 + addr: 0.0.0.0:6777 + timeout: 30s + tls: + enabled: false + certFile: + keyFile: + auth: + enabled: false + type: debug: addr: 0.0.0.0:8082 + timeout: 10s data: diff --git a/internal/data/common_test.go b/internal/data/common_test.go index f03766b..8312889 100644 --- a/internal/data/common_test.go +++ b/internal/data/common_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "github.com/go-kratos/kratos/v2/log" "github.com/jackc/pgx/v5/pgxpool" "github.com/pbufio/pbuf-registry/migrations" "github.com/pbufio/pbuf-registry/test_utils" @@ -49,7 +50,7 @@ func (s *TestSuite) SetupSuite() { } migrations.Migrate(db) - s.registryRepository = NewRegistryRepository(pool) + s.registryRepository = NewRegistryRepository(pool, log.DefaultLogger) } func (s *TestSuite) TearDownSuite() { diff --git a/internal/data/registry.go b/internal/data/registry.go index 46567af..dc8246c 100644 --- a/internal/data/registry.go +++ b/internal/data/registry.go @@ -6,7 +6,7 @@ import ( "errors" "fmt" - "github.com/google/martian/log" + "github.com/go-kratos/kratos/v2/log" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" v1 "github.com/pbufio/pbuf-registry/gen/pbuf-registry/v1" @@ -25,12 +25,14 @@ type RegistryRepository interface { } type registryRepository struct { - pool *pgxpool.Pool + pool *pgxpool.Pool + logger *log.Helper } -func NewRegistryRepository(pool *pgxpool.Pool) RegistryRepository { +func NewRegistryRepository(pool *pgxpool.Pool, logger log.Logger) RegistryRepository { return ®istryRepository{ - pool: pool, + pool: pool, + logger: log.NewHelper(logger), } } @@ -66,7 +68,7 @@ func (r *registryRepository) GetModule(ctx context.Context, name string) (*v1.Mo if err != nil { // tags not found if errors.Is(err, pgx.ErrNoRows) { - log.Infof("no tags found for module %s", name) + r.logger.Infof("no tags found for module %s", name) return &module, nil } @@ -138,7 +140,7 @@ func (r *registryRepository) DeleteModule(ctx context.Context, name string) erro } if res.RowsAffected() > 0 { - log.Infof("deleted %d protofiles for module %s", res.RowsAffected(), name) + r.logger.Infof("deleted %d protofiles for module %s", res.RowsAffected(), name) } // delete all module dependencies @@ -150,7 +152,7 @@ func (r *registryRepository) DeleteModule(ctx context.Context, name string) erro } if res.RowsAffected() > 0 { - log.Infof("deleted %d dependencies for module %s", res.RowsAffected(), name) + r.logger.Infof("deleted %d dependencies for module %s", res.RowsAffected(), name) } // delete all module tags @@ -162,7 +164,7 @@ func (r *registryRepository) DeleteModule(ctx context.Context, name string) erro } if res.RowsAffected() > 0 { - log.Infof("deleted %d tags for module %s", res.RowsAffected(), name) + r.logger.Infof("deleted %d tags for module %s", res.RowsAffected(), name) } // delete module @@ -174,7 +176,7 @@ func (r *registryRepository) DeleteModule(ctx context.Context, name string) erro } if res.RowsAffected() > 0 { - log.Infof("deleted module %s", name) + r.logger.Infof("deleted module %s", name) } else { return errors.New("module not found") } @@ -303,7 +305,7 @@ func (r *registryRepository) DeleteModuleTag(ctx context.Context, name string, t } if res.RowsAffected() > 0 { - log.Infof("deleted %d protofiles for tag %s", res.RowsAffected(), tag) + r.logger.Infof("deleted %d protofiles for tag %s", res.RowsAffected(), tag) } // delete dependencies @@ -315,7 +317,7 @@ func (r *registryRepository) DeleteModuleTag(ctx context.Context, name string, t } if res.RowsAffected() > 0 { - log.Infof("deleted %d dependencies for tag %s", res.RowsAffected(), tag) + r.logger.Infof("deleted %d dependencies for tag %s", res.RowsAffected(), tag) } // delete tag @@ -327,7 +329,7 @@ func (r *registryRepository) DeleteModuleTag(ctx context.Context, name string, t } if res.RowsAffected() > 0 { - log.Infof("deleted tag %s", tag) + r.logger.Infof("deleted tag %s", tag) } else { return errors.New("tag not found") } diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go new file mode 100644 index 0000000..3e7a5ea --- /dev/null +++ b/internal/middleware/auth.go @@ -0,0 +1,60 @@ +package middleware + +import ( + "context" + + "github.com/go-kratos/kratos/v2/middleware" + "github.com/go-kratos/kratos/v2/middleware/auth/jwt" + "github.com/go-kratos/kratos/v2/transport" +) + +const ( + authorizationKey = "Authorization" +) + +type AuthMiddleware interface { + NewAuthMiddleware() middleware.Middleware +} + +type noAuth struct { +} + +// NewNoAuth returns a no auth middleware +// It doesn't require any token +func NewNoAuth() AuthMiddleware { + return &noAuth{} +} + +func (n noAuth) NewAuthMiddleware() middleware.Middleware { + return func(handler middleware.Handler) middleware.Handler { + return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return handler(ctx, req) + } + } +} + +type staticTokenAuth struct { + token string +} + +// NewStaticTokenAuth returns a simple token auth middleware +// We pass the static token and use it to auth +func NewStaticTokenAuth(token string) AuthMiddleware { + return &staticTokenAuth{ + token: token, + } +} + +func (s staticTokenAuth) NewAuthMiddleware() middleware.Middleware { + return func(handler middleware.Handler) middleware.Handler { + return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + if serverContext, ok := transport.FromServerContext(ctx); ok { + if serverContext.RequestHeader().Get(authorizationKey) != s.token { + return nil, jwt.ErrTokenInvalid + } + return handler(ctx, req) + } + return nil, jwt.ErrWrongContext + } + } +} diff --git a/internal/middleware/auth_test.go b/internal/middleware/auth_test.go new file mode 100644 index 0000000..ff36f8a --- /dev/null +++ b/internal/middleware/auth_test.go @@ -0,0 +1,152 @@ +package middleware + +import ( + "context" + "net/http" + "testing" + + "github.com/go-kratos/kratos/v2/transport" +) + +type headerCarrier http.Header + +func (hc headerCarrier) Get(key string) string { return http.Header(hc).Get(key) } + +func (hc headerCarrier) Set(key string, value string) { http.Header(hc).Set(key, value) } + +func (hc headerCarrier) Add(key string, value string) { http.Header(hc).Add(key, value) } + +// Keys lists the keys stored in this carrier. +func (hc headerCarrier) Keys() []string { + keys := make([]string, 0, len(hc)) + for k := range http.Header(hc) { + keys = append(keys, k) + } + return keys +} + +// Values returns a slice value associated with the passed key. +func (hc headerCarrier) Values(key string) []string { + return http.Header(hc).Values(key) +} + +func newTokenHeader(headerKey string, token string) *headerCarrier { + header := &headerCarrier{} + header.Set(headerKey, token) + return header +} + +type Transport struct { + kind transport.Kind + endpoint string + operation string + reqHeader transport.Header +} + +func (tr *Transport) Kind() transport.Kind { + return tr.kind +} + +func (tr *Transport) Endpoint() string { + return tr.endpoint +} + +func (tr *Transport) Operation() string { + return tr.operation +} + +func (tr *Transport) RequestHeader() transport.Header { + return tr.reqHeader +} + +func (tr *Transport) ReplyHeader() transport.Header { + return nil +} + +func Test_noAuth_NewAuthMiddleware(t *testing.T) { + tests := []struct { + name string + }{ + { + name: "noAuth_NewAuthMiddleware", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + n := noAuth{} + + auth := n.NewAuthMiddleware() + handler := auth(func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return "hello", nil + }) + + response, err := handler(context.Background(), nil) + + if err != nil { + t.Errorf("noAuth.NewAuthMiddleware() error = %v", err) + return + } + + if response != "hello" { + t.Errorf("noAuth.NewAuthMiddleware() response = %v", response) + return + } + }) + } +} + +func Test_staticTokenAuth_NewAuthMiddleware(t *testing.T) { + type fields struct { + token string + } + tests := []struct { + name string + fields fields + want string + wantErr bool + }{ + { + name: "staticTokenAuth", + fields: fields{ + token: "simple-token", + }, + want: "hello", + }, + { + name: "wrongToken", + fields: fields{ + "wrong-token", + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticTokenAuth{ + token: "simple-token", + } + + auth := s.NewAuthMiddleware() + + handler := auth(func(ctx context.Context, req interface{}) (reply interface{}, err error) { + return "hello", nil + }) + + serverContext := transport.NewServerContext( + context.Background(), + &Transport{reqHeader: newTokenHeader(authorizationKey, tt.fields.token)}, + ) + + response, err := handler(serverContext, nil) + if err != nil && !tt.wantErr { + t.Errorf("staticTokenAuth.NewAuthMiddleware() error = %v", err) + return + } + + if response != tt.want && !tt.wantErr { + t.Errorf("staticTokenAuth.NewAuthMiddleware() response = %v", response) + return + } + }) + } +} diff --git a/internal/middleware/config.go b/internal/middleware/config.go new file mode 100644 index 0000000..68cc69c --- /dev/null +++ b/internal/middleware/config.go @@ -0,0 +1,29 @@ +package middleware + +import ( + "fmt" + "os" + + "github.com/go-kratos/kratos/v2/log" + "github.com/pbufio/pbuf-registry/internal/config" +) + +func CreateAuthMiddleware(cfg *config.Auth, logger log.Logger) (AuthMiddleware, error) { + helper := log.NewHelper(logger) + + if !cfg.Enabled { + helper.Infof("Auth is disabled. NoAuth middleware is used.") + return NewNoAuth(), nil + } + + switch cfg.Type { + case "static-token": + staticToken := os.Getenv("SERVER_STATIC_TOKEN") + if staticToken == "" { + panic("SERVER_STATIC_TOKEN is not set") + } + return NewStaticTokenAuth(staticToken), nil + } + + return nil, fmt.Errorf("unknown auth type: %s", cfg.Type) +} diff --git a/internal/mocks/auth_middleware.go b/internal/mocks/auth_middleware.go new file mode 100644 index 0000000..e878655 --- /dev/null +++ b/internal/mocks/auth_middleware.go @@ -0,0 +1,43 @@ +// Code generated by mockery v2.37.1. DO NOT EDIT. + +package mocks + +import ( + middleware "github.com/go-kratos/kratos/v2/middleware" + mock "github.com/stretchr/testify/mock" +) + +// AuthMiddleware is an autogenerated mock type for the AuthMiddleware type +type AuthMiddleware struct { + mock.Mock +} + +// NewAuthMiddleware provides a mock function with given fields: +func (_m *AuthMiddleware) NewAuthMiddleware() middleware.Middleware { + ret := _m.Called() + + var r0 middleware.Middleware + if rf, ok := ret.Get(0).(func() middleware.Middleware); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(middleware.Middleware) + } + } + + return r0 +} + +// NewAuthMiddleware creates a new instance of AuthMiddleware. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewAuthMiddleware(t interface { + mock.TestingT + Cleanup(func()) +}) *AuthMiddleware { + mock := &AuthMiddleware{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/internal/mocks/registry_repository.go b/internal/mocks/registry_repository.go index 5e5ab8c..7160922 100644 --- a/internal/mocks/registry_repository.go +++ b/internal/mocks/registry_repository.go @@ -1,4 +1,4 @@ -// Code generated by mockery v2.36.0. DO NOT EDIT. +// Code generated by mockery v2.37.1. DO NOT EDIT. package mocks diff --git a/internal/server/debug.go b/internal/server/debug.go new file mode 100644 index 0000000..3f9e75e --- /dev/null +++ b/internal/server/debug.go @@ -0,0 +1,44 @@ +package server + +import ( + "net/http" + + "github.com/go-kratos/kratos/v2/log" + kratosHttp "github.com/go-kratos/kratos/v2/transport/http" + "github.com/pbufio/pbuf-registry/internal/config" +) + +func NewDebugServer(cfg *config.Server, logger log.Logger) *kratosHttp.Server { + logHelper := log.NewHelper(logger) + + opts := []kratosHttp.ServerOption{ + kratosHttp.Address(cfg.Debug.Addr), + kratosHttp.Timeout(cfg.Debug.Timeout), + } + + srv := kratosHttp.NewServer(opts...) + + // add healthz endpoint to debug server + srv.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + status := http.StatusOK + + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") + w.Header().Set("Pragma", "no-cache") + w.Header().Set("Expires", "0") + + w.WriteHeader(status) + _, err := w.Write([]byte("{}\n")) + if err != nil { + logHelper.Errorf("failed to write response: %v", err) + return + } + }) + + return srv +} diff --git a/internal/server/grpc.go b/internal/server/grpc.go new file mode 100644 index 0000000..aaa1942 --- /dev/null +++ b/internal/server/grpc.go @@ -0,0 +1,62 @@ +package server + +import ( + "crypto/tls" + + "github.com/go-kratos/kratos/v2/log" + "github.com/go-kratos/kratos/v2/transport/grpc" + v1 "github.com/pbufio/pbuf-registry/gen/pbuf-registry/v1" + "github.com/pbufio/pbuf-registry/internal/config" + "github.com/pbufio/pbuf-registry/internal/middleware" +) + +// NewGRPCServer new a gRPC server. +func NewGRPCServer(cfg *config.Server, registryServer *RegistryServer, logger log.Logger) *grpc.Server { + logHelper := log.NewHelper(logger) + + tlsConfig, err := createTLSConfig(cfg, logHelper) + if err != nil { + logHelper.Fatalf("failed to create TLS config: %v", err) + } + + authMiddleware, err := middleware.CreateAuthMiddleware(&cfg.GRPC.Auth, logger) + if err != nil { + logHelper.Fatalf("failed to create auth middleware: %v", err) + } + + opts := []grpc.ServerOption{ + grpc.Address(cfg.GRPC.Addr), + grpc.Timeout(cfg.GRPC.Timeout), + grpc.TLSConfig(tlsConfig), + grpc.Middleware( + authMiddleware.NewAuthMiddleware(), + ), + } + + grpcServer := grpc.NewServer(opts...) + + v1.RegisterRegistryServer(grpcServer, registryServer) + + return grpcServer +} + +// createTLSConfig creates a TLS config +func createTLSConfig(cfg *config.Server, logHelper *log.Helper) (*tls.Config, error) { + logHelper.Infof("TLS Config: %v", cfg.GRPC.TLS) + + if !cfg.GRPC.TLS.Enabled { + logHelper.Infof("TLS is disabled. Skipping TLS config creation.") + return nil, nil + } + + cert, err := tls.LoadX509KeyPair(cfg.GRPC.TLS.CertFile, cfg.GRPC.TLS.KeyFile) + if err != nil { + logHelper.Errorf("failed to load TLS key pair: %v", err) + return nil, err + } + + return &tls.Config{ + Certificates: []tls.Certificate{cert}, + ClientAuth: tls.NoClientCert, + }, nil +} diff --git a/internal/server/http.go b/internal/server/http.go new file mode 100644 index 0000000..bc32776 --- /dev/null +++ b/internal/server/http.go @@ -0,0 +1,33 @@ +package server + +import ( + "github.com/go-kratos/kratos/v2/log" + kratosHttp "github.com/go-kratos/kratos/v2/transport/http" + v1 "github.com/pbufio/pbuf-registry/gen/pbuf-registry/v1" + "github.com/pbufio/pbuf-registry/internal/config" + "github.com/pbufio/pbuf-registry/internal/middleware" +) + +// NewHTTPServer new a HTTP server. +func NewHTTPServer(cfg *config.Server, registryServer *RegistryServer, logger log.Logger) *kratosHttp.Server { + logHelper := log.NewHelper(logger) + + authMiddleware, err := middleware.CreateAuthMiddleware(&cfg.GRPC.Auth, logger) + if err != nil { + logHelper.Fatalf("failed to create auth middleware: %v", err) + } + + opts := []kratosHttp.ServerOption{ + kratosHttp.Address(cfg.HTTP.Addr), + kratosHttp.Timeout(cfg.HTTP.Timeout), + kratosHttp.Middleware( + authMiddleware.NewAuthMiddleware(), + ), + } + + srv := kratosHttp.NewServer(opts...) + + v1.RegisterRegistryHTTPServer(srv, registryServer) + + return srv +} diff --git a/internal/server/registry.go b/internal/server/registry.go index ede6b99..1273da8 100644 --- a/internal/server/registry.go +++ b/internal/server/registry.go @@ -4,7 +4,7 @@ import ( "context" "errors" - "github.com/google/martian/log" + "github.com/go-kratos/kratos/v2/log" v1 "github.com/pbufio/pbuf-registry/gen/pbuf-registry/v1" "github.com/pbufio/pbuf-registry/internal/data" "github.com/pbufio/pbuf-registry/internal/utils" @@ -17,11 +17,13 @@ const ( type RegistryServer struct { v1.UnimplementedRegistryServer registryRepository data.RegistryRepository + logger *log.Helper } -func NewRegistryServer(registryRepository data.RegistryRepository) *RegistryServer { +func NewRegistryServer(registryRepository data.RegistryRepository, logger log.Logger) *RegistryServer { return &RegistryServer{ registryRepository: registryRepository, + logger: log.NewHelper(log.With(logger, "module", "server/RegistryServer")), } } @@ -34,7 +36,7 @@ func (r *RegistryServer) RegisterModule(ctx context.Context, request *v1.Registe err := r.registryRepository.RegisterModule(ctx, name) if err != nil { - log.Infof("error registering module: %v", err) + r.logger.Infof("error registering module: %v", err) return nil, err } @@ -52,7 +54,7 @@ func (r *RegistryServer) GetModule(ctx context.Context, request *v1.GetModuleReq module, err := r.registryRepository.GetModule(ctx, name) if err != nil { - log.Infof("error getting module: %v", err) + r.logger.Infof("error getting module: %v", err) return nil, err } @@ -71,7 +73,7 @@ func (r *RegistryServer) ListModules(ctx context.Context, request *v1.ListModule modules, nextPageToken, err := r.registryRepository.ListModules(ctx, pageSize, request.PageToken) if err != nil { - log.Infof("error listing modules: %v", err) + r.logger.Infof("error listing modules: %v", err) return nil, err } @@ -90,7 +92,7 @@ func (r *RegistryServer) DeleteModule(ctx context.Context, request *v1.DeleteMod err := r.registryRepository.DeleteModule(ctx, name) if err != nil { - log.Infof("error deleting module: %v", err) + r.logger.Infof("error deleting module: %v", err) return nil, err } @@ -117,13 +119,13 @@ func (r *RegistryServer) PushModule(ctx context.Context, request *v1.PushModuleR module, err := r.registryRepository.PushModule(ctx, name, tag, request.Protofiles) if err != nil { - log.Infof("error pushing module: %v", err) + r.logger.Infof("error pushing module: %v", err) return nil, err } err = r.registryRepository.AddModuleDependencies(ctx, name, tag, request.Dependencies) if err != nil { - log.Infof("error while adding dependencies for module: %v", err) + r.logger.Infof("error while adding dependencies for module: %v", err) return nil, err } @@ -143,7 +145,7 @@ func (r *RegistryServer) PullModule(ctx context.Context, request *v1.PullModuleR module, protoFiles, err := r.registryRepository.PullModule(ctx, name, tag) if err != nil { - log.Infof("error pulling module: %v", err) + r.logger.Infof("error pulling module: %v", err) return nil, err } @@ -166,7 +168,7 @@ func (r *RegistryServer) DeleteModuleTag(ctx context.Context, request *v1.Delete err := r.registryRepository.DeleteModuleTag(ctx, name, tag) if err != nil { - log.Infof("error deleting module tag: %v", err) + r.logger.Infof("error deleting module tag: %v", err) return nil, err } @@ -184,7 +186,7 @@ func (r *RegistryServer) GetModuleDependencies(ctx context.Context, request *v1. dependencies, err := r.registryRepository.GetModuleDependencies(ctx, name, request.Tag) if err != nil { - log.Infof("error getting module dependencies: %v", err) + r.logger.Infof("error getting module dependencies: %v", err) return nil, err } diff --git a/internal/server/registry_test.go b/internal/server/registry_test.go index cf2ffb9..f955ffc 100644 --- a/internal/server/registry_test.go +++ b/internal/server/registry_test.go @@ -23,7 +23,7 @@ func setup(ctx context.Context) (v1.RegistryClient, func()) { registryRepository := &mocks.RegistryRepository{} registryRepository.On("RegisterModule", mock.Anything, "hello").Return(nil) - v1.RegisterRegistryServer(baseServer, NewRegistryServer(registryRepository)) + v1.RegisterRegistryServer(baseServer, NewRegistryServer(registryRepository, nil)) go func() { if err := baseServer.Serve(lis); err != nil { log.Printf("error serving server: %v", err) diff --git a/pbuf.yaml b/pbuf.yaml index cdce6bd..ab1d267 100644 --- a/pbuf.yaml +++ b/pbuf.yaml @@ -1,8 +1,7 @@ version: v1 name: pbufio/pbuf-registry registry: - addr: pbuf.cloud:8081 - insecure: true + addr: pbuf.cloud export: paths: - api @@ -11,4 +10,4 @@ modules: repository: https://github.com/googleapis/googleapis path: google/api branch: master - out: third_party/google/api \ No newline at end of file + out: third_party/google/api diff --git a/scripts/cert-gen.sh b/scripts/cert-gen.sh new file mode 100755 index 0000000..3641a41 --- /dev/null +++ b/scripts/cert-gen.sh @@ -0,0 +1,17 @@ +#!/bin/sh + +CERT_GEN_PATH=./gen/certs + +rm -f $CERT_GEN_PATH + +mkdir -p $CERT_GEN_PATH + +echo "subjectAltName=DNS:pbuf.cloud" > $CERT_GEN_PATH/extfile.cnf + +openssl req -x509 -newkey rsa:4096 -days 365 -nodes -keyout $CERT_GEN_PATH/ca-key.pem -out $CERT_GEN_PATH/ca-cert.pem -subj "/CN=pbuf.cloud/emailAddress=hello@pbuf.io" +openssl x509 -in $CERT_GEN_PATH/ca-cert.pem -noout -text + +openssl req -newkey rsa:4096 -nodes -keyout $CERT_GEN_PATH/server-key.pem -out $CERT_GEN_PATH/server-req.pem -subj "/CN=pbuf.cloud/emailAddress=hello@pbuf.io" +openssl x509 -req -in $CERT_GEN_PATH/server-req.pem -days 60 -CA $CERT_GEN_PATH/ca-cert.pem -CAkey $CERT_GEN_PATH/ca-key.pem -CAcreateserial -out $CERT_GEN_PATH/server-cert.pem -extfile $CERT_GEN_PATH/extfile.cnf + +openssl x509 -in $CERT_GEN_PATH/server-cert.pem -noout -text \ No newline at end of file