Merge branch 'master' of /home/q3k/Projects/hscloud/go/src/code.hackerspace.pl/q3k/cmc-proxy
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..045c22e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+arista-proxy
+*swp
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..bbb4580
--- /dev/null
+++ b/README.md
@@ -0,0 +1,13 @@
+hscloud monorepo
+================
+
+This is the main git repository for all HSWAW cloud related code.
+
+Building stuff
+--------------
+
+No bazel yet :^).
+
+    go get -d code.hackerspace.pl/hscloud
+    go generate code.hackerspace.pl/hscloud/...
+    go build code.hackerspace.pl/hcloud/go/svc/arista-proxy
diff --git a/go/mirko/README b/go/mirko/README
new file mode 100644
index 0000000..ba8be71
--- /dev/null
+++ b/go/mirko/README
@@ -0,0 +1,54 @@
+Mirko, the HSWAW microservice helper library
+============================================
+
+Wanna write a Go microservice for HSWAW? Can't be arsed to copy paste code? This is the library for you!
+
+Usage (dev)
+-----------
+
+    package main
+
+    import (
+        "code.hackerspace.pl/hscloud/go/mirko"
+    )
+
+    func main() {
+        m := mirko.New()
+
+        // setup/checks before TCP ports are opened...
+        // ...
+
+        if err := m.Listen(); err != nil {
+            glog.Exitf("Listen(): %v", err)
+        }
+
+        // register your gRPC and http handlers...
+        // (relfection and basic debug http is automatically registered)
+        // pb.RegisterFooServer(m.GRPC(), s)
+        // m.HTTPMux().HandleFunc("/debug/foo", fooHandler)
+
+        if err := m.Serve(); err != nil {
+            glog.Exitf("Serve(): %v", err)
+        }
+
+        // start any other background processing...
+        // (you can use m.Context() to get a context that will get
+        // canceled when the service is about to shut down)
+
+        <-m.Done()
+    }
+
+Usage (running)
+---------------
+
+The following flags are automatically registered:
+
+ - `-listen_address` (default: `127.0.0.1:4200`): where to listen for gRPC requests
+ - `-debug_address` (default: `127.0.0.1:4201`): where to listen for debug HTTP requests
+ - `-debug_allow_all` (default: false): whether to allow all IP address (vs. localhost) to connect to debug endpoint
+
+The following debug HTTP handlers are installed:
+
+ - `/debug/status`: show the [statusz](https://github.com/q3k/statusz) page
+ - `/debug/requests`: show the [net/trace](https://godoc.org/golang.org/x/net/trace) page (including gRPC traces)
+
diff --git a/go/mirko/mirko.go b/go/mirko/mirko.go
new file mode 100644
index 0000000..46c2987
--- /dev/null
+++ b/go/mirko/mirko.go
@@ -0,0 +1,206 @@
+package mirko
+
+import (
+	"context"
+	"flag"
+	"fmt"
+	"net"
+	"net/http"
+	"os"
+	"os/signal"
+	"time"
+
+	"code.hackerspace.pl/hscloud/go/pki"
+	"github.com/golang/glog"
+	"github.com/q3k/statusz"
+	"golang.org/x/net/trace"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/reflection"
+)
+
+var (
+	flagListenAddress string
+	flagDebugAddress  string
+	flagDebugAllowAll bool
+)
+
+func init() {
+	flag.StringVar(&flagListenAddress, "listen_address", "127.0.0.1:4200", "gRPC listen address")
+	flag.StringVar(&flagDebugAddress, "debug_address", "127.0.0.1:4201", "HTTP debug/status listen address")
+	flag.BoolVar(&flagDebugAllowAll, "debug_allow_all", false, "HTTP debug/status available to everyone")
+	flag.Set("logtostderr", "true")
+}
+
+type Mirko struct {
+	grpcListen net.Listener
+	grpcServer *grpc.Server
+	httpListen net.Listener
+	httpServer *http.Server
+	httpMux    *http.ServeMux
+
+	ctx     context.Context
+	cancel  context.CancelFunc
+	waiters []chan bool
+}
+
+func New() *Mirko {
+	ctx, cancel := context.WithCancel(context.Background())
+	return &Mirko{
+		ctx:     ctx,
+		cancel:  cancel,
+		waiters: []chan bool{},
+	}
+}
+
+func authRequest(req *http.Request) (any, sensitive bool) {
+	host, _, err := net.SplitHostPort(req.RemoteAddr)
+	if err != nil {
+		host = req.RemoteAddr
+	}
+
+	if flagDebugAllowAll {
+		return true, true
+	}
+
+	switch host {
+	case "localhost", "127.0.0.1", "::1":
+		return true, true
+	default:
+		return false, false
+	}
+}
+
+func (m *Mirko) Listen() error {
+	grpc.EnableTracing = true
+	trace.AuthRequest = authRequest
+
+	grpcLis, err := net.Listen("tcp", flagListenAddress)
+	if err != nil {
+		return fmt.Errorf("net.Listen: %v", err)
+	}
+	m.grpcListen = grpcLis
+	m.grpcServer = grpc.NewServer(pki.WithServerHSPKI()...)
+	reflection.Register(m.grpcServer)
+
+	httpLis, err := net.Listen("tcp", flagDebugAddress)
+	if err != nil {
+		return fmt.Errorf("net.Listen: %v", err)
+	}
+
+	m.httpMux = http.NewServeMux()
+	// Canonical URLs
+	m.httpMux.HandleFunc("/debug/status", func(w http.ResponseWriter, r *http.Request) {
+		any, _ := authRequest(r)
+		if !any {
+			http.Error(w, "not allowed", http.StatusUnauthorized)
+			return
+		}
+		statusz.StatusHandler(w, r)
+	})
+	m.httpMux.HandleFunc("/debug/requests", trace.Traces)
+
+	// -z legacy URLs
+	m.httpMux.HandleFunc("/statusz", func(w http.ResponseWriter, r *http.Request) {
+		http.Redirect(w, r, "/debug/status", http.StatusSeeOther)
+	})
+	m.httpMux.HandleFunc("/rpcz", func(w http.ResponseWriter, r *http.Request) {
+		http.Redirect(w, r, "/debug/requests", http.StatusSeeOther)
+	})
+	m.httpMux.HandleFunc("/requestz", func(w http.ResponseWriter, r *http.Request) {
+		http.Redirect(w, r, "/debug/requests", http.StatusSeeOther)
+	})
+
+	// root redirect
+	m.httpMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+		http.Redirect(w, r, "/debug/status", http.StatusSeeOther)
+	})
+
+	m.httpListen = httpLis
+	m.httpServer = &http.Server{
+		Addr:    flagDebugAddress,
+		Handler: m.httpMux,
+	}
+
+	return nil
+}
+
+// Trace logs debug information to either a context trace (if present)
+// or stderr (if not)
+func Trace(ctx context.Context, f string, args ...interface{}) {
+	tr, ok := trace.FromContext(ctx)
+	if !ok {
+		fmtd := fmt.Sprintf(f, args...)
+		glog.Warningf("No trace in %v: %s", ctx, fmtd)
+		return
+	}
+	tr.LazyPrintf(f, args...)
+}
+
+// GRPC returns the microservice's grpc.Server object
+func (m *Mirko) GRPC() *grpc.Server {
+	if m.grpcServer == nil {
+		panic("GRPC() called before Listen()")
+	}
+	return m.grpcServer
+}
+
+// HTTPMux returns the microservice's debug HTTP mux
+func (m *Mirko) HTTPMux() *http.ServeMux {
+	if m.httpMux == nil {
+		panic("HTTPMux() called before Listen()")
+	}
+	return m.httpMux
+}
+
+// Context returns a background microservice context that will be canceled
+// when the service is shut down
+func (m *Mirko) Context() context.Context {
+	return m.ctx
+}
+
+// Done() returns a channel that will emit a value when the service is
+// shut down. This should be used in the main() function instead of a select{}
+// call, to allow the background context to be canceled fully.
+func (m *Mirko) Done() chan bool {
+	c := make(chan bool, 1)
+	m.waiters = append(m.waiters, c)
+	return c
+}
+
+// Serve starts serving HTTP and gRPC requests
+func (m *Mirko) Serve() error {
+	errs := make(chan error, 1)
+	go func() {
+		if err := m.grpcServer.Serve(m.grpcListen); err != nil {
+			errs <- err
+		}
+	}()
+	go func() {
+		if err := m.httpServer.Serve(m.httpListen); err != nil {
+			errs <- err
+		}
+	}()
+
+	signalCh := make(chan os.Signal, 1)
+	signal.Notify(signalCh, os.Interrupt)
+	go func() {
+		select {
+		case <-signalCh:
+			m.cancel()
+			time.Sleep(time.Second)
+			for _, w := range m.waiters {
+				w <- true
+			}
+		}
+	}()
+
+	ticker := time.NewTicker(1 * time.Second)
+	select {
+	case <-ticker.C:
+		glog.Infof("gRPC listening on %s", flagListenAddress)
+		glog.Infof("HTTP listening on %s", flagDebugAddress)
+		return nil
+	case err := <-errs:
+		return err
+	}
+}
diff --git a/go/pki/README.md b/go/pki/README.md
new file mode 100644
index 0000000..b84c32d
--- /dev/null
+++ b/go/pki/README.md
@@ -0,0 +1,96 @@
+HSCloud PKI
+===========
+
+a.k.a. API tokens are so 2012
+
+Introduction
+------------
+
+The HSCloud Public Key Infrastructure system is a lightweight specification on how microservices within the HSCloud ecosystem authenticate themselves.
+
+The driving force behind this being standardized is to make it very easy for developers to write new microservices and other tools that can mutually authenticate themselves without having to use public TLS certificates, API tokens or passwords.
+
+Each microservice or tool has a key/certificate pair that it uses to both serve incoming requests and to use as a client certificate when performing outgoing requests.
+
+We currently support gRPC as a first-class transport. Other transports (HTTPS for debug pages, HTTPS for JSON(-RPC)) are not yet implemented.
+
+Where do I get certificates from?
+---------------------------------
+
+The distribution of HSPKI certificates to production services is currently being designed (and will likely be based on Hashicorp Vault or a similar NIH tool). For development purposes, the `gen.sh` script in `dev-certs/` can be used to generate a temporary CA, service keypair and developer keypair.
+
+Concepts
+--------
+
+All certs for mutual auth have the following CN/SAN format:
+
+    <job>.<principal>.<realm>
+
+For example, if principal maps into a 'group' and job into a 'user':
+
+    arista-proxy-dcr01u23.cluster-management-prod.c.example.com
+
+    job = arista-proxy-dcr01u23
+    principal = cluster-management-prod
+    realm = c.example.com
+
+The Realm is a DNS name that is global to all jobs that need mutual authentication.
+
+The Principal is any name that carries significance for logical grouping of jobs.
+It can, but doesn't need to, group jobs by similar permissions.
+
+The Job is any name that identifies uniquely (within the principal) a security
+endpoint that describes a single security policy for a gRPC endpoint.
+
+The entire CN should be DNS resolvable into an IP address that would respond to
+gRPC requests on port 42000 (with a server TLS certificate that represents this CN) if the
+job represents a service.
+
+This maps nicely to the Kubernetes Cluster DNS format if you set `realm` to `svc.cluster.local`.
+Then, `principal` maps to a Kubernetes namespace, and `job` maps into a Kubernetes service.
+
+    arista-proxy-dcr01u23.infrastructure-prod.svc.cluster.local
+
+    job/service = arista-proxy-dcr01u23
+    principal/namespace = infrastructure-prod
+    realm = svc.cluster.local
+
+ACL, or How do I restrict access to my service?
+-----------------------------------------------
+
+Currently you'll have to manually check the PKI information via your language's library and reject unauthorized access within your handler. A unified ACL system with an external RBAC store is currently being designed.
+
+Go Library
+==========
+
+We provide a Go library that all microservices should use to interact with HSPKI.
+
+Usage with gRPC
+---------------
+
+In lieu of a godoc (soon (TM)), here's a quick usage example:
+
+
+    import (
+        "code.hackerspace.pl/hscloud/go/pki"
+    )
+    ...
+    g := grpc.NewServer(pki.WithServerHSPKI()...)
+    pb.RegiserXXXServer(g, service)
+    ...
+
+Flags
+-----
+
+Once linked into your program, the following flags will be automatically present:
+
+    -hspki_realm string
+        PKI realm (default "svc.cluster.local")
+    -hspki_tls_ca_path string
+        Path to PKI CA certificate (default "pki/ca.pem")
+    -hspki_tls_certificate_path string
+        Path to PKI service certificate (default "pki/service.pem")
+    -hspki_tls_key_path string
+        Path to PKI service private key (default "pki/service-key.pem")
+
+These should be set accordingly in your development environment.
diff --git a/go/pki/dev-certs/.gitignore b/go/pki/dev-certs/.gitignore
new file mode 100644
index 0000000..e24607d
--- /dev/null
+++ b/go/pki/dev-certs/.gitignore
@@ -0,0 +1,2 @@
+*csr
+*pem
diff --git a/go/pki/dev-certs/ca_config.json b/go/pki/dev-certs/ca_config.json
new file mode 100644
index 0000000..113a08f
--- /dev/null
+++ b/go/pki/dev-certs/ca_config.json
@@ -0,0 +1,13 @@
+{
+  "signing": {
+    "default": {
+      "expiry": "8760h"
+    },
+    "profiles": {
+      "test": {
+        "usages": ["signing", "key encipherment", "server auth", "client auth"],
+        "expiry": "8760h"
+      }
+    }
+  }
+}
diff --git a/go/pki/dev-certs/ca_csr.json b/go/pki/dev-certs/ca_csr.json
new file mode 100644
index 0000000..b24c638
--- /dev/null
+++ b/go/pki/dev-certs/ca_csr.json
@@ -0,0 +1,11 @@
+{
+    "names": [
+        {
+            "C":  "US",
+            "L":  "San Francisco",
+            "O":  "Internet Widgets, Inc.",
+            "OU": "WWW",
+            "ST": "California"
+        }
+    ]
+}
diff --git a/go/pki/dev-certs/clean.sh b/go/pki/dev-certs/clean.sh
new file mode 100755
index 0000000..490223d
--- /dev/null
+++ b/go/pki/dev-certs/clean.sh
@@ -0,0 +1,6 @@
+#!/bin/sh
+
+set -e -x
+
+rm *pem
+rm *csr
diff --git a/go/pki/dev-certs/client_csr.json b/go/pki/dev-certs/client_csr.json
new file mode 100644
index 0000000..26fc041
--- /dev/null
+++ b/go/pki/dev-certs/client_csr.json
@@ -0,0 +1,12 @@
+{
+    "CN": "developer.humans.svc.cluster.local",
+    "names": [
+        {
+            "C":  "US",
+            "L":  "San Francisco",
+            "O":  "Internet Widgets, Inc.",
+            "OU": "WWW",
+            "ST": "California"
+        }
+    ]
+}
diff --git a/go/pki/dev-certs/gen.sh b/go/pki/dev-certs/gen.sh
new file mode 100755
index 0000000..e09e9f3
--- /dev/null
+++ b/go/pki/dev-certs/gen.sh
@@ -0,0 +1,7 @@
+#!/bin/sh
+
+set -e -x
+
+test -f ca.pem || ( cfssl gencert -initca ca_csr.json | cfssljson -bare ca )
+test -f service.pem || ( cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca_config.json -profile=test service_csr.json | cfssljson -bare service )
+test -f client.pem || ( cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca_config.json -profile=test client_csr.json | cfssljson -bare client )
diff --git a/go/pki/dev-certs/service_csr.json b/go/pki/dev-certs/service_csr.json
new file mode 100644
index 0000000..72c910e
--- /dev/null
+++ b/go/pki/dev-certs/service_csr.json
@@ -0,0 +1,12 @@
+{
+    "CN": "test.arista-proxy.svc.cluster.local",
+    "names": [
+        {
+            "C":  "US",
+            "L":  "San Francisco",
+            "O":  "Internet Widgets, Inc.",
+            "OU": "WWW",
+            "ST": "California"
+        }
+    ]
+}
diff --git a/go/pki/grpc.go b/go/pki/grpc.go
new file mode 100644
index 0000000..f014a34
--- /dev/null
+++ b/go/pki/grpc.go
@@ -0,0 +1,216 @@
+package pki
+
+// Copyright 2018 Sergiusz Bazanski <q3k@hackerspace.pl>
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+import (
+	"context"
+	"crypto/tls"
+	"crypto/x509"
+	"flag"
+	"fmt"
+	"io/ioutil"
+	"strings"
+
+	"github.com/golang/glog"
+	"golang.org/x/net/trace"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/credentials"
+	"google.golang.org/grpc/peer"
+	"google.golang.org/grpc/status"
+)
+
+var (
+	flagCAPath          string
+	flagCertificatePath string
+	flagKeyPath         string
+	flagPKIRealm        string
+
+	// Enable logging HSPKI info into traces
+	Trace = true
+	// Enable logging HSPKI info into glog
+	Log = false
+)
+
+const (
+	ctxKeyClientInfo = "hspki-client-info"
+)
+
+func init() {
+	flag.StringVar(&flagCAPath, "hspki_tls_ca_path", "pki/ca.pem", "Path to PKI CA certificate")
+	flag.StringVar(&flagCertificatePath, "hspki_tls_certificate_path", "pki/service.pem", "Path to PKI service certificate")
+	flag.StringVar(&flagKeyPath, "hspki_tls_key_path", "pki/service-key.pem", "Path to PKI service private key")
+	flag.StringVar(&flagPKIRealm, "hspki_realm", "svc.cluster.local", "PKI realm")
+}
+
+func maybeTrace(ctx context.Context, f string, args ...interface{}) {
+	if Log {
+		glog.Infof(f, args...)
+	}
+
+	if !Trace {
+		return
+	}
+
+	tr, ok := trace.FromContext(ctx)
+	if !ok {
+		if !Log {
+			fmtd := fmt.Sprintf(f, args...)
+			glog.Info("[no trace] %v", fmtd)
+		}
+		return
+	}
+	tr.LazyPrintf(f, args...)
+}
+
+func parseClientName(name string) (*ClientInfo, error) {
+	if !strings.HasSuffix(name, "."+flagPKIRealm) {
+		return nil, fmt.Errorf("invalid realm")
+	}
+	service := strings.TrimSuffix(name, "."+flagPKIRealm)
+	parts := strings.Split(service, ".")
+	if len(parts) != 2 {
+		return nil, fmt.Errorf("invalid job/principal format")
+	}
+	return &ClientInfo{
+		Realm:     flagPKIRealm,
+		Principal: parts[1],
+		Job:       parts[0],
+	}, nil
+}
+
+func withPKIInfo(ctx context.Context, c *ClientInfo) context.Context {
+	maybeTrace(ctx, "HSPKI: Applying ClientInfo: %s", c.String())
+	return context.WithValue(ctx, ctxKeyClientInfo, c)
+}
+
+func grpcInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
+	peer, ok := peer.FromContext(ctx)
+	if !ok {
+		maybeTrace(ctx, "HSPKI: Could not establish identity of peer.")
+		return nil, status.Errorf(codes.PermissionDenied, "no peer info")
+	}
+
+	authInfo, ok := peer.AuthInfo.(credentials.TLSInfo)
+	if !ok {
+		maybeTrace(ctx, "HSPKI: Could not establish TLS identity of peer.")
+		return nil, status.Errorf(codes.PermissionDenied, "no TLS certificate presented")
+	}
+
+	chains := authInfo.State.VerifiedChains
+	if len(chains) != 1 {
+		maybeTrace(ctx, "HSPKI: No trusted chains found.")
+		return nil, status.Errorf(codes.PermissionDenied, "no trusted TLS certificate presented")
+	}
+
+	chain := chains[0]
+
+	certDNs := make([]string, len(chain))
+	for i, cert := range chain {
+		certDNs[i] = cert.Subject.String()
+	}
+	maybeTrace(ctx, "HSPKI: Trust chain: %s", strings.Join(certDNs, ", "))
+
+	clientInfo, err := parseClientName(chain[0].Subject.CommonName)
+	if err != nil {
+		maybeTrace(ctx, "HSPKI: Invalid CN %q: %v", chain[0].Subject.CommonName, err)
+		return nil, status.Errorf(codes.PermissionDenied, "invalid TLS CN format")
+	}
+	ctx = withPKIInfo(ctx, clientInfo)
+	return handler(ctx, req)
+}
+
+// ClientInfo contains information about the HSPKI authentication data of the
+// gRPC client that has made the request.
+type ClientInfo struct {
+	Realm     string
+	Principal string
+	Job       string
+}
+
+// String returns a human-readable representation of the ClientInfo in the
+// form "job=foo, principal=bar, realm=baz".
+func (c *ClientInfo) String() string {
+	return fmt.Sprintf("job=%q, principal=%q, realm=%q", c.Job, c.Principal, c.Realm)
+}
+
+// ClientInfoFromContext returns ClientInfo from a gRPC service context.
+func ClientInfoFromContext(ctx context.Context) *ClientInfo {
+	v := ctx.Value(ctxKeyClientInfo)
+	if v == nil {
+		return nil
+	}
+	ci, ok := v.(*ClientInfo)
+	if !ok {
+		return nil
+	}
+	return ci
+}
+
+// WithServerHSPKI is a grpc.ServerOptions array that ensures that the gRPC server:
+// - runs with HSPKI TLS Service Certificate
+// - rejects all non_HSPKI compatible requests
+// - injects ClientInfo into the service context, which can be later retrieved
+//   using ClientInfoFromContext
+func WithServerHSPKI() []grpc.ServerOption {
+	if !flag.Parsed() {
+		glog.Exitf("WithServerHSPKI called before flag.Parse!")
+	}
+	serverCert, err := tls.LoadX509KeyPair(flagCertificatePath, flagKeyPath)
+	if err != nil {
+		glog.Exitf("WithServerHSPKI: cannot load service certificate/key: %v", err)
+	}
+
+	certPool := x509.NewCertPool()
+	ca, err := ioutil.ReadFile(flagCAPath)
+	if err != nil {
+		glog.Exitf("WithServerHSPKI: cannot load CA certificate: %v", err)
+	}
+	if ok := certPool.AppendCertsFromPEM(ca); !ok {
+		glog.Exitf("WithServerHSPKI: cannot use CA certificate: %v", err)
+	}
+
+	creds := grpc.Creds(credentials.NewTLS(&tls.Config{
+		ClientAuth:   tls.RequireAndVerifyClientCert,
+		Certificates: []tls.Certificate{serverCert},
+		ClientCAs:    certPool,
+	}))
+
+	interceptor := grpc.UnaryInterceptor(grpcInterceptor)
+
+	return []grpc.ServerOption{creds, interceptor}
+}
+
+func WithClientHSPKI() grpc.DialOption {
+	certPool := x509.NewCertPool()
+	ca, err := ioutil.ReadFile(flagCAPath)
+	if err != nil {
+		glog.Exitf("WithClientHSPKI: cannot load CA certificate: %v", err)
+	}
+	if ok := certPool.AppendCertsFromPEM(ca); !ok {
+		glog.Exitf("WithClientHSPKI: cannot use CA certificate: %v", err)
+	}
+
+	clientCert, err := tls.LoadX509KeyPair(flagCertificatePath, flagKeyPath)
+	if err != nil {
+		glog.Exitf("WithClientHSPKI: cannot load service certificate/key: %v", err)
+	}
+
+	creds := credentials.NewTLS(&tls.Config{
+		Certificates: []tls.Certificate{clientCert},
+		RootCAs:      certPool,
+	})
+	return grpc.WithTransportCredentials(creds)
+}
diff --git a/go/svc/arista-proxy/README.md b/go/svc/arista-proxy/README.md
new file mode 100644
index 0000000..60368dc
--- /dev/null
+++ b/go/svc/arista-proxy/README.md
@@ -0,0 +1,44 @@
+Old Shitty Arista eAPI/Capi <-> gRPC proxy
+==========================================
+
+Our Arista 7148S does not support gRPC/OpenConfig, so we have to make our own damn gRPC proxy.
+
+The schema is supposed to be 1:1 mapped to the JSON-RPC EAPI. This is just a dumb proxy.
+
+Getting and Building
+--------------------
+
+    go get -d -u code.hackerspace.pl/q3k/arista-proxy
+    go generate code.hackerspace.pl/q3k/arista-proxy/proto
+    go build code.hackerspace.pl/q3k/arista-proxy
+
+Debug Status Page
+-----------------
+
+The `debug_address` flag controls spawning an HTTP server useful for debugging. You can use it to inspect gRPC request and view general status information of the proxy.
+
+Flags
+-----
+
+    ./arista-proxy -help
+    Usage of ./arista-proxy:
+      -alsologtostderr
+        	log to standard error as well as files
+      -arista_api string
+        	Arista remote endpoint (default "http://admin:password@1.2.3.4:80/command-api")
+      -debug_address string
+        	Debug HTTP listen address, or empty to disable (default "127.0.0.1:42000")
+      -listen_address string
+        	gRPC listen address (default "127.0.0.1:43001")
+      -log_backtrace_at value
+        	when logging hits line file:N, emit a stack trace
+      -log_dir string
+        	If non-empty, write log files in this directory
+      -logtostderr
+        	log to standard error instead of files
+      -stderrthreshold value
+        	logs at or above this threshold go to stderr
+      -v value
+        	log level for V logs
+      -vmodule value
+        	comma-separated list of pattern=N settings for file-filtered logging
diff --git a/go/svc/arista-proxy/arista.proto b/go/svc/arista-proxy/arista.proto
new file mode 100644
index 0000000..d6bf105
--- /dev/null
+++ b/go/svc/arista-proxy/arista.proto
@@ -0,0 +1,31 @@
+syntax = "proto3";
+
+package proto;
+
+message ShowVersionRequest {
+};
+
+message ShowVersionResponse {
+    string model_name = 1;
+    string internal_version = 2;
+    string system_mac_address = 3;
+    string serial_number = 4;
+    int64 mem_total = 5;
+    double bootup_timestamp = 6;
+    int64 mem_free = 7;
+    string version = 8;
+    string architecture = 9;
+    string internal_build_id = 10;
+    string hardware_revision = 11;
+};
+
+message ShowEnvironmentTemperatureRequest {
+};
+
+message ShowEnvironmentTemperatureResponse {
+};
+
+service AristaProxy {
+    rpc ShowVersion(ShowVersionRequest) returns (ShowVersionResponse);
+    rpc ShowEnvironmentTemperature(ShowEnvironmentTemperatureRequest) returns (ShowEnvironmentTemperatureResponse);
+};
diff --git a/go/svc/arista-proxy/main.go b/go/svc/arista-proxy/main.go
new file mode 100644
index 0000000..1227cb1
--- /dev/null
+++ b/go/svc/arista-proxy/main.go
@@ -0,0 +1,67 @@
+package main
+
+import (
+	"flag"
+	"fmt"
+
+	"code.hackerspace.pl/hscloud/go/mirko"
+	"github.com/golang/glog"
+	"github.com/ybbus/jsonrpc"
+
+	pb "code.hackerspace.pl/hscloud/go/svc/arista-proxy/proto"
+)
+
+var (
+	flagAristaAPI string
+)
+
+type aristaClient struct {
+	rpc jsonrpc.RPCClient
+}
+
+func (c *aristaClient) structuredCall(res interface{}, command ...string) error {
+	cmd := struct {
+		Version int      `json:"version"`
+		Cmds    []string `json:"cmds"`
+		Format  string   `json:"format"`
+	}{
+		Version: 1,
+		Cmds:    command,
+		Format:  "json",
+	}
+
+	err := c.rpc.CallFor(res, "runCmds", cmd)
+	if err != nil {
+		return fmt.Errorf("could not execute structured call: %v", err)
+	}
+	return nil
+}
+
+type server struct {
+	arista *aristaClient
+}
+
+func main() {
+	flag.StringVar(&flagAristaAPI, "arista_api", "http://admin:password@1.2.3.4:80/command-api", "Arista remote endpoint")
+	flag.Parse()
+
+	arista := &aristaClient{
+		rpc: jsonrpc.NewClient(flagAristaAPI),
+	}
+
+	m := mirko.New()
+	if err := m.Listen(); err != nil {
+		glog.Exitf("Listen(): %v", err)
+	}
+
+	s := &server{
+		arista: arista,
+	}
+	pb.RegisterAristaProxyServer(m.GRPC(), s)
+
+	if err := m.Serve(); err != nil {
+		glog.Exitf("Serve(): %v", err)
+	}
+
+	select {}
+}
diff --git a/go/svc/arista-proxy/proto/.gitignore b/go/svc/arista-proxy/proto/.gitignore
new file mode 100644
index 0000000..46ddcab
--- /dev/null
+++ b/go/svc/arista-proxy/proto/.gitignore
@@ -0,0 +1 @@
+arista.pb.go
diff --git a/go/svc/arista-proxy/proto/generate.go b/go/svc/arista-proxy/proto/generate.go
new file mode 100644
index 0000000..92f2720
--- /dev/null
+++ b/go/svc/arista-proxy/proto/generate.go
@@ -0,0 +1,3 @@
+//go:generate protoc -I.. ../arista.proto --go_out=plugins=grpc:.
+
+package proto
diff --git a/go/svc/arista-proxy/service.go b/go/svc/arista-proxy/service.go
new file mode 100644
index 0000000..d7e2a29
--- /dev/null
+++ b/go/svc/arista-proxy/service.go
@@ -0,0 +1,97 @@
+package main
+
+import (
+	"context"
+
+	"github.com/golang/glog"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+
+	pb "code.hackerspace.pl/hscloud/go/svc/arista-proxy/proto"
+)
+
+func (s *server) ShowVersion(ctx context.Context, req *pb.ShowVersionRequest) (*pb.ShowVersionResponse, error) {
+	var version []struct {
+		ModelName        string  `json:"modelName"`
+		InternalVersion  string  `json:"internalVersion"`
+		SystemMacAddress string  `json:"systemMacAddress"`
+		SerialNumber     string  `json:"serialNumber"`
+		MemTotal         int64   `json:"memTotal"`
+		BootupTimestamp  float64 `json:"bootupTimestamp"`
+		MemFree          int64   `json:"memFree"`
+		Version          string  `json:"version"`
+		Architecture     string  `json:"architecture"`
+		InternalBuildId  string  `json:"internalBuildId"`
+		HardwareRevision string  `json:"hardwareRevision"`
+	}
+
+	err := s.arista.structuredCall(&version, "show version")
+	if err != nil {
+		glog.Errorf("EOS Capi: show version: %v", err)
+		return nil, status.Error(codes.Unavailable, "EOS Capi call failed")
+	}
+
+	if len(version) != 1 {
+		glog.Errorf("Expected 1-length result, got %d", len(version))
+		return nil, status.Error(codes.Internal, "Internal error")
+	}
+
+	d := version[0]
+
+	return &pb.ShowVersionResponse{
+		ModelName:        d.ModelName,
+		InternalVersion:  d.InternalVersion,
+		SystemMacAddress: d.SystemMacAddress,
+		SerialNumber:     d.SerialNumber,
+		MemTotal:         d.MemTotal,
+		BootupTimestamp:  d.BootupTimestamp,
+		MemFree:          d.MemFree,
+		Version:          d.Version,
+		Architecture:     d.Architecture,
+		InternalBuildId:  d.InternalBuildId,
+		HardwareRevision: d.HardwareRevision,
+	}, nil
+}
+
+type temperatureSensor struct {
+	InAlertState       bool    `json:"inAlertState"`
+	MaxTemperature     float64 `json:"maxTemperature"`
+	RelPos             int64   `json:"relPos"`
+	Description        string  `json:"description"`
+	Name               string  `json:"name"`
+	AlertCount         int64   `json:"alertCount"`
+	CurrentTemperature float64 `json:"currentTemperature"`
+	OverheatThreshold  float64 `json:"overheatThreshold"`
+	CriticalThreshold  float64 `json:"criticalThreshold"`
+	HwStatus           string  `json:"hwStatus"`
+}
+
+func (s *server) ShowEnvironmentTemperature(ctx context.Context, req *pb.ShowEnvironmentTemperatureRequest) (*pb.ShowEnvironmentTemperatureResponse, error) {
+	var response []struct {
+		PowerSuppplySlots []struct {
+			TempSensors      []temperatureSensor `json:"tempSensors"`
+			EntPhysicalClass string              `json:"entPhysicalClass"`
+			RelPos           int64               `json:"relPos"`
+		} `json:"powerSupplySlots"`
+
+		ShutdownOnOverheat bool                `json:"shutdownOnOverheat"`
+		TempSensors        []temperatureSensor `json:"tempSensors"`
+		SystemStatus       string              `json:"systemStatus"`
+	}
+
+	err := s.arista.structuredCall(&response, "show environment temperature")
+	if err != nil {
+		glog.Errorf("EOS Capi: show environment temperature: %v", err)
+		return nil, status.Error(codes.Unavailable, "EOS Capi call failed")
+	}
+
+	if len(response) != 1 {
+		glog.Errorf("Expected 1-length result, got %d", len(response))
+		return nil, status.Error(codes.Internal, "Internal error")
+	}
+
+	d := response[0]
+	glog.Infof("%+v", d)
+
+	return &pb.ShowEnvironmentTemperatureResponse{}, nil
+}