webapi

package
v0.0.0-...-3bfe646 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2023 License: Apache-2.0 Imports: 64 Imported by: 0

README

This is a description of HTTP response headers that we set in our API handlers. These headers help with preventing caching of HTTP traffic and with XXS/CSRF attack mitigation.

Below table shows a list of headers per request type. This list is a subject to change based on the new findings and recommendations.

index.html REST api
Cache-Control: no-store; no-cache;must-revalidate y y
Strict-Transport-Security: max-age=31536000; includeSubDomains y
Pragma: no-cache y
Expires: 0 y
X-Frame-Options:SAMEORIGIN y
X-XSS-Protection:1; mode=block y
X-Content-Type-Options", "nosniff" y
content-security-policy:script-src 'self';style-src 'self' 'unsafe-inline';object-src 'none';img-src 'self' data: blob:;child-src 'self' y

Caching headers

Cache-Control

This header is used to specify directives for caches along the request/response chain. Such cache directives are unidirectional in that the presence of a directive in a request does not imply that the same directive is to be given in the response.

no-store - indicates that a cache MUST NOT store any part of either this request or any response to it.

no-cache - indicates that a cache MUST NOT use a stored response to satisfy the request without successful validation on the origin server.

must-revalidate - once the cache expires, refuse to return stale responses to the user even if they say that stale responses are acceptable.

Both, request and response may have these flags instructing other sides on caching.

Unless specifically constrained by a cache-control (section 14.9) directive, a caching system MAY always store a successful response (see section 13.8) as a cache entry, MAY return it without validation if it is fresh, and MAY return it after successful validation. If there is neither a cache validator nor an explicit expiration time associated with a response, we do not expect it to be cached, but certain caches MAY violate this expectation (for example, when little or no network connectivity is available). A client can usually detect that such a response was taken from a cache by comparing the Date header to the current time.

https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4

https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.4

https://tools.ietf.org/html/rfc7234#page-21

https://stackoverflow.com/questions/1046966/whats-the-difference-between-cache-control-max-age-0-and-no-cache

Pragma

This is a HTTP 1.0 directive that was retained in HTTP 1.1 for backward compatibility. When specified in HTTP requests, this directive instructs proxies in the path not to cache the request.

no-cache - the same as Cache-Control no-store.

Developers often misuse it by adding it to the server response when page is served to the browser (facebook is an example). We are are going to misuse it as well since it does no harm including it.

https://tools.ietf.org/html/rfc7234#section-5.4

Expires

This is yet another HTTP 1.0 directive that was retained for backward compatibility. This directive tells the browser when a page is set to expire. Once the page expires, the browser does not display the page to the user. Instead it shows a message like “Warning: Page has expired”.

0 - a cache recipient MUST interpret invalid date formats, especially the value "0", as representing a time in the past (i.e., "already expired").

https://tools.ietf.org/html/rfc7234#section-5.3

XXS Attack Protection Headers

X-Frame-Options

This header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe> or <object> . Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

SAMEORIGIN - the page can only be displayed in a frame on the same origin as the page itself.

https://tools.ietf.org/html/rfc7034

X-XSS-Protection

This header is a feature of Internet Explorer, Chrome and Safari that stops pages from loading when they detect reflected cross-site scripting (XSS) attacks. Although these protections are largely unnecessary in modern browsers when sites implement a strong Content-Security-Policy that disables the use of inline JavaScript ('unsafe-inline'), they can still provide protections for users of older web browsers that don't yet support CSP.

:1; mode=block - enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection

X-Content-Type-Options

This header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should not be changed and be followed. This allows to opt-out of MIME type sniffing, or, in other words, it is a way to say that the webmasters knew what they were doing.

nosniff - blocks a request if the requested type is style and the MIME type is not "text/css", or script and the MIME type is not a javascript type.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options

Strict-Transport-Security

This header is an opt-in security enhancement that is specified by a web application through the use of a special response header. Once a supported browser receives this header that browser will prevent any communications from being sent over HTTP to the specified domain and will instead send all communications over HTTPS. It also prevents HTTPS click through prompts on browsers.The specification has been released and published end of 2012 as RFC 6797.

max-age=31536000; includeSubDomains - tells a browser to enable HSTS for that exact domain or subdomain, and to remember it for a given number of seconds (1 year)

https://https.cio.gov/hsts/

Content-Security-Policy

This header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks (XSS).

Directive Meaning
script-src 'self' same origin javascript files
style-src 'self' 'unsafe-inline' same origin styles or inline styles
object-src 'none' no embedded objects
img-src 'self' data: blob: same origin images or images with data and blob URIs
child-src 'self' same origin sources for browsing contexts loaded using elements such as webworker and <iframe>

