api

package
v0.0.0-...-b9bb202 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: AGPL-3.0 Imports: 48 Imported by: 305

Documentation

Index

Constants

View Source
const AnonymousUsername = "jujuanonymous"

AnonymousUsername is the special username to use for anonymous logins.

View Source
const (
	// ErrorLoginFirst indicates that login has not taken place yet.
	ErrorLoginFirst = errors.ConstError("login provider needs to be logged in")
)
View Source
const PingPeriod = 1 * time.Minute

PingPeriod defines how often the internal connection health check will run.

Variables

View Source
var WebsocketDial = WebsocketDialWithErrors

WebsocketDial is called instead of dialer.Dial so we can override it in tests.

Functions

func AuthHTTPRequest

func AuthHTTPRequest(req *http.Request, info *Info) error

AuthHTTPRequest adds Juju auth info (username, password, nonce, macaroons) to the given HTTP request, suitable for sending to a Juju API server.

func ControllerAPIURL

func ControllerAPIURL(addr string, port int) string

ControllerAPIURL returns the URL to use to connect to the controller API.

func CookieURLFromHost

func CookieURLFromHost(host string) *url.URL

CookieURLFromHost creates a url.URL from a given host.

func CreateCertPool

func CreateCertPool(caCert string) (*x509.CertPool, error)

CreateCertPool creates a new x509.CertPool and adds in the caCert passed in. All certs from the cert directory (/etc/juju/cert.d on ubuntu) are also added.

func NewClientCredentialsLoginProvider

func NewClientCredentialsLoginProvider(clientID, clientSecret string) *clientCredentialsLoginProvider

NewClientCredentialsLoginProvider returns a LoginProvider implementation that authenticates the entity with the given client credentials.

func NewFakeStreamReader

func NewFakeStreamReader(r io.Reader) base.Stream

func NewLegacyLoginProvider

func NewLegacyLoginProvider(
	tag names.Tag,
	password string,
	nonce string,
	macaroons []macaroon.Slice,
	bakeryClient *httpbakery.Client,
	cookieURL *url.URL,
) *legacyLoginProvider

NewLegacyLoginProvider returns a LoginProvider implementation that authenticates the entity with the given name and password or macaroons. The nonce should be empty unless logging in as a machine agent.

func NewSessionTokenLoginProvider

func NewSessionTokenLoginProvider(
	token string,
	output io.Writer,
	updateAccountDetailsFunc func(string) error,
) *sessionTokenLoginProvider

NewSessionTokenLoginProvider returns a LoginProvider implementation that authenticates the entity with the session token.

func NewTLSConfig

func NewTLSConfig(certPool *x509.CertPool) *tls.Config

NewTLSConfig returns a new *tls.Config suitable for connecting to a Juju API server. If certPool is non-nil, we use it as the config's RootCAs, and the server name is set to "juju-apiserver".

func PerferredHost

func PerferredHost(info *Info) string

PerferredHost returns the SNI hostname or controller name for the cookie URL so that it is stable when used with a HA controller cluster.

func SupportedFacadeVersions

func SupportedFacadeVersions() facades.FacadeVersions

SupportedFacadeVersions returns the list of facades that the api supports.

func WebsocketDialWithErrors

func WebsocketDialWithErrors(dialer WebsocketDialer, urlStr string, requestHeader http.Header) (base.Stream, error)

WebsocketDialWithErrors dials the websocket and extracts any error from the response if there's a handshake error setting up the socket. Any other errors are returned normally.

Types

type Connection

