httpmw
packageThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Index¶
- Constants
- func APIKey(r *http.Request) database.APIKey
- func APIKeyOptional(r *http.Request) (database.APIKey, bool)
- func APITokenFromRequest(r *http.Request) string
- func AsAuthzSystem(mws ...func(http.Handler) http.Handler) func(http.Handler) http.Handler
- func AttachRequestID(next http.Handler) http.Handler
- func CSPHeaders(websocketHosts func() []string) func(next http.Handler) http.Handler
- func CSRF(secureCookie bool) func(next http.Handler) http.Handler
- func Cors(allowAll bool, origins ...string) func(next http.Handler) http.Handler
- func EnsureXForwardedForHeader(req *http.Request) error
- func ExtractAPIKeyMW(cfg ExtractAPIKeyConfig) func(http.Handler) http.Handler
- func ExtractGitAuthParam(configs []*gitauth.Config) func(next http.Handler) http.Handler
- func ExtractGroupByNameParam(db database.Store) func(http.Handler) http.Handler
- func ExtractGroupParam(db database.Store) func(http.Handler) http.Handler
- func ExtractOAuth2(config OAuth2Config, client *http.Client, authURLOpts map[string]string) func(http.Handler) http.Handler
- func ExtractOrganizationMemberParam(db database.Store) func(http.Handler) http.Handler
- func ExtractOrganizationParam(db database.Store) func(http.Handler) http.Handler
- func ExtractRealIP(config *RealIPConfig) func(next http.Handler) http.Handler
- func ExtractRealIPAddress(config *RealIPConfig, req *http.Request) (net.IP, error)
- func ExtractTemplateParam(db database.Store) func(http.Handler) http.Handler
- func ExtractTemplateVersionParam(db database.Store) func(http.Handler) http.Handler
- func ExtractUserParam(db database.Store, redirectToLoginOnMe bool) func(http.Handler) http.Handler
- func ExtractWorkspaceAgent(opts ExtractWorkspaceAgentConfig) func(http.Handler) http.Handler
- func ExtractWorkspaceAgentParam(db database.Store) func(http.Handler) http.Handler
- func ExtractWorkspaceAndAgentParam(db database.Store) func(http.Handler) http.Handler
- func ExtractWorkspaceBuildParam(db database.Store) func(http.Handler) http.Handler
- func ExtractWorkspaceParam(db database.Store) func(http.Handler) http.Handler
- func ExtractWorkspaceProxy(opts ExtractWorkspaceProxyConfig) func(http.Handler) http.Handler
- func ExtractWorkspaceProxyParam(db database.Store, deploymentID string, ...) func(http.Handler) http.Handler
- func ExtractWorkspaceResourceParam(db database.Store) func(http.Handler) http.Handler
- func FilterUntrustedOriginHeaders(config *RealIPConfig, req *http.Request)
- func GitAuthParam(r *http.Request) *gitauth.Config
- func GroupParam(r *http.Request) database.Group
- func HSTS(next http.Handler, cfg HSTSConfig) http.Handler
- func Logger(log slog.Logger) func(next http.Handler) http.Handler
- func OrganizationMemberParam(r *http.Request) database.OrganizationMember
- func OrganizationParam(r *http.Request) database.Organization
- func ParseUUIDParam(rw http.ResponseWriter, r *http.Request, param string) (uuid.UUID, bool)
- func Prometheus(register prometheus.Registerer) func(http.Handler) http.Handler
- func RateLimit(count int, window time.Duration) func(http.Handler) http.Handler
- func Recover(log slog.Logger) func(h http.Handler) http.Handler
- func RedirectToLogin(rw http.ResponseWriter, r *http.Request, dashboardURL *url.URL, message string)
- func ReportCLITelemetry(log slog.Logger, rep telemetry.Reporter) func(http.Handler) http.Handler
- func RequestID(r *http.Request) uuid.UUID
- func RequireAPIKeyOrWorkspaceAgent() func(http.Handler) http.Handler
- func RequireAPIKeyOrWorkspaceProxyAuth() func(http.Handler) http.Handler
- func SplitAPIToken(token string) (id string, secret string, err error)
- func TemplateParam(r *http.Request) database.Template
- func TemplateVersionParam(r *http.Request) database.TemplateVersion
- func UserParam(r *http.Request) database.User
- func WorkspaceAgent(r *http.Request) database.WorkspaceAgent
- func WorkspaceAgentOptional(r *http.Request) (database.WorkspaceAgent, bool)
- func WorkspaceAgentParam(r *http.Request) database.WorkspaceAgent
- func WorkspaceAppCors(regex *regexp.Regexp, app httpapi.ApplicationURL) func(next http.Handler) http.Handler
- func WorkspaceBuildParam(r *http.Request) database.WorkspaceBuild
- func WorkspaceParam(r *http.Request) database.Workspace
- func WorkspaceProxy(r *http.Request) database.WorkspaceProxy
- func WorkspaceProxyOptional(r *http.Request) (database.WorkspaceProxy, bool)
- func WorkspaceProxyParam(r *http.Request) database.WorkspaceProxy
- func WorkspaceResourceParam(r *http.Request) database.WorkspaceResource
- type Authorization
- type CSPFetchDirective
- type ExtractAPIKeyConfig
- type ExtractWorkspaceAgentConfig
- type ExtractWorkspaceProxyConfig
- type HSTSConfig
- type OAuth2Config
- type OAuth2Configs
- type OAuth2State
- type RealIPConfig
- type RealIPState
Constants¶
const (// Server headers.AccessControlAllowOriginHeader = "Access-Control-Allow-Origin"AccessControlAllowCredentialsHeader = "Access-Control-Allow-Credentials"AccessControlAllowMethodsHeader = "Access-Control-Allow-Methods"AccessControlAllowHeadersHeader = "Access-Control-Allow-Headers"VaryHeader = "Vary"// Client headers.OriginHeader = "Origin"AccessControlRequestMethodsHeader = "Access-Control-Request-Methods"AccessControlRequestHeadersHeader = "Access-Control-Request-Headers")
const (SignedOutErrorMessage = "You are signed out or your session has expired. Please sign in again to continue.")
const (// WorkspaceProxyAuthTokenHeader is the auth header used for requests from// external workspace proxies.//// The format of an external proxy token is:// <proxy id>:<proxy secret>////nolint:gosecWorkspaceProxyAuthTokenHeader = "Coder-External-Proxy-Token")
Variables¶
This section is empty.
Functions¶
funcAPIKeyOptional¶added inv0.9.0
APIKeyOptional may return an API key from the ExtractAPIKey handler.
funcAPITokenFromRequest¶added inv0.23.0
APITokenFromRequest returns the api token from the request.Find the session token from:1: The cookie1: The devurl cookie3: The old cookie4. The coder_session_token query parameter5. The custom auth header
funcAsAuthzSystem¶added inv0.17.2
AsAuthzSystem is a chained handler that temporarily sets the dbauthz contextto System for the inner handlers, and resets the context afterwards.
TODO: Refactor the middleware functions to not require this.This is a bit of a kludge for now as some middleware functions requireusage as a system user in some cases, but not all cases. To avoid largerefactors, we use this middleware to temporarily set the context to a system.
funcAttachRequestID¶added inv0.8.12
AttachRequestID adds a request ID to each HTTP request.
funcCSPHeaders¶added inv0.23.1
CSPHeaders returns a middleware that sets the Content-Security-Policy headerfor coderd. It takes a function that allows adding supported external websockethosts. This is primarily to support the terminal connecting to a workspace proxy.
funcCSRF¶added inv0.8.15
CSRF is a middleware that verifies that a CSRF token is present in the requestfor non-GET requests.
funcEnsureXForwardedForHeader¶added inv0.11.0
EnsureXForwardedForHeader ensures that the request has an X-Forwarded-Forheader. It uses the following logic:
- If we have a direct connection (remoteAddr == proxyAddr), thenset it to remoteAddr
- If we have a proxied connection (remoteAddr != proxyAddr) andX-Forwarded-For doesn't begin with remoteAddr, then overwriteit with remoteAddr,proxyAddr
- If we have a proxied connection (remoteAddr != proxyAddr) andX-Forwarded-For begins with remoteAddr, then append proxyAddrto the original X-Forwarded-For header
- If X-Forwarded-Proto is not set, then it will be set to "https"if req.TLS != nil, otherwise it will be set to "http"
funcExtractAPIKeyMW¶added inv0.19.0
func ExtractAPIKeyMW(cfgExtractAPIKeyConfig) func(http.Handler)http.Handler
ExtractAPIKeyMW calls ExtractAPIKey with the given config on each request,storing the result in the request context.
funcExtractGitAuthParam¶added inv0.25.0
funcExtractGroupByNameParam¶added inv0.12.0
funcExtractGroupParam¶added inv0.9.9
ExtraGroupParam grabs a group from the "group" URL parameter.
funcExtractOAuth2¶added inv0.4.4
func ExtractOAuth2(configOAuth2Config, client *http.Client, authURLOpts map[string]string) func(http.Handler)http.Handler
ExtractOAuth2 is a middleware for automatically redirecting to OAuthURLs, and handling the exchange inbound. Any route that does not havea "code" URL parameter will be redirected.AuthURLOpts are passed to the AuthCodeURL function. If this is nil,the default option oauth2.AccessTypeOffline will be used.
funcExtractOrganizationMemberParam¶added inv0.6.0
ExtractOrganizationMemberParam grabs a user membership from the "organization" and "user" URL parameter.This middleware requires the ExtractUser and ExtractOrganization middleware higher in the stack
funcExtractOrganizationParam¶
ExtractOrganizationParam grabs an organization from the "organization" URL parameter.This middleware requires the API key middleware higher in the call stack for authentication.
funcExtractRealIP¶added inv0.11.0
func ExtractRealIP(config *RealIPConfig) func(nexthttp.Handler)http.Handler
ExtractRealIP is a middleware that uses headers from reverse proxies topropagate origin IP address information, when configured to do so.
funcExtractRealIPAddress¶added inv0.11.0
ExtractRealIPAddress returns the original client address according to theconfiguration and headers. It does not mutate the original request.
funcExtractTemplateParam¶added inv0.4.0
ExtractTemplateParam grabs a template from the "template" URL parameter.
funcExtractTemplateVersionParam¶added inv0.4.0
ExtractTemplateVersionParam grabs template version from the "templateversion" URL parameter.
funcExtractUserParam¶
ExtractUserParam extracts a user from an ID/username in the {user} URLparameter.
funcExtractWorkspaceAgent¶
func ExtractWorkspaceAgent(optsExtractWorkspaceAgentConfig) func(http.Handler)http.Handler
ExtractWorkspaceAgent requires authentication using a valid agent token.
funcExtractWorkspaceAgentParam¶added inv0.4.1
ExtractWorkspaceAgentParam grabs a workspace agent from the "workspaceagent" URL parameter.
funcExtractWorkspaceAndAgentParam¶added inv0.8.9
ExtractWorkspaceAndAgentParam grabs a workspace and an agent from the"workspace_and_agent" URL parameter. `ExtractUserParam` must be calledbefore this.This can be in the form of:
- "<workspace-name>.[workspace-agent]": If multiple agents exist
- "<workspace-name>": If one agent exists
funcExtractWorkspaceBuildParam¶
ExtractWorkspaceBuildParam grabs workspace build from the "workspacebuild" URL parameter.
funcExtractWorkspaceParam¶
ExtractWorkspaceParam grabs a workspace from the "workspace" URL parameter.
funcExtractWorkspaceProxy¶added inv0.23.0
func ExtractWorkspaceProxy(optsExtractWorkspaceProxyConfig) func(http.Handler)http.Handler
ExtractWorkspaceProxy extracts the external workspace proxy from the requestusing the external proxy auth token header.
funcExtractWorkspaceProxyParam¶added inv0.23.0
func ExtractWorkspaceProxyParam(dbdatabase.Store, deploymentIDstring, fetchPrimaryProxy func(ctxcontext.Context) (database.WorkspaceProxy,error)) func(http.Handler)http.Handler
ExtractWorkspaceProxyParam extracts a workspace proxy from an ID/name in the {workspaceproxy} URLparameter.
funcExtractWorkspaceResourceParam¶
ExtractWorkspaceResourceParam grabs a workspace resource from the "provisionerjob" URL parameter.
funcFilterUntrustedOriginHeaders¶added inv0.11.0
func FilterUntrustedOriginHeaders(config *RealIPConfig, req *http.Request)
FilterUntrustedOriginHeaders removes all known proxy headers from therequest for untrusted origins, and ensures that only one copyof each proxy header is set.
funcGroupParam¶added inv0.9.9
GroupParam returns the group extracted via the ExtraGroupParam middleware.
funcHSTS¶added inv0.17.2
func HSTS(nexthttp.Handler, cfgHSTSConfig)http.Handler
HSTS will add the strict-transport-security header if enabled. This headerforces a browser to always use https for the domain after it loads https once.Meaning: On first load of product.coder.com, they are redirected to https. Onall subsequent loads, the client's local browser forces https. This preventsman in the middle.
This header only makes sense if the app is using tls.
Full header example:Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
funcOrganizationMemberParam¶
func OrganizationMemberParam(r *http.Request)database.OrganizationMember
OrganizationMemberParam returns the organization membership that allowed the queryfrom the ExtractOrganizationParam handler.
funcOrganizationParam¶
func OrganizationParam(r *http.Request)database.Organization
OrganizationParam returns the organization from the ExtractOrganizationParam handler.
funcParseUUIDParam¶added inv0.26.2
ParseUUIDParam consumes a url parameter and parses it as a UUID.
funcPrometheus¶added inv0.5.4
func Prometheus(registerprometheus.Registerer) func(http.Handler)http.Handler
funcRateLimit¶added inv0.11.0
RateLimit returns a handler that limits requests per-minute basedon IP, endpoint, and user ID (if available).
funcRedirectToLogin¶added inv0.10.0
RedirectToLogin redirects the user to the login page with the `message` and`redirect` query parameters set.
If dashboardURL is nil, the redirect will be relative to the currentrequest's host. If it is not nil, the redirect will be absolute with dashboardurl as the host.
funcReportCLITelemetry¶added inv0.23.6
funcRequireAPIKeyOrWorkspaceAgent¶added inv0.25.0
RequireAPIKeyOrWorkspaceAgent is middleware that should be inserted afteroptional ExtractAPIKey and ExtractWorkspaceAgent middlewares to ensure one ofthe two is provided.
If both are provided an error is returned to avoid misuse.
funcRequireAPIKeyOrWorkspaceProxyAuth¶added inv0.23.0
RequireAPIKeyOrWorkspaceProxyAuth is middleware that should be inserted afteroptional ExtractAPIKey and ExtractWorkspaceProxy middlewares to ensure one ofthe two authentication methods is provided.
If both are provided, an error is returned to avoid misuse.
funcSplitAPIToken¶added inv0.9.0
SplitAPIToken verifies the format of an API key and returns the split ID andsecret.
APIKeys are formatted: ${ID}-${SECRET}
funcTemplateParam¶added inv0.4.0
TemplateParam returns the template from the ExtractTemplateParam handler.
funcTemplateVersionParam¶added inv0.4.0
func TemplateVersionParam(r *http.Request)database.TemplateVersion
TemplateVersionParam returns the template version from the ExtractTemplateVersionParam handler.
funcWorkspaceAgent¶
func WorkspaceAgent(r *http.Request)database.WorkspaceAgent
WorkspaceAgent returns the workspace agent from the ExtractAgent handler.
funcWorkspaceAgentOptional¶added inv0.25.0
func WorkspaceAgentOptional(r *http.Request) (database.WorkspaceAgent,bool)
funcWorkspaceAgentParam¶added inv0.4.1
func WorkspaceAgentParam(r *http.Request)database.WorkspaceAgent
WorkspaceAgentParam returns the workspace agent from the ExtractWorkspaceAgentParam handler.
funcWorkspaceAppCors¶added inv0.24.0
funcWorkspaceBuildParam¶
func WorkspaceBuildParam(r *http.Request)database.WorkspaceBuild
WorkspaceBuildParam returns the workspace build from the ExtractWorkspaceBuildParam handler.
funcWorkspaceParam¶
WorkspaceParam returns the workspace from the ExtractWorkspaceParam handler.
funcWorkspaceProxy¶added inv0.23.0
func WorkspaceProxy(r *http.Request)database.WorkspaceProxy
WorkspaceProxy returns the workspace proxy from the ExtractWorkspaceProxymiddleware.
funcWorkspaceProxyOptional¶added inv0.23.0
func WorkspaceProxyOptional(r *http.Request) (database.WorkspaceProxy,bool)
WorkspaceProxyOptional may return the workspace proxy from the ExtractWorkspaceProxymiddleware.
funcWorkspaceProxyParam¶added inv0.23.0
func WorkspaceProxyParam(r *http.Request)database.WorkspaceProxy
WorkspaceProxyParam returns the worksace proxy from the ExtractWorkspaceProxyParam handler.
funcWorkspaceResourceParam¶
func WorkspaceResourceParam(r *http.Request)database.WorkspaceResource
ProvisionerJobParam returns the template from the ExtractTemplateParam handler.
Types¶
typeAuthorization¶added inv0.9.0
type Authorization struct {Actorrbac.Subject// ActorName is required for logging and human friendly related identification.// It is usually the "username" of the user, but it can be the name of the// external workspace proxy or other service type actor.ActorNamestring}
funcExtractAPIKey¶
func ExtractAPIKey(rwhttp.ResponseWriter, r *http.Request, cfgExtractAPIKeyConfig) (*database.APIKey, *Authorization,bool)
ExtractAPIKey requires authentication using a valid API key. It handlesextending an API key if it comes close to expiry, updating the last used timein the database.
If the configuration specifies that the API key is optional, a nil API keyand authz object may be returned. False is returned if a response was writtento the request and the caller should give up.nolint:revive
funcUserAuthorization¶added inv0.9.0
func UserAuthorization(r *http.Request)Authorization
UserAuthorization returns the roles and scope used for authorization. Dependson the ExtractAPIKey handler.
funcUserAuthorizationOptional¶added inv0.9.0
func UserAuthorizationOptional(r *http.Request) (Authorization,bool)
UserAuthorizationOptional may return the roles and scope used forauthorization. Depends on the ExtractAPIKey handler.
typeCSPFetchDirective¶added inv0.23.1
type CSPFetchDirectivestring
CSPFetchDirective is the list of all constant fetch directives thatcan be used/appended to.
typeExtractAPIKeyConfig¶added inv0.9.0
type ExtractAPIKeyConfig struct {DBdatabase.StoreOAuth2Configs *OAuth2ConfigsRedirectToLoginboolDisableSessionExpiryRefreshbool// Optional governs whether the API key is optional. Use this if you want to// allow unauthenticated requests.//// If true and no session token is provided, nothing will be written to the// request context. Use the APIKeyOptional and UserAuthorizationOptional// functions to retrieve the API key and authorization instead of the// regular ones.//// If true and the API key is invalid (i.e. deleted, expired), the cookie// will be deleted and the request will continue. If the request is not a// cookie-based request, the request will be rejected with a 401.Optionalbool// SessionTokenFunc is a custom function that can be used to extract the API// key. If nil, the default behavior is used.SessionTokenFunc func(r *http.Request)string}
typeExtractWorkspaceAgentConfig¶added inv0.25.0
typeExtractWorkspaceProxyConfig¶added inv0.23.0
typeHSTSConfig¶added inv0.17.2
type HSTSConfig struct {// HeaderValue is an empty string if hsts header is disabled.HeaderValuestring}
funcHSTSConfigOptions¶added inv0.17.2
func HSTSConfigOptions(maxAgeint, options []string) (HSTSConfig,error)
typeOAuth2Config¶
type OAuth2Config interface {AuthCodeURL(statestring, opts ...oauth2.AuthCodeOption)stringExchange(ctxcontext.Context, codestring, opts ...oauth2.AuthCodeOption) (*oauth2.Token,error)TokenSource(context.Context, *oauth2.Token)oauth2.TokenSource}
OAuth2Config exposes a subset of *oauth2.Config functions for easier testing.*oauth2.Config should be used instead of implementing this in production.
typeOAuth2Configs¶added inv0.4.4
type OAuth2Configs struct {GithubOAuth2ConfigOIDCOAuth2Config}
OAuth2Configs is a collection of configurations for OAuth-based authentication.This should be extended to support other authentication types in the future.
func (*OAuth2Configs)IsZero¶added inv0.26.1
func (c *OAuth2Configs) IsZero()bool
typeOAuth2State¶added inv0.4.4
funcOAuth2¶added inv0.4.4
func OAuth2(r *http.Request)OAuth2State
OAuth2 returns the state from an oauth request.
typeRealIPConfig¶added inv0.11.0
type RealIPConfig struct {// TrustedOrigins is a list of networks that will be trusted. If// any non-trusted address supplies these headers, they will be// ignored.TrustedOrigins []*net.IPNet// TrustedHeaders lists headers that are trusted for forwarding// IP addresses. e.g. "CF-Connecting-IP", "True-Client-IP", etc.TrustedHeaders []string}
RealIPConfig configures the search order for the function, which controlswhich headers to consider trusted.
funcParseRealIPConfig¶added inv0.11.0
func ParseRealIPConfig(headers, origins []string) (*RealIPConfig,error)
ParseRealIPConfig takes a raw string array of headers and originsto produce a config.
typeRealIPState¶added inv0.11.0
type RealIPState struct {// Config is the configuration applied in the middleware. Consider// this read-only and do not modify.Config *RealIPConfig// OriginalRemoteAddr is the original RemoteAddr for the request.OriginalRemoteAddrstring}
RealIPState is the original state prior to modification by this middleware,useful for getting information about the connecting client if needed.
funcRealIP¶added inv0.11.0
func RealIP(ctxcontext.Context) *RealIPState
FromContext retrieves the state from the given context.Context.
Source Files¶
- actor.go
- apikey.go
- authz.go
- clitelemetry.go
- cors.go
- csp.go
- csrf.go
- gitauthparam.go
- groupparam.go
- hsts.go
- httpmw.go
- logger.go
- oauth2.go
- organizationparam.go
- prometheus.go
- ratelimit.go
- realip.go
- recover.go
- requestid.go
- templateparam.go
- templateversionparam.go
- userparam.go
- workspaceagent.go
- workspaceagentparam.go
- workspacebuildparam.go
- workspaceparam.go
- workspaceproxy.go
- workspaceresourceparam.go