blob: 845ce5d21618153773e7fbcc47911826fb9577a1 [file] [log] [blame]
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +00001/*
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"
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +000027 "errors"
28 "fmt"
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +000029 "net"
30
31 "github.com/golang/protobuf/proto"
Dinesh Belwalkar396b6522020-02-06 22:11:53 +000032 "google.golang.org/grpc/internal"
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +000033)
34
35// PerRPCCredentials defines the common interface for the credentials which need to
36// attach security information to every RPC (e.g., oauth2).
37type PerRPCCredentials interface {
38 // GetRequestMetadata gets the current request metadata, refreshing
39 // tokens if required. This should be called by the transport layer on
40 // each request, and the data should be populated in headers or other
41 // context. If a status code is returned, it will be used as the status
42 // for the RPC. uri is the URI of the entry point for the request.
43 // When supported by the underlying implementation, ctx can be used for
44 // timeout and cancellation. Additionally, RequestInfo data will be
45 // available via ctx to this call.
46 // TODO(zhaoq): Define the set of the qualified keys instead of leaving
47 // it as an arbitrary string.
48 GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
49 // RequireTransportSecurity indicates whether the credentials requires
50 // transport security.
51 RequireTransportSecurity() bool
52}
53
Dinesh Belwalkar396b6522020-02-06 22:11:53 +000054// SecurityLevel defines the protection level on an established connection.
55//
56// This API is experimental.
57type SecurityLevel int
58
59const (
60 // NoSecurity indicates a connection is insecure.
61 // The zero SecurityLevel value is invalid for backward compatibility.
62 NoSecurity SecurityLevel = iota + 1
63 // IntegrityOnly indicates a connection only provides integrity protection.
64 IntegrityOnly
65 // PrivacyAndIntegrity indicates a connection provides both privacy and integrity protection.
66 PrivacyAndIntegrity
67)
68
69// String returns SecurityLevel in a string format.
70func (s SecurityLevel) String() string {
71 switch s {
72 case NoSecurity:
73 return "NoSecurity"
74 case IntegrityOnly:
75 return "IntegrityOnly"
76 case PrivacyAndIntegrity:
77 return "PrivacyAndIntegrity"
78 }
79 return fmt.Sprintf("invalid SecurityLevel: %v", int(s))
80}
81
82// CommonAuthInfo contains authenticated information common to AuthInfo implementations.
83// It should be embedded in a struct implementing AuthInfo to provide additional information
84// about the credentials.
85//
86// This API is experimental.
87type CommonAuthInfo struct {
88 SecurityLevel SecurityLevel
89}
90
91// GetCommonAuthInfo returns the pointer to CommonAuthInfo struct.
92func (c *CommonAuthInfo) GetCommonAuthInfo() *CommonAuthInfo {
93 return c
94}
95
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +000096// ProtocolInfo provides information regarding the gRPC wire protocol version,
97// security protocol, security protocol version in use, server name, etc.
98type ProtocolInfo struct {
99 // ProtocolVersion is the gRPC wire protocol version.
100 ProtocolVersion string
101 // SecurityProtocol is the security protocol in use.
102 SecurityProtocol string
103 // SecurityVersion is the security protocol version.
104 SecurityVersion string
105 // ServerName is the user-configured server name.
106 ServerName string
107}
108
109// AuthInfo defines the common interface for the auth information the users are interested in.
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000110// A struct that implements AuthInfo should embed CommonAuthInfo by including additional
111// information about the credentials in it.
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000112type AuthInfo interface {
113 AuthType() string
114}
115
116// ErrConnDispatched indicates that rawConn has been dispatched out of gRPC
117// and the caller should not close rawConn.
118var ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC")
119
120// TransportCredentials defines the common interface for all the live gRPC wire
121// protocols and supported transport security protocols (e.g., TLS, SSL).
122type TransportCredentials interface {
123 // ClientHandshake does the authentication handshake specified by the corresponding
124 // authentication protocol on rawConn for clients. It returns the authenticated
125 // connection and the corresponding auth information about the connection.
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000126 // The auth information should embed CommonAuthInfo to return additional information about
127 // the credentials. Implementations must use the provided context to implement timely cancellation.
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000128 // gRPC will try to reconnect if the error returned is a temporary error
129 // (io.EOF, context.DeadlineExceeded or err.Temporary() == true).
130 // If the returned error is a wrapper error, implementations should make sure that
131 // the error implements Temporary() to have the correct retry behaviors.
132 //
133 // If the returned net.Conn is closed, it MUST close the net.Conn provided.
134 ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error)
135 // ServerHandshake does the authentication handshake for servers. It returns
136 // the authenticated connection and the corresponding auth information about
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000137 // the connection. The auth information should embed CommonAuthInfo to return additional information
138 // about the credentials.
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000139 //
140 // If the returned net.Conn is closed, it MUST close the net.Conn provided.
141 ServerHandshake(net.Conn) (net.Conn, AuthInfo, error)
142 // Info provides the ProtocolInfo of this TransportCredentials.
143 Info() ProtocolInfo
144 // Clone makes a copy of this TransportCredentials.
145 Clone() TransportCredentials
146 // OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server.
147 // gRPC internals also use it to override the virtual hosting name if it is set.
148 // It must be called before dialing. Currently, this is only used by grpclb.
149 OverrideServerName(string) error
150}
151
152// Bundle is a combination of TransportCredentials and PerRPCCredentials.
153//
154// It also contains a mode switching method, so it can be used as a combination
155// of different credential policies.
156//
157// Bundle cannot be used together with individual TransportCredentials.
158// PerRPCCredentials from Bundle will be appended to other PerRPCCredentials.
159//
160// This API is experimental.
161type Bundle interface {
162 TransportCredentials() TransportCredentials
163 PerRPCCredentials() PerRPCCredentials
164 // NewWithMode should make a copy of Bundle, and switch mode. Modifying the
165 // existing Bundle may cause races.
166 //
167 // NewWithMode returns nil if the requested mode is not supported.
168 NewWithMode(mode string) (Bundle, error)
169}
170
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000171// RequestInfo contains request data attached to the context passed to GetRequestMetadata calls.
172//
173// This API is experimental.
174type RequestInfo struct {
175 // The method passed to Invoke or NewStream for this RPC. (For proto methods, this has the format "/some.Service/Method")
176 Method string
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000177 // AuthInfo contains the information from a security handshake (TransportCredentials.ClientHandshake, TransportCredentials.ServerHandshake)
178 AuthInfo AuthInfo
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000179}
180
181// requestInfoKey is a struct to be used as the key when attaching a RequestInfo to a context object.
182type requestInfoKey struct{}
183
184// RequestInfoFromContext extracts the RequestInfo from the context if it exists.
185//
186// This API is experimental.
187func RequestInfoFromContext(ctx context.Context) (ri RequestInfo, ok bool) {
188 ri, ok = ctx.Value(requestInfoKey{}).(RequestInfo)
189 return
190}
191
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000192// CheckSecurityLevel checks if a connection's security level is greater than or equal to the specified one.
193// It returns success if 1) the condition is satisified or 2) AuthInfo struct does not implement GetCommonAuthInfo() method
194// or 3) CommonAuthInfo.SecurityLevel has an invalid zero value. For 2) and 3), it is for the purpose of backward-compatibility.
195//
196// This API is experimental.
197func CheckSecurityLevel(ctx context.Context, level SecurityLevel) error {
198 type internalInfo interface {
199 GetCommonAuthInfo() *CommonAuthInfo
200 }
201 ri, _ := RequestInfoFromContext(ctx)
202 if ri.AuthInfo == nil {
203 return errors.New("unable to obtain SecurityLevel from context")
204 }
205 if ci, ok := ri.AuthInfo.(internalInfo); ok {
206 // CommonAuthInfo.SecurityLevel has an invalid value.
207 if ci.GetCommonAuthInfo().SecurityLevel == 0 {
208 return nil
209 }
210 if ci.GetCommonAuthInfo().SecurityLevel < level {
211 return fmt.Errorf("requires SecurityLevel %v; connection has %v", level, ci.GetCommonAuthInfo().SecurityLevel)
212 }
213 }
214 // The condition is satisfied or AuthInfo struct does not implement GetCommonAuthInfo() method.
215 return nil
216}
217
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000218func init() {
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000219 internal.NewRequestInfoContext = func(ctx context.Context, ri RequestInfo) context.Context {
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +0000220 return context.WithValue(ctx, requestInfoKey{}, ri)
221 }
222}
Dinesh Belwalkar396b6522020-02-06 22:11:53 +0000223
224// ChannelzSecurityInfo defines the interface that security protocols should implement
225// in order to provide security info to channelz.
226//
227// This API is experimental.
228type ChannelzSecurityInfo interface {
229 GetSecurityValue() ChannelzSecurityValue
230}
231
232// ChannelzSecurityValue defines the interface that GetSecurityValue() return value
233// should satisfy. This interface should only be satisfied by *TLSChannelzSecurityValue
234// and *OtherChannelzSecurityValue.
235//
236// This API is experimental.
237type ChannelzSecurityValue interface {
238 isChannelzSecurityValue()
239}
240
241// OtherChannelzSecurityValue defines the struct that non-TLS protocol should return
242// from GetSecurityValue(), which contains protocol specific security info. Note
243// the Value field will be sent to users of channelz requesting channel info, and
244// thus sensitive info should better be avoided.
245//
246// This API is experimental.
247type OtherChannelzSecurityValue struct {
248 ChannelzSecurityValue
249 Name string
250 Value proto.Message
251}