HTTP Service
The HTTP service is a basic servlet container, dispatching HTTP requests to the handler registered for the given path. A servlet can be a simple class or a component, registered programmatically to the HTTP service, or a service registered in the Pelix framework and automatically registered by the HTTP service.
Note
Even if it borrows the concept of servlets from Java, the Pelix HTTP service doesn’t follow the OSGi specification. The latter inherits a lot from the existing Java APIs, while this is an uncommon way to work in Python.
The basic implementation of the HTTP service is defined in pelix.http.basic.
It is based on the HTTP server available in the standard Python library
(see http.server).
Future implementations might appear in the future Pelix implementations, based
on more robust requests handlers.
Configuration properties
All implementations of the HTTP service must support the following properties:
Property |
Default |
Description |
|---|---|---|
pelix.http.address |
0.0.0.0 |
The address the HTTP server is bound to |
pelix.http.port |
8080 |
The port the HTTP server is bound to |
pelix.http.debug |
False |
If set, error pages sent to the clients contain the stack trace of the error, and the 404 page lists the registered servlet paths |
pelix.http.max_body_size |
1048576 |
Maximum size, in bytes, of the body of a request. A request with a bigger body is answered with a 413 error code. A value lesser than or equal to 0 removes the limit |
pelix.http.socket_timeout |
60 |
Timeout, in seconds, of the sockets handling the requests. A client which takes longer to send its request gets a 408 error code. A value lesser than or equal to 0 removes the timeout |
pelix.http.case_sensitive_paths |
True |
If set, servlet paths are matched case-sensitively, as URI paths are defined to be. Unset it to restore the folding of earlier releases |
pelix.http.auth.required |
False |
If set, requests must carry valid credentials (see Authentication) |
pelix.http.auth.realm |
Pelix |
Protection space given in the authentication challenges |
Added in version 3.2.2: pelix.http.max_body_size and pelix.http.socket_timeout.
Before that release, the body of a request was read without any size limit,
and a request without a Content-Length header blocked its handling
thread until the client closed the connection.
Added in version 3.2.3: pelix.http.case_sensitive_paths.
Note
pelix.http.socket_timeout is only applied by the synchronous HTTP
service.
The asynchronous service accepts the property, as it is common to all the
implementations, but leaves the timeouts of the connections to aiohttp.
Request paths
Before a servlet is looked for, the path of a request is normalized: its query
string is removed, it is percent-decoded, its repeated slashes are collapsed
and its . and .. segments are resolved.
A request whose path holds a control character, or resolves above the root, is
answered with a 400 error code and never reaches a servlet.
The same normalized path is used to find the servlet and to compute what
get_path() and
get_sub_path() return, so the
router and the servlet can never disagree about what was requested.
Servlet paths are matched case-sensitively: /admin and /Admin are
two different resources, as RFC 3986 defines them to be.
Changed in version 3.2.3: Paths used to be matched after being lowered, and were neither decoded nor resolved. A servlet was given the original path while the server routed on the folded one, so a check made on the path a servlet received could be evaded by changing its case.
Warning
A decoded path segment never holds a separator, but it can hold anything else the client encoded.
A servlet mapping a segment onto a file system, a database key or another name space still has to validate it. The server normalizes the structure of the path; it cannot know what a segment means to the servlet.
Warning
pelix.http.debug must be kept unset in production.
A stack trace describes the server: the paths of its files, the packages it uses and the data it was handling. By default, the error page only gives an error ID, which allows to find the details of the error in the logs of the server.
The same goes for the paths of the registered servlets: by default, the 404 page doesn’t list them, as they would tell any client what the server exposes.
Instantiation
The HTTP bundle defines a component factory which name is
implementation-dependent.
The HTTP service factory provided by Pelix/iPOPO is
pelix.http.service.basic.factory.
Here is a snippet that starts a HTTP server component, named http-server,
which only accepts local clients on port 9000:
from pelix.framework import FrameworkFactory
from pelix.ipopo.constants import use_ipopo
# Start the framework
framework = FrameworkFactory.get_framework()
framework.start()
context = framework.get_bundle_context()
# Install & start iPOPO
context.install_bundle('pelix.ipopo.core').start()
# Install & start the basic HTTP service
context.install_bundle('pelix.http.basic').start()
# Instantiate a HTTP service component
with use_ipopo(context) as ipopo:
ipopo.instantiate(
'pelix.http.service.basic.factory', 'http-server',
{'pelix.http.address': 'localhost',
'pelix.http.port': 9000})
This code starts an HTTP server which will be listening on port 9000 and the HTTP service will be ready to handle requests. As no servlet service has been registered, the server will only return 404 errors.
Cross-Origin Resource Sharing (CORS)
A browser only lets a script read the response to a request sent to another
origin (scheme, host and port) if the server allows it, with the
Access-Control-* headers defined by the
CORS protocol.
By default, the HTTP services don’t send any of those headers: a script loaded from another origin can’t read their responses. Both the basic and the asynchronous HTTP services apply a CORS policy when one is given, either for the whole server or per servlet:
for the whole server, with a
CorsHandlerservice. Thepelix.http.corsbundle provides thepelix.http.cors.factorycomponent factory (FACTORY_HTTP_CORS), configured with the properties below. The HTTP services bind the best ranked CORS handler service, if any;per servlet, with the same properties set on the servlet service, or in the parameters of
register_servlet(). A servlet declares its own policy by settingpelix.http.cors.origins: its policy then replaces the one of the CORS handler service for the requests it handles.
Property |
Default |
Description |
|---|---|---|
pelix.http.cors.origins |
(none) |
Origins allowed to read the responses.
|
pelix.http.cors.methods |
(all) |
Methods allowed in cross-origin requests. If not set, the method announced by a preflight is allowed |
pelix.http.cors.headers |
(all) |
Request headers allowed in cross-origin requests. If not set, the headers announced by a preflight are allowed |
pelix.http.cors.expose_headers |
(none) |
Response headers a script can read, in addition to the CORS-safelisted ones |
pelix.http.cors.credentials |
False |
If set, requests can carry credentials
(cookies, |
pelix.http.cors.max_age |
(none) |
Time, in seconds, a browser can cache the result of a preflight |
List properties accept a list of strings or a comma-separated string.
The HTTP services then behave as follows, for requests carrying an Origin
header on a path covered by a policy:
a preflight request (an
OPTIONSrequest with anAccess-Control-Request-Methodheader) is answered by the HTTP service itself, even if no servlet is registered on its path:204with theAccess-Control-Allow-*headers if the policy accepts it, else403. Thedo_OPTIONSmethod of the servlet is not called;the response to any other request gets the
Access-Control-Allow-Originheader (and the other ones of the policy) if the policy accepts its origin, including the error pages (400, 404, 413, 500, …) and the WebSocket handshakes. A header the servlet set itself is kept as is.
A refused origin doesn’t prevent the request from being handled: CORS is enforced by the browser, which won’t let the script read the response. It doesn’t protect the server against a client which ignores it.
When credentials are allowed, the origin of the request is always sent back
instead of *, as browsers refuse credentials with a wildcard. A
Vary: Origin header is then added so that caches don’t mix the responses
sent to different origins.
Warning
Allowing credentials lets the allowed origins send requests on behalf of the users of the server, with their cookies. Only allow the origins you trust.
For example, to allow a web application served from another host to call the servlets of an HTTP service:
context.install_bundle("pelix.http.cors").start()
with use_ipopo(context) as ipopo:
ipopo.instantiate(
"pelix.http.cors.factory",
"cors-policy",
{
"pelix.http.cors.origins": ["https://app.example.com"],
"pelix.http.cors.headers": ["Content-Type", "Authorization"],
"pelix.http.cors.credentials": True,
"pelix.http.cors.max_age": 600,
},
)
A CorsHandler service can also be written to give a different policy
to different paths, as each of its methods is given the path of the request:
- class pelix.http.CorsHandler(*args, **kwargs)
Gives the Cross-Origin Resource Sharing (CORS) policy of the HTTP services.
Each method is given the normalized path of the request, so that a single handler can give a different policy to different parts of the server.
- allows_credentials(path: str) bool
Checks if cross-origin requests on the given path can carry credentials
- Parameters:
path – Request path
- Returns:
True to allow credentials
- get_allowed_headers(path: str) Iterable[str] | None
Returns the request headers allowed in cross-origin requests on the given path
- Parameters:
path – Request path
- Returns:
The allowed headers, or None to allow those of the request
- get_allowed_methods(path: str) Iterable[str] | None
Returns the methods allowed in cross-origin requests on the given path
- Parameters:
path – Request path
- Returns:
The allowed methods, or None to allow the one of the request
- get_allowed_origins(path: str) Iterable[str]
Returns the origins allowed to read the responses to requests on the given path
- Parameters:
path – Request path
- Returns:
The allowed origins;
*allows any origin
- get_exposed_headers(path: str) Iterable[str] | None
Returns the response headers a client script is allowed to read
- Parameters:
path – Request path
- Returns:
The exposed headers, or None
- get_max_age(path: str) int | None
Returns the time, in seconds, a client can cache the result of a preflight request on the given path
- Parameters:
path – Request path
- Returns:
A time in seconds, or None to let the client decide
Added in version 3.2.3.
Authentication
Both the basic and the asynchronous HTTP services authenticate the requests with the security layer. The work is split in two:
an
HttpAuthenticatorservice extracts the credentials from the request, for an authentication scheme. Thepelix.http.authbundle provides thepelix.http.auth.basic.factorycomponent factory (FACTORY_HTTP_AUTH_BASIC), for the HTTP Basic scheme;the
pelix.securityservices check them and resolve the groups and roles of the user, e.g. with an.htpasswdfile. Thepelix.security.corebundle must be started.
When the HTTP service has no authenticator bound and no requirement set, nothing changes: requests are handled as anonymous.
Otherwise, for each request:
credentials presented by the client are always checked, even if the resource doesn’t require them. Wrong or malformed credentials are refused with a
401error;if the resource requires authentication (
pelix.http.auth.required, set on the HTTP service or on the servlet), a request without credentials is refused with a401error, carrying the challenges of the authenticators in itsWWW-Authenticateheader. When the HTTP service requires it, unknown paths get the same answer rather than a404, so that an unauthenticated client can’t tell which paths exist;the servlet is called as the authenticated subject (or as the anonymous one): it gets it with
pelix.security.get_current_subject(), and thepelix.security.decoratorscan be applied to its methods. AnAuthenticationRequirederror raised by the servlet becomes a401with the challenges, so that the client can retry with credentials, and anAccessDeniederror becomes a403.
A servlet can override the requirement of the HTTP service in both directions, e.g. to publish a health check on a protected server, or to protect a single servlet on a public one. If authentication is required but no authenticator is bound, all the requests are refused: a resource doesn’t become public because its authenticator is gone.
CORS preflight requests are answered before the authentication, as browsers never send credentials in them (see Cross-Origin Resource Sharing (CORS)).
Warning
The Basic scheme sends the password in clear text, only encoded: only use it over HTTPS. The HTTP service logs a warning when it receives credentials over plain HTTP.
For example, to protect all the servlets of an HTTP service with the users of an
.htpasswd file, except those of a public servlet:
for name in ("pelix.security.core", "pelix.security.htpasswd", "pelix.http.auth"):
context.install_bundle(name).start()
with use_ipopo(context) as ipopo:
ipopo.instantiate(
"pelix.security.htpasswd.factory",
"users",
{"pelix.security.htpasswd.file": "/etc/my-app/.htpasswd"},
)
ipopo.instantiate("pelix.http.auth.basic.factory", "http-basic-auth", {})
ipopo.instantiate(
"pelix.http.service.basic.factory",
"http-server",
{
"pelix.http.port": 8443,
"pelix.https.cert_file": "/etc/my-app/server.crt",
"pelix.https.key_file": "/etc/my-app/server.key",
"pelix.http.auth.required": True,
},
)
# A servlet which stays public
context.register_service(
"pelix.http.servlet",
HealthServlet(),
{"pelix.http.path": "/health", "pelix.http.auth.required": False},
)
Another authentication scheme can be supported by providing an
HttpAuthenticator service, which turns the headers of a request into
pelix.security.Credentials handled by an
pelix.security.Authenticator service:
- class pelix.http.HttpAuthenticator(*args, **kwargs)
Extracts credentials from HTTP requests, for an authentication scheme.
The credentials are then checked by the
pelix.securityservices: an HTTP authenticator doesn’t decide whether they are valid.- extract_credentials(headers: HeadersView) Credentials | None
Extracts the credentials carried by a request, if it uses the scheme of this authenticator
- Parameters:
headers – The headers of the request
- Returns:
The credentials, or None if the request doesn’t carry credentials of this scheme
- Raises:
pelix.security.AuthenticationFailed – Malformed credentials
- get_challenge(realm: str) str
Returns the challenge sent in the
WWW-Authenticateheader of a 401 response, telling the client how to authenticate- Parameters:
realm – The protection space of the requested resource
- Returns:
The challenge, e.g.
Basic realm="Pelix", charset="UTF-8"
- get_scheme() str
Returns the name of the authentication scheme, e.g.
Basic- Returns:
The authentication scheme
Added in version 3.2.3.
API
HTTP service
The HTTP service provides the following interface:
- class pelix.http.HTTPService(*args, **kwargs)
HTTP service interface
- get_access() tuple[str, int]
Retrieves the (address, port) tuple to access the server
- get_hostname() str
Retrieves the server host name
- Returns:
The server host name
- get_registered_paths() list[str]
Returns the paths registered by servlets
- Returns:
The paths registered by servlets (sorted list)
- get_servlet(path: str | None) tuple[Servlet, dict[str, Any], str, ServletType] | None
Retrieves the servlet matching the given path and its parameters. Returns None if no servlet matches the given path.
- Parameters:
path – A request URI
- Returns:
A tuple (servlet, parameters, prefix, type) or None
- is_https() bool
Returns True if this is an HTTPS server
- Returns:
True if this server uses SSL
- register_servlet(path: str, servlet: Servlet, parameters: dict[str, Any] | None = None, servlet_type: ServletType = ServletType.SYNC) bool
Registers a servlet
- Parameters:
path – Path handled by this servlet
servlet – The servlet instance
parameters – The parameters associated to this path
servlet_type – The type of servlet (sync, async, websocket, …)
- Returns:
True if the servlet has been registered, False if it refused the binding.
- Raises:
ValueError – Invalid path or handler
The service also provides two utility methods to ease the display of error pages:
- class pelix.http.HTTPService(*args, **kwargs)
HTTP service interface
- make_exception_page(path: str, stack: str) str
Prepares a page printing an exception stack trace in a 500 error
- Parameters:
path – Request path
stack – Exception stack trace
- Returns:
A HTML page
- make_not_found_page(path: str) str
Prepares a “page not found” page for a 404 error
- Parameters:
path – Request path
- Returns:
A HTML page
Servlet service
To use the whiteboard pattern, a servlet can be registered as a service
providing the pelix.http.servlet specification.
It must also have a valid pelix.http.path property, or it will be ignored.
The binding methods described below have a parameters argument, which
represents a set of properties of the server, given as a dictionary.
Some parameters can also be given when using the
register_servlet() method, with the parameters argument.
In any case, the following entries must be set by all implementations of the HTTP service and can’t be overridden when register a servlet. Note that their content and liability is implementation-dependent:
http.address: the binding address (str) of the HTTP server;http.port: the real listening port (int) of the HTTP server;http.https: a boolean flag indicating if the server is listening to HTTP (False) or HTTPS (True) requests;http.name: the name (str) of the server. If the server is an iPOPO component, it should be the instance name;http.extra: an implementation dependent set of properties.http.async: a boolean flag indicating if the servlet is asynchronous (True) or synchronous (False). In the case of the basic HTTP service, this is always False, as it only supports synchronous servlets.
A servlet can, on the other hand, configure the way the HTTP service handles the requests it will be given, with the following entries:
pelix.http.max_body_size: the maximum size, in bytes, of the body of a request handled by this servlet. It overrides the property of the same name of the HTTP service, in both directions: a servlet can accept bodies bigger than the other ones, which is useful to carry RPC payloads, or restrict itself to smaller ones. A value lesser than or equal to 0 removes the limit.pelix.http.cors.originsand the otherpelix.http.cors.*entries: the CORS policy of the servlet, which replaces the one of the CORS handler service (see Cross-Origin Resource Sharing (CORS)).pelix.http.auth.requiredandpelix.http.auth.realm: whether the requests handled by the servlet must be authenticated, in both directions, and the realm of their challenges (see Authentication).
They can be given either as properties of the servlet service, next to
pelix.http.path, or in the parameters argument of
register_servlet().
Added in version 3.2.2: The pelix.http.max_body_size entry.
Added in version 3.2.3: The pelix.http.cors.* and pelix.http.auth.* entries.
A servlet for the Pelix HTTP service has the following methods:
- class pelix.http.Servlet
These are the methods that the HTTP service can call in a servlet. Note that it is not necessary to implement them all: the service has a default behaviour for missing methods.
- accept_binding(path: str, parameters: Dict[str, Any]) bool | None
This method is called before trying to bind the servlet. If it returns False, the servlet won’t be bound to the server. This allows a servlet service to be bound to a specific server.
If this method doesn’t exist or returns None or anything else but False, the calling HTTP service will consider that the servlet accepts to be bound to it.
- Parameters:
path (str) – The path of the servlet in the server
parameters (dict) – The parameters of the server
- bound_to(path: str, parameters: Dict[str, Any]) bool | None
This method is called when the servlet is bound to a path. If it returns False or raises an Exception, the registration is aborted.
- Parameters:
path (str) – The path of the servlet in the server
parameters (dict) – The parameters of the server
- unbound_from(path: str, parameters: Dict[str, Any]) None
This method is called when the servlet is bound to a path. The parameters are the ones given in
accept_binding()andbound_to().- Parameters:
path (str) – The path of the servlet in the server
parameters (dict) – The parameters of the server
- do_XXX(request: AbstractHTTPServletRequest, response: AbstractHTTPServletResponse) None
Each request is handled by the method call
do_XXXwhereXXXis the name of an HTTP method (do_GET,do_POST,do_PUT,do_HEAD, …).If it raises an exception, the server automatically sends an HTTP 500 error page. In nominal behaviour, the method must use the
responseargument to send a reply to the client.- Parameters:
request – A
AbstractHTTPServletRequestrepresentation of the requestresponse – The
AbstractHTTPServletResponseobject to use to reply to the client
HTTP request
Each request method has a request helper argument, which implements the
AbstractHTTPServletRequest abstract class.
- class pelix.http.AbstractHTTPServletRequest
Abstract HTTP Servlet request helper
- abstractmethod get_client_address() tuple[str, int]
Returns the address of the client
- Returns:
A (host, port) tuple
- abstractmethod get_command() str
Returns the HTTP verb (GET, POST, …) used for the request
- abstractmethod get_header(name: str, default: Any = None) Any
Returns the value of a header
- Parameters:
name – Header name
default – Default value if the header doesn’t exist
- Returns:
The header value or the default one
- abstractmethod get_headers() dict[str, Any]
Returns a copy all headers, with a dictionary interface
- Returns:
A dictionary-like object
- abstractmethod get_path() str
Returns the request full path, normalized.
The path is percent-decoded, its query string is removed, its repeated slashes are collapsed and its
.and..segments are resolved. A segment therefore never holds a separator. Everything else the client encoded reaches the servlet unchanged, so a servlet mapping a segment onto a file system or another name space still has to validate it.- Returns:
A request full path (string)
- abstractmethod get_prefix_path() str
Returns the path to the servlet root, as the servlet was registered.
Servlet paths are matched case-sensitively unless
HTTP_CASE_SENSITIVE_PATHSsays otherwise.- Returns:
A request path (string)
- abstractmethod get_rfile() IO[bytes]
Returns the request input as a file stream.
The stream gives the raw body of the request: it is not limited by
pelix.http.max_body_size, unlikeread_data(). A servlet reading it is responsible for limiting the number of bytes it accepts.- Returns:
A file-like input stream
- abstractmethod get_sub_path() str
Returns the servlet-relative path, i.e. after the prefix.
It is cut out of the path
get_path()returns, so it carries the same guarantees.- Returns:
A request path (string)
- read_data() bytes
Reads the body of the request, within the limit given by the
pelix.http.max_body_sizeproperty.A request which doesn’t declare a valid
Content-Lengthheader is considered as having an empty body: reading until the end of the stream would block the thread handling the request until the client decides to close the connection.- Returns:
The read data
- Raises:
BodyTooLargeError – The declared body is bigger than the accepted maximum size
HTTP response
Each request method also has a response helper argument, which implements the
AbstractHTTPServletResponse abstract class.
- class pelix.http.AbstractHTTPServletResponse
HTTP Servlet response helper
- abstractmethod end_headers() None
Ends the headers part
- abstractmethod get_wfile() IO[bytes]
Retrieves the output as a file stream.
end_headers()should have been called before, except if you want to write your own headers.- Returns:
A file-like output stream
- abstractmethod is_header_set(name: str) bool
Checks if the given header has already been set
- Parameters:
name – Header name
- Returns:
True if it has already been set
- send_content(http_code: int, content: str, mime_type: str | None = 'text/html', http_message: str | None = None, content_length: int = -1) None
Utility method to send the given content as an answer. You can still use get_wfile or write afterwards, if you forced the content length.
If content_length is negative (default), it will be computed as the length of the content; if it is positive, the given value will be used; if it is None, the content-length header won’t be sent.
- Parameters:
http_code – HTTP result code
content – Data to be sent (must be a string)
mime_type – Content MIME type (content-type)
http_message – HTTP code description
content_length – Forced content length
- abstractmethod set_header(name: str, value: Any) None
Sets the value of a header. This method should not be called after
end_headers().- Parameters:
name – Header name
value – Header value
- abstractmethod set_response(code: int, message: str | None = None) None
Sets the response line. This method should be the first called when sending an answer.
- Parameters:
code – HTTP result code
message – Associated message
- abstractmethod write(data: bytes) None
Writes the given data.
end_headers()should have been called before, except if you want to write your own headers.- Parameters:
data – Data to be written
Write a servlet
This snippet shows how to write a component providing the servlet service:
from pelix.ipopo.decorators import ComponentFactory, Property, Provides, \
Requires, Validate, Invalidate, Unbind, Bind, Instantiate
@ComponentFactory(name='simple-servlet-factory')
@Instantiate('simple-servlet')
@Provides(specifications='pelix.http.servlet')
@Property('_path', 'pelix.http.path', "/servlet")
class SimpleServletFactory:
"""
Simple servlet factory
"""
def __init__(self):
self._path = None
def bound_to(self, path, params):
"""
Servlet bound to a path
"""
print('Bound to ' + path)
return True
def unbound_from(self, path, params):
"""
Servlet unbound from a path
"""
print('Unbound from ' + path)
return None
def do_GET(self, request, response):
"""
Handle a GET
"""
content = """<html>
<head>
<title>Test SimpleServlet</title>
</head>
<body>
<ul>
<li>Client address: {clt_addr[0]}</li>
<li>Client port: {clt_addr[1]}</li>
<li>Host: {host}</li>
<li>Keys: {keys}</li>
</ul>
</body>
</html>""".format(clt_addr=request.get_client_address(),
host=request.get_header('host', 0),
keys=request.get_headers().keys())
response.send_content(200, content)
To test this snippet, install and start this bundle and the HTTP service bundle in a framework, then open a browser to the servlet URL. If you used the HTTP service instantiation sample, this URL should be http://localhost:9000/servlet.