type Connection interface {

	// Close closes the connection.
	Close() error

	// Addr returns the address used to connect to the API server.
	Addr() string

	// IPAddr returns the IP address used to connect to the API server.
	IPAddr() string

	// APIHostPorts returns addresses that may be used to connect
	// to the API server, including the address used to connect.
	//
	// The addresses are scoped (public, cloud-internal, etc.), so
	// the client may choose which addresses to attempt. For the
	// Juju CLI, all addresses must be attempted, as the CLI may
	// be invoked both within and outside the model (think
	// private clouds).
	APIHostPorts() []network.MachineHostPorts

	// Broken returns a channel which will be closed if the connection
	// is detected to be broken, either because the underlying
	// connection has closed or because API pings have failed.
	Broken() <-chan struct{}

	// IsBroken returns whether the connection is broken. It checks
	// the Broken channel and if that is open, attempts a connection
	// ping.
	IsBroken(ctx context.Context) bool

	// IsProxied returns weather the connection is proxied.
	IsProxied() bool

	// Proxy returns the Proxier used to establish the connection if one was
	// used at all. If no Proxier was used then it's expected that returned
	// Proxier will be nil. Use IsProxied() to test for the presence of a proxy.
	Proxy() proxy.Proxier

	// PublicDNSName returns the host name for which an officially
	// signed certificate will be used for TLS connection to the server.
	// If empty, the private Juju CA certificate must be used to verify
	// the connection.
	PublicDNSName() string

	// These are a bit off -- ServerVersion is apparently not known until after
	// Login()? Maybe evidence of need for a separate AuthenticatedConnection..?
	Login(ctx context.Context, name names.Tag, password, nonce string, ms []macaroon.Slice) error
	ServerVersion() (version.Number, bool)

	// APICaller provides the facility to make API calls directly.
	// This should not be used outside the api/* packages or tests.
	base.APICaller

	// ControllerTag returns the tag of the controller.
	// This could be defined on base.APICaller.
	ControllerTag() names.ControllerTag

	// AuthTag returns the tag of the authorized user of the conn API
	// connection.
	AuthTag() names.Tag

	// ControllerAccess returns the access level of authorized user to the controller.
	ControllerAccess() string

	// CookieURL returns the URL that HTTP cookies for the API will be
	// associated with.
	CookieURL() *url.URL
}

Connection represents a connection to a Juju API server.

func Open

func Open(ctx context.Context, info *Info, opts DialOpts) (Connection, error)

Open establishes a connection to the API server using the Info given, returning a State instance which can be used to make API requests.

If the model is hosted on a different server, Open will return an error with a *RedirectError cause holding the details of another server to connect to.

See Connect for details of the connection mechanics.

type DNSCache

type DNSCache interface {
	// Lookup returns the IP addresses associated
	// with the given host.
	Lookup(host string) []string
	// Add sets the IP addresses associated with
	// the given host name.
	Add(host string, ips []string)
}

DNSCache implements a cache of DNS lookup results.

type DeadlineStream

type DeadlineStream struct {
	*websocket.Conn

	Timeout time.Duration
}

DeadlineStream wraps a websocket connection and applies a write deadline to each WriteJSON call.

func (*DeadlineStream) WriteJSON

func (s *DeadlineStream) WriteJSON(v interface{}) error

WriteJSON is part of base.Stream.

type DialOption

type DialOption func(*DialOpts)

DialOption is the type of functions that mutate DialOpts

func WithDialOpts

func WithDialOpts(newOpts DialOpts) DialOption

WithDialOpts sets the DialOpts to the one specified

func WithLoginProvider

func WithLoginProvider(lp LoginProvider) DialOption

WithLoginProvider returns a DialOption that sets the login provider to the one specified.

type DialOpts

type DialOpts struct {
	// LoginProvider performs the log in on the open connection.
	LoginProvider LoginProvider

	// DialAddressInterval is the amount of time to wait
	// before starting to dial another address.
	DialAddressInterval time.Duration

	// DialTimeout is the amount of time to wait for the dial
	// portion only of the api.Open to succeed. If this is zero,
	// there is no dial timeout.
	DialTimeout time.Duration

	// Timeout is the amount of time to wait for the entire
	// api.Open to succeed (including dial and login). If this is
	// zero, there is no timeout.
	Timeout time.Duration

	// RetryDelay is the amount of time to wait between
	// unsuccessful connection attempts. If this is
	// zero, only one attempt will be made.
	RetryDelay time.Duration

	// BakeryClient is the httpbakery Client, which
	// is used to do the macaroon-based authorization.
	// This and the *http.Client inside it are copied
	// by Open, and any RoundTripper field
	// the HTTP client is ignored.
	BakeryClient *httpbakery.Client

	// InsecureSkipVerify skips TLS certificate verification
	// when connecting to the controller. This should only
	// be used in tests, or when verification cannot be
	// performed and the communication need not be secure.
	InsecureSkipVerify bool

	// DialWebsocket is used to make connections to API servers.
	// It will be called with a websocket URL to connect to,
	// and the TLS configuration to use to secure the connection.
	// If ipAddr is non-empty, the actual net.Dial should use
	// that IP address, regardless of the URL host.
	//
	// If DialWebsocket is nil, a default implementation using
	// gorilla websockets will be used.
	DialWebsocket func(ctx context.Context, urlStr string, tlsConfig *tls.Config, ipAddr string) (jsoncodec.JSONConn, error)

	// IPAddrResolver is used to resolve host names to IP addresses.
	// If it is nil, net.DefaultResolver will be used.
	IPAddrResolver IPAddrResolver

	// DNSCache is consulted to find and store cached DNS lookups.
	// If it is nil, no cache will be used or updated.
	DNSCache DNSCache

	// Clock is used as a time source for retries.
	// If it is nil, clock.WallClock will be used.
	Clock clock.Clock

	// VerifyCA is an optional callback that is invoked by the dialer when
	// the remote server presents a CA certificate that cannot be
	// automatically verified. If the callback returns a non-nil error then
	// the connection attempt will be aborted.
	VerifyCA func(host, endpoint string, caCert *x509.Certificate) error
}

