cubefs
288 строк · 11.5 Кб
1/*
2*
3* Copyright 2014 gRPC authors.
4*
5* Licensed under the Apache License, Version 2.0 (the "License");
6* you may not use this file except in compliance with the License.
7* You may obtain a copy of the License at
8*
9* http://www.apache.org/licenses/LICENSE-2.0
10*
11* Unless required by applicable law or agreed to in writing, software
12* distributed under the License is distributed on an "AS IS" BASIS,
13* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14* See the License for the specific language governing permissions and
15* limitations under the License.
16*
17*/
18
19// Package credentials implements various credentials supported by gRPC library,
20// which encapsulate all the state needed by a client to authenticate with a
21// server and make various assertions, e.g., about the client's identity, role,
22// or whether it is authorized to make a particular call.
23package credentials // import "google.golang.org/grpc/credentials"
24
25import (
26"context"
27"errors"
28"fmt"
29"net"
30
31"github.com/golang/protobuf/proto"
32"google.golang.org/grpc/attributes"
33"google.golang.org/grpc/internal"
34)
35
36// PerRPCCredentials defines the common interface for the credentials which need to
37// attach security information to every RPC (e.g., oauth2).
38type PerRPCCredentials interface {
39// GetRequestMetadata gets the current request metadata, refreshing
40// tokens if required. This should be called by the transport layer on
41// each request, and the data should be populated in headers or other
42// context. If a status code is returned, it will be used as the status
43// for the RPC. uri is the URI of the entry point for the request.
44// When supported by the underlying implementation, ctx can be used for
45// timeout and cancellation. Additionally, RequestInfo data will be
46// available via ctx to this call.
47// TODO(zhaoq): Define the set of the qualified keys instead of leaving
48// it as an arbitrary string.
49GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
50// RequireTransportSecurity indicates whether the credentials requires
51// transport security.
52RequireTransportSecurity() bool
53}
54
55// SecurityLevel defines the protection level on an established connection.
56//
57// This API is experimental.
58type SecurityLevel int
59
60const (
61// InvalidSecurityLevel indicates an invalid security level.
62// The zero SecurityLevel value is invalid for backward compatibility.
63InvalidSecurityLevel SecurityLevel = iota
64// NoSecurity indicates a connection is insecure.
65NoSecurity
66// IntegrityOnly indicates a connection only provides integrity protection.
67IntegrityOnly
68// PrivacyAndIntegrity indicates a connection provides both privacy and integrity protection.
69PrivacyAndIntegrity
70)
71
72// String returns SecurityLevel in a string format.
73func (s SecurityLevel) String() string {
74switch s {
75case NoSecurity:
76return "NoSecurity"
77case IntegrityOnly:
78return "IntegrityOnly"
79case PrivacyAndIntegrity:
80return "PrivacyAndIntegrity"
81}
82return fmt.Sprintf("invalid SecurityLevel: %v", int(s))
83}
84
85// CommonAuthInfo contains authenticated information common to AuthInfo implementations.
86// It should be embedded in a struct implementing AuthInfo to provide additional information
87// about the credentials.
88//
89// This API is experimental.
90type CommonAuthInfo struct {
91SecurityLevel SecurityLevel
92}
93
94// GetCommonAuthInfo returns the pointer to CommonAuthInfo struct.
95func (c CommonAuthInfo) GetCommonAuthInfo() CommonAuthInfo {
96return c
97}
98
99// ProtocolInfo provides information regarding the gRPC wire protocol version,
100// security protocol, security protocol version in use, server name, etc.
101type ProtocolInfo struct {
102// ProtocolVersion is the gRPC wire protocol version.
103ProtocolVersion string
104// SecurityProtocol is the security protocol in use.
105SecurityProtocol string
106// SecurityVersion is the security protocol version. It is a static version string from the
107// credentials, not a value that reflects per-connection protocol negotiation. To retrieve
108// details about the credentials used for a connection, use the Peer's AuthInfo field instead.
109//
110// Deprecated: please use Peer.AuthInfo.
111SecurityVersion string
112// ServerName is the user-configured server name.
113ServerName string
114}
115
116// AuthInfo defines the common interface for the auth information the users are interested in.
117// A struct that implements AuthInfo should embed CommonAuthInfo by including additional
118// information about the credentials in it.
119type AuthInfo interface {
120AuthType() string
121}
122
123// ErrConnDispatched indicates that rawConn has been dispatched out of gRPC
124// and the caller should not close rawConn.
125var ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC")
126
127// TransportCredentials defines the common interface for all the live gRPC wire
128// protocols and supported transport security protocols (e.g., TLS, SSL).
129type TransportCredentials interface {
130// ClientHandshake does the authentication handshake specified by the
131// corresponding authentication protocol on rawConn for clients. It returns
132// the authenticated connection and the corresponding auth information
133// about the connection. The auth information should embed CommonAuthInfo
134// to return additional information about the credentials. Implementations
135// must use the provided context to implement timely cancellation. gRPC
136// will try to reconnect if the error returned is a temporary error
137// (io.EOF, context.DeadlineExceeded or err.Temporary() == true). If the
138// returned error is a wrapper error, implementations should make sure that
139// the error implements Temporary() to have the correct retry behaviors.
140// Additionally, ClientHandshakeInfo data will be available via the context
141// passed to this call.
142//
143// If the returned net.Conn is closed, it MUST close the net.Conn provided.
144ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error)
145// ServerHandshake does the authentication handshake for servers. It returns
146// the authenticated connection and the corresponding auth information about
147// the connection. The auth information should embed CommonAuthInfo to return additional information
148// about the credentials.
149//
150// If the returned net.Conn is closed, it MUST close the net.Conn provided.
151ServerHandshake(net.Conn) (net.Conn, AuthInfo, error)
152// Info provides the ProtocolInfo of this TransportCredentials.
153Info() ProtocolInfo
154// Clone makes a copy of this TransportCredentials.
155Clone() TransportCredentials
156// OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server.
157// gRPC internals also use it to override the virtual hosting name if it is set.
158// It must be called before dialing. Currently, this is only used by grpclb.
159OverrideServerName(string) error
160}
161
162// Bundle is a combination of TransportCredentials and PerRPCCredentials.
163//
164// It also contains a mode switching method, so it can be used as a combination
165// of different credential policies.
166//
167// Bundle cannot be used together with individual TransportCredentials.
168// PerRPCCredentials from Bundle will be appended to other PerRPCCredentials.
169//
170// This API is experimental.
171type Bundle interface {
172TransportCredentials() TransportCredentials
173PerRPCCredentials() PerRPCCredentials
174// NewWithMode should make a copy of Bundle, and switch mode. Modifying the
175// existing Bundle may cause races.
176//
177// NewWithMode returns nil if the requested mode is not supported.
178NewWithMode(mode string) (Bundle, error)
179}
180
181// RequestInfo contains request data attached to the context passed to GetRequestMetadata calls.
182//
183// This API is experimental.
184type RequestInfo struct {
185// The method passed to Invoke or NewStream for this RPC. (For proto methods, this has the format "/some.Service/Method")
186Method string
187// AuthInfo contains the information from a security handshake (TransportCredentials.ClientHandshake, TransportCredentials.ServerHandshake)
188AuthInfo AuthInfo
189}
190
191// requestInfoKey is a struct to be used as the key when attaching a RequestInfo to a context object.
192type requestInfoKey struct{}
193
194// RequestInfoFromContext extracts the RequestInfo from the context if it exists.
195//
196// This API is experimental.
197func RequestInfoFromContext(ctx context.Context) (ri RequestInfo, ok bool) {
198ri, ok = ctx.Value(requestInfoKey{}).(RequestInfo)
199return
200}
201
202// ClientHandshakeInfo holds data to be passed to ClientHandshake. This makes
203// it possible to pass arbitrary data to the handshaker from gRPC, resolver,
204// balancer etc. Individual credential implementations control the actual
205// format of the data that they are willing to receive.
206//
207// This API is experimental.
208type ClientHandshakeInfo struct {
209// Attributes contains the attributes for the address. It could be provided
210// by the gRPC, resolver, balancer etc.
211Attributes *attributes.Attributes
212}
213
214// clientHandshakeInfoKey is a struct used as the key to store
215// ClientHandshakeInfo in a context.
216type clientHandshakeInfoKey struct{}
217
218// ClientHandshakeInfoFromContext returns the ClientHandshakeInfo struct stored
219// in ctx.
220//
221// This API is experimental.
222func ClientHandshakeInfoFromContext(ctx context.Context) ClientHandshakeInfo {
223chi, _ := ctx.Value(clientHandshakeInfoKey{}).(ClientHandshakeInfo)
224return chi
225}
226
227// CheckSecurityLevel checks if a connection's security level is greater than or equal to the specified one.
228// It returns success if 1) the condition is satisified or 2) AuthInfo struct does not implement GetCommonAuthInfo() method
229// or 3) CommonAuthInfo.SecurityLevel has an invalid zero value. For 2) and 3), it is for the purpose of backward-compatibility.
230//
231// This API is experimental.
232func CheckSecurityLevel(ai AuthInfo, level SecurityLevel) error {
233type internalInfo interface {
234GetCommonAuthInfo() CommonAuthInfo
235}
236if ai == nil {
237return errors.New("AuthInfo is nil")
238}
239if ci, ok := ai.(internalInfo); ok {
240// CommonAuthInfo.SecurityLevel has an invalid value.
241if ci.GetCommonAuthInfo().SecurityLevel == InvalidSecurityLevel {
242return nil
243}
244if ci.GetCommonAuthInfo().SecurityLevel < level {
245return fmt.Errorf("requires SecurityLevel %v; connection has %v", level, ci.GetCommonAuthInfo().SecurityLevel)
246}
247}
248// The condition is satisfied or AuthInfo struct does not implement GetCommonAuthInfo() method.
249return nil
250}
251
252func init() {
253internal.NewRequestInfoContext = func(ctx context.Context, ri RequestInfo) context.Context {
254return context.WithValue(ctx, requestInfoKey{}, ri)
255}
256internal.NewClientHandshakeInfoContext = func(ctx context.Context, chi ClientHandshakeInfo) context.Context {
257return context.WithValue(ctx, clientHandshakeInfoKey{}, chi)
258}
259}
260
261// ChannelzSecurityInfo defines the interface that security protocols should implement
262// in order to provide security info to channelz.
263//
264// This API is experimental.
265type ChannelzSecurityInfo interface {
266GetSecurityValue() ChannelzSecurityValue
267}
268
269// ChannelzSecurityValue defines the interface that GetSecurityValue() return value
270// should satisfy. This interface should only be satisfied by *TLSChannelzSecurityValue
271// and *OtherChannelzSecurityValue.
272//
273// This API is experimental.
274type ChannelzSecurityValue interface {
275isChannelzSecurityValue()
276}
277
278// OtherChannelzSecurityValue defines the struct that non-TLS protocol should return
279// from GetSecurityValue(), which contains protocol specific security info. Note
280// the Value field will be sent to users of channelz requesting channel info, and
281// thus sensitive info should better be avoided.
282//
283// This API is experimental.
284type OtherChannelzSecurityValue struct {
285ChannelzSecurityValue
286Name string
287Value proto.Message
288}
289