sdk

package module
v0.0.0-...-83af2a2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2023 License: MIT Imports: 14 Imported by: 0

README

go-sdk

A lightweight Go SDK for use within OpenFaaS functions and to control the OpenFaaS gateway.

For use within any Go code (not just OpenFaaS Functions):

  • Client - A client for the OpenFaaS REST API

For use within functions:

  • ReadSecret() - Read a named secret from within an OpenFaaS Function
  • ReadSecrets() - Read all available secrets returning a queryable map

Authentication helpers (See: Authentication with IAM):

  • ServiceAccountTokenSource - An implementation of the TokenSource interface to get an ID token by reading a Kubernetes projected service account token from /var/secrets/tokens/openfaas-token or the path set by the token_mount_path environment variable.

Usage

import "github.com/openfaas/go-sdk"

Construct a new OpenFaaS client and use it to access the OpenFaaS gateway API.

gatewayURL, _ := url.Parse("http://127.0.0.1:8080")
auth := &sdk.BasicAuth{
    Username: username,
    Password: password,
}

client := sdk.NewClient(gatewayURL, auth, http.DefaultClient)

namespace, err := client.GetNamespaces(context.Background())

Authentication with IAM

To authenticate with an OpenFaaS deployment that has Identity and Access Management (IAM) enabled, the client needs to exchange an ID token for an OpenFaaS ID token.

To get a token that can be exchanged for an OpenFaaS token you need to implement the TokenSource interface.

This is an example of a token source that gets a service account token mounted into a pod with ServiceAccount token volume projection.

type ServiceAccountTokenSource struct{}

func (ts *ServiceAccountTokenSource) Token() (string, error) {
	tokenMountPath := getEnv("token_mount_path", "/var/secrets/tokens")
	if len(tokenMountPath) == 0 {
		return "", fmt.Errorf("invalid token_mount_path specified for reading the service account token")
	}

	idTokenPath := path.Join(tokenMountPath, "openfaas-token")
	idToken, err := os.ReadFile(idTokenPath)
	if err != nil {
		return "", fmt.Errorf("unable to load service account token: %s", err)
	}

	return string(idToken), nil
}

The service account token returned by the TokenSource is automatically exchanged for an OpenFaaS token that is then used in the Authorization header for all requests made to the API.

If the OpenFaaS token is expired the TokenSource is asked for a token and the token exchange will run again.

gatewayURL, _ := url.Parse("https://gw.openfaas.example.com")

auth := &sdk.TokenAuth{
    TokenURL "https://gw.openfaas.example.com/oauth/token",
    TokenSource: &ServiceAccountTokenSource{}
}

client := sdk.NewClient(gatewayURL, auth, http.DefaultClient)

Authentication with Federated Gateway

func Test_ClientCredentials(t *testing.T) {
	clientID := ""
	clientSecret := ""
	tokenURL := "https://keycloak.example.com/realms/openfaas/protocol/openid-connect/token"
	scope := "email"
	grantType := "client_credentials"

	audience = "" // Optional

	auth := NewClientCredentialsTokenSource(clientID, clientSecret, tokenURL, scope, grantType, audience)

	token, err := auth.Token()
	if err != nil {
		t.Fatal(err)
	}

	if token == "" {
		t.Fatal("token is empty")
	}

	u, _ := url.Parse("https://fed-gw.example.com")

	client := NewClient(u, &ClientCredentialsAuth{tokenSource: auth}, http.DefaultClient)

	fns, err := client.GetFunctions(context.Background(), "openfaas-fn")
	if err != nil {
		t.Fatal(err)
	}

	if len(fns) == 0 {
		t.Fatal("no functions found")
	}
}

License

License: MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReadSecret

func ReadSecret(key string) (string, error)

ReadSecrets reads a single secrets from /var/openfaas/secrets or from the environment "secret_mount_path" if set.

Types

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

BasicAuth basic authentication for the the OpenFaaS client

func (*BasicAuth) Set

func (auth *BasicAuth) Set(req *http.Request) error

Set Authorization Basic header on request

type Client

type Client struct {
	GatewayURL *url.URL
	Client     *http.Client
	ClientAuth ClientAuth
}

Client is used to manage OpenFaaS functions

func NewClient

func NewClient(gatewayURL *url.URL, auth ClientAuth, client *http.Client) *Client

NewClient creates an Client for managing OpenFaaS

func (*Client) CreateNamespace

func (s *Client) CreateNamespace(ctx context.Context, spec types.FunctionNamespace) (int, error)

CreateNamespace creates a namespace

func (*Client) DeleteFunction

func (s *Client) DeleteFunction(ctx context.Context, functionName, namespace string) error

DeleteFunction deletes a function

func (*Client) DeleteNamespace

func (s *Client) DeleteNamespace(ctx context.Context, namespace string) error

DeleteNamespace deletes a namespace

func (*Client) Deploy

func (s *Client) Deploy(ctx context.Context, spec types.FunctionDeployment) (int, error)

func (*Client) GetFunction

func (s *Client) GetFunction(ctx context.Context, name, namespace string) (types.FunctionStatus, error)

GetFunction gives a richer payload than GetFunctions, but for a specific function

func (*Client) GetFunctions

func (s *Client) GetFunctions(ctx context.Context, namespace string) ([]types.FunctionStatus, error)

GetFunctions lists all functions

func (*Client) GetInfo

func (s *Client) GetInfo(ctx context.Context) (SystemInfo, error)

func (*Client) GetNamespace

func (s *Client) GetNamespace(ctx context.Context, namespace string) (types.FunctionNamespace, error)

GetNamespaces get openfaas namespaces

func (*Client) GetNamespaces

func (s *Client) GetNamespaces(ctx context.Context) ([]string, error)

GetNamespaces get openfaas namespaces

func (*Client) ScaleFunction

func (s *Client) ScaleFunction(ctx context.Context, functionName, namespace string, replicas uint64) error

ScaleFunction scales a function to a number of replicas

func (*Client) Update

func (s *Client) Update(ctx context.Context, spec types.FunctionDeployment) (int, error)

func (*Client) UpdateNamespace

func (s *Client) UpdateNamespace(ctx context.Context, spec types.FunctionNamespace) (int, error)

UpdateNamespace updates a namespace

type ClientAuth

type ClientAuth interface {
	Set(req *http.Request) error
}

ClientAuth an interface for client authentication. to add authentication to the client implement this interface

type ClientCredentialsAuth

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

func NewClientCredentialsAuth

func NewClientCredentialsAuth(ts TokenSource) *ClientCredentialsAuth

func (*ClientCredentialsAuth) Set

func (cca *ClientCredentialsAuth) Set(req *http.Request) error

type ClientCredentialsToken

type ClientCredentialsToken struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
	ExpiresIn   int    `json:"expires_in"`
	ObtainedAt  time.Time
}

ClientCredentialsToken represents an access_token obtained through the client credentials grant type. This token is not associated with a human user.

func (*ClientCredentialsToken) Expired

func (t *ClientCredentialsToken) Expired() bool

Expired returns true if the token is expired or if the expiry time is not known. The token will always expire 10s early to avoid clock skew.

type ClientCredentialsTokenSource

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

ClientCredentialsTokenSource can be used to obtain an access token using the client credentials grant type. Tested with Keycloak's token endpoint, additional changes may be required for additional OIDC token endpoints.

func (*ClientCredentialsTokenSource) Token

func (ts *ClientCredentialsTokenSource) Token() (string, error)

type Provider

type Provider struct {
	Provider      string            `json:"provider,omitempty"`
	Version       types.VersionInfo `json:"version,omitempty"`
	Orchestration string            `json:"orchestration,omitempty"`
}

type SecretMap

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

func ReadSecrets

func ReadSecrets() (SecretMap, error)

ReadSecrets reads all secrets from /var/openfaas/secrets or from the environment "secret_mount_path" if set. The results are returned in a map of key/value pairs.

func (*SecretMap) Exists

func (s *SecretMap) Exists(key string) bool

func (*SecretMap) Get

func (s *SecretMap) Get(key string) (string, error)

type ServiceAccountTokenSource

type ServiceAccountTokenSource struct{}

A TokenSource to get ID token by reading a Kubernetes projected service account token from /var/secrets/tokens/openfaas-token or the path set by the token_mount_path environment variable.

func (*ServiceAccountTokenSource) Token

func (ts *ServiceAccountTokenSource) Token() (string, error)

Token returns a Kubernetes projected service account token read from /var/secrets/tokens/openfaas-token or the path set by the token_mount_path environment variable.

type SystemInfo

type SystemInfo struct {
	Arch     string            `json:"arch,omitempty"`
	Provider Provider          `json:"provider,omitempty"`
	Version  types.VersionInfo `json:"version,omitempty"`
}

type Token

type Token struct {
	// IDToken is the OIDC access token that authorizes and authenticates
	// the requests.
	IDToken string

	// Expiry is the expiration time of the access token.
	//
	// A zero value means the token never expires.
	Expiry time.Time
}

Token represents an OpenFaaS ID token

func ExchangeIDToken

func ExchangeIDToken(tokenURL, rawIDToken string) (*Token, error)

Exchange an OIDC ID Token from an IdP for OpenFaaS token using the token exchange grant type. tokenURL should be the OpenFaaS token endpoint within the internal OIDC service

func (*Token) Expired

func (t *Token) Expired() bool

Expired reports whether the token is expired, and will start to return false 10s before the actual expiration time.

type TokenAuth

type TokenAuth struct {
	// TokenURL represents the OpenFaaS gateways token endpoint URL.
	TokenURL string

	// TokenSource used to get an ID token that can be exchanged for an OpenFaaS ID token.
	TokenSource TokenSource
	// contains filtered or unexported fields
}

TokenAuth bearer token authentication for OpenFaaS deployments with OpenFaaS IAM enabled.

func (*TokenAuth) Set

func (a *TokenAuth) Set(req *http.Request) error

Set Authorization Bearer header on request. Set validates the token expiry on each call. If it's expired it will exchange an ID token from the TokenSource for a new OpenFaaS token.

type TokenSource

type TokenSource interface {
	// Token returns a token or an error.
	Token() (string, error)
}

A TokenSource is anything that can return an OIDC ID token that can be exchanged for an OpenFaaS token.

func NewClientCredentialsTokenSource

func NewClientCredentialsTokenSource(clientID, clientSecret, tokenURL, scope, grantType, audience string) TokenSource

Jump to

Keyboard shortcuts

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