cbauth

package module
v0.1.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 27, 2024 License: Apache-2.0 Imports: 23 Imported by: 75

README

= 4 ways golang services can interact with ns_server
Aliaksey Kandratsenka <alk@tut.by

== Stats

Stats is a simple way to expose certain state to ns_server. And
preferred format is expvar's like as documented elsewhere.

== metakv

metakv is a simple way for your service to store certain low-traffic
metadata (i.e. settings) in cluster-manager. metakv also allows you to
subscribe to settings changes. So it makes it simple way for your
service consume ns_server-managed settings. It is good at delivering
settings changes to your service (or between services) in asynchronous
fashion.

Look at godoc of github.com/couchbase/cbauth/metakv package for more
details.

== revrpc

revrpc is secure and simple-to-use facility to expose rpc services to
ns_server. Unlike metakv it is well suited for cases when you need
some synchronous updates from ns_server (and you can return something
back too). Now-defunct "cluster topology changes management protocol"
where ns_server needs to ask services to update their topology and
wait for results is one example. cbauth itself is
another. saslauthd-port is using revrpc too.

As revrpc client you typically only need to create your Service
instance and than start it via BabysitService while passing your rpc
setup function. That function will receive rpc.Server instance and is
expected to publish whatever rpc service you need onto that rpc.Server
instance. Instances published in this way are available via simple
call to ns_server's json_rpc_connection module. I.e. revrpc gives you
all convenience of net/rpc. See net/rpc and net/rpc/jsonrpc godoc for
details.

Thus revrpc calls are convenient to use both for ns_server side and
golang side.

Note that as of now there are no users of revrpc outside of cbauth
itself, but I do anticipate that this might change. It is certainly
going to be our preferred choice in cases we're given choice.

One arguable downside of revrpc is that it's harder to invoke it
manually because it's not just plain REST API (which is merely a flip
side of security advantage mentioned above). We will provide script to
help folks perform arbitrary revrpc calls via ns_server.

Under the hood revrpc works by establishing special connection to
ns_server (with authorization and via special http method). And then
using "plain socket" jsonrpc from ns_server to your service via that
connection. Thus "rev" (from reverse) in it's name. Even though just
single connection is used per single revrpc.Service instance, it can
deal with arbitrary number of outstanding, in-flight calls. This is
feature of json-rpc spec (i.e. out-of-order replies). And golang's
net/rpc facility is enabling it by simply spawning fresh goroutine for
every incoming call (which then "injects" response into
rpc.ServerCodec as soon as result is ready).

