coordinator

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2020 License: Apache-2.0 Imports: 48 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LoginEvent  auditModels.EventName = "user-login"
	LogoutEvent auditModels.EventName = "user-logout"
)

Variables

View Source
var (
	InvalidConfigCause   = errors.NewCause(errors.BadRequestCategory, "invalid_config")
	InvalidArgumentCause = errors.NewCause(errors.BadRequestCategory, "invalid_argument")
)
View Source
var (
	// InvalidParametersCause happens when you pass invalid input
	InvalidParametersCause = errors.NewCause(errors.BadRequestCategory, "invalid_input_parameters")

	BadJSONCause = errors.NewCause(errors.BadRequestCategory, "bad_json_cause")
)
View Source
var NetworkCause = errors.NewCause(errors.RequestTimeoutCategory, "network_error")

NetworkCause occurs when the client cannot reach the server

Functions

func AuthTokenMiddleware

func AuthTokenMiddleware(next http.Handler) http.Handler

AuthTokenMiddleware sets the session ID on the request context for us in graphql handlers and elsewhere

func DecodeJSONBody added in v0.0.2

func DecodeJSONBody(w http.ResponseWriter, r *http.Request, dst interface{}) error

func IsAuthenticatedMiddleware

func IsAuthenticatedMiddleware(coordinator *Coordinator) func(http.Handler) http.Handler

IsAuthenticatedMiddleware checks to make sure a query is authenticated

func LogMiddleware

func LogMiddleware(log *zerolog.Logger) func(http.Handler) http.Handler

LogMiddleware sets a zerolog.Logger on the request context for use in downstream callers. This middleware relies on the requestIDMiddleware.

func LoginHandler

func LoginHandler(coordinator *Coordinator) http.HandlerFunc

func LogoutHandler

func LogoutHandler(coordinator *Coordinator) http.HandlerFunc

func RecoveryMiddleware

func RecoveryMiddleware(next http.Handler) http.Handler

RecoveryMiddleware catches any panics that occur in the call chain of the http request and response. If a panic does occur the panic is captured, a log is produced, and an internal server error is returned to the caller.

func RequestIDMiddleware

func RequestIDMiddleware(next http.Handler) http.Handler

RequestIDMiddleware sets a UUID on the response header and request context for use in tracing and

func RoundtripLoggerMiddleware

func RoundtripLoggerMiddleware(next http.Handler) http.Handler

RoundtripLoggerMiddleware logs information about request and response generated by the server. It depends on the logMiddleware.

func VersionHandler

func VersionHandler(instanceID string) http.HandlerFunc

VersionHandler returns the version information for this instance of cape.

Types

type ApproveSuggestionResponse

type ApproveSuggestionResponse struct {
	Project models.Project `json:"approveProjectSuggestion"`
}

type AuditLogResponse added in v0.0.2

type AuditLogResponse struct {
	Log []auditModels.Event `json:"getAuditLog"`
}

type Client

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

Client is a wrapper around the graphql client that connects to the coordinator and sends queries

func NewClient

func NewClient(transport ClientTransport) *Client

NewClient returns a new client that connects to the given the configured transport

func (*Client) AddContributor

func (c *Client) AddContributor(ctx context.Context, project models.Project, user models.Email, role models.Label) (*models.Contributor, error)

func (*Client) ApproveSuggestion

func (c *Client) ApproveSuggestion(ctx context.Context, suggestion models.Suggestion) error

func (*Client) AttemptRecovery

func (c *Client) AttemptRecovery(ctx context.Context, ID string, secret models.Password, newPassword models.Password) error

func (*Client) AuditLog added in v0.0.2

func (c *Client) AuditLog(ctx context.Context, options model.AuditLogQueryOptions) ([]auditModels.Event, error)

func (*Client) Authenticated

func (c *Client) Authenticated() bool

func (*Client) CreateProject

func (c *Client) CreateProject(
	ctx context.Context,
	name models.ProjectDisplayName,
	label *models.Label,
	desc models.ProjectDescription) (*models.Project, error)

func (*Client) CreateRecovery

func (c *Client) CreateRecovery(ctx context.Context, email models.Email) error

func (*Client) CreateToken

func (c *Client) CreateToken(ctx context.Context, user *models.User) (*auth.APIToken, *models.Token, error)

CreateToken creates a new API token for the provided user. You can pass nil and it will return a token for you

func (*Client) CreateUser

func (c *Client) CreateUser(ctx context.Context, name models.Name, email models.Email) (*models.User, models.Password, error)

CreateUser creates a user and returns it

func (*Client) EmailLogin

func (c *Client) EmailLogin(ctx context.Context, email models.Email, password models.Password) (*LoginResponse, error)

EmailLogin calls the CreateLoginSession and CreateAuthSession mutations

func (*Client) GetAllSuggestions added in v0.0.2

func (c *Client) GetAllSuggestions(ctx context.Context) ([]GetSuggestionResponse, error)

func (*Client) GetOrgPolicy added in v0.0.2

func (c *Client) GetOrgPolicy(ctx context.Context) (*models.Policy, error)

func (*Client) GetProject

func (c *Client) GetProject(ctx context.Context, id string, label *models.Label) (*GetProject, error)

func (*Client) GetProjectSuggestion

func (c *Client) GetProjectSuggestion(ctx context.Context, id string) (*ProjectSuggestion, error)

func (*Client) GetProjectSuggestions

func (c *Client) GetProjectSuggestions(ctx context.Context, projectLabel models.Label) ([]GetSuggestionResponse, error)

func (*Client) GetUser

func (c *Client) GetUser(ctx context.Context, id string) (*UserResponse, error)

GetUser returns a user and it's roles!

func (*Client) GetUsers

func (c *Client) GetUsers(ctx context.Context, emails []models.Email) ([]*models.User, error)

GetUsers returns all users for the given emails

func (*Client) ListContributors

func (c *Client) ListContributors(ctx context.Context, project models.Project) ([]GQLContributor, error)

func (*Client) ListProjects

func (c *Client) ListProjects(ctx context.Context, status models.ProjectStatus) ([]*models.Project, error)

func (*Client) ListTokens

func (c *Client) ListTokens(ctx context.Context, user *models.User) ([]string, error)

ListTokens lists all of the auth tokens for the provided user

func (*Client) ListUsers

func (c *Client) ListUsers(ctx context.Context) ([]*models.User, error)

ListUsers returns all of the users in the database

func (*Client) Logout

func (c *Client) Logout(ctx context.Context, authToken *base64.Value) error

Logout calls the deleteSession mutation

func (*Client) Me

func (c *Client) Me(ctx context.Context) (*models.User, error)

Me returns the user of the current authenticated session

func (*Client) MyProjectRole

func (c *Client) MyProjectRole(ctx context.Context, project models.Label) (*models.Role, error)

func (*Client) MyRole

func (c *Client) MyRole(ctx context.Context) (*models.Role, error)

func (*Client) RejectSuggestion

func (c *Client) RejectSuggestion(ctx context.Context, suggestion models.Suggestion) error

func (*Client) RemoveContributor

func (c *Client) RemoveContributor(ctx context.Context, user models.User, project models.Project) (*models.Contributor, error)

func (*Client) RemoveToken

func (c *Client) RemoveToken(ctx context.Context, tokenID string) error

RemoveToken removes the provided token from the database

func (*Client) SessionToken

func (c *Client) SessionToken() *base64.Value

SessionToken returns the client's current session token

func (*Client) SetOrgRole

func (c *Client) SetOrgRole(ctx context.Context, user models.Email, role models.Label) error

func (*Client) SetProjectRole

func (c *Client) SetProjectRole(ctx context.Context, user models.Email, project models.Label, role models.Label) error

func (*Client) SuggestOrgPolicy added in v0.0.2

func (c *Client) SuggestOrgPolicy(
	ctx context.Context,
	name models.ProjectDisplayName,
	description models.ProjectDescription,
	spec *models.PolicyFile) (*models.Suggestion, error)

func (*Client) SuggestProjectPolicy added in v0.0.2

func (c *Client) SuggestProjectPolicy(
	ctx context.Context,
	projectLabel models.Label,
	name models.ProjectDisplayName,
	description models.ProjectDescription,
	spec *models.PolicyFile) (*models.Suggestion, error)

func (*Client) TokenLogin

func (c *Client) TokenLogin(ctx context.Context, token *auth.APIToken) (*LoginResponse, error)

func (*Client) UpdateProject

func (c *Client) UpdateProject(
	ctx context.Context,
	id string,
	label *models.Label,
	name *models.ProjectDisplayName,
	desc *models.ProjectDescription) (*models.Project, error)

func (*Client) UpdateProjectSpec

func (c *Client) UpdateProjectSpec(ctx context.Context, projectLabel models.Label, spec *models.PolicyFile) (*models.Project, *models.Policy, error)

type ClientTransport

type ClientTransport interface {
	Raw(ctx context.Context, query string, variables map[string]interface{}, resp interface{}) error

	// Post does a raw http POST to the specified url
	Post(url string, req interface{}) ([]byte, error)

	Authenticated() bool
	URL() *models.URL
	SetToken(*base64.Value)
	Token() *base64.Value

	EmailLogin(ctx context.Context, email models.Email, password models.Password) (*LoginResponse, error)
	TokenLogin(ctx context.Context, apiToken *auth.APIToken) (*LoginResponse, error)

	Logout(ctx context.Context, authToken *base64.Value) error
}

ClientTransport is an interface that describes how a coordinator client should communicate with a coordinator

func NewHTTPTransport

func NewHTTPTransport(coordinatorURL *models.URL, authToken *base64.Value, certFile string, insecure bool) ClientTransport

NewHTTPTransport returns a ClientTransport configured to make requests via GraphQL over HTTP

type Config

type Config struct {
	Version    int          `json:"version"`
	DB         *DBConfig    `json:"db" envconfig:"DB_URL"`
	InstanceID models.Label `json:"instance_id,omitempty"`
	Addr       string       `json:"addr"`

	// RootKey is used to encrypt/decrypt EncryptionKey and should
	// be stored in a separate config file in a secret or
	// other secure location.
	RootKey string `json:"root_key"`

	// The kdf algorithm is not externally configurable (e.g. not available on
	// the configuration file) as it's only required to be configurable for
	// testing.
	//
	// In future when we support more than one production algorithm we can
	// expose this feature to customers.
	CredentialProducerAlg models.CredentialsAlgType `json:"-"`

	// CertFile contains a path to the coordinators Certificate file.
	CertFile string `json:"tls_cert,omitempty" envconfig:"TLS_CERT"`

	// KeyFile contains a path to the coordinators TLS private key.
	KeyFile string `json:"tls_key,omitempty" envconfig:"TLS_KEY"`

	// Cors specifies the configuration for serving (or disabling)
	// CORS headers
	Cors CorsConfig `json:"cors"`

	// Required if no admin user has been c
	User *UserConfig `json:"user,omitempty"`
}

Config represents the configuration that needs to be provided to the Coordinator.

func LoadConfig

func LoadConfig(filePath string) (*Config, error)

LoadConfig parses a configuration file from given filepath and returns an initialized & validated config!

func NewConfig

func NewConfig(addr string, dbURL *models.DBURL) (*Config, error)

func (*Config) GetInstanceID

func (c *Config) GetInstanceID() models.Label

GetInstanceID returns the instance id to satisfy the framework.Component interface

func (*Config) Validate

func (c *Config) Validate() error

Validate returns an error if the config is invalid

func (*Config) Write

func (c *Config) Write(filePath string) error

Write writes the configuration to the given filepath

type Coordinator

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

Coordinator is the central brain of Cape. It keeps track of system users, policy, etc

func New

func New(cfg *Config, logger *zerolog.Logger, mailer mailer.Mailer) (*Coordinator, error)

New validates the input and returns a constructed Coordinator.

If the mode is set to Testing then the Coordinator will use the SHA256 algorithm for hashing passwords. This mode should only be used within the context of unit & integration tests.

func (*Coordinator) DB added in v0.0.2

func (c *Coordinator) DB() db.Interface

DB returns the Coordinator's underlying database. TODO(thor): This should be inverte so that we can pass a database to the constructor rather than return the one created.

func (*Coordinator) ServeHTTP added in v0.0.2

func (c *Coordinator) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Coordinator) Teardown

func (c *Coordinator) Teardown() error

Teardown the coordinator taking it back to it's start state!

func (*Coordinator) TokenAuthority added in v0.0.2

func (c *Coordinator) TokenAuthority() *auth.TokenAuthority

TokenAuthority returns the TokenAuthority created at startup

type CorsConfig

type CorsConfig struct {
	Enable      bool     `json:"enable"`
	AllowOrigin []string `json:"allow_origin,omitempty"`
}

type CreateProjectResponse

type CreateProjectResponse struct {
	Project *models.Project `json:"createProject"`
}

type CreateTokenMutation

type CreateTokenMutation struct {
	Secret models.Password `json:"secret"`
	Token  *models.Token   `json:"token"`
}

type CreateTokenResponse

type CreateTokenResponse struct {
	Response *CreateTokenMutation `json:"createToken"`
}

type DBConfig

type DBConfig struct {
	Addr *models.DBURL `json:"addr"`
}

DBConfig represent the database configuration

func (*DBConfig) Decode

func (db *DBConfig) Decode(value string) error

Decode implements envconfig.Decoder for decoding environment variables

func (*DBConfig) Validate

func (db *DBConfig) Validate() error

Validate returns an error if the DBConfig is invalid

type GQLContributor

type GQLContributor struct {
	*models.Contributor
	User    models.User    `json:"user"`
	Project models.Project `json:"project"`
	Role    models.Role    `json:"role"`
}

type GetOrgPolicy added in v0.0.2

type GetOrgPolicy struct {
	Policy models.Policy `json:"orgPolicy"`
}

type GetProject

type GetProject struct {
	*models.Project
	Policy       *models.Policy   `json:"current_spec"`
	Contributors []GQLContributor `json:"contributors"`
}

type GetProjectResponse

type GetProjectResponse struct {
	GetProject GetProject `json:"project"`
}

type GetProjectSuggestionResponse

type GetProjectSuggestionResponse struct {
	SuggestionResponse ProjectSuggestion `json:"getProjectSuggestion"`
}

type GetProjectSuggestionsResponseWrapper added in v0.0.2

type GetProjectSuggestionsResponseWrapper struct {
	Suggestions []GetSuggestionResponse `json:"getProjectSuggestions"`
}

type GetSuggestionResponse added in v0.0.2

type GetSuggestionResponse struct {
	*models.Suggestion
	Project models.Project `json:"project"`
}

type GetSuggestionsResponseWrapper added in v0.0.2

type GetSuggestionsResponseWrapper struct {
	Suggestions []GetSuggestionResponse `json:"listSuggestions"`
}

type HTTPTransport

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

HTTPTransport is a ClientTransport that interacts with the Coordinator via GraphQL over HTTP.

func (*HTTPTransport) Authenticated

func (c *HTTPTransport) Authenticated() bool

Authenticated returns whether the client is authenticated or not. If the authToken is not nil then its authenticated!

func (*HTTPTransport) EmailLogin

func (c *HTTPTransport) EmailLogin(ctx context.Context, email models.Email, password models.Password) (*LoginResponse, error)

EmailLogin starts step 1 of the login flow using an email & password

func (*HTTPTransport) Logout

func (c *HTTPTransport) Logout(ctx context.Context, authToken *base64.Value) error

Logout of the active session

func (*HTTPTransport) Post

func (c *HTTPTransport) Post(url string, req interface{}) ([]byte, error)

Post does a raw http POST to the specified url

func (*HTTPTransport) Raw

func (c *HTTPTransport) Raw(ctx context.Context, query string, variables map[string]interface{}, resp interface{}) error

Raw wraps the NewRequest and does common req changes like adding authorization headers. It calls Run passing the object to be filled with the request data.

func (*HTTPTransport) SetToken

func (c *HTTPTransport) SetToken(value *base64.Value)

SetToken enables a caller to set the auth token used by the transport

func (*HTTPTransport) Token

func (c *HTTPTransport) Token() *base64.Value

Token enables a caller to retrieve the current auth token used by the transport

func (*HTTPTransport) TokenLogin

func (c *HTTPTransport) TokenLogin(ctx context.Context, apiToken *auth.APIToken) (*LoginResponse, error)

TokenLogin enables a user or service to login using an APIToken

func (*HTTPTransport) URL

func (c *HTTPTransport) URL() *models.URL

URL returns the underlying URL used by this Transport

type ListContributorsResponse

type ListContributorsResponse struct {
	Contributors []GQLContributor `json:"listContributors"`
}

type ListProjectsResponse

type ListProjectsResponse struct {
	Projects []*models.Project `json:"projects"`
}

type ListRecoveriesResponse

type ListRecoveriesResponse struct {
	Recoveries []models.Recovery `json:"recoveries"`
}

type ListTokensResponse

type ListTokensResponse struct {
	IDs []string `json:"tokens"`
}

type LoginRequest

type LoginRequest struct {
	Email   *models.Email   `json:"email"`
	TokenID *string         `json:"token_id"`
	Secret  models.Password `json:"secret"`
}

type LoginResponse added in v0.0.2

type LoginResponse struct {
	Token  *base64.Value `json:"token"`   // The session token used to authenticate further requests
	UserID string        `json:"user_id"` // The identifier of the authenticated user
}

type LogoutRequest

type LogoutRequest struct {
	Token *base64.Value `json:"token"`
}

type MeResponse

type MeResponse struct {
	User *models.User `json:"me"`
}

type MockClientTransport

type MockClientTransport struct {
	Endpoint  *models.URL
	Requests  []*MockRequest
	Responses []*MockResponse
	Counter   int
	// contains filtered or unexported fields
}

MockClientTransport replaces the default transport on the client so we can return fake Responses for unit testing

func NewMockClientTransport

func NewMockClientTransport(url *models.URL, responses []*MockResponse) (*MockClientTransport, error)

func (*MockClientTransport) Authenticated

func (m *MockClientTransport) Authenticated() bool

func (*MockClientTransport) EmailLogin

func (m *MockClientTransport) EmailLogin(ctx context.Context, email models.Email, password models.Password) (*LoginResponse, error)

func (*MockClientTransport) Logout

func (m *MockClientTransport) Logout(ctx context.Context, authToken *base64.Value) error

func (*MockClientTransport) Post

func (m *MockClientTransport) Post(url string, req interface{}) ([]byte, error)

Post does a raw http POST to the specified url

func (*MockClientTransport) Raw

func (m *MockClientTransport) Raw(ctx context.Context, query string, variables map[string]interface{}, resp interface{}) error

Raw returns the appropriate response for the number request.

func (*MockClientTransport) SetToken

func (m *MockClientTransport) SetToken(value *base64.Value)

func (*MockClientTransport) Token

func (m *MockClientTransport) Token() *base64.Value

func (*MockClientTransport) TokenLogin

func (m *MockClientTransport) TokenLogin(ctx context.Context, apiToken *auth.APIToken) (*LoginResponse, error)

func (*MockClientTransport) URL

func (m *MockClientTransport) URL() *models.URL

type MockRequest

type MockRequest struct {
	Query     string
	Variables map[string]interface{}
	Body      interface{}
}

type MockResponse

type MockResponse struct {
	Value interface{}
	Error error
}

type MyRoleResponse

type MyRoleResponse struct {
	Role models.Role `json:"myRole"`
}

Role Routes

type ProjectSuggestion

type ProjectSuggestion struct {
	*models.Suggestion
	Policy  models.Policy  `json:"policy"`
	Project models.Project `json:"project"`
}

type RejectSuggestionResponse

type RejectSuggestionResponse struct {
	Project models.Project `json:"rejectProjectSuggestion"`
}

type RemoveContributorResponse

type RemoveContributorResponse struct {
	Contributor models.Contributor `json:"removeContributor"`
}

type SetupRequest

type SetupRequest struct {
	Name     models.Name     `json:"name"`
	Email    models.Email    `json:"email"`
	Password models.Password `json:"password"`
}

type SuggestOrgPolicyResponse added in v0.0.2

type SuggestOrgPolicyResponse struct {
	Suggestion models.Suggestion `json:"suggestPolicy"`
}

type SuggestPolicyResponse

type SuggestPolicyResponse struct {
	Suggestion models.Suggestion `json:"suggestProjectPolicy"`
}

type UpdateContributorResponse

type UpdateContributorResponse struct {
	*models.Contributor `json:"updateContributor"`
	User                *models.User `json:"user"`
}

type UpdateProjectResponse

type UpdateProjectResponse struct {
	Project *models.Project `json:"updateProject"`
}

type UpdateProjectSpecResponse

type UpdateProjectSpecResponse struct {
	UpdateProjectSpecResponseBody `json:"updateProjectSpec"`
}

type UpdateProjectSpecResponseBody

type UpdateProjectSpecResponseBody struct {
	*models.Project
	ProjectSpec *models.Policy `json:"current_spec"`
}

type UserConfig

type UserConfig struct {
	Name     models.Name  `json:"name"`
	Email    models.Email `json:"email"`
	Password string       `json:"password"`
}

type UserResponse

type UserResponse struct {
	*models.User
	Role models.Role `json:"role"`
}

UserResponse is a User with an extra Roles field that maps to the GraphQL type.

type VersionResponse

type VersionResponse struct {
	InstanceID string `json:"instance_id"`
	Version    string `json:"version"`
	BuildDate  string `json:"build_date"`
}

VersionResponse represents the data returned when querying the version handler

Directories

Path Synopsis
db
dbtest
dbtest contains functionality for writing tests
dbtest contains functionality for writing tests
package harness contains functionality for setting up and testing the coordinator in various different states.
package harness contains functionality for setting up and testing the coordinator in various different states.

Jump to

Keyboard shortcuts

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