DialOpts holds configuration parameters that control the Dialing behavior when connecting to a controller.

func DefaultDialOpts

func DefaultDialOpts() DialOpts

DefaultDialOpts returns a DialOpts representing the default parameters for contacting a controller.

type IPAddrResolver

type IPAddrResolver interface {
	LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)
}

IPAddrResolver implements a resolved from host name to the set of IP addresses associated with it. It is notably implemented by net.Resolver.

type Info

type Info struct {

	// Addrs holds the addresses of the controllers.
	Addrs []string

	// ControllerUUID is the UUID of the controller.
	ControllerUUID string

	// SNIHostName optionally holds the host name to use for
	// server name indication (SNI) when connecting
	// to the addresses in Addrs above. If CACert is non-empty,
	// this field is ignored.
	SNIHostName string

	// CACert holds the CA certificate that will be used
	// to validate the controller's certificate, in PEM format.
	// If this is empty, the standard system root certificates
	// will be used.
	CACert string

	// ModelTag holds the model tag for the model we are
	// trying to connect to. If this is empty, a controller-only
	// login will be made.
	ModelTag names.ModelTag

	// SkipLogin, if true, skips the Login call on connection. It is an
	// error to set Tag, Password, or Macaroons if SkipLogin is true.
	SkipLogin bool `yaml:"-"`

	// Tag holds the name of the entity that is connecting.
	// If this is nil, and the password is empty, macaroon authentication
	// will be used to log in unless SkipLogin is true.
	Tag names.Tag

	// Password holds the password for the administrator or connecting entity.
	Password string

	// Macaroons holds a slice of macaroon.Slice that may be used to
	// authenticate with the API server.
	Macaroons []macaroon.Slice `yaml:",omitempty"`

	// Nonce holds the nonce used when provisioning the machine. Used
	// only by the machine agent.
	Nonce string `yaml:",omitempty"`

	// Proxier describes a proxier to use to for establing an API connection
	// A nil proxier means that it will not be used.
	Proxier proxy.Proxier
}

Info encapsulates information about a server holding juju state and can be used to make a connection to it.

func (*Info) Ports

func (info *Info) Ports() []int

Ports returns the unique ports for the api addresses.

func (*Info) Validate

func (info *Info) Validate() error

Validate validates the API info.

type LoginProvider

type LoginProvider interface {
	// Login performs log in when connecting to the controller.
	Login(ctx context.Context, caller base.APICaller) (*LoginResultParams, error)
	// AuthHeader returns an HTTP header used for authentication.
	// This is normally used as part of basic authentication in scenarios where a client
	// makes use of a StreamConnector like when fetching logs using `juju debug-log`.
	// Can return [ErrorLoginFirst] when the provider requires an RPC login before basic auth
	// can be performed.
	// Other errors are also possible indicating an internal error in the provider.
	AuthHeader() (http.Header, error)
}

LoginProvider implements a way to log in when connecting to a controller.

type LoginResultParams

type LoginResultParams struct {
	// contains filtered or unexported fields
}

LoginResultParams holds the login result parameters.

func NewLoginResultParams

func NewLoginResultParams(result params.LoginResult) (*LoginResultParams, error)

NewLoginResultParams constructs a LoginResultParams from a Juju login response.

func (*LoginResultParams) EnsureTag

func (l *LoginResultParams) EnsureTag(tag names.Tag)

EnsureTag should be used when a login provider needs to ensure a login result has a tag set, particularly in cases where the server doesn't return a user identity.

type OpenFunc

type OpenFunc func(context.Context, *Info, DialOpts) (Connection, error)