revrpc is usually initialized by CBAUTH_REVRPC_URL variable (of the
form of
http://%40:<urlencoded-node's-password>@127.0.0.1:8091/<your-program's-name>).

In order to use it for your service look at
revrpc.GetDefaultServiceFromEnv. serviceName argument is "subservice"
that you want to expose. "cbauth" subservice is reserved for cbauth
itself. So your subservice for e.g. indexer could be "main" or
"indexer". Then at ns_server's side Label argument to
json_rpc_connection:perform_call function would be 'indexer-indexer'
(service, dash, subservice).

Note that there is currently no way to stop revrpc service that is
started. Due to lack of demand for that feature.

== cbauth

cbauth is simple way to get credentials to access cluster services and
to authenticate/authorize incoming http requests.

See this package's godoc as well as ./cmd/multi-bucket-demo and
./cmd/cbauth-demo programs for user API.

cbauth works by receiving cluster-manager's "creds database" via
revrpc facility (described above). revrpc itself is configured via
environment variable(s) passed by ns_server. So, unlike in initial
implementation, cbauth is not directly configured from environment
variables anymore, but is merely one of consumers of revrpc.

It is quite important to internalize that cbauth works only if revrpc
is properly configured. When your service is started by ns_server this
is usually the case.

Sometimes you want to start your application manually (i.e. for
debugging). In which case consider looking at
cbauth.InternalRetryDefaultInit function for way to initialize cbauth
"manually". But note that in any case cbauth will in still depend on
working (and up-to-date) ns_server. Or you might want to set revrpc
environment variable manually prior to running your program (see
above).

Documentation

Overview

Package cbauth provides auth{N,Z} for couchbase server services.

Index

Constants

View Source
const (
	CFG_CHANGE_CERTS_TLSCONFIG uint64 = 1 << iota
	CFG_CHANGE_CLUSTER_ENCRYPTION
	CFG_CHANGE_CLIENT_CERTS_TLSCONFIG
	CFG_CHANGE_GUARDRAIL_STATUSES
)

The following constants are used as flags to indicate which configuration has changed. These flags are passed as an argument to 'ConfigRefreshcallback' function registered using the 'RegisterConfigRefreshCallback' API.

Variables

View Source
var ErrNoAuth = cbauthimpl.ErrNoAuth

ErrNoAuth is an error that is returned when the user credentials are not recognized

View Source
var ErrNoUuid = cbauthimpl.ErrNoUuid

ErrNoUuid is an error that is returned when the uuid for user is empty

View Source
var ErrNotInitialized = errors.New("cbauth was not initialized")

ErrNotInitialized is used to signal that ns_server environment variables are not set, and thus Default authenticator is not configured for calls that use default authenticator.

Functions

func CipherOrder

func CipherOrder() bool

CipherOrder function is deprecated. Use cbauth.GetTLSConfig() instead

func CipherSuites

func CipherSuites() []uint16

CipherSuites function is deprecated. Use cbauth.GetTLSConfig() instead

func ExtractCredsGeneric added in v0.1.9

func ExtractCredsGeneric(hdr httpreq.HttpHeader) (user string, pwd string, err error)

ExtractCredsGeneric extracts Basic auth creds from header.

func ExtractOnBehalfIdentityGeneric added in v0.1.9

func ExtractOnBehalfIdentityGeneric(hdr httpreq.HttpHeader) (user string,
	domain string, err error)

ExtractOnBehalfIdentityGeneric extracts 'on behalf' identity from header.

func ForbiddenJSON

func ForbiddenJSON(permission string) ([]byte, error)

ForbiddenJSON returns json 403 response for given permission

func GetClientCertAuthType

func GetClientCertAuthType() (tls.ClientAuthType, error)

GetClientCertAuthType returns TLS cert type

func GetHTTPServiceAuth

func GetHTTPServiceAuth(hostport string) (user, pwd string, err error)

GetHTTPServiceAuth returns user/password creds giving "admin" access to given http service inside couchbase cluster. Uses default authenticator.

func GetMemcachedServiceAuth

func GetMemcachedServiceAuth(hostport string) (user, pwd string, err error)

GetMemcachedServiceAuth returns user/password creds given "admin" access to given memcached service. Uses default authenticator.

func GetUserBuckets added in v0.1.2

func GetUserBuckets(user, domain string) ([]string, error)

func GetUserUuid added in v0.1.1

func GetUserUuid(user, domain string) (string, error)

func InitExternal added in v0.1.11

func InitExternal(service, mgmtHostPort, user, password string) error

InitExternal should be used by external cbauth client to enable cbauth with limited functionality.

func InitExternalWithHeartbeat added in v0.1.11

func InitExternalWithHeartbeat(service, mgmtHostPort, user, password string,
	heartbeatInterval, heartbeatWait int) error

InitExternalWithHeartbeat should be used by external cbauth client to enable cbauth with limited functionality and enabling heartbeats. heartbeatInterval - interval in seconds at which heartbeats should be sent heartbeatWait - defines how many seconds we wait until declaring the database stale

func InternalRetryDefaultInit

func InternalRetryDefaultInit(mgmtHostPort, user, password string) (bool, error)

InternalRetryDefaultInit can be used by golang services that are willing to perform manual initialization of cbauth (i.e. for easier testing). This API is subject to change and should be used only if really needed. Returns false if Default Authenticator was already initialized.

func InternalRetryDefaultInitWithService

func InternalRetryDefaultInitWithService(service, mgmtHostPort, user, password string) (bool, error)

InternalRetryDefaultInitWithService can be used by golang services that are willing to perform manual initialization of cbauth (i.e. for easier testing). This API is subject to change and should be used only if really needed. Returns false if Default Authenticator was already initialized.

func MinTLSVersion

func MinTLSVersion() uint16

MinTLSVersion function is deprecated. Use cbauth.GetTLSConfig() instead

func RegisterConfigRefreshCallback

func RegisterConfigRefreshCallback(callback ConfigRefreshCallback) error

func RegisterTLSRefreshCallback

func RegisterTLSRefreshCallback(callback TLSRefreshCallback) error

RegisterTLSRefreshCallback registers a callback to be called when any field of TLS settings change. The callback is called in separate routine

func SendForbidden

func SendForbidden(w http.ResponseWriter, permission string) error

SendForbidden sends 403 Forbidden with json payload that contains list of required permissions to response on given response writer.

func SendUnauthorized

func SendUnauthorized(w http.ResponseWriter)

SendUnauthorized sends 401 Unauthorized response on given response writer.

func SetRequestAuth

func SetRequestAuth(req *http.Request) error

SetRequestAuth sets basic auth header in given http request according to default authenticator. Simply calls SetRequestAuthVia with nil authenticator.

func SetRequestAuthVia

func SetRequestAuthVia(req *http.Request, a Authenticator) error

SetRequestAuthVia sets basic auth header in given http request according to given authenticator. It will extract target hostname/port from request and figure out right service credentials for that endpoint. If nil authenticator is passed, Default authenticator is used.

func SplitHostPort

func SplitHostPort(hostport string) (host string, port int, err error)

SplitHostPort separates hostport into string host and numeric port.

func WithAuthenticator

func WithAuthenticator(a Authenticator, body func(a Authenticator) error) error

WithAuthenticator calls given body with either passed authenticator or default authenticator if `a' is nil. ErrNotInitialized is returned if a is nil and default authenticator is not configured.

func WithDefault

func WithDefault(body func(a Authenticator) error) error

WithDefault calls given body with default authenticator. If default authenticator is not configured, it returns ErrNotInitialized.

func WrapHTTPTransport

func WrapHTTPTransport(transport http.RoundTripper, a Authenticator) http.RoundTripper

WrapHTTPTransport constructs http transport that automatically does SetRequestAuthVia for requests it sends. As usual, if nil authenticator is passed, default authenticator is used.

Types

type AuthHandler

type AuthHandler struct {
	Bucket string
	A      Authenticator
}

AuthHandler is a type that implements go-couchbase AuthHandler, GenericMcdAuthHandler and HTTPAuthHandler interfaces. It integrate cbauth into go-couchbase.

func NewAuthHandler

func NewAuthHandler(a Authenticator) *AuthHandler

NewAuthHandler returns AuthHandler instance that is using given authenticator instance to authenticate memcached connections for go-couchbase client. If given authenticator is nil, Default authenticator will be used during AuthenticateMemcachedConn calls.

func (*AuthHandler) AuthenticateMemcachedConn

func (ah *AuthHandler) AuthenticateMemcachedConn(host string, conn *memcached.Client) error

AuthenticateMemcachedConn method grabs creds for given host destination and performs auth and select-bucket on given memcached.Client. It is called by go-couchbase as part of setting up fresh connection in its memcached connections pool.

func (*AuthHandler) ForBucket

func (ah *AuthHandler) ForBucket(bucket string) couchbase.AuthHandler

ForBucket method returns copy of AuthHandler that is configured for different bucket.

func (*AuthHandler) GetCredentials

func (ah *AuthHandler) GetCredentials() (string, string, string)

GetCredentials method returns empty creds (it is not supposed to be used in practice).

func (*AuthHandler) SetCredsForRequest

func (ah *AuthHandler) SetCredsForRequest(req *http.Request) error

SetCredsForRequest calls SetRequestAuthVia on given request and authhandler's Authenticator.

type Authenticator

type Authenticator interface {
	BaseAuthenticator
	GetHTTPServiceAuth(hostport string) (user, pwd string, err error)
	// GetMemcachedServiceAuth returns user/password creds given
	// "admin" access to given memcached service.
	GetMemcachedServiceAuth(hostport string) (user, pwd string, err error)
	// RegisterTLSRefreshCallback registers callback for refreshing TLS Config whenever
	// SSL certificates are refreshed or when client certificate auth state is changed.
	// Deprecated: Use RegisterConfigRefreshCallback instead.
	RegisterTLSRefreshCallback(callback TLSRefreshCallback) error
	// RegisterConfigRefreshCallback registers a callback function that will
	// be called whenever there is a change in certificates, TLS config or
	// cluster encryption settings.
	RegisterConfigRefreshCallback(callback ConfigRefreshCallback) error
	// GetClientCertAuthType returns the client certificate authentication
	// type to be used by the web-server.
	// Deprecated: Use cbauth.GetTLSConfig() instead.
	GetClientCertAuthType() (tls.ClientAuthType, error)
	// GetClusterEncryptionConfig returns ClusterEncryptionConfig which indicates
	// whether the client should used SSL ports for communication and whether
	// the unencrypted (non-SSL) ports should be disabled.
	GetClusterEncryptionConfig() (ClusterEncryptionConfig, error)
	// GetTLSConfig returns TLSConfig structure which includes cipher suites,
	// min tls version, etc.
	GetTLSConfig() (TLSConfig, error)
	// GetUserUuid returns uuid for a user.
	GetUserUuid(user, domain string) (string, error)
	// GetUserBuckets returns buckets on which a user has any of the
	// following permissions to:
	// - Access documents in any collection in the bucket
	// - Access collections metadata for any scope in the bucket
	GetUserBuckets(user, domain string) ([]string, error)
	GetGuardrailStatuses() (GuardrailStatuses, error)
}

Authenticator is main cbauth interface. It supports both incoming and outgoing auth.

var Default Authenticator

Default variable holds default authenticator. Default authenticator is constructed automatically from environment variables passed by ns_server. It is nil if your process was not (correctly) spawned by ns_server.

type BaseAuthenticator added in v0.1.11

type BaseAuthenticator interface {
	// AuthWebCreds method extracts credentials from given http request.
	AuthWebCreds(req *http.Request) (creds Creds, err error)
	// AuthWebCredsGeneric method extracts credentials from an HTTP request
	// that is generic (not necessarily using the net/http library)
	AuthWebCredsGeneric(req httpreq.HttpRequest) (creds Creds, err error)
	// Auth method constructs credentials from given user and password pair.
	Auth(user, pwd string) (creds Creds, err error)
}

type ClusterEncryptionConfig

type ClusterEncryptionConfig cbauthimpl.ClusterEncryptionConfig

ClusterEncryptionConfig contains info about whether to use SSL ports for communication channels and whether to disable non-SSL ports.

func GetClusterEncryptionConfig

func GetClusterEncryptionConfig() (ClusterEncryptionConfig, error)

type ConfigRefreshCallback

type ConfigRefreshCallback cbauthimpl.ConfigRefreshCallback

ConfigRefreshCallback type describes the callback that is called when there is a change in SSL certificates or TLS Config or cluster encryption config.

type Creds

type Creds interface {
	// Name method returns user name (e.g. for auditing)
	Name() string
	// Domain method returns user domain (for auditing)
	Domain() string
	// User method returns user and domain for non auditing purpose.
	User() (name, domain string)
	// IsAllowed method returns true if the permission is granted
	// for these credentials
	IsAllowed(permission string) (bool, error)
}

Creds type represents credentials and answers queries on this creds authorized actions. Note: it'll become (possibly much) wider API in future, but it's main purpose right now is to get us started.

func Auth

func Auth(user, pwd string) (creds Creds, err error)

Auth method constructs credentials from given user and password pair. Uses default authenticator.

func AuthWebCreds

func AuthWebCreds(req *http.Request) (creds Creds, err error)

AuthWebCreds method extracts credentials from given http request using default authenticator.

func AuthWebCredsGeneric added in v0.1.9

func AuthWebCredsGeneric(req httpreq.HttpRequest) (creds Creds, err error)

AuthWebCredsGeneric method extracts credentials from an HTTP request that is generic (not necessarily using the net/http library)

type DBStaleError

type DBStaleError struct {
	Err error
}

DBStaleError is kind of error that signals that cbauth internal state is not synchronized with ns_server yet or anymore.

func (*DBStaleError) Error

func (e *DBStaleError) Error() string

type ExternalAuthenticator added in v0.1.11

type ExternalAuthenticator interface {
	BaseAuthenticator
	// GetNodeUuid returns UUID of the node cbauth is currently connecting to
	GetNodeUuid() (string, error)
	// GetClusterUuid returns UUID of the cluster cbauth is currently
	// connecting to
	GetClusterUuid() (string, error)
	// SetExpectedClusterUuid sets the UUID we expect the cluster to be
	SetExpectedClusterUuid(clusterUUID string) error
}

ExternalAuthenticator is cbauth interface for external clients. It supports only incoming auth.

func GetExternalAuthenticator added in v0.1.11

func GetExternalAuthenticator() ExternalAuthenticator

type GuardrailStatuses added in v0.1.12

type GuardrailStatuses []cbauthimpl.GuardrailStatus

GuardrailStatuses contains a list of any currently breached guardrails, with their severities. Only guardrails applicable to the service will be included

func GetGuardrailStatuses added in v0.1.12

func GetGuardrailStatuses() (GuardrailStatuses, error)

type TLSConfig

type TLSConfig cbauthimpl.TLSConfig

TLSConfig contains tls settings to be used by cbauth clients When something in tls config changes user is notified via TLSRefreshCallback

func GetTLSConfig

func GetTLSConfig() (TLSConfig, error)

GetTLSConfig returns current tls config that contains cipher suites, min TLS version, etc.

type TLSRefreshCallback

type TLSRefreshCallback cbauthimpl.TLSRefreshCallback

TLSRefreshCallback type describes callback for reinitializing TLSConfig when ssl certificate or client cert auth setting changes.

type UnknownHostPortError

type UnknownHostPortError string

UnknownHostPortError is returned from GetMemcachedServiceAuth and GetHTTPServiceAuth calls for unknown host:port arguments.

func (UnknownHostPortError) Error

func (s UnknownHostPortError) Error() string

Directories

Path Synopsis
Package cbauthimpl contains internal implementation details of cbauth.
Package cbauthimpl contains internal implementation details of cbauth.
cmd
cache-service
@author Couchbase <info@couchbase.com> @copyright 2016 Couchbase, Inc.
@author Couchbase <info@couchbase.com> @copyright 2016 Couchbase, Inc.
Package metakv provides simple KV API to some "metadata store".
Package metakv provides simple KV API to some "metadata store".
Package revrpc provides jsonrpc library that matches ns_server's json_rpc_connection module.
Package revrpc provides jsonrpc library that matches ns_server's json_rpc_connection module.
@author Couchbase <info@couchbase.com> @copyright 2015 Couchbase, Inc.
@author Couchbase <info@couchbase.com> @copyright 2015 Couchbase, Inc.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL