Commit 81081f31 authored by Nick Thomas's avatar Nick Thomas

Merge branch 'gitaly-auth-v2' into 'master'

Use the new Gitaly auth scheme (v2)

See merge request gitlab-org/gitlab-workhorse!298
parents 99ac3db3 63c48b89
......@@ -97,7 +97,7 @@ func CloseConnections() {
func newConnection(server Server) (*grpc.ClientConn, error) {
connOpts := append(gitalyclient.DefaultDialOpts,
grpc.WithPerRPCCredentials(gitalyauth.RPCCredentials(server.Token)),
grpc.WithPerRPCCredentials(gitalyauth.RPCCredentialsV2(server.Token)),
grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor),
grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
)
......
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
Types of changes:
- `Added` for new features.
- `Changed` for changes in existing functionality.
- `Deprecated` for soon-to-be removed features.
- `Removed` for now removed features.
- `Fixed` for any bug fixes.
- `Security` in case of vulnerabilities.
## [Unreleased]
### Added
- This CHANGELOG file to keep track of changes.
## 1.0.0 - 2018-05-08
### Added
- grpc_auth
- grpc_ctxtags
- grpc_zap
- grpc_logrus
- grpc_opentracing
- grpc_retry
- grpc_validator
- grpc_recovery
[Unreleased]: https://github.com/grpc-ecosystem/go-grpc-middleware/compare/v1.0.0...HEAD
# Contributing
We would love to have people submit pull requests and help make `grpc-ecosystem/go-grpc-middleware` even better 👍.
Fork, then clone the repo:
```bash
git clone git@github.com:your-username/go-grpc-middleware.git
```
Before checking in please run the following:
```bash
make all
```
This will `vet`, `fmt`, regenerate documentation and run all tests.
Push to your fork and open a pull request.
\ No newline at end of file
# grpc_middleware
`import "github.com/grpc-ecosystem/go-grpc-middleware"`
* [Overview](#pkg-overview)
* [Imported Packages](#pkg-imports)
* [Index](#pkg-index)
## <a name="pkg-overview">Overview</a>
`grpc_middleware` is a collection of gRPC middleware packages: interceptors, helpers and tools.
### Middleware
gRPC is a fantastic RPC middleware, which sees a lot of adoption in the Golang world. However, the
upstream gRPC codebase is relatively bare bones.
This package, and most of its child packages provides commonly needed middleware for gRPC:
client-side interceptors for retires, server-side interceptors for input validation and auth,
functions for chaining said interceptors, metadata convenience methods and more.
### Chaining
By default, gRPC doesn't allow one to have more than one interceptor either on the client nor on
the server side. `grpc_middleware` provides convenient chaining methods
Simple way of turning a multiple interceptors into a single interceptor. Here's an example for
server chaining:
myServer := grpc.NewServer(
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(loggingStream, monitoringStream, authStream)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(loggingUnary, monitoringUnary, authUnary),
)
These interceptors will be executed from left to right: logging, monitoring and auth.
Here's an example for client side chaining:
clientConn, err = grpc.Dial(
address,
grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(monitoringClientUnary, retryUnary)),
grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(monitoringClientStream, retryStream)),
)
client = pb_testproto.NewTestServiceClient(clientConn)
resp, err := client.PingEmpty(s.ctx, &myservice.Request{Msg: "hello"})
These interceptors will be executed from left to right: monitoring and then retry logic.
The retry interceptor will call every interceptor that follows it whenever when a retry happens.
### Writing Your Own
Implementing your own interceptor is pretty trivial: there are interfaces for that. But the interesting
bit exposing common data to handlers (and other middleware), similarly to HTTP Middleware design.
For example, you may want to pass the identity of the caller from the auth interceptor all the way
to the handling function.
For example, a client side interceptor example for auth looks like:
func FakeAuthUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
newCtx := context.WithValue(ctx, "user_id", "john@example.com")
return handler(newCtx, req)
}
Unfortunately, it's not as easy for streaming RPCs. These have the `context.Context` embedded within
the `grpc.ServerStream` object. To pass values through context, a wrapper (`WrappedServerStream`) is
needed. For example:
func FakeAuthStreamingInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
newStream := grpc_middleware.WrapServerStream(stream)
newStream.WrappedContext = context.WithValue(ctx, "user_id", "john@example.com")
return handler(srv, stream)
}
## <a name="pkg-imports">Imported Packages</a>
- [golang.org/x/net/context](https://godoc.org/golang.org/x/net/context)
- [google.golang.org/grpc](https://godoc.org/google.golang.org/grpc)
## <a name="pkg-index">Index</a>
* [func ChainStreamClient(interceptors ...grpc.StreamClientInterceptor) grpc.StreamClientInterceptor](#ChainStreamClient)
* [func ChainStreamServer(interceptors ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor](#ChainStreamServer)
* [func ChainUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor](#ChainUnaryClient)
* [func ChainUnaryServer(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor](#ChainUnaryServer)
* [func WithStreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption](#WithStreamServerChain)
* [func WithUnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption](#WithUnaryServerChain)
* [type WrappedServerStream](#WrappedServerStream)
* [func WrapServerStream(stream grpc.ServerStream) \*WrappedServerStream](#WrapServerStream)
* [func (w \*WrappedServerStream) Context() context.Context](#WrappedServerStream.Context)
#### <a name="pkg-files">Package files</a>
[chain.go](./chain.go) [doc.go](./doc.go) [wrappers.go](./wrappers.go)
## <a name="ChainStreamClient">func</a> [ChainStreamClient](./chain.go#L136)
``` go
func ChainStreamClient(interceptors ...grpc.StreamClientInterceptor) grpc.StreamClientInterceptor
```
ChainStreamClient creates a single interceptor out of a chain of many interceptors.
Execution is done in left-to-right order, including passing of context.
For example ChainStreamClient(one, two, three) will execute one before two before three.
## <a name="ChainStreamServer">func</a> [ChainStreamServer](./chain.go#L58)
``` go
func ChainStreamServer(interceptors ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor
```
ChainStreamServer creates a single interceptor out of a chain of many interceptors.
Execution is done in left-to-right order, including passing of context.
For example ChainUnaryServer(one, two, three) will execute one before two before three.
If you want to pass context between interceptors, use WrapServerStream.
## <a name="ChainUnaryClient">func</a> [ChainUnaryClient](./chain.go#L97)
``` go
func ChainUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor
```
ChainUnaryClient creates a single interceptor out of a chain of many interceptors.
Execution is done in left-to-right order, including passing of context.
For example ChainUnaryClient(one, two, three) will execute one before two before three.
## <a name="ChainUnaryServer">func</a> [ChainUnaryServer](./chain.go#L18)
``` go
func ChainUnaryServer(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor
```
ChainUnaryServer creates a single interceptor out of a chain of many interceptors.
Execution is done in left-to-right order, including passing of context.
For example ChainUnaryServer(one, two, three) will execute one before two before three, and three
will see context changes of one and two.
## <a name="WithStreamServerChain">func</a> [WithStreamServerChain](./chain.go#L181)
``` go
func WithStreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption
```
WithStreamServerChain is a grpc.Server config option that accepts multiple stream interceptors.
Basically syntactic sugar.
## <a name="WithUnaryServerChain">func</a> [WithUnaryServerChain](./chain.go#L175)
``` go
func WithUnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption
```
Chain creates a single interceptor out of a chain of many interceptors.
WithUnaryServerChain is a grpc.Server config option that accepts multiple unary interceptors.
Basically syntactic sugar.
## <a name="WrappedServerStream">type</a> [WrappedServerStream](./wrappers.go#L12-L16)
``` go
type WrappedServerStream struct {
grpc.ServerStream
// WrappedContext is the wrapper's own Context. You can assign it.
WrappedContext context.Context
}
```
WrappedServerStream is a thin wrapper around grpc.ServerStream that allows modifying context.
### <a name="WrapServerStream">func</a> [WrapServerStream](./wrappers.go#L24)
``` go
func WrapServerStream(stream grpc.ServerStream) *WrappedServerStream
```
WrapServerStream returns a ServerStream that has the ability to overwrite context.
### <a name="WrappedServerStream.Context">func</a> (\*WrappedServerStream) [Context](./wrappers.go#L19)
``` go
func (w *WrappedServerStream) Context() context.Context
```
Context returns the wrapper's WrappedContext, overwriting the nested grpc.ServerStream.Context()
- - -
Generated by [godoc2ghmd](https://github.com/GandalfUK/godoc2ghmd)
\ No newline at end of file
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
name = "cloud.google.com/go"
packages = ["compute/metadata"]
revision = "2d3a6656c17a60b0815b7e06ab0be04eacb6e613"
version = "v0.16.0"
[[projects]]
name = "github.com/davecgh/go-spew"
packages = ["spew"]
revision = "346938d642f2ec3594ed81d874461961cd0faa76"
version = "v1.1.0"
[[projects]]
name = "github.com/gogo/protobuf"
packages = ["gogoproto","proto","protoc-gen-gogo/descriptor"]
revision = "342cbe0a04158f6dcb03ca0079991a51a4248c02"
version = "v0.5"
[[projects]]
branch = "master"
name = "github.com/golang/protobuf"
packages = ["jsonpb","proto","ptypes","ptypes/any","ptypes/duration","ptypes/struct","ptypes/timestamp"]
revision = "1e59b77b52bf8e4b449a57e6f79f21226d571845"
[[projects]]
name = "github.com/opentracing/opentracing-go"
packages = [".","ext","log","mocktracer"]
revision = "1949ddbfd147afd4d964a9f00b24eb291e0e7c38"
version = "v1.0.2"
[[projects]]
name = "github.com/pmezard/go-difflib"
packages = ["difflib"]
revision = "792786c7400a136282c1664665ae0a8db921c6c2"
version = "v1.0.0"
[[projects]]
name = "github.com/sirupsen/logrus"
packages = ["."]
revision = "f006c2ac4710855cf0f916dd6b77acf6b048dc6e"
version = "v1.0.3"
[[projects]]
name = "github.com/stretchr/testify"
packages = ["assert","require","suite"]
revision = "69483b4bd14f5845b5a1e55bca19e954e827f1d0"
version = "v1.1.4"
[[projects]]
name = "go.uber.org/atomic"
packages = ["."]
revision = "8474b86a5a6f79c443ce4b2992817ff32cf208b8"
version = "v1.3.1"
[[projects]]
name = "go.uber.org/multierr"
packages = ["."]
revision = "3c4937480c32f4c13a875a1829af76c98ca3d40a"
version = "v1.1.0"
[[projects]]
name = "go.uber.org/zap"
packages = [".","buffer","internal/bufferpool","internal/color","internal/exit","zapcore"]
revision = "35aad584952c3e7020db7b839f6b102de6271f89"
version = "v1.7.1"
[[projects]]
branch = "master"
name = "golang.org/x/crypto"
packages = ["ssh/terminal"]
revision = "94eea52f7b742c7cbe0b03b22f0c4c8631ece122"
[[projects]]
branch = "master"
name = "golang.org/x/net"
packages = ["context","context/ctxhttp","http2","http2/hpack","idna","internal/timeseries","lex/httplex","trace"]
revision = "a8b9294777976932365dabb6640cf1468d95c70f"
[[projects]]
branch = "master"
name = "golang.org/x/oauth2"
packages = [".","google","internal","jws","jwt"]
revision = "f95fa95eaa936d9d87489b15d1d18b97c1ba9c28"
[[projects]]
branch = "master"
name = "golang.org/x/sys"
packages = ["unix","windows"]
revision = "13fcbd661c8ececa8807a29b48407d674b1d8ed8"
[[projects]]
branch = "master"
name = "golang.org/x/text"
packages = ["collate","collate/build","internal/colltab","internal/gen","internal/tag","internal/triegen","internal/ucd","language","secure/bidirule","transform","unicode/bidi","unicode/cldr","unicode/norm","unicode/rangetable"]
revision = "75cc3cad82b5f47d3fb229ddda8c5167da14f294"
[[projects]]
name = "google.golang.org/appengine"
packages = [".","internal","internal/app_identity","internal/base","internal/datastore","internal/log","internal/modules","internal/remote_api","internal/urlfetch","urlfetch"]
revision = "150dc57a1b433e64154302bdc40b6bb8aefa313a"
version = "v1.0.0"
[[projects]]
branch = "master"
name = "google.golang.org/genproto"
packages = ["googleapis/rpc/status"]
revision = "7f0da29060c682909f650ad8ed4e515bd74fa12a"
[[projects]]
name = "google.golang.org/grpc"
packages = [".","balancer","balancer/roundrobin","codes","connectivity","credentials","credentials/oauth","encoding","grpclb/grpc_lb_v1/messages","grpclog","internal","keepalive","metadata","naming","peer","resolver","resolver/dns","resolver/passthrough","stats","status","tap","transport"]
revision = "5a9f7b402fe85096d2e1d0383435ee1876e863d0"
version = "v1.8.0"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "b24c6670412eb0bc44ed1db77fecc52333f8725f3e3272bdc568f5683a63031f"
solver-name = "gps-cdcl"
solver-version = 1
[[constraint]]
name = "github.com/gogo/protobuf"
version = "0.5.0"
[[constraint]]
branch = "master"
name = "github.com/golang/protobuf"
[[constraint]]
name = "github.com/opentracing/opentracing-go"
version = "1.0.2"
[[constraint]]
name = "github.com/sirupsen/logrus"
version = "1.0.3"
[[constraint]]
name = "github.com/stretchr/testify"
version = "1.1.4"
[[constraint]]
name = "go.uber.org/zap"
version = "1.7.1"
[[constraint]]
branch = "master"
name = "golang.org/x/net"
[[constraint]]
branch = "master"
name = "golang.org/x/oauth2"
[[constraint]]
name = "google.golang.org/grpc"
version = "1.8.0"
This diff is collapsed.
# Go gRPC Middleware
[![Travis Build](https://travis-ci.org/grpc-ecosystem/go-grpc-middleware.svg?branch=master)](https://travis-ci.org/grpc-ecosystem/go-grpc-middleware)
[![Go Report Card](https://goreportcard.com/badge/github.com/grpc-ecosystem/go-grpc-middleware)](https://goreportcard.com/report/github.com/grpc-ecosystem/go-grpc-middleware)
[![GoDoc](http://img.shields.io/badge/GoDoc-Reference-blue.svg)](https://godoc.org/github.com/grpc-ecosystem/go-grpc-middleware)
[![SourceGraph](https://sourcegraph.com/github.com/grpc-ecosystem/go-grpc-middleware/-/badge.svg)](https://sourcegraph.com/github.com/grpc-ecosystem/go-grpc-middleware/?badge)
[![codecov](https://codecov.io/gh/grpc-ecosystem/go-grpc-middleware/branch/master/graph/badge.svg)](https://codecov.io/gh/grpc-ecosystem/go-grpc-middleware)
[![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![quality: production](https://img.shields.io/badge/quality-production-orange.svg)](#status)
[![Slack](slack.png)](https://join.slack.com/t/improbable-eng/shared_invite/enQtMzQ1ODcyMzQ5MjM4LWY5ZWZmNGM2ODc5MmViNmQ3ZTA3ZTY3NzQwOTBlMTkzZmIxZTIxODk0OWU3YjZhNWVlNDU3MDlkZGViZjhkMjc)
[gRPC Go](https://github.com/grpc/grpc-go) Middleware: interceptors, helpers, utilities.
**Important** The repo recently moved to `github.com/grpc-ecosystem/go-grpc-middleware`, please update your import paths.
## Middleware
[gRPC Go](https://github.com/grpc/grpc-go) recently acquired support for
Interceptors, i.e. [middleware](https://medium.com/@matryer/writing-middleware-in-golang-and-how-go-makes-it-so-much-fun-4375c1246e81#.gv7tdlghs)
that is executed either on the gRPC Server before the request is passed onto the user's application logic, or on the gRPC client either around the user call. It is a perfect way to implement
common patterns: auth, logging, message, validation, retries or monitoring.
These are generic building blocks that make it easy to build multiple microservices easily.
The purpose of this repository is to act as a go-to point for such reusable functionality. It contains
some of them itself, but also will link to useful external repos.
`grpc_middleware` itself provides support for chaining interceptors. See [Documentation](DOC.md), but here's an example:
```go
import "github.com/grpc-ecosystem/go-grpc-middleware"
myServer := grpc.NewServer(
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
grpc_ctxtags.StreamServerInterceptor(),
grpc_opentracing.StreamServerInterceptor(),
grpc_prometheus.StreamServerInterceptor,
grpc_zap.StreamServerInterceptor(zapLogger),
grpc_auth.StreamServerInterceptor(myAuthFunction),
grpc_recovery.StreamServerInterceptor(),
)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
grpc_ctxtags.UnaryServerInterceptor(),
grpc_opentracing.UnaryServerInterceptor(),
grpc_prometheus.UnaryServerInterceptor,
grpc_zap.UnaryServerInterceptor(zapLogger),
grpc_auth.UnaryServerInterceptor(myAuthFunction),
grpc_recovery.UnaryServerInterceptor(),
)),
)
```
## Interceptors
*Please send a PR to add new interceptors or middleware to this list*
#### Auth
* [`grpc_auth`](auth) - a customizable (via `AuthFunc`) piece of auth middleware
#### Logging
* [`grpc_ctxtags`](tags/) - a library that adds a `Tag` map to context, with data populated from request body
* [`grpc_zap`](logging/zap/) - integration of [zap](https://github.com/uber-go/zap) logging library into gRPC handlers.
* [`grpc_logrus`](logging/logrus/) - integration of [logrus](https://github.com/sirupsen/logrus) logging library into gRPC handlers.
#### Monitoring
* [`grpc_prometheus`⚡](https://github.com/grpc-ecosystem/go-grpc-prometheus) - Prometheus client-side and server-side monitoring middleware
* [`otgrpc`⚡](https://github.com/grpc-ecosystem/grpc-opentracing/tree/master/go/otgrpc) - [OpenTracing](http://opentracing.io/) client-side and server-side interceptors
* [`grpc_opentracing`](tracing/opentracing) - [OpenTracing](http://opentracing.io/) client-side and server-side interceptors with support for streaming and handler-returned tags
#### Client
* [`grpc_retry`](retry/) - a generic gRPC response code retry mechanism, client-side middleware
#### Server
* [`grpc_validator`](validator/) - codegen inbound message validation from `.proto` options
* [`grpc_recovery`](recovery/) - turn panics into gRPC errors
## Status
This code has been running in *production* since May 2016 as the basis of the gRPC micro services stack at [Improbable](https://improbable.io).
Additional tooling will be added, and contributions are welcome.
## License
`go-grpc-middleware` is released under the Apache 2.0 license. See the [LICENSE](LICENSE) file for details.
# grpc_auth
`import "github.com/grpc-ecosystem/go-grpc-middleware/auth"`
* [Overview](#pkg-overview)
* [Imported Packages](#pkg-imports)
* [Index](#pkg-index)
* [Examples](#pkg-examples)
## <a name="pkg-overview">Overview</a>
`grpc_auth` a generic server-side auth middleware for gRPC.
### Server Side Auth Middleware
It allows for easy assertion of `:authorization` headers in gRPC calls, be it HTTP Basic auth, or
OAuth2 Bearer tokens.
The middleware takes a user-customizable `AuthFunc`, which can be customized to verify and extract
auth information from the request. The extracted information can be put in the `context.Context` of
handlers downstream for retrieval.
It also allows for per-service implementation overrides of `AuthFunc`. See `ServiceAuthFuncOverride`.
Please see examples for simple examples of use.
#### Example:
<details>
<summary>Click to expand code.</summary>
```go
package grpc_auth_test
import (
"github.com/grpc-ecosystem/go-grpc-middleware/auth"
"github.com/grpc-ecosystem/go-grpc-middleware/tags"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
var (
cc *grpc.ClientConn
)
func parseToken(token string) (struct{}, error) {
return struct{}{}, nil
}
func userClaimFromToken(struct{}) string {
return "foobar"
}
// Simple example of server initialization code.
func Example_serverConfig() {
exampleAuthFunc := func(ctx context.Context) (context.Context, error) {
token, err := grpc_auth.AuthFromMD(ctx, "bearer")
if err != nil {
return nil, err
}
tokenInfo, err := parseToken(token)
if err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "invalid auth token: %v", err)
}
grpc_ctxtags.Extract(ctx).Set("auth.sub", userClaimFromToken(tokenInfo))
newCtx := context.WithValue(ctx, "tokenInfo", tokenInfo)
return newCtx, nil
}
_ = grpc.NewServer(
grpc.StreamInterceptor(grpc_auth.StreamServerInterceptor(exampleAuthFunc)),
grpc.UnaryInterceptor(grpc_auth.UnaryServerInterceptor(exampleAuthFunc)),
)
}
```
</details>
## <a name="pkg-imports">Imported Packages</a>
- [github.com/grpc-ecosystem/go-grpc-middleware](./..)
- [github.com/grpc-ecosystem/go-grpc-middleware/util/metautils](./../util/metautils)
- [golang.org/x/net/context](https://godoc.org/golang.org/x/net/context)
- [google.golang.org/grpc](https://godoc.org/google.golang.org/grpc)
- [google.golang.org/grpc/codes](https://godoc.org/google.golang.org/grpc/codes)
## <a name="pkg-index">Index</a>
* [func AuthFromMD(ctx context.Context, expectedScheme string) (string, error)](#AuthFromMD)
* [func StreamServerInterceptor(authFunc AuthFunc) grpc.StreamServerInterceptor](#StreamServerInterceptor)
* [func UnaryServerInterceptor(authFunc AuthFunc) grpc.UnaryServerInterceptor](#UnaryServerInterceptor)
* [type AuthFunc](#AuthFunc)
* [type ServiceAuthFuncOverride](#ServiceAuthFuncOverride)
#### <a name="pkg-examples">Examples</a>
* [Package (ServerConfig)](#example__serverConfig)
#### <a name="pkg-files">Package files</a>
[auth.go](./auth.go) [doc.go](./doc.go) [metadata.go](./metadata.go)
## <a name="AuthFromMD">func</a> [AuthFromMD](./metadata.go#L24)
``` go
func AuthFromMD(ctx context.Context, expectedScheme string) (string, error)
```
AuthFromMD is a helper function for extracting the :authorization header from the gRPC metadata of the request.
It expects the `:authorization` header to be of a certain scheme (e.g. `basic`, `bearer`), in a
case-insensitive format (see rfc2617, sec 1.2). If no such authorization is found, or the token
is of wrong scheme, an error with gRPC status `Unauthenticated` is returned.
## <a name="StreamServerInterceptor">func</a> [StreamServerInterceptor](./auth.go#L51)
``` go
func StreamServerInterceptor(authFunc AuthFunc) grpc.StreamServerInterceptor
```
StreamServerInterceptor returns a new unary server interceptors that performs per-request auth.
## <a name="UnaryServerInterceptor">func</a> [UnaryServerInterceptor](./auth.go#L34)
``` go
func UnaryServerInterceptor(authFunc AuthFunc) grpc.UnaryServerInterceptor
```
UnaryServerInterceptor returns a new unary server interceptors that performs per-request auth.
## <a name="AuthFunc">type</a> [AuthFunc](./auth.go#L23)
``` go
type AuthFunc func(ctx context.Context) (context.Context, error)
```
AuthFunc is the pluggable function that performs authentication.
The passed in `Context` will contain the gRPC metadata.MD object (for header-based authentication) and
the peer.Peer information that can contain transport-based credentials (e.g. `credentials.AuthInfo`).
The returned context will be propagated to handlers, allowing user changes to `Context`. However,
please make sure that the `Context` returned is a child `Context` of the one passed in.
If error is returned, its `grpc.Code()` will be returned to the user as well as the verbatim message.
Please make sure you use `codes.Unauthenticated` (lacking auth) and `codes.PermissionDenied`
(authed, but lacking perms) appropriately.
## <a name="ServiceAuthFuncOverride">type</a> [ServiceAuthFuncOverride](./auth.go#L29-L31)
``` go
type ServiceAuthFuncOverride interface {
AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error)
}
```
ServiceAuthFuncOverride allows a given gRPC service implementation to override the global `AuthFunc`.
If a service implements the AuthFuncOverride method, it takes precedence over the `AuthFunc` method,
and will be called instead of AuthFunc for all method invocations within that service.
- - -
Generated by [godoc2ghmd](https://github.com/GandalfUK/godoc2ghmd)
\ No newline at end of file
# grpc_auth
`import "github.com/grpc-ecosystem/go-grpc-middleware/auth"`
* [Overview](#pkg-overview)
* [Imported Packages](#pkg-imports)
* [Index](#pkg-index)
* [Examples](#pkg-examples)
## <a name="pkg-overview">Overview</a>
`grpc_auth` a generic server-side auth middleware for gRPC.
### Server Side Auth Middleware
It allows for easy assertion of `:authorization` headers in gRPC calls, be it HTTP Basic auth, or
OAuth2 Bearer tokens.
The middleware takes a user-customizable `AuthFunc`, which can be customized to verify and extract
auth information from the request. The extracted information can be put in the `context.Context` of
handlers downstream for retrieval.
It also allows for per-service implementation overrides of `AuthFunc`. See `ServiceAuthFuncOverride`.
Please see examples for simple examples of use.
#### Example:
<details>
<summary>Click to expand code.</summary>
```go
package grpc_auth_test
import (
"github.com/grpc-ecosystem/go-grpc-middleware/auth"
"github.com/grpc-ecosystem/go-grpc-middleware/tags"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
var (
cc *grpc.ClientConn
)
func parseToken(token string) (struct{}, error) {
return struct{}{}, nil
}
func userClaimFromToken(struct{}) string {
return "foobar"
}
// Simple example of server initialization code.
func Example_serverConfig() {
exampleAuthFunc := func(ctx context.Context) (context.Context, error) {
token, err := grpc_auth.AuthFromMD(ctx, "bearer")
if err != nil {
return nil, err
}
tokenInfo, err := parseToken(token)
if err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "invalid auth token: %v", err)
}
grpc_ctxtags.Extract(ctx).Set("auth.sub", userClaimFromToken(tokenInfo))
newCtx := context.WithValue(ctx, "tokenInfo", tokenInfo)
return newCtx, nil
}
_ = grpc.NewServer(
grpc.StreamInterceptor(grpc_auth.StreamServerInterceptor(exampleAuthFunc)),
grpc.UnaryInterceptor(grpc_auth.UnaryServerInterceptor(exampleAuthFunc)),
)
}
```
</details>
## <a name="pkg-imports">Imported Packages</a>
- [github.com/grpc-ecosystem/go-grpc-middleware](./..)
- [github.com/grpc-ecosystem/go-grpc-middleware/util/metautils](./../util/metautils)
- [golang.org/x/net/context](https://godoc.org/golang.org/x/net/context)
- [google.golang.org/grpc](https://godoc.org/google.golang.org/grpc)
- [google.golang.org/grpc/codes](https://godoc.org/google.golang.org/grpc/codes)
## <a name="pkg-index">Index</a>
* [func AuthFromMD(ctx context.Context, expectedScheme string) (string, error)](#AuthFromMD)
* [func StreamServerInterceptor(authFunc AuthFunc) grpc.StreamServerInterceptor](#StreamServerInterceptor)
* [func UnaryServerInterceptor(authFunc AuthFunc) grpc.UnaryServerInterceptor](#UnaryServerInterceptor)
* [type AuthFunc](#AuthFunc)
* [type ServiceAuthFuncOverride](#ServiceAuthFuncOverride)
#### <a name="pkg-examples">Examples</a>
* [Package (ServerConfig)](#example__serverConfig)
#### <a name="pkg-files">Package files</a>
[auth.go](./auth.go) [doc.go](./doc.go) [metadata.go](./metadata.go)
## <a name="AuthFromMD">func</a> [AuthFromMD](./metadata.go#L24)
``` go
func AuthFromMD(ctx context.Context, expectedScheme string) (string, error)
```
AuthFromMD is a helper function for extracting the :authorization header from the gRPC metadata of the request.
It expects the `:authorization` header to be of a certain scheme (e.g. `basic`, `bearer`), in a
case-insensitive format (see rfc2617, sec 1.2). If no such authorization is found, or the token
is of wrong scheme, an error with gRPC status `Unauthenticated` is returned.
## <a name="StreamServerInterceptor">func</a> [StreamServerInterceptor](./auth.go#L51)
``` go
func StreamServerInterceptor(authFunc AuthFunc) grpc.StreamServerInterceptor
```
StreamServerInterceptor returns a new unary server interceptors that performs per-request auth.
## <a name="UnaryServerInterceptor">func</a> [UnaryServerInterceptor](./auth.go#L34)
``` go
func UnaryServerInterceptor(authFunc AuthFunc) grpc.UnaryServerInterceptor
```
UnaryServerInterceptor returns a new unary server interceptors that performs per-request auth.
## <a name="AuthFunc">type</a> [AuthFunc](./auth.go#L23)
``` go
type AuthFunc func(ctx context.Context) (context.Context, error)
```
AuthFunc is the pluggable function that performs authentication.
The passed in `Context` will contain the gRPC metadata.MD object (for header-based authentication) and
the peer.Peer information that can contain transport-based credentials (e.g. `credentials.AuthInfo`).
The returned context will be propagated to handlers, allowing user changes to `Context`. However,
please make sure that the `Context` returned is a child `Context` of the one passed in.
If error is returned, its `grpc.Code()` will be returned to the user as well as the verbatim message.
Please make sure you use `codes.Unauthenticated` (lacking auth) and `codes.PermissionDenied`
(authed, but lacking perms) appropriately.
## <a name="ServiceAuthFuncOverride">type</a> [ServiceAuthFuncOverride](./auth.go#L29-L31)
``` go
type ServiceAuthFuncOverride interface {
AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error)
}
```
ServiceAuthFuncOverride allows a given gRPC service implementation to override the global `AuthFunc`.
If a service implements the AuthFuncOverride method, it takes precedence over the `AuthFunc` method,
and will be called instead of AuthFunc for all method invocations within that service.
- - -
Generated by [godoc2ghmd](https://github.com/GandalfUK/godoc2ghmd)
\ No newline at end of file
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package grpc_auth
import (
"github.com/grpc-ecosystem/go-grpc-middleware"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
// AuthFunc is the pluggable function that performs authentication.
//
// The passed in `Context` will contain the gRPC metadata.MD object (for header-based authentication) and
// the peer.Peer information that can contain transport-based credentials (e.g. `credentials.AuthInfo`).
//
// The returned context will be propagated to handlers, allowing user changes to `Context`. However,
// please make sure that the `Context` returned is a child `Context` of the one passed in.
//
// If error is returned, its `grpc.Code()` will be returned to the user as well as the verbatim message.
// Please make sure you use `codes.Unauthenticated` (lacking auth) and `codes.PermissionDenied`
// (authed, but lacking perms) appropriately.
type AuthFunc func(ctx context.Context) (context.Context, error)
// ServiceAuthFuncOverride allows a given gRPC service implementation to override the global `AuthFunc`.
//
// If a service implements the AuthFuncOverride method, it takes precedence over the `AuthFunc` method,
// and will be called instead of AuthFunc for all method invocations within that service.
type ServiceAuthFuncOverride interface {
AuthFuncOverride(ctx context.Context, fullMethodName string) (context.Context, error)
}
// UnaryServerInterceptor returns a new unary server interceptors that performs per-request auth.
func UnaryServerInterceptor(authFunc AuthFunc) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
var newCtx context.Context
var err error
if overrideSrv, ok := info.Server.(ServiceAuthFuncOverride); ok {
newCtx, err = overrideSrv.AuthFuncOverride(ctx, info.FullMethod)
} else {
newCtx, err = authFunc(ctx)
}
if err != nil {
return nil, err
}
return handler(newCtx, req)
}
}
// StreamServerInterceptor returns a new unary server interceptors that performs per-request auth.
func StreamServerInterceptor(authFunc AuthFunc) grpc.StreamServerInterceptor {
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
var newCtx context.Context
var err error
if overrideSrv, ok := srv.(ServiceAuthFuncOverride); ok {
newCtx, err = overrideSrv.AuthFuncOverride(stream.Context(), info.FullMethod)
} else {
newCtx, err = authFunc(stream.Context())
}
if err != nil {
return err
}
wrapped := grpc_middleware.WrapServerStream(stream)
wrapped.WrappedContext = newCtx
return handler(srv, wrapped)
}
}
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
/*
`grpc_auth` a generic server-side auth middleware for gRPC.
Server Side Auth Middleware
It allows for easy assertion of `:authorization` headers in gRPC calls, be it HTTP Basic auth, or
OAuth2 Bearer tokens.
The middleware takes a user-customizable `AuthFunc`, which can be customized to verify and extract
auth information from the request. The extracted information can be put in the `context.Context` of
handlers downstream for retrieval.
It also allows for per-service implementation overrides of `AuthFunc`. See `ServiceAuthFuncOverride`.
Please see examples for simple examples of use.
*/
package grpc_auth
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package grpc_auth
import (
"strings"
"github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
var (
headerAuthorize = "authorization"
)
// AuthFromMD is a helper function for extracting the :authorization header from the gRPC metadata of the request.
//
// It expects the `:authorization` header to be of a certain scheme (e.g. `basic`, `bearer`), in a
// case-insensitive format (see rfc2617, sec 1.2). If no such authorization is found, or the token
// is of wrong scheme, an error with gRPC status `Unauthenticated` is returned.
func AuthFromMD(ctx context.Context, expectedScheme string) (string, error) {
val := metautils.ExtractIncoming(ctx).Get(headerAuthorize)
if val == "" {
return "", grpc.Errorf(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
}
splits := strings.SplitN(val, " ", 2)
if len(splits) < 2 {
return "", grpc.Errorf(codes.Unauthenticated, "Bad authorization string")
}
if strings.ToLower(splits[0]) != strings.ToLower(expectedScheme) {
return "", grpc.Errorf(codes.Unauthenticated, "Request unauthenticated with "+expectedScheme)
}
return splits[1], nil
}
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
// gRPC Server Interceptor chaining middleware.
package grpc_middleware
import (
"golang.org/x/net/context"
"google.golang.org/grpc"
)
// ChainUnaryServer creates a single interceptor out of a chain of many interceptors.
//
// Execution is done in left-to-right order, including passing of context.
// For example ChainUnaryServer(one, two, three) will execute one before two before three, and three
// will see context changes of one and two.
func ChainUnaryServer(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
n := len(interceptors)
if n > 1 {
lastI := n - 1
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
var (
chainHandler grpc.UnaryHandler
curI int
)
chainHandler = func(currentCtx context.Context, currentReq interface{}) (interface{}, error) {
if curI == lastI {
return handler(currentCtx, currentReq)
}
curI++
resp, err := interceptors[curI](currentCtx, currentReq, info, chainHandler)
curI--
return resp, err
}
return interceptors[0](ctx, req, info, chainHandler)
}
}
if n == 1 {
return interceptors[0]
}
// n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil.
return func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
return handler(ctx, req)
}
}
// ChainStreamServer creates a single interceptor out of a chain of many interceptors.
//
// Execution is done in left-to-right order, including passing of context.
// For example ChainUnaryServer(one, two, three) will execute one before two before three.
// If you want to pass context between interceptors, use WrapServerStream.
func ChainStreamServer(interceptors ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor {
n := len(interceptors)
if n > 1 {
lastI := n - 1
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
var (
chainHandler grpc.StreamHandler
curI int
)
chainHandler = func(currentSrv interface{}, currentStream grpc.ServerStream) error {
if curI == lastI {
return handler(currentSrv, currentStream)
}
curI++
err := interceptors[curI](currentSrv, currentStream, info, chainHandler)
curI--
return err
}
return interceptors[0](srv, stream, info, chainHandler)
}
}
if n == 1 {
return interceptors[0]
}
// n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil.
return func(srv interface{}, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return handler(srv, stream)
}
}
// ChainUnaryClient creates a single interceptor out of a chain of many interceptors.
//
// Execution is done in left-to-right order, including passing of context.
// For example ChainUnaryClient(one, two, three) will execute one before two before three.
func ChainUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor {
n := len(interceptors)
if n > 1 {
lastI := n - 1
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
var (
chainHandler grpc.UnaryInvoker
curI int
)
chainHandler = func(currentCtx context.Context, currentMethod string, currentReq, currentRepl interface{}, currentConn *grpc.ClientConn, currentOpts ...grpc.CallOption) error {
if curI == lastI {
return invoker(currentCtx, currentMethod, currentReq, currentRepl, currentConn, currentOpts...)
}
curI++
err := interceptors[curI](currentCtx, currentMethod, currentReq, currentRepl, currentConn, chainHandler, currentOpts...)
curI--
return err
}
return interceptors[0](ctx, method, req, reply, cc, chainHandler, opts...)
}
}
if n == 1 {
return interceptors[0]
}
// n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil.
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return invoker(ctx, method, req, reply, cc, opts...)
}
}
// ChainStreamClient creates a single interceptor out of a chain of many interceptors.
//
// Execution is done in left-to-right order, including passing of context.
// For example ChainStreamClient(one, two, three) will execute one before two before three.
func ChainStreamClient(interceptors ...grpc.StreamClientInterceptor) grpc.StreamClientInterceptor {
n := len(interceptors)
if n > 1 {
lastI := n - 1
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
var (
chainHandler grpc.Streamer
curI int
)
chainHandler = func(currentCtx context.Context, currentDesc *grpc.StreamDesc, currentConn *grpc.ClientConn, currentMethod string, currentOpts ...grpc.CallOption) (grpc.ClientStream, error) {
if curI == lastI {
return streamer(currentCtx, currentDesc, currentConn, currentMethod, currentOpts...)
}
curI++
stream, err := interceptors[curI](currentCtx, currentDesc, currentConn, currentMethod, chainHandler, currentOpts...)
curI--
return stream, err
}
return interceptors[0](ctx, desc, cc, method, chainHandler, opts...)
}
}
if n == 1 {
return interceptors[0]
}
// n == 0; Dummy interceptor maintained for backward compatibility to avoid returning nil.
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
return streamer(ctx, desc, cc, method, opts...)
}
}
// Chain creates a single interceptor out of a chain of many interceptors.
//
// WithUnaryServerChain is a grpc.Server config option that accepts multiple unary interceptors.
// Basically syntactic sugar.
func WithUnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption {
return grpc.UnaryInterceptor(ChainUnaryServer(interceptors...))
}
// WithStreamServerChain is a grpc.Server config option that accepts multiple stream interceptors.
// Basically syntactic sugar.
func WithStreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption {
return grpc.StreamInterceptor(ChainStreamServer(interceptors...))
}
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
/*
`grpc_middleware` is a collection of gRPC middleware packages: interceptors, helpers and tools.
Middleware
gRPC is a fantastic RPC middleware, which sees a lot of adoption in the Golang world. However, the
upstream gRPC codebase is relatively bare bones.
This package, and most of its child packages provides commonly needed middleware for gRPC:
client-side interceptors for retires, server-side interceptors for input validation and auth,
functions for chaining said interceptors, metadata convenience methods and more.
Chaining
By default, gRPC doesn't allow one to have more than one interceptor either on the client nor on
the server side. `grpc_middleware` provides convenient chaining methods
Simple way of turning a multiple interceptors into a single interceptor. Here's an example for
server chaining:
myServer := grpc.NewServer(
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(loggingStream, monitoringStream, authStream)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(loggingUnary, monitoringUnary, authUnary),
)
These interceptors will be executed from left to right: logging, monitoring and auth.
Here's an example for client side chaining:
clientConn, err = grpc.Dial(
address,
grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(monitoringClientUnary, retryUnary)),
grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(monitoringClientStream, retryStream)),
)
client = pb_testproto.NewTestServiceClient(clientConn)
resp, err := client.PingEmpty(s.ctx, &myservice.Request{Msg: "hello"})
These interceptors will be executed from left to right: monitoring and then retry logic.
The retry interceptor will call every interceptor that follows it whenever when a retry happens.
Writing Your Own
Implementing your own interceptor is pretty trivial: there are interfaces for that. But the interesting
bit exposing common data to handlers (and other middleware), similarly to HTTP Middleware design.
For example, you may want to pass the identity of the caller from the auth interceptor all the way
to the handling function.
For example, a client side interceptor example for auth looks like:
func FakeAuthUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
newCtx := context.WithValue(ctx, "user_id", "john@example.com")
return handler(newCtx, req)
}
Unfortunately, it's not as easy for streaming RPCs. These have the `context.Context` embedded within
the `grpc.ServerStream` object. To pass values through context, a wrapper (`WrappedServerStream`) is
needed. For example:
func FakeAuthStreamingInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
newStream := grpc_middleware.WrapServerStream(stream)
newStream.WrappedContext = context.WithValue(ctx, "user_id", "john@example.com")
return handler(srv, stream)
}
*/
package grpc_middleware
SHELL="/bin/bash"
GOFILES_NOVENDOR = $(shell go list ./... | grep -v /vendor/)
all: vet fmt docs test
docs:
./scripts/docs.sh generate
checkdocs:
./scripts/docs.sh check
fmt:
go fmt $(GOFILES_NOVENDOR)
vet:
go vet $(GOFILES_NOVENDOR)
test: vet
./scripts/test_all.sh
.PHONY: all docs validate test
# metautils
`import "github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"`
* [Overview](#pkg-overview)
* [Imported Packages](#pkg-imports)
* [Index](#pkg-index)
## <a name="pkg-overview">Overview</a>
## <a name="pkg-imports">Imported Packages</a>
- [golang.org/x/net/context](https://godoc.org/golang.org/x/net/context)
- [google.golang.org/grpc/metadata](https://godoc.org/google.golang.org/grpc/metadata)
## <a name="pkg-index">Index</a>
* [type NiceMD](#NiceMD)
* [func ExtractIncoming(ctx context.Context) NiceMD](#ExtractIncoming)
* [func ExtractOutgoing(ctx context.Context) NiceMD](#ExtractOutgoing)
* [func (m NiceMD) Add(key string, value string) NiceMD](#NiceMD.Add)
* [func (m NiceMD) Clone(copiedKeys ...string) NiceMD](#NiceMD.Clone)
* [func (m NiceMD) Del(key string) NiceMD](#NiceMD.Del)
* [func (m NiceMD) Get(key string) string](#NiceMD.Get)
* [func (m NiceMD) Set(key string, value string) NiceMD](#NiceMD.Set)
* [func (m NiceMD) ToIncoming(ctx context.Context) context.Context](#NiceMD.ToIncoming)
* [func (m NiceMD) ToOutgoing(ctx context.Context) context.Context](#NiceMD.ToOutgoing)
#### <a name="pkg-files">Package files</a>
[doc.go](./doc.go) [nicemd.go](./nicemd.go) [single_key.go](./single_key.go)
## <a name="NiceMD">type</a> [NiceMD](./nicemd.go#L14)
``` go
type NiceMD metadata.MD
```
NiceMD is a convenience wrapper definiting extra functions on the metadata.
### <a name="ExtractIncoming">func</a> [ExtractIncoming](./nicemd.go#L20)
``` go
func ExtractIncoming(ctx context.Context) NiceMD
```
ExtractIncoming extracts an inbound metadata from the server-side context.
This function always returns a NiceMD wrapper of the metadata.MD, in case the context doesn't have metadata it returns
a new empty NiceMD.
### <a name="ExtractOutgoing">func</a> [ExtractOutgoing](./nicemd.go#L32)
``` go
func ExtractOutgoing(ctx context.Context) NiceMD
```
ExtractOutgoing extracts an outbound metadata from the client-side context.
This function always returns a NiceMD wrapper of the metadata.MD, in case the context doesn't have metadata it returns
a new empty NiceMD.
### <a name="NiceMD.Add">func</a> (NiceMD) [Add](./nicemd.go#L122)
``` go
func (m NiceMD) Add(key string, value string) NiceMD
```
Add retrieves a single value from the metadata.
It works analogously to http.Header.Add, as it appends to any existing values associated with key.
The function is binary-key safe.
### <a name="NiceMD.Clone">func</a> (NiceMD) [Clone](./nicemd.go#L44)
``` go
func (m NiceMD) Clone(copiedKeys ...string) NiceMD
```
Clone performs a *deep* copy of the metadata.MD.
You can specify the lower-case copiedKeys to only copy certain whitelisted keys. If no keys are explicitly whitelisted
all keys get copied.
### <a name="NiceMD.Del">func</a> (NiceMD) [Del](./nicemd.go#L100)
``` go
func (m NiceMD) Del(key string) NiceMD
```
### <a name="NiceMD.Get">func</a> (NiceMD) [Get](./nicemd.go#L85)
``` go
func (m NiceMD) Get(key string) string
```
Get retrieves a single value from the metadata.
It works analogously to http.Header.Get, returning the first value if there are many set. If the value is not set,
an empty string is returned.
The function is binary-key safe.
### <a name="NiceMD.Set">func</a> (NiceMD) [Set](./nicemd.go#L111)
``` go
func (m NiceMD) Set(key string, value string) NiceMD
```
Set sets the given value in a metadata.
It works analogously to http.Header.Set, overwriting all previous metadata values.
The function is binary-key safe.
### <a name="NiceMD.ToIncoming">func</a> (NiceMD) [ToIncoming](./nicemd.go#L75)
``` go
func (m NiceMD) ToIncoming(ctx context.Context) context.Context
```
ToIncoming sets the given NiceMD as a server-side context for dispatching.
This is mostly useful in ServerInterceptors..
### <a name="NiceMD.ToOutgoing">func</a> (NiceMD) [ToOutgoing](./nicemd.go#L68)
``` go
func (m NiceMD) ToOutgoing(ctx context.Context) context.Context
```
ToOutgoing sets the given NiceMD as a client-side context for dispatching.
- - -
Generated by [godoc2ghmd](https://github.com/GandalfUK/godoc2ghmd)
\ No newline at end of file
# metautils
`import "github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"`
* [Overview](#pkg-overview)
* [Imported Packages](#pkg-imports)
* [Index](#pkg-index)
## <a name="pkg-overview">Overview</a>
## <a name="pkg-imports">Imported Packages</a>
- [golang.org/x/net/context](https://godoc.org/golang.org/x/net/context)
- [google.golang.org/grpc/metadata](https://godoc.org/google.golang.org/grpc/metadata)
## <a name="pkg-index">Index</a>
* [type NiceMD](#NiceMD)
* [func ExtractIncoming(ctx context.Context) NiceMD](#ExtractIncoming)
* [func ExtractOutgoing(ctx context.Context) NiceMD](#ExtractOutgoing)
* [func (m NiceMD) Add(key string, value string) NiceMD](#NiceMD.Add)
* [func (m NiceMD) Clone(copiedKeys ...string) NiceMD](#NiceMD.Clone)
* [func (m NiceMD) Del(key string) NiceMD](#NiceMD.Del)
* [func (m NiceMD) Get(key string) string](#NiceMD.Get)
* [func (m NiceMD) Set(key string, value string) NiceMD](#NiceMD.Set)
* [func (m NiceMD) ToIncoming(ctx context.Context) context.Context](#NiceMD.ToIncoming)
* [func (m NiceMD) ToOutgoing(ctx context.Context) context.Context](#NiceMD.ToOutgoing)
#### <a name="pkg-files">Package files</a>
[doc.go](./doc.go) [nicemd.go](./nicemd.go) [single_key.go](./single_key.go)
## <a name="NiceMD">type</a> [NiceMD](./nicemd.go#L14)
``` go
type NiceMD metadata.MD
```
NiceMD is a convenience wrapper definiting extra functions on the metadata.
### <a name="ExtractIncoming">func</a> [ExtractIncoming](./nicemd.go#L20)
``` go
func ExtractIncoming(ctx context.Context) NiceMD
```
ExtractIncoming extracts an inbound metadata from the server-side context.
This function always returns a NiceMD wrapper of the metadata.MD, in case the context doesn't have metadata it returns
a new empty NiceMD.
### <a name="ExtractOutgoing">func</a> [ExtractOutgoing](./nicemd.go#L32)
``` go
func ExtractOutgoing(ctx context.Context) NiceMD
```
ExtractOutgoing extracts an outbound metadata from the client-side context.
This function always returns a NiceMD wrapper of the metadata.MD, in case the context doesn't have metadata it returns
a new empty NiceMD.
### <a name="NiceMD.Add">func</a> (NiceMD) [Add](./nicemd.go#L122)
``` go
func (m NiceMD) Add(key string, value string) NiceMD
```
Add retrieves a single value from the metadata.
It works analogously to http.Header.Add, as it appends to any existing values associated with key.
The function is binary-key safe.
### <a name="NiceMD.Clone">func</a> (NiceMD) [Clone](./nicemd.go#L44)
``` go
func (m NiceMD) Clone(copiedKeys ...string) NiceMD
```
Clone performs a *deep* copy of the metadata.MD.
You can specify the lower-case copiedKeys to only copy certain whitelisted keys. If no keys are explicitly whitelisted
all keys get copied.
### <a name="NiceMD.Del">func</a> (NiceMD) [Del](./nicemd.go#L100)
``` go
func (m NiceMD) Del(key string) NiceMD
```
### <a name="NiceMD.Get">func</a> (NiceMD) [Get](./nicemd.go#L85)
``` go
func (m NiceMD) Get(key string) string
```
Get retrieves a single value from the metadata.
It works analogously to http.Header.Get, returning the first value if there are many set. If the value is not set,
an empty string is returned.
The function is binary-key safe.
### <a name="NiceMD.Set">func</a> (NiceMD) [Set](./nicemd.go#L111)
``` go
func (m NiceMD) Set(key string, value string) NiceMD
```
Set sets the given value in a metadata.
It works analogously to http.Header.Set, overwriting all previous metadata values.
The function is binary-key safe.
### <a name="NiceMD.ToIncoming">func</a> (NiceMD) [ToIncoming](./nicemd.go#L75)
``` go
func (m NiceMD) ToIncoming(ctx context.Context) context.Context
```
ToIncoming sets the given NiceMD as a server-side context for dispatching.
This is mostly useful in ServerInterceptors..
### <a name="NiceMD.ToOutgoing">func</a> (NiceMD) [ToOutgoing](./nicemd.go#L68)
``` go
func (m NiceMD) ToOutgoing(ctx context.Context) context.Context
```
ToOutgoing sets the given NiceMD as a client-side context for dispatching.
- - -
Generated by [godoc2ghmd](https://github.com/GandalfUK/godoc2ghmd)
\ No newline at end of file
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
/*
Package `metautils` provides convenience functions for dealing with gRPC metadata.MD objects inside
Context handlers.
While the upstream grpc-go package contains decent functionality (see https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md)
they are hard to use.
The majority of functions center around the NiceMD, which is a convenience wrapper around metadata.MD. For example
the following code allows you to easily extract incoming metadata (server handler) and put it into a new client context
metadata.
nmd := metautils.ExtractIncoming(serverCtx).Clone(":authorization", ":custom")
clientCtx := nmd.Set("x-client-header", "2").Set("x-another", "3").ToOutgoing(ctx)
*/
package metautils
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package metautils
import (
"strings"
"golang.org/x/net/context"
"google.golang.org/grpc/metadata"
)
// NiceMD is a convenience wrapper definiting extra functions on the metadata.
type NiceMD metadata.MD
// ExtractIncoming extracts an inbound metadata from the server-side context.
//
// This function always returns a NiceMD wrapper of the metadata.MD, in case the context doesn't have metadata it returns
// a new empty NiceMD.
func ExtractIncoming(ctx context.Context) NiceMD {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return NiceMD(metadata.Pairs())
}
return NiceMD(md)
}
// ExtractOutgoing extracts an outbound metadata from the client-side context.
//
// This function always returns a NiceMD wrapper of the metadata.MD, in case the context doesn't have metadata it returns
// a new empty NiceMD.
func ExtractOutgoing(ctx context.Context) NiceMD {
md, ok := metadata.FromOutgoingContext(ctx)
if !ok {
return NiceMD(metadata.Pairs())
}
return NiceMD(md)
}
// Clone performs a *deep* copy of the metadata.MD.
//
// You can specify the lower-case copiedKeys to only copy certain whitelisted keys. If no keys are explicitly whitelisted
// all keys get copied.
func (m NiceMD) Clone(copiedKeys ...string) NiceMD {
newMd := NiceMD(metadata.Pairs())
for k, vv := range m {
found := false
if len(copiedKeys) == 0 {
found = true
} else {
for _, allowedKey := range copiedKeys {
if strings.ToLower(allowedKey) == strings.ToLower(k) {
found = true
break
}
}
}
if !found {
continue
}
newMd[k] = make([]string, len(vv))
copy(newMd[k], vv)
}
return NiceMD(newMd)
}
// ToOutgoing sets the given NiceMD as a client-side context for dispatching.
func (m NiceMD) ToOutgoing(ctx context.Context) context.Context {
return metadata.NewOutgoingContext(ctx, metadata.MD(m))
}
// ToIncoming sets the given NiceMD as a server-side context for dispatching.
//
// This is mostly useful in ServerInterceptors..
func (m NiceMD) ToIncoming(ctx context.Context) context.Context {
return metadata.NewIncomingContext(ctx, metadata.MD(m))
}
// Get retrieves a single value from the metadata.
//
// It works analogously to http.Header.Get, returning the first value if there are many set. If the value is not set,
// an empty string is returned.
//
// The function is binary-key safe.
func (m NiceMD) Get(key string) string {
k, _ := encodeKeyValue(key, "")
vv, ok := m[k]
if !ok {
return ""
}
return vv[0]
}
// Del retrieves a single value from the metadata.
//
// It works analogously to http.Header.Del, deleting all values if they exist.
//
// The function is binary-key safe.
func (m NiceMD) Del(key string) NiceMD {
k, _ := encodeKeyValue(key, "")
delete(m, k)
return m
}
// Set sets the given value in a metadata.
//
// It works analogously to http.Header.Set, overwriting all previous metadata values.
//
// The function is binary-key safe.
func (m NiceMD) Set(key string, value string) NiceMD {
k, v := encodeKeyValue(key, value)
m[k] = []string{v}
return m
}
// Add retrieves a single value from the metadata.
//
// It works analogously to http.Header.Add, as it appends to any existing values associated with key.
//
// The function is binary-key safe.
func (m NiceMD) Add(key string, value string) NiceMD {
k, v := encodeKeyValue(key, value)
m[k] = append(m[k], v)
return m
}
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package metautils
import (
"encoding/base64"
"strings"
)
const (
binHdrSuffix = "-bin"
)
func encodeKeyValue(k, v string) (string, string) {
k = strings.ToLower(k)
if strings.HasSuffix(k, binHdrSuffix) {
val := base64.StdEncoding.EncodeToString([]byte(v))
v = string(val)
}
return k, v
}
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package grpc_middleware
import (
"golang.org/x/net/context"
"google.golang.org/grpc"
)
// WrappedServerStream is a thin wrapper around grpc.ServerStream that allows modifying context.
type WrappedServerStream struct {
grpc.ServerStream
// WrappedContext is the wrapper's own Context. You can assign it.
WrappedContext context.Context
}
// Context returns the wrapper's WrappedContext, overwriting the nested grpc.ServerStream.Context()
func (w *WrappedServerStream) Context() context.Context {
return w.WrappedContext
}
// WrapServerStream returns a ServerStream that has the ability to overwrite context.
func WrapServerStream(stream grpc.ServerStream) *WrappedServerStream {
if existing, ok := stream.(*WrappedServerStream); ok {
return existing
}
return &WrappedServerStream{ServerStream: stream, WrappedContext: stream.Context()}
}
......@@ -2,6 +2,9 @@ package gitalyauth
import (
"encoding/base64"
"fmt"
"strconv"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc/credentials"
......@@ -23,3 +26,31 @@ func (*rpcCredentials) RequireTransportSecurity() bool { return false }
func (rc *rpcCredentials) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
return map[string]string{"authorization": "Bearer " + rc.token}, nil
}
// RPCCredentialsV2 can be used with grpc.WithPerRPCCredentials to create a
// grpc.DialOption that inserts an HMAC token with the current timestamp
// for authentication with a Gitaly server.
func RPCCredentialsV2(token string) credentials.PerRPCCredentials {
return &rpcCredentialsV2{token: token}
}
type rpcCredentialsV2 struct {
token string
}
func (*rpcCredentialsV2) RequireTransportSecurity() bool { return false }
func (rc *rpcCredentialsV2) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
return map[string]string{"authorization": "Bearer " + rc.hmacToken()}, nil
}
func (rc *rpcCredentialsV2) hmacToken() string {
return hmacToken("v2", []byte(rc.token), time.Now())
}
func hmacToken(version string, secret []byte, timestamp time.Time) string {
intTime := timestamp.Unix()
signedTimestamp := hmacSign(secret, strconv.FormatInt(intTime, 10))
return fmt.Sprintf("%s.%x.%d", version, signedTimestamp, intTime)
}
package gitalyauth
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"strconv"
"strings"
"time"
"github.com/grpc-ecosystem/go-grpc-middleware/auth"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
timestampThreshold = 30 * time.Second
)
var (
errUnauthenticated = status.Errorf(codes.Unauthenticated, "authentication required")
errDenied = status.Errorf(codes.PermissionDenied, "permission denied")
)
// AuthInfo contains the authentication information coming from a request
type AuthInfo struct {
Version string
SignedMessage []byte
Message string
}
// CheckToken checks the 'authentication' header of incoming gRPC
// metadata in ctx. It returns nil if and only if the token matches
// secret.
func CheckToken(ctx context.Context, secret string, targetTime time.Time) error {
if len(secret) == 0 {
panic("CheckToken: secret may not be empty")
}
authInfo, err := ExtractAuthInfo(ctx)
if err != nil {
return errUnauthenticated
}
switch authInfo.Version {
case "v1":
decodedToken, err := base64.StdEncoding.DecodeString(authInfo.Message)
if err != nil {
return errUnauthenticated
}
if tokensEqual(decodedToken, []byte(secret)) {
return nil
}
case "v2":
if hmacInfoValid(authInfo.Message, authInfo.SignedMessage, []byte(secret), targetTime, timestampThreshold) {
return nil
}
}
return errDenied
}
func tokensEqual(tok1, tok2 []byte) bool {
return subtle.ConstantTimeCompare(tok1, tok2) == 1
}
// ExtractAuthInfo returns an `AuthInfo` with the data extracted from `ctx`
func ExtractAuthInfo(ctx context.Context) (*AuthInfo, error) {
token, err := grpc_auth.AuthFromMD(ctx, "bearer")
if err != nil {
return nil, err
}
split := strings.SplitN(string(token), ".", 3)
// v1 is base64-encoded using base64.StdEncoding, which cannot contain a ".".
// A v1 token cannot slip through here.
if len(split) != 3 {
return &AuthInfo{Version: "v1", Message: token}, nil
}
version, sig, msg := split[0], split[1], split[2]
decodedSig, err := hex.DecodeString(sig)
if err != nil {
return nil, err
}
return &AuthInfo{Version: version, SignedMessage: decodedSig, Message: msg}, nil
}
func hmacInfoValid(message string, signedMessage, secret []byte, targetTime time.Time, timestampThreshold time.Duration) bool {
expectedHMAC := hmacSign(secret, message)
if !hmac.Equal(signedMessage, expectedHMAC) {
return false
}
timestamp, err := strconv.ParseInt(message, 10, 64)
if err != nil {
return false
}
issuedAt := time.Unix(timestamp, 0)
lowerBound := targetTime.Add(-timestampThreshold)
upperBound := targetTime.Add(timestampThreshold)
return issuedAt.After(lowerBound) && issuedAt.Before(upperBound)
}
func hmacSign(secret []byte, message string) []byte {
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(message))
return mac.Sum(nil)
}
......@@ -90,6 +90,24 @@
"path": "github.com/gorilla/websocket",
"revision": "e8f0f8aaa98dfb6586cbdf2978d511e3199a960a"
},
{
"checksumSHA1": "ZRhE1BjkcaROD1NZMZwICtPemTs=",
"path": "github.com/grpc-ecosystem/go-grpc-middleware",
"revision": "15ea7401d63d2d8c2f17472d22359564615a9f7a",
"revisionTime": "2018-08-24T10:49:23Z"
},
{
"checksumSHA1": "tvOR7YKj51rBR+j5C/ZyZj6rvYc=",
"path": "github.com/grpc-ecosystem/go-grpc-middleware/auth",
"revision": "15ea7401d63d2d8c2f17472d22359564615a9f7a",
"revisionTime": "2018-08-24T10:49:23Z"
},
{
"checksumSHA1": "L5z1C445GhhQmDKSisTFv754LdU=",
"path": "github.com/grpc-ecosystem/go-grpc-middleware/util/metautils",
"revision": "15ea7401d63d2d8c2f17472d22359564615a9f7a",
"revisionTime": "2018-08-24T10:49:23Z"
},
{
"checksumSHA1": "3iVD2sJv4uYnA8YgkR8yzZiUF7o=",
"path": "github.com/grpc-ecosystem/go-grpc-prometheus",
......@@ -239,12 +257,12 @@
"versionExact": "v0.111.0"
},
{
"checksumSHA1": "dUHJbKas746n5fLzlwxHb6FOCxs=",
"checksumSHA1": "SbYAalNU5azT8lJGerDI4I/Nw84=",
"path": "gitlab.com/gitlab-org/gitaly/auth",
"revision": "95a198aef54c42fd8e84c62acc63f0cd620864b3",
"revisionTime": "2018-01-18T11:33:00Z",
"version": "v0.71.0",
"versionExact": "v0.71.0"
"revision": "8a8daada771e4659baeb6fc08178179ea78010a6",
"revisionTime": "2018-09-07T08:03:54Z",
"version": "v0.120.0",
"versionExact": "v0.120.0"
},
{
"checksumSHA1": "s53Qjro9ZHX0DV2tCYQXLO2FHqI=",
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment