gproxy

package module
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 2, 2021 License: Apache-2.0 Imports: 27 Imported by: 0

README

gproxy

a library for creating lets-encrypt secured gRPC and http reverse proxies

GoDoc

go get -u github.com/graphikDB/gproxy
        proxy, err := gproxy.New(ctx,
		gproxy.WithInsecurePort(8080),
		gproxy.WithHTTPRoutes(func(ctx context.Context, host string) string {
			if host == "acme.graphik.com" {
				return "graphik.acme.cluster.local"
			}
			return "" //
		}),
		gproxy.WithHostPolicy(func(ctx context.Context, host string) error {
			if host != "www.graphik.io" {
                return errors.New("forbidden")
            }       
            return nil
		}))
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	if err := proxy.Serve(ctx); err != nil {
		fmt.Println(err.Error())
		return
	}

GProxy Service

docker pull graphikDB:gproxy:v0.0.5

default config path: gproxy.yaml

Local Config(example)

# enable debug logs
debug: true
# lets encrypt autocert allowed domains
autocert:
  - "www.example.com"
routing:
  # http reverse proxy routes using trigger framework: github.com/graphikDB/trigger
  http:
    - "this.host == 'localhost:8080' => { 'target': 'http://localhost:7821' }"
  grpc:
    - "this.host == 'localhost:8080' => { 'target': 'localhost:7820' }"
server:
  # unencrypted server port
  insecure_port: 8080
  # encrypted server port
  secure_port: 443
# cross origin resource sharing config
cors:
  origins: "*"
  methods: "*"
  headers:
    - "GET"
    - "POST"
    - "PUT"
    - "DELETE"
    - "PATCH"

Kubernetes Config (example)


apiVersion: v1
kind: Namespace
metadata:
  name: gproxy
---
kind: ConfigMap
apiVersion: v1
metadata:
  name: gproxy-config
  namespace: gproxy
data:
  gproxy.yaml: |-
    debug: true
    autocert:
      - "www.example.com"
    routing:
      http:
        - "this.host == 'localhost:8080' => { 'target': 'http://localhost:7821' }"
      grpc:
        - "this.host == 'localhost:8080' => { 'target': 'localhost:7820' }"
    server:
      insecure_port: 8080
      secure_port: 443
    cors:
      origins: "*"
      methods: "*"
      headers:
        - "GET"
        - "POST"
        - "PUT"
        - "DELETE"
        - "PATCH"
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: gproxy
  namespace: gproxy
  labels:
    app: gproxy
spec:
  replicas: 3
  selector:
    matchLabels:
      app: gproxy
  serviceName: "gproxy"
  template:
    metadata:
      labels:
        app: gproxy
    spec:
      containers:
        - name: gproxy
          image: graphikdb/gproxy:v0.0.5
          ports:
            - containerPort: 80
            - containerPort: 443
          env:
            - name: GPROXY_CONFIG
              value: /tmp/gproxy/graphik.yaml
          volumeMounts:
            - mountPath: /tmp/gproxy/gproxy.yaml
              name: config-volume

            - mountPath: /tmp/certs
              name: certs-volume
      volumes:
        - name: config-volume
          configMap:
            # Provide the name of the ConfigMap containing the files you want
            # to add to the container
            name: gproxy-config
  volumeClaimTemplates:
    - metadata:
        name: certs-volume
      spec:
        accessModes: [ "ReadWriteOnce" ]
        resources:
          requests:
            storage: 5Mi

---
apiVersion: v1
kind: Service
metadata:
  name: gproxy
  namespace: gproxy
spec:
  selector:
    app: gproxy
  ports:
    - protocol: TCP
      port: 80
      name: insecure
    - protocol: TCP
      port: 443
      name: secure
  type: LoadBalancer
---

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Middleware

type Middleware func(handler http.Handler) http.Handler

Middleware is an http middleware

type Opt

type Opt func(p *Proxy)

Opt is a function that configures a Proxy instance

func WithCertCacheDir added in v0.0.5

func WithCertCacheDir(certCache string) Opt

WithCertCacheDir sets the directory in which certificates will be cached (default: /tmp/certs)

func WithGRPCRoutes

func WithGRPCRoutes(router RouterFunc) Opt

WithGRPCRoutes sets the gRPC RouterFunc which takes a hostname and returns an endpoint to route to. either http routes, gRPC routes, or both are required.

func WithHTTPRoutes

func WithHTTPRoutes(router RouterFunc) Opt

WithHTTPRoutes sets the http RouterFunc which takes a hostname and returns an endpoint to route to either http routes, gRPC routes, or both are required.

func WithHostPolicy

func WithHostPolicy(policy autocert.HostPolicy) Opt

WithHostPolicy sets the host policy function on the proxy(required)

func WithInsecurePort

func WithInsecurePort(insecurePort int) Opt

WithInsecurePort sets the port that non-encrypted traffic will be served on(optional)

func WithLogger

func WithLogger(logger *logger.Logger) Opt

WithLogger sets the proxies logger instance(optional)

func WithMiddlewares

func WithMiddlewares(middlewares ...Middleware) Opt

WithMiddlewares sets the http middlewares on encrypted & non-encrypted traffic(optional)

func WithSecurePort

func WithSecurePort(securePort int) Opt

WithSecurePort sets the port that encrypted traffic will be served on(optional)

func WithStreamInterceptors

func WithStreamInterceptors(sinterceptors ...grpc.StreamServerInterceptor) Opt

WithStreamInterceptors adds gRPC stream interceptors to the proxy instance

func WithUnaryInterceptors

func WithUnaryInterceptors(uinterceptors ...grpc.UnaryServerInterceptor) Opt

WithUnaryInterceptors adds gRPC unary interceptors to the proxy instance

type Proxy

type Proxy struct {
	// contains filtered or unexported fields
}

Proxy is a secure(lets encrypt) gRPC & http reverse proxy

func New

func New(ctx context.Context, opts ...Opt) (*Proxy, error)

New creates a new proxy instance. A host policy & either http routes, gRPC routes, or both are required.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"github.com/graphikDB/gproxy"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello world"))
	}))

	proxy, err := gproxy.New(ctx,
		gproxy.WithInsecurePort(8080),
		gproxy.WithHTTPRoutes(func(ctx context.Context, host string) (string, error) {
			if strings.Contains(host, "localhost") {
				return srv.URL, nil
			}
			return "", errors.New(fmt.Sprintf("%s not allowed", host))
		}),
		gproxy.WithHostPolicy(func(ctx context.Context, host string) error {
			return nil
		}))
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	if err := proxy.Serve(ctx); err != nil {
		fmt.Println(err.Error())
		return
	}
}
Output:

func (*Proxy) Serve

func (p *Proxy) Serve(ctx context.Context) error

Serve starts the gRPC(if grpc router was registered) & http proxy(if http router was registered)

type RouterFunc

type RouterFunc func(ctx context.Context, host string) (string, error)

RouterFunc takes a hostname and returns an endpoint to route to

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL