coderdtest

package
v0.27.3 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2023 License: AGPL-3.0 Imports: 86 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AppSecurityKey = must(workspaceapps.KeyFromString("6465616e207761732068657265206465616e207761732068657265206465616e207761732068657265206465616e207761732068657265206465616e207761732068657265206465616e207761732068657265206465616e2077617320686572"))

AppSecurityKey is a 96-byte key used to sign JWTs and encrypt JWEs for workspace app tokens in tests.

View Source
var FirstUserParams = codersdk.CreateFirstUserRequest{
	Email:    "testuser@coder.com",
	Username: "testuser",
	Password: "SomeSecurePassword!",
}

Functions

func AwaitTemplateVersionJob added in v0.4.0

func AwaitTemplateVersionJob(t *testing.T, client *codersdk.Client, version uuid.UUID) codersdk.TemplateVersion

AwaitTemplateImportJob awaits for an import job to reach completed status.

func AwaitWorkspaceAgents

func AwaitWorkspaceAgents(t *testing.T, client *codersdk.Client, workspaceID uuid.UUID, agentNames ...string) []codersdk.WorkspaceResource

AwaitWorkspaceAgents waits for all resources with agents to be connected. If specific agents are provided, it will wait for those agents to be connected but will not fail if other agents are not connected.

func AwaitWorkspaceBuildJob

func AwaitWorkspaceBuildJob(t *testing.T, client *codersdk.Client, build uuid.UUID) codersdk.WorkspaceBuild

AwaitWorkspaceBuildJob waits for a workspace provision job to reach completed status.

func CreateAnotherUser

func CreateAnotherUser(t *testing.T, client *codersdk.Client, organizationID uuid.UUID, roles ...string) (*codersdk.Client, codersdk.User)

CreateAnotherUser creates and authenticates a new user.

func CreateAnotherUserMutators added in v0.25.0

func CreateAnotherUserMutators(t *testing.T, client *codersdk.Client, organizationID uuid.UUID, roles []string, mutators ...func(r *codersdk.CreateUserRequest)) (*codersdk.Client, codersdk.User)

func CreateFirstUser

func CreateFirstUser(t testing.TB, client *codersdk.Client) codersdk.CreateFirstUserResponse

CreateFirstUser creates a user with preset credentials and authenticates with the passed in codersdk client.

func CreateTemplate added in v0.4.0

func CreateTemplate(t *testing.T, client *codersdk.Client, organization uuid.UUID, version uuid.UUID, mutators ...func(*codersdk.CreateTemplateRequest)) codersdk.Template

CreateTemplate creates a template with the "echo" provisioner for compatibility with testing. The name assigned is randomly generated.

func CreateTemplateVersion added in v0.4.0

func CreateTemplateVersion(t *testing.T, client *codersdk.Client, organizationID uuid.UUID, res *echo.Responses, mutators ...func(*codersdk.CreateTemplateVersionRequest)) codersdk.TemplateVersion

CreateTemplateVersion creates a template import provisioner job with the responses provided. It uses the "echo" provisioner for compatibility with testing.

func CreateWorkspace

func CreateWorkspace(t *testing.T, client *codersdk.Client, organization uuid.UUID, templateID uuid.UUID, mutators ...func(*codersdk.CreateWorkspaceRequest)) codersdk.Workspace

CreateWorkspace creates a workspace for the user and template provided. A random name is generated for it. To customize the defaults, pass a mutator func.

func CreateWorkspaceBuild added in v0.6.0

func CreateWorkspaceBuild(
	t *testing.T,
	client *codersdk.Client,
	workspace codersdk.Workspace,
	transition database.WorkspaceTransition,
	mutators ...func(*codersdk.CreateWorkspaceBuildRequest),
) codersdk.WorkspaceBuild

CreateWorkspaceBuild creates a workspace build for the given workspace and transition.

func DeploymentValues added in v0.19.0

func DeploymentValues(t testing.TB) *codersdk.DeploymentValues

func MustTransitionWorkspace added in v0.6.3

func MustTransitionWorkspace(t *testing.T, client *codersdk.Client, workspaceID uuid.UUID, from, to database.WorkspaceTransition) codersdk.Workspace

TransitionWorkspace is a convenience method for transitioning a workspace from one state to another.

func MustWorkspace added in v0.6.3

func MustWorkspace(t *testing.T, client *codersdk.Client, workspaceID uuid.UUID) codersdk.Workspace

MustWorkspace is a convenience method for fetching a workspace that should exist.

func New

func New(t testing.TB, options *Options) *codersdk.Client

New constructs a codersdk client connected to an in-memory API instance.

func NewAWSInstanceIdentity

func NewAWSInstanceIdentity(t *testing.T, instanceID string) (awsidentity.Certificates, *http.Client)

NewAWSInstanceIdentity returns a metadata client and ID token validator for faking instance authentication for AWS.

func NewAzureInstanceIdentity added in v0.4.4

func NewAzureInstanceIdentity(t *testing.T, instanceID string) (x509.VerifyOptions, *http.Client)

NewAzureInstanceIdentity returns a metadata client and ID token validator for faking instance authentication for Azure.

func NewExternalProvisionerDaemon added in v0.12.8

func NewExternalProvisionerDaemon(t *testing.T, client *codersdk.Client, org uuid.UUID, tags map[string]string) io.Closer

func NewGoogleInstanceIdentity

func NewGoogleInstanceIdentity(t *testing.T, instanceID string, expired bool) (*idtoken.Validator, *metadata.Client)

NewGoogleInstanceIdentity returns a metadata client and ID token validator for faking instance authentication for Google Cloud. nolint:revive

func NewOptions added in v0.9.0

func NewOptions(t testing.TB, options *Options) (func(http.Handler), context.CancelFunc, *url.URL, *coderd.Options)

func NewProvisionerDaemon

func NewProvisionerDaemon(t testing.TB, coderAPI *coderd.API) io.Closer

NewProvisionerDaemon launches a provisionerd instance configured to work well with coderd testing. It registers the "echo" provisioner for quick testing.

func NewWithAPI added in v0.6.1

func NewWithAPI(t testing.TB, options *Options) (*codersdk.Client, io.Closer, *coderd.API)

NewWithAPI constructs an in-memory API instance and returns a client to talk to it. Most tests never need a reference to the API, but AuthorizationTest in this module uses it. Do not expose the API or wrath shall descend upon thee.

func NewWithProvisionerCloser added in v0.7.6

func NewWithProvisionerCloser(t *testing.T, options *Options) (*codersdk.Client, io.Closer)

NewWithProvisionerCloser returns a client as well as a handle to close the provisioner. This is a temporary function while work is done to standardize how provisioners are registered with coderd. The option to include a provisioner is set to true for convenience.

func RandomRBACAction added in v0.17.2

func RandomRBACAction() rbac.Action

func RandomRBACObject added in v0.17.2

func RandomRBACObject() rbac.Object

func RandomRBACSubject added in v0.17.2

func RandomRBACSubject() rbac.Subject

func RequestGitAuthCallback added in v0.18.0

func RequestGitAuthCallback(t *testing.T, providerID string, client *codersdk.Client) *http.Response

RequestGitAuthCallback makes a request with the proper OAuth2 state cookie to the git auth callback endpoint.

func SDKError added in v0.8.12

func SDKError(t *testing.T, err error) *codersdk.Error

SDKError coerces err into an SDK error.

func UpdateTemplateVersion added in v0.5.6

func UpdateTemplateVersion(t *testing.T, client *codersdk.Client, organizationID uuid.UUID, res *echo.Responses, templateID uuid.UUID) codersdk.TemplateVersion

UpdateTemplateVersion creates a new template version with the "echo" provisioner and associates it with the given templateID.

func VerifySwaggerDefinitions added in v0.15.0

func VerifySwaggerDefinitions(t *testing.T, router chi.Router, swaggerComments []SwaggerComment)

Types

type ActionObjectPair added in v0.17.0

type ActionObjectPair struct {
	Action rbac.Action
	Object rbac.Object
}

type AuthCall added in v0.20.0

type AuthCall struct {
	rbac.AuthCall
	// contains filtered or unexported fields
}

type FakeAuthorizer added in v0.17.0

type FakeAuthorizer struct {
	// AlwaysReturn is the error that will be returned by Authorize.
	AlwaysReturn error
}

FakeAuthorizer is an Authorizer that always returns the same error.

func (*FakeAuthorizer) Authorize added in v0.17.0

func (d *FakeAuthorizer) Authorize(_ context.Context, _ rbac.Subject, _ rbac.Action, _ rbac.Object) error

func (*FakeAuthorizer) Prepare added in v0.17.0

func (d *FakeAuthorizer) Prepare(_ context.Context, subject rbac.Subject, action rbac.Action, _ string) (rbac.PreparedAuthorized, error)

type OIDCConfig added in v0.10.2

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

func NewOIDCConfig added in v0.10.2

func NewOIDCConfig(t *testing.T, issuer string) *OIDCConfig

func (*OIDCConfig) AuthCodeURL added in v0.10.2

func (*OIDCConfig) AuthCodeURL(state string, _ ...oauth2.AuthCodeOption) string

func (*OIDCConfig) EncodeClaims added in v0.10.2

func (o *OIDCConfig) EncodeClaims(t *testing.T, claims jwt.MapClaims) string

func (*OIDCConfig) Exchange added in v0.10.2

func (*OIDCConfig) Exchange(_ context.Context, code string, _ ...oauth2.AuthCodeOption) (*oauth2.Token, error)

func (*OIDCConfig) OIDCConfig added in v0.10.2

func (o *OIDCConfig) OIDCConfig(t *testing.T, userInfoClaims jwt.MapClaims, opts ...func(cfg *coderd.OIDCConfig)) *coderd.OIDCConfig

func (*OIDCConfig) TokenSource added in v0.10.2

type Options

type Options struct {
	// AccessURL denotes a custom access URL. By default we use the httptest
	// server's URL. Setting this may result in unexpected behavior (especially
	// with running agents).
	AccessURL             *url.URL
	AppHostname           string
	AWSCertificates       awsidentity.Certificates
	Authorizer            rbac.Authorizer
	AzureCertificates     x509.VerifyOptions
	GithubOAuth2Config    *coderd.GithubOAuth2Config
	RealIPConfig          *httpmw.RealIPConfig
	OIDCConfig            *coderd.OIDCConfig
	GoogleTokenValidator  *idtoken.Validator
	SSHKeygenAlgorithm    gitsshkey.Algorithm
	AutobuildTicker       <-chan time.Time
	AutobuildStats        chan<- autobuild.Stats
	Auditor               audit.Auditor
	TLSCertificates       []tls.Certificate
	GitAuthConfigs        []*gitauth.Config
	TrialGenerator        func(context.Context, string) error
	TemplateScheduleStore schedule.TemplateScheduleStore
	Coordinator           tailnet.Coordinator

	HealthcheckFunc    func(ctx context.Context, apiKey string) *healthcheck.Report
	HealthcheckTimeout time.Duration
	HealthcheckRefresh time.Duration

	// All rate limits default to -1 (unlimited) in tests if not set.
	APIRateLimit   int
	LoginRateLimit int
	FilesRateLimit int

	// IncludeProvisionerDaemon when true means to start an in-memory provisionerD
	IncludeProvisionerDaemon    bool
	MetricsCacheRefreshInterval time.Duration
	AgentStatsRefreshInterval   time.Duration
	DeploymentValues            *codersdk.DeploymentValues

	// Set update check options to enable update check.
	UpdateCheckOptions *updatecheck.Options

	// Overriding the database is heavily discouraged.
	// It should only be used in cases where multiple Coder
	// test instances are running against the same database.
	Database database.Store
	Pubsub   pubsub.Pubsub

	ConfigSSH codersdk.SSHConfigResponse

	SwaggerEndpoint bool
	// Logger should only be overridden if you expect errors
	// as part of your test.
	Logger *slog.Logger
}

type PreparedRecorder added in v0.17.0

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

PreparedRecorder is the prepared version of the RecordingAuthorizer. It records the Authorize() calls to the original recorder. If the caller uses CompileToSQL, all recording stops. This is to support parity between memory and SQL backed dbs.

func (*PreparedRecorder) Authorize added in v0.17.0

func (s *PreparedRecorder) Authorize(ctx context.Context, object rbac.Object) error

func (*PreparedRecorder) CompileToSQL added in v0.17.0

func (s *PreparedRecorder) CompileToSQL(ctx context.Context, cfg regosql.ConvertConfig) (string, error)

type RBACAsserter added in v0.20.0

type RBACAsserter struct {
	Subject rbac.Subject

	Recorder *RecordingAuthorizer
}

RBACAsserter is a helper for asserting that the correct RBAC checks are performed. This struct is tied to a given user, and only authorizes calls for this user are checked.

func AssertRBAC added in v0.20.0

func AssertRBAC(t *testing.T, api *coderd.API, client *codersdk.Client) RBACAsserter

AssertRBAC returns an RBACAsserter for the given user. This asserter will allow asserting that the correct RBAC checks are performed for the given user. All checks that are not run against this user will be ignored.

func (RBACAsserter) AllCalls added in v0.20.0

func (a RBACAsserter) AllCalls() []AuthCall

AllCalls is for debugging. If you are not sure where calls are coming from, call this and use a debugger or print them. They have small callstacks on them to help locate the 'Authorize' call. Only calls to Authorize by the given subject will be returned. Note that duplicate rbac calls are handled by the rbac.Cacher(), but will be recorded twice. So AllCalls() returns calls regardless if they were returned from the cached or not.

func (RBACAsserter) AssertChecked added in v0.20.0

func (a RBACAsserter) AssertChecked(t *testing.T, action rbac.Action, objects ...interface{})

AssertChecked will assert a given rbac check was performed. It does not care about order of checks, or any other checks. This is useful when you do not care about asserting every check that was performed.

func (RBACAsserter) AssertInOrder added in v0.20.0

func (a RBACAsserter) AssertInOrder(t *testing.T, action rbac.Action, objects ...interface{})

AssertInOrder must be called in the correct order of authz checks. If the objects or actions are not in the correct order, the test will fail.

func (RBACAsserter) Reset added in v0.20.0

func (a RBACAsserter) Reset() RBACAsserter

Reset will clear all previously recorded authz calls. This is helpful when wanting to ignore checks run in test setup.

type RecordingAuthorizer added in v0.9.0

type RecordingAuthorizer struct {
	sync.RWMutex
	Called  []AuthCall
	Wrapped rbac.Authorizer
}

RecordingAuthorizer wraps any rbac.Authorizer and records all Authorize() calls made. This is useful for testing as these calls can later be asserted.

func (*RecordingAuthorizer) AllAsserted added in v0.17.0

func (r *RecordingAuthorizer) AllAsserted() error

AllAsserted returns an error if all calls to Authorize() have not been asserted and checked. This is useful for testing to ensure that all Authorize() calls are checked in the unit test.

func (*RecordingAuthorizer) AllCalls added in v0.20.0

func (r *RecordingAuthorizer) AllCalls(actor *rbac.Subject) []AuthCall

AllCalls is useful for debugging.

func (*RecordingAuthorizer) AssertActor added in v0.17.0

func (r *RecordingAuthorizer) AssertActor(t *testing.T, actor rbac.Subject, did ...ActionObjectPair)

AssertActor asserts in order. If the order of authz calls does not match, this will fail.

func (*RecordingAuthorizer) AssertOutOfOrder added in v0.20.0

func (r *RecordingAuthorizer) AssertOutOfOrder(t *testing.T, actor rbac.Subject, did ...ActionObjectPair)

AssertOutOfOrder asserts that the given actor performed the given action on the given objects. It does not care about the order of the calls. When marking authz calls as asserted, it will mark the first matching calls first.

func (*RecordingAuthorizer) Authorize added in v0.15.3

func (r *RecordingAuthorizer) Authorize(ctx context.Context, subject rbac.Subject, action rbac.Action, object rbac.Object) error

func (*RecordingAuthorizer) Pair added in v0.17.0

Pair is on the RecordingAuthorizer to be easy to find and keep the pkg interface smaller.

func (*RecordingAuthorizer) Prepare added in v0.15.3

func (r *RecordingAuthorizer) Prepare(ctx context.Context, subject rbac.Subject, action rbac.Action, objectType string) (rbac.PreparedAuthorized, error)

func (*RecordingAuthorizer) Reset added in v0.17.0

func (r *RecordingAuthorizer) Reset()

Reset clears the recorded Authorize() calls.

type SwaggerComment added in v0.15.0

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

func ParseSwaggerComments added in v0.15.0

func ParseSwaggerComments(dirs ...string) ([]SwaggerComment, error)

Jump to

Keyboard shortcuts

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