Documentation

Overview

Package webapi implements web proxy handler that provides various helpers for web UI, so it's OK to put UI specific stuff here

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewTCPAddr

func NewTCPAddr(a string) net.Addr

NewTCPAddr creates an instance of ADDR

func ServeStaticFiles

func ServeStaticFiles(wh *WebHandler, path string, root http.FileSystem)

ServeStaticFiles serves static files such as js/css/images. https://github.com/julienschmidt/httprouter/issues/40 (this is as is copy of julienschmidt ServerFile method that adds security headers)

Types

type AuthContext

type AuthContext struct {
	// Context is the request context
	Context context.Context
	// User is a current user
	User storage.User
	// Checkers is access checker
	Checker teleservices.AccessChecker
	// Operator is the interface to operations service
	Operator *ops.OperatorACL
	// Applications is the interface to application management service
	Applications app.Applications
	// Packages is the interface to package management service
	Packages pack.PackageService
	// Identity is identity service
	Identity users.Identity
	// SessionContext is a current session context
	SessionContext *teleweb.SessionContext
}

type CallbackParams

type CallbackParams struct {
	// Username is the name of the authenticated user
	Username string
	// Identity is the external identity of the authenticated user
	Identity teleservices.ExternalIdentity
	// Session is the created web session
	Session teleservices.WebSession
	// Cert is the generated SSH certificate
	Cert []byte
	// TLSCert is the generated TLS certificate
	TLSCert []byte
	// HostSigners is a list of signing host public keys trusted by proxy
	HostSigners []teleservices.CertAuthority
	// Type is the original request type
	Type string
	// CreateWebSession indicates sign in via UI
	CreateWebSession bool
	// CSRFToken the original request CSRF token
	CSRFToken string
	// PublicKey is an optional public key to sign in case of successful authentication
	PublicKey []byte
	// ClientRedirectURL is where successfully authenticated client is redirected
	ClientRedirectURL string
}

CallbackParams combines necessary parameters for OAuth2 callback handler

type Config

type Config struct {
	// Identity is identity service provided by web api
	Identity users.Identity
	// PrefixURL is a prefix redirect URL for this
	PrefixURL string
	// Auth is a client to authentication service
	Auth teleauth.ClientI
	// WebAuthenticator is used to authenticate web sessions
	WebAuthenticator httplib.Authenticator
	// Operator is the interface to operations service
	Operator ops.Operator
	// Applications is the interface to application management service
	Applications app.Applications
	// Packages is the interface to package management service
	Packages pack.PackageService
	// Providers defines cloud provider-specific functionality
	Providers Providers
	// Tunnel provides access to remote server
	Tunnel reversetunnel.Server
	// Clients provides access to clients for remote clusters such as operator or apps
	Clients *clients.ClusterClients
	// Converter converts objects to UI representation
	Converter ui.Converter
	// Mode is the mode the process is running in
	Mode string
	// Backend is storage backend
	Backend storage.Backend
	// ProxyHost is the address of Teleport proxy
	ProxyHost string
	// ServiceUser specifies the service user to use to
	// create a cluster with for wizard-based installation
	ServiceUser systeminfo.User
	// InstallToken specifies the token to install cluster with.
	// The token is used to authenticate agents during the install operation
	InstallToken string
}

Config represents web handler configuration parameters

func (Config) Check

func (c Config) Check() error

Check validates the config

type ForwardRequest

type ForwardRequest struct {
	// ClusterName is the name of the cluster to forward the request to
	ClusterName string
	// ServiceName is the name of the service to forward the request to
	ServiceName string
	// ServicePort is the service port
	ServicePort int
	// ServiceNamespace is the namespace where the service resides
	ServiceNamespace string
	// URL is the request URL
	URL string
}

ForwardRequest encapsulates parameters for request forwarding

type Forwarder

type Forwarder interface {
	// ForwardToKube forwards the request to the authenticated k8s API,
	// Requires operator bound to current user to function properly
	ForwardToKube(w http.ResponseWriter, r *http.Request, siteName, URL string) error
	// ForwardToService forwards the request to a Kubernetes service
	ForwardToService(w http.ResponseWriter, r *http.Request, req ForwardRequest) error
}

Forwarder allows to forward HTTP requests from OpsCenter or gravity site to a service running inside deployed k8s cluster

func NewForwarder

func NewForwarder(cfg ForwarderConfig) (Forwarder, error)

NewForwarder creates a new forwarder

type ForwarderConfig

type ForwarderConfig struct {
	// Tunnel is the teleport reverse tunnel
	Tunnel rt.Server
	// User specifies an optional override for Common Name
	// to use when requesting certificates for kubernetes
	User string
}

ForwarderConfig is a config for a forwarder

type Handler

type Handler struct {
	httprouter.Router

	log.FieldLogger
	// contains filtered or unexported fields
}

Handler is HTTP web API handler

func NewAPI

func NewAPI(cfg Config) (*Handler, error)

NewAPI returns a new instance of web api handler

func (*Handler) CallbackHandler

func (m *Handler) CallbackHandler(w http.ResponseWriter, r *http.Request, p CallbackParams) error

CallbackHandler is the generic OAuth2 provider callback handler

func (*Handler) GetConfig

func (m *Handler) GetConfig() Config

GetConfig returns the handler config

func (*Handler) GetHandlerContext

func (m *Handler) GetHandlerContext(w http.ResponseWriter, r *http.Request) (*AuthContext, error)

GetHandlerContext authenticates the session user and returns an appropriate handler context

func (*Handler) Resources

func (m *Handler) Resources(ctx *AuthContext) (resources.Resources, error)

Resources returns resource controller

func (*Handler) SetPlugin

func (m *Handler) SetPlugin(plugin Plugin)

SetPlugin sets the handler plugin

type Plugin

type Plugin interface {
	// Resources returns resource controller
	Resources(*AuthContext) (resources.Resources, error)
	// CallbackHandler is the OAuth2 provider callback handler
	CallbackHandler(http.ResponseWriter, *http.Request, CallbackParams) error
}

Plugin allows to customize handler behavior

type PodParams

type PodParams struct {
	// Namespace is a pod namespace
	Namespace string `json:"namespace"`
	// Name is a pod name
	Name string `json:"name"`
	// Container is a container name
	Container string `json:"container"`
}

PodParams specifies parameters to connect to a Pod

type PodTerminalRequest

type PodTerminalRequest struct {
	// User is linux username to connect as
	Login string `json:"login"`
	// Term sets PTY params like width and height
	Term telesession.TerminalParams `json:"term"`
	// Pod specifies pod to connect to
	Pod PodParams `json:"pod"`
	// SessionID is a teleport session ID to join as
	SessionID telesession.ID `json:"sid"`
}

PodTerminalRequest describes a request to create a web-based terminal to a remote Pod via SSH server

type Providers

type Providers interface {
	// Validate verifies certain aspects of the specified cloud provider
	// and obtains basic metadata
	Validate(ctx context.Context, req *ValidateInput) (*ValidateOutput, error)
}

Providers defines interface to a set of supported cloud providers

func NewProviders

func NewProviders(applications app.Applications) Providers

NewProviders creates a new instance of Providers implementation

type ValidateInput

type ValidateInput struct {
	// Provider defines the specific cloud provider to work with
	Provider string `json:"provider"`
	// Variables is a provider-specific input
	Variables ValidateVariables `json:"variables"`
	// Application defines the application package being installed
	Application packageLocator `json:"application"`
}

ValidateInput defines the input to provider validation

type ValidateOutput

type ValidateOutput struct {
	// AWS defines the output of the AWS provider
	AWS *aws.ValidateOutput `json:"aws"`
}

ValidateOutput defines the output of provider validation

type ValidateVariables

type ValidateVariables struct {
	// AccessKey is AWS access key
	AccessKey string `json:"access_key"`
	// SecretKey is AWS secret key
	SecretKey string `json:"secret_key"`
	// SessionToken is an AWS session token
	SessionToken string `json:"session_token"`
}

ValidateVariables contains provider-specific variables for validation request

type WebHandler

type WebHandler struct {
	// Router is used to route web requests
	httprouter.Router

	// FieldLogger allows handler to log messages
	log.FieldLogger
	// contains filtered or unexported fields
}

WebHandler serves web UI

func NewHandler

func NewHandler(cfg WebHandlerConfig) *WebHandler

NewHandler returns a new instance of NewHandler

type WebHandlerConfig

type WebHandlerConfig struct {
	// AssetsDir is the directory containing web assets
	AssetsDir string
	// Mode is the gravity process mode
	Mode string
	// Wizard is whether this process is install wizard
	Wizard bool
	// TeleportConfig is the teleport configuration
	TeleportConfig *service.Config
	// Identity is the cluster user service
	Identity users.Identity
	// Operator is the cluster operator service
	Operator ops.Operator
	// Authenticator is used to authenticate web requests
	Authenticator httplib.Authenticator
	// Forwarder is used to forward web requests to clusters
	Forwarder Forwarder
	// Backend is the cluster backend
	Backend storage.Backend
	// Clients provides access to remote cluster client
	Clients *clients.ClusterClients
}

WebHandlerConfig defines a configuration object for the handler

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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