OpenFunc is the usual form of a function that opens an API connection.

type RedirectError

type RedirectError struct {
	// Servers holds the sets of addresses of the redirected
	// servers.
	Servers []network.MachineHostPorts

	// CACert holds the certificate of the remote server.
	CACert string

	// FollowRedirect is set to true for cases like JAAS where the client
	// needs to automatically follow the redirect to the new controller.
	FollowRedirect bool

	// ControllerTag uniquely identifies the controller being redirected to.
	ControllerTag names.ControllerTag

	// An optional alias for the controller the model got redirected to.
	// It can be used by the client to present the user with a more
	// meaningful juju login -c XYZ command
	ControllerAlias string
}

RedirectError is returned from Open when the controller needs to inform the client that the model is hosted on a different set of API addresses.

func (*RedirectError) Error

func (e *RedirectError) Error() string

type UrlCatcher

type UrlCatcher struct {
	// contains filtered or unexported fields
}

func (*UrlCatcher) Headers

func (u *UrlCatcher) Headers() http.Header

func (*UrlCatcher) Location

func (u *UrlCatcher) Location() string

func (*UrlCatcher) RecordLocation

func (u *UrlCatcher) RecordLocation(d WebsocketDialer, urlStr string, header http.Header) (base.Stream, error)

type WebsocketDialer

type WebsocketDialer interface {
	Dial(string, http.Header) (*websocket.Conn, *http.Response, error)
}

WebsocketDialer is something that can make a websocket connection. Enables testing the error unpacking in websocketDialWithErrors.

Directories

Path Synopsis
hostkeyreporter
Package hostkeyreporter implements the client-side API facade used by the hostkeyreporter worker.
Package hostkeyreporter implements the client-side API facade used by the hostkeyreporter worker.
instancemutater/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
leadership
Package leadership implements the client to the analog leadership service.
Package leadership implements the client to the analog leadership service.
machineactions
Package machineactions implements the API side of running actions on machines.
Package machineactions implements the API side of running actions on machines.
provisioner/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
secretsdrain
Package secretsdrain provides the api client for the secretsdrain facade.
Package secretsdrain provides the api client for the secretsdrain facade.
secretsdrain/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
secretsmanager
Package secretsmanager provides the api client for the secretsmanager facade.
Package secretsmanager provides the api client for the secretsmanager facade.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
action
Package action defines the API client for the Action facade.
Package action defines the API client for the Action facade.
application
Package application provides access to the application API facade.
Package application provides access to the application API facade.
bundle
Package bundle provides access to the bundle API facade.
Package bundle provides access to the bundle API facade.
charms
Package charms provides a client for accessing the charms API.
Package charms provides a client for accessing the charms API.
modelupgrader/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
secretbackends
Package secretbackends provides the api client for the secretbackends facade.
Package secretbackends provides the api client for the secretbackends facade.
secrets
Package secrets provides the api client for the secrets facade.
Package secrets provides the api client for the secrets facade.
charms
Package charms provides common helpers for charm-related APIs.
Package charms provides common helpers for charm-related APIs.
secretbackends
Package secretbackends provides the api client for the secretbackends facade.
Package secretbackends provides the api client for the secretbackends facade.
secretbackends/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
secretsdrain
Package secretsdrain provides the api client for the secretsdrain facade.
Package secretsdrain provides the api client for the secretsdrain facade.
secretsdrain/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
migrationtarget
Package migrationtarget defines the client side API facade for use by the migration master worker when communicating with the target controller.
Package migrationtarget defines the client side API facade for use by the migration master worker when communicating with the target controller.
pubsub
Package pubsub implements the API for streaming pubsub messages between API servers.
Package pubsub implements the API for streaming pubsub messages between API servers.
secretsbackendmanager
Package secretsbackendmanager provides the api client for the secretsbackendmanager facade.
Package secretsbackendmanager provides the api client for the secretsbackendmanager facade.
usersecrets
Package usersecrets provides the api client for the usersecrets facade.
Package usersecrets provides the api client for the usersecrets facade.
usersecretsdrain
Package usersecretsdrain provides the api client for the usersecretsdrain facade.
Package usersecretsdrain provides the api client for the usersecretsdrain facade.
usersecretsdrain/mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package logsender implements the API for storing log messages on the API server.
Package logsender implements the API for storing log messages on the API server.

Jump to

Keyboard shortcuts

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