Skip to content

Instantly share code, notes, and snippets.

@tmarcus87
Last active October 2, 2018 05:12
Show Gist options
  • Save tmarcus87/88fd04a3289b001d625849ff6a2663e1 to your computer and use it in GitHub Desktop.
Save tmarcus87/88fd04a3289b001d625849ff6a2663e1 to your computer and use it in GitHub Desktop.
package main
:
import文省略
:
var permissions := make(map[string][]string) // なんか読み込む
func hasPermission(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) bool {
// 例えばCommonName単位でアクセス可能なパスを管理しておいて前方一致で比較する実装
if peer, ok := peer.FromContext(ctx); ok {
tlsInfo := peer.AuthInfo.(credentials.TLSInfo)
if len(tlsInfo.State.VerifiedChains) > 0 && len(tlsInfo.State.VerifiedChains[0]) {
commonName := tlsInfo.State.VerifiedChains[0][0].Subject.CommonName
for _, path := range permissions[commonName] {
if strings.HasPrefix(info.FullMethod, path) {
return true;
}
}
}
}
return false;
}
func permissionInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
if (!hasPermission(ctx, req, info)) {
return nil, grpc.Errorf(codes.PermissionDenied, "Unable to access to " + info.FullMethod)
}
return handler(ctx, req)
}
}
func main() {
cert, err :=
tls.LoadX509KeyPair(
"./certificate/server/out/dev-grpc-server.example.com.crt",
"./certificate/server/out/dev-grpc-server.example.com.pkcs8.pem")
if err != nil {
panic(err)
}
certPool := x509.NewCertPool()
ca, err := ioutil.ReadFile("./certificate/ca/ca.crt")
if err != nil {
panic(err)
}
if success := certPool.AppendCertsFromPEM(ca); !success {
log.Fatalln("Failed to append ca certs.")
panic()
}
creds := credentials.NewTLS(&tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{cert},
ClientCAs: certPool,
MinVersion: tls.VersionTLS12,
})
listen, err := net.Listen("tcp", ":443")
if err != nil {
panic(err)
}
server :=
grpc.NewServer(
grpc.Creds(creds),
permissionInterceptor())
pb.RegisterGreeterService(server)
server.Serve(listen)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment