blob: c8e337cdda07b7167d52d3e07f4aa7414f0cc88c [file] [log] [blame]
khenaidooac637102019-01-14 15:44:34 -05001/*
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"
khenaidooac637102019-01-14 15:44:34 -050027 "errors"
28 "fmt"
khenaidooac637102019-01-14 15:44:34 -050029 "net"
khenaidooac637102019-01-14 15:44:34 -050030
Abhay Kumara2ae5992025-11-10 14:02:24 +000031 "google.golang.org/grpc/attributes"
32 icredentials "google.golang.org/grpc/internal/credentials"
33 "google.golang.org/protobuf/proto"
khenaidooac637102019-01-14 15:44:34 -050034)
35
khenaidooac637102019-01-14 15:44:34 -050036// PerRPCCredentials defines the common interface for the credentials which need to
37// attach security information to every RPC (e.g., oauth2).
38type PerRPCCredentials interface {
Abhay Kumara2ae5992025-11-10 14:02:24 +000039 // GetRequestMetadata gets the current request metadata, refreshing tokens
40 // if required. This should be called by the transport layer on each
41 // 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 for
43 // the RPC (restricted to an allowable set of codes as defined by gRFC
44 // A54). uri is the URI of the entry point for the request. When supported
45 // by the underlying implementation, ctx can be used for timeout and
46 // cancellation. Additionally, RequestInfo data will be available via ctx
47 // to this call. TODO(zhaoq): Define the set of the qualified keys instead
48 // of leaving it as an arbitrary string.
khenaidooac637102019-01-14 15:44:34 -050049 GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
50 // RequireTransportSecurity indicates whether the credentials requires
51 // transport security.
52 RequireTransportSecurity() bool
53}
54
Abhay Kumara2ae5992025-11-10 14:02:24 +000055// 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.
63 InvalidSecurityLevel SecurityLevel = iota
64 // NoSecurity indicates a connection is insecure.
65 NoSecurity
66 // IntegrityOnly indicates a connection only provides integrity protection.
67 IntegrityOnly
68 // PrivacyAndIntegrity indicates a connection provides both privacy and integrity protection.
69 PrivacyAndIntegrity
70)
71
72// String returns SecurityLevel in a string format.
73func (s SecurityLevel) String() string {
74 switch s {
75 case NoSecurity:
76 return "NoSecurity"
77 case IntegrityOnly:
78 return "IntegrityOnly"
79 case PrivacyAndIntegrity:
80 return "PrivacyAndIntegrity"
81 }
82 return 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 {
91 SecurityLevel SecurityLevel
92}
93
94// GetCommonAuthInfo returns the pointer to CommonAuthInfo struct.
95func (c CommonAuthInfo) GetCommonAuthInfo() CommonAuthInfo {
96 return c
97}
98
99// ProtocolInfo provides static information regarding transport credentials.
khenaidooac637102019-01-14 15:44:34 -0500100type ProtocolInfo struct {
101 // ProtocolVersion is the gRPC wire protocol version.
Abhay Kumara2ae5992025-11-10 14:02:24 +0000102 //
103 // Deprecated: this is unused by gRPC.
khenaidooac637102019-01-14 15:44:34 -0500104 ProtocolVersion string
105 // SecurityProtocol is the security protocol in use.
106 SecurityProtocol string
Abhay Kumara2ae5992025-11-10 14:02:24 +0000107 // SecurityVersion is the security protocol version. It is a static version string from the
108 // credentials, not a value that reflects per-connection protocol negotiation. To retrieve
109 // details about the credentials used for a connection, use the Peer's AuthInfo field instead.
110 //
111 // Deprecated: please use Peer.AuthInfo.
khenaidooac637102019-01-14 15:44:34 -0500112 SecurityVersion string
Abhay Kumara2ae5992025-11-10 14:02:24 +0000113 // ServerName is the user-configured server name. If set, this overrides
114 // the default :authority header used for all RPCs on the channel using the
115 // containing credentials, unless grpc.WithAuthority is set on the channel,
116 // in which case that setting will take precedence.
117 //
118 // This must be a valid `:authority` header according to
119 // [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.2).
120 //
121 // Deprecated: Users should use grpc.WithAuthority to override the authority
122 // on a channel instead of configuring the credentials.
khenaidooac637102019-01-14 15:44:34 -0500123 ServerName string
124}
125
126// AuthInfo defines the common interface for the auth information the users are interested in.
Abhay Kumara2ae5992025-11-10 14:02:24 +0000127// A struct that implements AuthInfo should embed CommonAuthInfo by including additional
128// information about the credentials in it.
khenaidooac637102019-01-14 15:44:34 -0500129type AuthInfo interface {
130 AuthType() string
131}
132
Abhay Kumara2ae5992025-11-10 14:02:24 +0000133// AuthorityValidator validates the authority used to override the `:authority`
134// header. This is an optional interface that implementations of AuthInfo can
135// implement if they support per-RPC authority overrides. It is invoked when the
136// application attempts to override the HTTP/2 `:authority` header using the
137// CallAuthority call option.
138type AuthorityValidator interface {
139 // ValidateAuthority checks the authority value used to override the
140 // `:authority` header. The authority parameter is the override value
141 // provided by the application via the CallAuthority option. This value
142 // typically corresponds to the server hostname or endpoint the RPC is
143 // targeting. It returns non-nil error if the validation fails.
144 ValidateAuthority(authority string) error
145}
146
khenaidooac637102019-01-14 15:44:34 -0500147// ErrConnDispatched indicates that rawConn has been dispatched out of gRPC
148// and the caller should not close rawConn.
149var ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC")
150
151// TransportCredentials defines the common interface for all the live gRPC wire
152// protocols and supported transport security protocols (e.g., TLS, SSL).
153type TransportCredentials interface {
Abhay Kumara2ae5992025-11-10 14:02:24 +0000154 // ClientHandshake does the authentication handshake specified by the
155 // corresponding authentication protocol on rawConn for clients. It returns
156 // the authenticated connection and the corresponding auth information
157 // about the connection. The auth information should embed CommonAuthInfo
158 // to return additional information about the credentials. Implementations
159 // must use the provided context to implement timely cancellation. gRPC
160 // will try to reconnect if the error returned is a temporary error
161 // (io.EOF, context.DeadlineExceeded or err.Temporary() == true). If the
162 // returned error is a wrapper error, implementations should make sure that
khenaidooac637102019-01-14 15:44:34 -0500163 // the error implements Temporary() to have the correct retry behaviors.
Abhay Kumara2ae5992025-11-10 14:02:24 +0000164 // Additionally, ClientHandshakeInfo data will be available via the context
165 // passed to this call.
166 //
167 // The second argument to this method is the `:authority` header value used
168 // while creating new streams on this connection after authentication
169 // succeeds. Implementations must use this as the server name during the
170 // authentication handshake.
khenaidooac637102019-01-14 15:44:34 -0500171 //
172 // If the returned net.Conn is closed, it MUST close the net.Conn provided.
173 ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error)
174 // ServerHandshake does the authentication handshake for servers. It returns
175 // the authenticated connection and the corresponding auth information about
Abhay Kumara2ae5992025-11-10 14:02:24 +0000176 // the connection. The auth information should embed CommonAuthInfo to return additional information
177 // about the credentials.
khenaidooac637102019-01-14 15:44:34 -0500178 //
179 // If the returned net.Conn is closed, it MUST close the net.Conn provided.
180 ServerHandshake(net.Conn) (net.Conn, AuthInfo, error)
181 // Info provides the ProtocolInfo of this TransportCredentials.
182 Info() ProtocolInfo
183 // Clone makes a copy of this TransportCredentials.
184 Clone() TransportCredentials
Abhay Kumara2ae5992025-11-10 14:02:24 +0000185 // OverrideServerName specifies the value used for the following:
186 //
187 // - verifying the hostname on the returned certificates
188 // - as SNI in the client's handshake to support virtual hosting
189 // - as the value for `:authority` header at stream creation time
190 //
191 // The provided string should be a valid `:authority` header according to
192 // [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.2).
193 //
194 // Deprecated: this method is unused by gRPC. Users should use
195 // grpc.WithAuthority to override the authority on a channel instead of
196 // configuring the credentials.
khenaidooac637102019-01-14 15:44:34 -0500197 OverrideServerName(string) error
198}
199
200// Bundle is a combination of TransportCredentials and PerRPCCredentials.
201//
202// It also contains a mode switching method, so it can be used as a combination
203// of different credential policies.
204//
205// Bundle cannot be used together with individual TransportCredentials.
206// PerRPCCredentials from Bundle will be appended to other PerRPCCredentials.
207//
208// This API is experimental.
209type Bundle interface {
Abhay Kumara2ae5992025-11-10 14:02:24 +0000210 // TransportCredentials returns the transport credentials from the Bundle.
211 //
212 // Implementations must return non-nil transport credentials. If transport
213 // security is not needed by the Bundle, implementations may choose to
214 // return insecure.NewCredentials().
khenaidooac637102019-01-14 15:44:34 -0500215 TransportCredentials() TransportCredentials
Abhay Kumara2ae5992025-11-10 14:02:24 +0000216
217 // PerRPCCredentials returns the per-RPC credentials from the Bundle.
218 //
219 // May be nil if per-RPC credentials are not needed.
khenaidooac637102019-01-14 15:44:34 -0500220 PerRPCCredentials() PerRPCCredentials
Abhay Kumara2ae5992025-11-10 14:02:24 +0000221
khenaidooac637102019-01-14 15:44:34 -0500222 // NewWithMode should make a copy of Bundle, and switch mode. Modifying the
223 // existing Bundle may cause races.
224 //
225 // NewWithMode returns nil if the requested mode is not supported.
226 NewWithMode(mode string) (Bundle, error)
227}
228
Andrea Campanella3614a922021-02-25 12:40:42 +0100229// RequestInfo contains request data attached to the context passed to GetRequestMetadata calls.
230//
231// This API is experimental.
232type RequestInfo struct {
233 // The method passed to Invoke or NewStream for this RPC. (For proto methods, this has the format "/some.Service/Method")
234 Method string
Abhay Kumara2ae5992025-11-10 14:02:24 +0000235 // AuthInfo contains the information from a security handshake (TransportCredentials.ClientHandshake, TransportCredentials.ServerHandshake)
236 AuthInfo AuthInfo
Andrea Campanella3614a922021-02-25 12:40:42 +0100237}
238
Abhay Kumara2ae5992025-11-10 14:02:24 +0000239// requestInfoKey is a struct to be used as the key to store RequestInfo in a
240// context.
Andrea Campanella3614a922021-02-25 12:40:42 +0100241type requestInfoKey struct{}
242
243// RequestInfoFromContext extracts the RequestInfo from the context if it exists.
244//
245// This API is experimental.
246func RequestInfoFromContext(ctx context.Context) (ri RequestInfo, ok bool) {
247 ri, ok = ctx.Value(requestInfoKey{}).(RequestInfo)
Abhay Kumara2ae5992025-11-10 14:02:24 +0000248 return ri, ok
Andrea Campanella3614a922021-02-25 12:40:42 +0100249}
250
Abhay Kumara2ae5992025-11-10 14:02:24 +0000251// NewContextWithRequestInfo creates a new context from ctx and attaches ri to it.
252//
253// This RequestInfo will be accessible via RequestInfoFromContext.
254//
255// Intended to be used from tests for PerRPCCredentials implementations (that
256// often need to check connection's SecurityLevel). Should not be used from
257// non-test code: the gRPC client already prepares a context with the correct
258// RequestInfo attached when calling PerRPCCredentials.GetRequestMetadata.
259//
260// This API is experimental.
261func NewContextWithRequestInfo(ctx context.Context, ri RequestInfo) context.Context {
262 return context.WithValue(ctx, requestInfoKey{}, ri)
263}
264
265// ClientHandshakeInfo holds data to be passed to ClientHandshake. This makes
266// it possible to pass arbitrary data to the handshaker from gRPC, resolver,
267// balancer etc. Individual credential implementations control the actual
268// format of the data that they are willing to receive.
269//
270// This API is experimental.
271type ClientHandshakeInfo struct {
272 // Attributes contains the attributes for the address. It could be provided
273 // by the gRPC, resolver, balancer etc.
274 Attributes *attributes.Attributes
275}
276
277// ClientHandshakeInfoFromContext returns the ClientHandshakeInfo struct stored
278// in ctx.
279//
280// This API is experimental.
281func ClientHandshakeInfoFromContext(ctx context.Context) ClientHandshakeInfo {
282 chi, _ := icredentials.ClientHandshakeInfoFromContext(ctx).(ClientHandshakeInfo)
283 return chi
284}
285
286// CheckSecurityLevel checks if a connection's security level is greater than or equal to the specified one.
287// It returns success if 1) the condition is satisfied or 2) AuthInfo struct does not implement GetCommonAuthInfo() method
288// or 3) CommonAuthInfo.SecurityLevel has an invalid zero value. For 2) and 3), it is for the purpose of backward-compatibility.
289//
290// This API is experimental.
291func CheckSecurityLevel(ai AuthInfo, level SecurityLevel) error {
292 type internalInfo interface {
293 GetCommonAuthInfo() CommonAuthInfo
Andrea Campanella3614a922021-02-25 12:40:42 +0100294 }
Abhay Kumara2ae5992025-11-10 14:02:24 +0000295 if ai == nil {
296 return errors.New("AuthInfo is nil")
297 }
298 if ci, ok := ai.(internalInfo); ok {
299 // CommonAuthInfo.SecurityLevel has an invalid value.
300 if ci.GetCommonAuthInfo().SecurityLevel == InvalidSecurityLevel {
301 return nil
302 }
303 if ci.GetCommonAuthInfo().SecurityLevel < level {
304 return fmt.Errorf("requires SecurityLevel %v; connection has %v", level, ci.GetCommonAuthInfo().SecurityLevel)
305 }
306 }
307 // The condition is satisfied or AuthInfo struct does not implement GetCommonAuthInfo() method.
308 return nil
309}
310
311// ChannelzSecurityInfo defines the interface that security protocols should implement
312// in order to provide security info to channelz.
313//
314// This API is experimental.
315type ChannelzSecurityInfo interface {
316 GetSecurityValue() ChannelzSecurityValue
317}
318
319// ChannelzSecurityValue defines the interface that GetSecurityValue() return value
320// should satisfy. This interface should only be satisfied by *TLSChannelzSecurityValue
321// and *OtherChannelzSecurityValue.
322//
323// This API is experimental.
324type ChannelzSecurityValue interface {
325 isChannelzSecurityValue()
326}
327
328// OtherChannelzSecurityValue defines the struct that non-TLS protocol should return
329// from GetSecurityValue(), which contains protocol specific security info. Note
330// the Value field will be sent to users of channelz requesting channel info, and
331// thus sensitive info should better be avoided.
332//
333// This API is experimental.
334type OtherChannelzSecurityValue struct {
335 ChannelzSecurityValue
336 Name string
337 Value proto.Message
Andrea Campanella3614a922021-02-25 12:40:42 +0100338}