improve webserver, add domain redirects (aliases), add tests and admin page ui to manage the config
- make builtin http handlers serve on specific domains, such as for mta-sts, so
e.g. /.well-known/mta-sts.txt isn't served on all domains.
- add logging of a few more fields in access logging.
- small tweaks/bug fixes in webserver request handling.
- add config option for redirecting entire domains to another (common enough).
- split httpserver metric into two: one for duration until writing header (i.e.
performance of server), another for duration until full response is sent to
client (i.e. performance as perceived by users).
- add admin ui, a new page for managing the configs. after making changes
and hitting "save", the changes take effect immediately. the page itself
doesn't look very well-designed (many input fields, makes it look messy). i
have an idea to improve it (explained in admin.html as todo) by making the
layout look just like the config file. not urgent though.
i've already changed my websites/webapps over.
the idea of adding a webserver is to take away a (the) reason for folks to want
to complicate their mox setup by running an other webserver on the same machine.
i think the current webserver implementation can already serve most common use
cases. with a few more tweaks (feedback needed!) we should be able to get to 95%
of the use cases. the reverse proxy can take care of the remaining 5%.
nevertheless, a next step is still to change the quickstart to make it easier
for folks to run with an existing webserver, with existing tls certs/keys.
that's how this relates to issue #5.
2023-03-02 20:15:54 +03:00
package http
import (
"bytes"
2023-05-30 23:11:31 +03:00
"fmt"
"io"
"net"
improve webserver, add domain redirects (aliases), add tests and admin page ui to manage the config
- make builtin http handlers serve on specific domains, such as for mta-sts, so
e.g. /.well-known/mta-sts.txt isn't served on all domains.
- add logging of a few more fields in access logging.
- small tweaks/bug fixes in webserver request handling.
- add config option for redirecting entire domains to another (common enough).
- split httpserver metric into two: one for duration until writing header (i.e.
performance of server), another for duration until full response is sent to
client (i.e. performance as perceived by users).
- add admin ui, a new page for managing the configs. after making changes
and hitting "save", the changes take effect immediately. the page itself
doesn't look very well-designed (many input fields, makes it look messy). i
have an idea to improve it (explained in admin.html as todo) by making the
layout look just like the config file. not urgent though.
i've already changed my websites/webapps over.
the idea of adding a webserver is to take away a (the) reason for folks to want
to complicate their mox setup by running an other webserver on the same machine.
i think the current webserver implementation can already serve most common use
cases. with a few more tweaks (feedback needed!) we should be able to get to 95%
of the use cases. the reverse proxy can take care of the remaining 5%.
nevertheless, a next step is still to change the quickstart to make it easier
for folks to run with an existing webserver, with existing tls certs/keys.
that's how this relates to issue #5.
2023-03-02 20:15:54 +03:00
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
2023-05-30 23:11:31 +03:00
"golang.org/x/net/websocket"
improve webserver, add domain redirects (aliases), add tests and admin page ui to manage the config
- make builtin http handlers serve on specific domains, such as for mta-sts, so
e.g. /.well-known/mta-sts.txt isn't served on all domains.
- add logging of a few more fields in access logging.
- small tweaks/bug fixes in webserver request handling.
- add config option for redirecting entire domains to another (common enough).
- split httpserver metric into two: one for duration until writing header (i.e.
performance of server), another for duration until full response is sent to
client (i.e. performance as perceived by users).
- add admin ui, a new page for managing the configs. after making changes
and hitting "save", the changes take effect immediately. the page itself
doesn't look very well-designed (many input fields, makes it look messy). i
have an idea to improve it (explained in admin.html as todo) by making the
layout look just like the config file. not urgent though.
i've already changed my websites/webapps over.
the idea of adding a webserver is to take away a (the) reason for folks to want
to complicate their mox setup by running an other webserver on the same machine.
i think the current webserver implementation can already serve most common use
cases. with a few more tweaks (feedback needed!) we should be able to get to 95%
of the use cases. the reverse proxy can take care of the remaining 5%.
nevertheless, a next step is still to change the quickstart to make it easier
for folks to run with an existing webserver, with existing tls certs/keys.
that's how this relates to issue #5.
2023-03-02 20:15:54 +03:00
"github.com/mjl-/mox/mox-"
)
add webmail
it was far down on the roadmap, but implemented earlier, because it's
interesting, and to help prepare for a jmap implementation. for jmap we need to
implement more client-like functionality than with just imap. internal data
structures need to change. jmap has lots of other requirements, so it's already
a big project. by implementing a webmail now, some of the required data
structure changes become clear and can be made now, so the later jmap
implementation can do things similarly to the webmail code. the webmail
frontend and webmail are written together, making their interface/api much
smaller and simpler than jmap.
one of the internal changes is that we now keep track of per-mailbox
total/unread/unseen/deleted message counts and mailbox sizes. keeping this
data consistent after any change to the stored messages (through the code base)
is tricky, so mox now has a consistency check that verifies the counts are
correct, which runs only during tests, each time an internal account reference
is closed. we have a few more internal "changes" that are propagated for the
webmail frontend (that imap doesn't have a way to propagate on a connection),
like changes to the special-use flags on mailboxes, and used keywords in a
mailbox. more changes that will be required have revealed themselves while
implementing the webmail, and will be implemented next.
the webmail user interface is modeled after the mail clients i use or have
used: thunderbird, macos mail, mutt; and webmails i normally only use for
testing: gmail, proton, yahoo, outlook. a somewhat technical user is assumed,
but still the goal is to make this webmail client easy to use for everyone. the
user interface looks like most other mail clients: a list of mailboxes, a
search bar, a message list view, and message details. there is a top/bottom and
a left/right layout for the list/message view, default is automatic based on
screen size. the panes can be resized by the user. buttons for actions are just
text, not icons. clicking a button briefly shows the shortcut for the action in
the bottom right, helping with learning to operate quickly. any text that is
underdotted has a title attribute that causes more information to be displayed,
e.g. what a button does or a field is about. to highlight potential phishing
attempts, any text (anywhere in the webclient) that switches unicode "blocks"
(a rough approximation to (language) scripts) within a word is underlined
orange. multiple messages can be selected with familiar ui interaction:
clicking while holding control and/or shift keys. keyboard navigation works
with arrows/page up/down and home/end keys, and also with a few basic vi-like
keys for list/message navigation. we prefer showing the text instead of
html (with inlined images only) version of a message. html messages are shown
in an iframe served from an endpoint with CSP headers to prevent dangerous
resources (scripts, external images) from being loaded. the html is also
sanitized, with javascript removed. a user can choose to load external
resources (e.g. images for tracking purposes).
the frontend is just (strict) typescript, no external frameworks. all
incoming/outgoing data is typechecked, both the api request parameters and
response types, and the data coming in over SSE. the types and checking code
are generated with sherpats, which uses the api definitions generated by
sherpadoc based on the Go code. so types from the backend are automatically
propagated to the frontend. since there is no framework to automatically
propagate properties and rerender components, changes coming in over the SSE
connection are propagated explicitly with regular function calls. the ui is
separated into "views", each with a "root" dom element that is added to the
visible document. these views have additional functions for getting changes
propagated, often resulting in the view updating its (internal) ui state (dom).
we keep the frontend compilation simple, it's just a few typescript files that
get compiled (combined and types stripped) into a single js file, no additional
runtime code needed or complicated build processes used. the webmail is served
is served from a compressed, cachable html file that includes style and the
javascript, currently just over 225kb uncompressed, under 60kb compressed (not
minified, including comments). we include the generated js files in the
repository, to keep Go's easily buildable self-contained binaries.
authentication is basic http, as with the account and admin pages. most data
comes in over one long-term SSE connection to the backend. api requests signal
which mailbox/search/messages are requested over the SSE connection. fetching
individual messages, and making changes, are done through api calls. the
operations are similar to imap, so some code has been moved from package
imapserver to package store. the future jmap implementation will benefit from
these changes too. more functionality will probably be moved to the store
package in the future.
the quickstart enables webmail on the internal listener by default (for new
installs). users can enable it on the public listener if they want to. mox
localserve enables it too. to enable webmail on existing installs, add settings
like the following to the listeners in mox.conf, similar to AccountHTTP(S):
WebmailHTTP:
Enabled: true
WebmailHTTPS:
Enabled: true
special thanks to liesbeth, gerben, andrii for early user feedback.
there is plenty still to do, see the list at the top of webmail/webmail.ts.
feedback welcome as always.
2023-08-07 22:57:03 +03:00
func tcheck ( t * testing . T , err error , msg string ) {
t . Helper ( )
if err != nil {
t . Fatalf ( "%s: %s" , msg , err )
}
}
improve webserver, add domain redirects (aliases), add tests and admin page ui to manage the config
- make builtin http handlers serve on specific domains, such as for mta-sts, so
e.g. /.well-known/mta-sts.txt isn't served on all domains.
- add logging of a few more fields in access logging.
- small tweaks/bug fixes in webserver request handling.
- add config option for redirecting entire domains to another (common enough).
- split httpserver metric into two: one for duration until writing header (i.e.
performance of server), another for duration until full response is sent to
client (i.e. performance as perceived by users).
- add admin ui, a new page for managing the configs. after making changes
and hitting "save", the changes take effect immediately. the page itself
doesn't look very well-designed (many input fields, makes it look messy). i
have an idea to improve it (explained in admin.html as todo) by making the
layout look just like the config file. not urgent though.
i've already changed my websites/webapps over.
the idea of adding a webserver is to take away a (the) reason for folks to want
to complicate their mox setup by running an other webserver on the same machine.
i think the current webserver implementation can already serve most common use
cases. with a few more tweaks (feedback needed!) we should be able to get to 95%
of the use cases. the reverse proxy can take care of the remaining 5%.
nevertheless, a next step is still to change the quickstart to make it easier
for folks to run with an existing webserver, with existing tls certs/keys.
that's how this relates to issue #5.
2023-03-02 20:15:54 +03:00
func TestWebserver ( t * testing . T ) {
os . RemoveAll ( "../testdata/webserver/data" )
make mox compile on windows, without "mox serve" but with working "mox localserve"
getting mox to compile required changing code in only a few places where
package "syscall" was used: for accessing file access times and for umask
handling. an open problem is how to start a process as an unprivileged user on
windows. that's why "mox serve" isn't implemented yet. and just finding a way
to implement it now may not be good enough in the near future: we may want to
starting using a more complete privilege separation approach, with a process
handling sensitive tasks (handling private keys, authentication), where we may
want to pass file descriptors between processes. how would that work on
windows?
anyway, getting mox to compile for windows doesn't mean it works properly on
windows. the largest issue: mox would normally open a file, rename or remove
it, and finally close it. this happens during message delivery. that doesn't
work on windows, the rename/remove would fail because the file is still open.
so this commit swaps many "remove" and "close" calls. renames are a longer
story: message delivery had two ways to deliver: with "consuming" the
(temporary) message file (which would rename it to its final destination), and
without consuming (by hardlinking the file, falling back to copying). the last
delivery to a recipient of a message (and the only one in the common case of a
single recipient) would consume the message, and the earlier recipients would
not. during delivery, the already open message file was used, to parse the
message. we still want to use that open message file, and the caller now stays
responsible for closing it, but we no longer try to rename (consume) the file.
we always hardlink (or copy) during delivery (this works on windows), and the
caller is responsible for closing and removing (in that order) the original
temporary file. this does cost one syscall more. but it makes the delivery code
(responsibilities) a bit simpler.
there is one more obvious issue: the file system path separator. mox already
used the "filepath" package to join paths in many places, but not everywhere.
and it still used strings with slashes for local file access. with this commit,
the code now uses filepath.FromSlash for path strings with slashes, uses
"filepath" in a few more places where it previously didn't. also switches from
"filepath" to regular "path" package when handling mailbox names in a few
places, because those always use forward slashes, regardless of local file
system conventions. windows can handle forward slashes when opening files, so
test code that passes path strings with forward slashes straight to go stdlib
file i/o functions are left unchanged to reduce code churn. the regular
non-test code, or test code that uses path strings in places other than
standard i/o functions, does have the paths converted for consistent paths
(otherwise we would end up with paths with mixed forward/backward slashes in
log messages).
windows cannot dup a listening socket. for "mox localserve", it isn't
important, and we can work around the issue. the current approach for "mox
serve" (forking a process and passing file descriptors of listening sockets on
"privileged" ports) won't work on windows. perhaps it isn't needed on windows,
and any user can listen on "privileged" ports? that would be welcome.
on windows, os.Open cannot open a directory, so we cannot call Sync on it after
message delivery. a cursory internet search indicates that directories cannot
be synced on windows. the story is probably much more nuanced than that, with
long deep technical details/discussions/disagreement/confusion, like on unix.
for "mox localserve" we can get away with making syncdir a no-op.
2023-10-14 11:54:07 +03:00
mox . ConfigStaticPath = filepath . FromSlash ( "../testdata/webserver/mox.conf" )
improve webserver, add domain redirects (aliases), add tests and admin page ui to manage the config
- make builtin http handlers serve on specific domains, such as for mta-sts, so
e.g. /.well-known/mta-sts.txt isn't served on all domains.
- add logging of a few more fields in access logging.
- small tweaks/bug fixes in webserver request handling.
- add config option for redirecting entire domains to another (common enough).
- split httpserver metric into two: one for duration until writing header (i.e.
performance of server), another for duration until full response is sent to
client (i.e. performance as perceived by users).
- add admin ui, a new page for managing the configs. after making changes
and hitting "save", the changes take effect immediately. the page itself
doesn't look very well-designed (many input fields, makes it look messy). i
have an idea to improve it (explained in admin.html as todo) by making the
layout look just like the config file. not urgent though.
i've already changed my websites/webapps over.
the idea of adding a webserver is to take away a (the) reason for folks to want
to complicate their mox setup by running an other webserver on the same machine.
i think the current webserver implementation can already serve most common use
cases. with a few more tweaks (feedback needed!) we should be able to get to 95%
of the use cases. the reverse proxy can take care of the remaining 5%.
nevertheless, a next step is still to change the quickstart to make it easier
for folks to run with an existing webserver, with existing tls certs/keys.
that's how this relates to issue #5.
2023-03-02 20:15:54 +03:00
mox . ConfigDynamicPath = filepath . Join ( filepath . Dir ( mox . ConfigStaticPath ) , "domains.conf" )
2023-06-16 14:27:27 +03:00
mox . MustLoadConfig ( true , false )
improve webserver, add domain redirects (aliases), add tests and admin page ui to manage the config
- make builtin http handlers serve on specific domains, such as for mta-sts, so
e.g. /.well-known/mta-sts.txt isn't served on all domains.
- add logging of a few more fields in access logging.
- small tweaks/bug fixes in webserver request handling.
- add config option for redirecting entire domains to another (common enough).
- split httpserver metric into two: one for duration until writing header (i.e.
performance of server), another for duration until full response is sent to
client (i.e. performance as perceived by users).
- add admin ui, a new page for managing the configs. after making changes
and hitting "save", the changes take effect immediately. the page itself
doesn't look very well-designed (many input fields, makes it look messy). i
have an idea to improve it (explained in admin.html as todo) by making the
layout look just like the config file. not urgent though.
i've already changed my websites/webapps over.
the idea of adding a webserver is to take away a (the) reason for folks to want
to complicate their mox setup by running an other webserver on the same machine.
i think the current webserver implementation can already serve most common use
cases. with a few more tweaks (feedback needed!) we should be able to get to 95%
of the use cases. the reverse proxy can take care of the remaining 5%.
nevertheless, a next step is still to change the quickstart to make it easier
for folks to run with an existing webserver, with existing tls certs/keys.
that's how this relates to issue #5.
2023-03-02 20:15:54 +03:00
2023-08-21 22:52:35 +03:00
loadStaticGzipCache ( mox . DataDirPath ( "tmp/httpstaticcompresscache" ) , 1024 * 1024 )
improve webserver, add domain redirects (aliases), add tests and admin page ui to manage the config
- make builtin http handlers serve on specific domains, such as for mta-sts, so
e.g. /.well-known/mta-sts.txt isn't served on all domains.
- add logging of a few more fields in access logging.
- small tweaks/bug fixes in webserver request handling.
- add config option for redirecting entire domains to another (common enough).
- split httpserver metric into two: one for duration until writing header (i.e.
performance of server), another for duration until full response is sent to
client (i.e. performance as perceived by users).
- add admin ui, a new page for managing the configs. after making changes
and hitting "save", the changes take effect immediately. the page itself
doesn't look very well-designed (many input fields, makes it look messy). i
have an idea to improve it (explained in admin.html as todo) by making the
layout look just like the config file. not urgent though.
i've already changed my websites/webapps over.
the idea of adding a webserver is to take away a (the) reason for folks to want
to complicate their mox setup by running an other webserver on the same machine.
i think the current webserver implementation can already serve most common use
cases. with a few more tweaks (feedback needed!) we should be able to get to 95%
of the use cases. the reverse proxy can take care of the remaining 5%.
nevertheless, a next step is still to change the quickstart to make it easier
for folks to run with an existing webserver, with existing tls certs/keys.
that's how this relates to issue #5.
2023-03-02 20:15:54 +03:00
srv := & serve { Webserver : true }
test := func ( method , target string , reqhdrs map [ string ] string , expCode int , expContent string , expHeaders map [ string ] string ) {
t . Helper ( )
req := httptest . NewRequest ( method , target , nil )
for k , v := range reqhdrs {
req . Header . Add ( k , v )
}
rw := httptest . NewRecorder ( )
rw . Body = & bytes . Buffer { }
srv . ServeHTTP ( rw , req )
resp := rw . Result ( )
if resp . StatusCode != expCode {
t . Fatalf ( "got statuscode %d, expected %d" , resp . StatusCode , expCode )
}
if expContent != "" {
s := rw . Body . String ( )
if s != expContent {
t . Fatalf ( "got response data %q, expected %q" , s , expContent )
}
}
for k , v := range expHeaders {
if xv := resp . Header . Get ( k ) ; xv != v {
t . Fatalf ( "got %q for header %q, expected %q" , xv , k , v )
}
}
}
test ( "GET" , "http://redir.mox.example" , nil , http . StatusPermanentRedirect , "" , map [ string ] string { "Location" : "https://mox.example/" } )
2023-03-09 01:29:44 +03:00
// http to https redirect, and stay on https afterwards without redirect loop.
test ( "GET" , "http://schemeredir.example" , nil , http . StatusPermanentRedirect , "" , map [ string ] string { "Location" : "https://schemeredir.example/" } )
test ( "GET" , "https://schemeredir.example" , nil , http . StatusNotFound , "" , nil )
2023-08-21 22:52:35 +03:00
accgzip := map [ string ] string { "Accept-Encoding" : "gzip" }
test ( "GET" , "http://mox.example/static/" , accgzip , http . StatusOK , "" , map [ string ] string { "X-Test" : "mox" , "Content-Encoding" : "gzip" } ) // index.html
test ( "GET" , "http://mox.example/static/dir/hi.txt" , accgzip , http . StatusOK , "" , map [ string ] string { "X-Test" : "mox" , "Content-Encoding" : "" } ) // too small to compress
test ( "GET" , "http://mox.example/static/dir/" , accgzip , http . StatusOK , "" , map [ string ] string { "X-Test" : "mox" , "Content-Encoding" : "gzip" } ) // listing
test ( "GET" , "http://mox.example/static/dir" , accgzip , http . StatusTemporaryRedirect , "" , map [ string ] string { "Location" : "/static/dir/" } ) // redirect to dir
test ( "GET" , "http://mox.example/static/bogus" , accgzip , http . StatusNotFound , "" , map [ string ] string { "Content-Encoding" : "" } )
improve webserver, add domain redirects (aliases), add tests and admin page ui to manage the config
- make builtin http handlers serve on specific domains, such as for mta-sts, so
e.g. /.well-known/mta-sts.txt isn't served on all domains.
- add logging of a few more fields in access logging.
- small tweaks/bug fixes in webserver request handling.
- add config option for redirecting entire domains to another (common enough).
- split httpserver metric into two: one for duration until writing header (i.e.
performance of server), another for duration until full response is sent to
client (i.e. performance as perceived by users).
- add admin ui, a new page for managing the configs. after making changes
and hitting "save", the changes take effect immediately. the page itself
doesn't look very well-designed (many input fields, makes it look messy). i
have an idea to improve it (explained in admin.html as todo) by making the
layout look just like the config file. not urgent though.
i've already changed my websites/webapps over.
the idea of adding a webserver is to take away a (the) reason for folks to want
to complicate their mox setup by running an other webserver on the same machine.
i think the current webserver implementation can already serve most common use
cases. with a few more tweaks (feedback needed!) we should be able to get to 95%
of the use cases. the reverse proxy can take care of the remaining 5%.
nevertheless, a next step is still to change the quickstart to make it easier
for folks to run with an existing webserver, with existing tls certs/keys.
that's how this relates to issue #5.
2023-03-02 20:15:54 +03:00
test ( "GET" , "http://mox.example/nolist/" , nil , http . StatusOK , "" , nil ) // index.html
test ( "GET" , "http://mox.example/nolist/dir/" , nil , http . StatusForbidden , "" , nil ) // no listing
test ( "GET" , "http://mox.example/tls/" , nil , http . StatusPermanentRedirect , "" , map [ string ] string { "Location" : "https://mox.example/tls/" } ) // redirect to tls
test ( "GET" , "http://mox.example/baseurl/x?y=2" , nil , http . StatusPermanentRedirect , "" , map [ string ] string { "Location" : "https://tls.mox.example/baseurl/x?q=1&y=2#fragment" } )
test ( "GET" , "http://mox.example/pathonly/old/x?q=2" , nil , http . StatusTemporaryRedirect , "" , map [ string ] string { "Location" : "http://mox.example/pathonly/new/x?q=2" } )
test ( "GET" , "http://mox.example/baseurlpath/old/x?y=2" , nil , http . StatusPermanentRedirect , "" , map [ string ] string { "Location" : "//other.mox.example/baseurlpath/new/x?q=1&y=2#fragment" } )
test ( "GET" , "http://mox.example/strip/x" , nil , http . StatusBadGateway , "" , nil ) // no server yet
test ( "GET" , "http://mox.example/nostrip/x" , nil , http . StatusBadGateway , "" , nil ) // no server yet
badForwarded := map [ string ] string {
"Forwarded" : "bad" ,
"X-Forwarded-For" : "bad" ,
"X-Forwarded-Proto" : "bad" ,
"X-Forwarded-Host" : "bad" ,
"X-Forwarded-Ext" : "bad" ,
}
// Server that echoes path, and forwarded request headers.
server := httptest . NewServer ( http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
for k , v := range badForwarded {
if r . Header . Get ( k ) == v {
w . WriteHeader ( http . StatusInternalServerError )
return
}
}
for k , vl := range r . Header {
if k == "Forwarded" || k == "X-Forwarded" || strings . HasPrefix ( k , "X-Forwarded-" ) {
w . Header ( ) [ k ] = vl
}
}
w . Write ( [ ] byte ( r . URL . Path ) )
} ) )
defer server . Close ( )
serverURL , err := url . Parse ( server . URL )
if err != nil {
t . Fatalf ( "parsing url: %v" , err )
}
serverURL . Path = "/a"
// warning: it is not normally allowed to access the dynamic config without lock. don't propagate accesses like this!
mox . Conf . Dynamic . WebHandlers [ len ( mox . Conf . Dynamic . WebHandlers ) - 2 ] . WebForward . TargetURL = serverURL
mox . Conf . Dynamic . WebHandlers [ len ( mox . Conf . Dynamic . WebHandlers ) - 1 ] . WebForward . TargetURL = serverURL
test ( "GET" , "http://mox.example/strip/x" , badForwarded , http . StatusOK , "/a/x" , map [ string ] string {
"X-Test" : "mox" ,
"X-Forwarded-For" : "192.0.2.1" , // IP is hardcoded in Go's src/net/http/httptest/httptest.go
"X-Forwarded-Proto" : "http" ,
"X-Forwarded-Host" : "mox.example" ,
"X-Forwarded-Ext" : "" ,
} )
test ( "GET" , "http://mox.example/nostrip/x" , map [ string ] string { "X-OK" : "ok" } , http . StatusOK , "/a/nostrip/x" , map [ string ] string { "X-Test" : "mox" } )
test ( "GET" , "http://mox.example/bogus" , nil , http . StatusNotFound , "" , nil ) // path not registered.
test ( "GET" , "http://bogus.mox.example/static/" , nil , http . StatusNotFound , "" , nil ) // domain not registered.
improve http request handling for internal services and multiple domains
per listener, you could enable the admin/account/webmail/webapi handlers. but
that would serve those services on their configured paths (/admin/, /,
/webmail/, /webapi/) on all domains mox would be webserving, including any
non-mail domains. so your www.example/admin/ would be serving the admin web
interface, with no way to disabled that.
with this change, the admin interface is only served on requests to (based on
Host header):
- ip addresses
- the listener host name (explicitly configured in the listener, with fallback
to global hostname)
- "localhost" (for ssh tunnel/forwarding scenario's)
the account/webmail/webapi interfaces are served on the same domains as the
admin interface, and additionally:
- the client settings domains, as optionally configured in each Domain in
domains.conf. typically "mail.<yourdomain>".
this means the internal services are no longer served on other domains
configured in the webserver, e.g. www.example.org/admin/ will not be handled
specially.
the order of evaluation of routes/services is also changed:
before this change, the internal handlers would always be evaluated first.
with this change, only the system handlers for
MTA-STS/autoconfig/ACME-validation will be evaluated first. then the webserver
handlers. and finally the internal services (admin/account/webmail/webapi).
this allows an admin to configure overrides for some of the domains (per
hostname-matching rules explained above) that would normally serve these
services.
webserver handlers can now be configured that pass the request to an internal
service: in addition to the existing static/redirect/forward config options,
there is now an "internal" config option, naming the service
(admin/account/webmail/webapi) for handling the request. this allows enabling
the internal services on custom domains.
for issue #160 by TragicLifeHu, thanks for reporting!
2024-05-11 12:13:14 +03:00
test ( "GET" , "http://mox.example/xadmin/" , nil , http . StatusOK , "" , nil ) // internal admin service
test ( "GET" , "http://mox.example/xaccount/" , nil , http . StatusOK , "" , nil ) // internal account service
test ( "GET" , "http://mox.example/xwebmail/" , nil , http . StatusOK , "" , nil ) // internal webmail service
test ( "GET" , "http://mox.example/xwebapi/v0/" , nil , http . StatusOK , "" , nil ) // internal webapi service
2023-08-21 22:52:35 +03:00
npaths := len ( staticgzcache . paths )
if npaths != 1 {
t . Fatalf ( "%d file(s) in staticgzcache, expected 1" , npaths )
}
loadStaticGzipCache ( mox . DataDirPath ( "tmp/httpstaticcompresscache" ) , 1024 * 1024 )
npaths = len ( staticgzcache . paths )
if npaths != 1 {
t . Fatalf ( "%d file(s) in staticgzcache after loading from disk, expected 1" , npaths )
}
loadStaticGzipCache ( mox . DataDirPath ( "tmp/httpstaticcompresscache" ) , 0 )
npaths = len ( staticgzcache . paths )
if npaths != 0 {
t . Fatalf ( "%d file(s) in staticgzcache after setting max size to 0, expected 0" , npaths )
}
loadStaticGzipCache ( mox . DataDirPath ( "tmp/httpstaticcompresscache" ) , 0 )
npaths = len ( staticgzcache . paths )
if npaths != 0 {
t . Fatalf ( "%d file(s) in staticgzcache after setting max size to 0 and reloading from disk, expected 0" , npaths )
}
improve webserver, add domain redirects (aliases), add tests and admin page ui to manage the config
- make builtin http handlers serve on specific domains, such as for mta-sts, so
e.g. /.well-known/mta-sts.txt isn't served on all domains.
- add logging of a few more fields in access logging.
- small tweaks/bug fixes in webserver request handling.
- add config option for redirecting entire domains to another (common enough).
- split httpserver metric into two: one for duration until writing header (i.e.
performance of server), another for duration until full response is sent to
client (i.e. performance as perceived by users).
- add admin ui, a new page for managing the configs. after making changes
and hitting "save", the changes take effect immediately. the page itself
doesn't look very well-designed (many input fields, makes it look messy). i
have an idea to improve it (explained in admin.html as todo) by making the
layout look just like the config file. not urgent though.
i've already changed my websites/webapps over.
the idea of adding a webserver is to take away a (the) reason for folks to want
to complicate their mox setup by running an other webserver on the same machine.
i think the current webserver implementation can already serve most common use
cases. with a few more tweaks (feedback needed!) we should be able to get to 95%
of the use cases. the reverse proxy can take care of the remaining 5%.
nevertheless, a next step is still to change the quickstart to make it easier
for folks to run with an existing webserver, with existing tls certs/keys.
that's how this relates to issue #5.
2023-03-02 20:15:54 +03:00
}
2023-05-30 23:11:31 +03:00
func TestWebsocket ( t * testing . T ) {
os . RemoveAll ( "../testdata/websocket/data" )
make mox compile on windows, without "mox serve" but with working "mox localserve"
getting mox to compile required changing code in only a few places where
package "syscall" was used: for accessing file access times and for umask
handling. an open problem is how to start a process as an unprivileged user on
windows. that's why "mox serve" isn't implemented yet. and just finding a way
to implement it now may not be good enough in the near future: we may want to
starting using a more complete privilege separation approach, with a process
handling sensitive tasks (handling private keys, authentication), where we may
want to pass file descriptors between processes. how would that work on
windows?
anyway, getting mox to compile for windows doesn't mean it works properly on
windows. the largest issue: mox would normally open a file, rename or remove
it, and finally close it. this happens during message delivery. that doesn't
work on windows, the rename/remove would fail because the file is still open.
so this commit swaps many "remove" and "close" calls. renames are a longer
story: message delivery had two ways to deliver: with "consuming" the
(temporary) message file (which would rename it to its final destination), and
without consuming (by hardlinking the file, falling back to copying). the last
delivery to a recipient of a message (and the only one in the common case of a
single recipient) would consume the message, and the earlier recipients would
not. during delivery, the already open message file was used, to parse the
message. we still want to use that open message file, and the caller now stays
responsible for closing it, but we no longer try to rename (consume) the file.
we always hardlink (or copy) during delivery (this works on windows), and the
caller is responsible for closing and removing (in that order) the original
temporary file. this does cost one syscall more. but it makes the delivery code
(responsibilities) a bit simpler.
there is one more obvious issue: the file system path separator. mox already
used the "filepath" package to join paths in many places, but not everywhere.
and it still used strings with slashes for local file access. with this commit,
the code now uses filepath.FromSlash for path strings with slashes, uses
"filepath" in a few more places where it previously didn't. also switches from
"filepath" to regular "path" package when handling mailbox names in a few
places, because those always use forward slashes, regardless of local file
system conventions. windows can handle forward slashes when opening files, so
test code that passes path strings with forward slashes straight to go stdlib
file i/o functions are left unchanged to reduce code churn. the regular
non-test code, or test code that uses path strings in places other than
standard i/o functions, does have the paths converted for consistent paths
(otherwise we would end up with paths with mixed forward/backward slashes in
log messages).
windows cannot dup a listening socket. for "mox localserve", it isn't
important, and we can work around the issue. the current approach for "mox
serve" (forking a process and passing file descriptors of listening sockets on
"privileged" ports) won't work on windows. perhaps it isn't needed on windows,
and any user can listen on "privileged" ports? that would be welcome.
on windows, os.Open cannot open a directory, so we cannot call Sync on it after
message delivery. a cursory internet search indicates that directories cannot
be synced on windows. the story is probably much more nuanced than that, with
long deep technical details/discussions/disagreement/confusion, like on unix.
for "mox localserve" we can get away with making syncdir a no-op.
2023-10-14 11:54:07 +03:00
mox . ConfigStaticPath = filepath . FromSlash ( "../testdata/websocket/mox.conf" )
2023-05-30 23:11:31 +03:00
mox . ConfigDynamicPath = filepath . Join ( filepath . Dir ( mox . ConfigStaticPath ) , "domains.conf" )
2023-06-16 14:27:27 +03:00
mox . MustLoadConfig ( true , false )
2023-05-30 23:11:31 +03:00
srv := & serve { Webserver : true }
var handler http . Handler // Active handler during test.
backend := httptest . NewServer ( http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
handler . ServeHTTP ( w , r )
} ) )
defer backend . Close ( )
backendURL , err := url . Parse ( backend . URL )
if err != nil {
t . Fatalf ( "parsing backend url: %v" , err )
}
backendURL . Path = "/"
// warning: it is not normally allowed to access the dynamic config without lock. don't propagate accesses like this!
mox . Conf . Dynamic . WebHandlers [ len ( mox . Conf . Dynamic . WebHandlers ) - 1 ] . WebForward . TargetURL = backendURL
server := httptest . NewServer ( srv )
defer server . Close ( )
serverURL , err := url . Parse ( server . URL )
tcheck ( t , err , "parsing server url" )
_ , port , err := net . SplitHostPort ( serverURL . Host )
tcheck ( t , err , "parsing host port in server url" )
wsurl := fmt . Sprintf ( "ws://%s/ws/" , net . JoinHostPort ( "localhost" , port ) )
handler = websocket . Handler ( func ( c * websocket . Conn ) {
io . Copy ( c , c )
} )
// Test a correct websocket connection.
wsconn , err := websocket . Dial ( wsurl , "ignored" , "http://ignored.example" )
tcheck ( t , err , "websocket dial" )
_ , err = fmt . Fprint ( wsconn , "test" )
tcheck ( t , err , "write to websocket" )
buf := make ( [ ] byte , 128 )
n , err := wsconn . Read ( buf )
tcheck ( t , err , "read from websocket" )
if string ( buf [ : n ] ) != "test" {
t . Fatalf ( ` got websocket data %q, expected "test" ` , buf [ : n ] )
}
err = wsconn . Close ( )
tcheck ( t , err , "closing websocket connection" )
// Test with server.ServeHTTP directly.
test := func ( method string , reqhdrs map [ string ] string , expCode int , expHeaders map [ string ] string ) {
t . Helper ( )
req := httptest . NewRequest ( method , wsurl , nil )
for k , v := range reqhdrs {
req . Header . Add ( k , v )
}
rw := httptest . NewRecorder ( )
rw . Body = & bytes . Buffer { }
srv . ServeHTTP ( rw , req )
resp := rw . Result ( )
if resp . StatusCode != expCode {
t . Fatalf ( "got statuscode %d, expected %d" , resp . StatusCode , expCode )
}
for k , v := range expHeaders {
if xv := resp . Header . Get ( k ) ; xv != v {
t . Fatalf ( "got %q for header %q, expected %q" , xv , k , v )
}
}
}
wsreqhdrs := map [ string ] string {
"Upgrade" : "keep-alive, websocket" ,
"Connection" : "X, Upgrade" ,
"Sec-Websocket-Version" : "13" ,
"Sec-Websocket-Key" : "AAAAAAAAAAAAAAAAAAAAAA==" ,
}
test ( "POST" , wsreqhdrs , http . StatusBadRequest , nil )
clone := func ( m map [ string ] string ) map [ string ] string {
r := map [ string ] string { }
for k , v := range m {
r [ k ] = v
}
return r
}
hdrs := clone ( wsreqhdrs )
hdrs [ "Sec-Websocket-Version" ] = "14"
test ( "GET" , hdrs , http . StatusBadRequest , map [ string ] string { "Sec-Websocket-Version" : "13" } )
httpurl := fmt . Sprintf ( "http://%s/ws/" , net . JoinHostPort ( "localhost" , port ) )
// Must now do actual HTTP requests and read the HTTP response. Cannot call
// ServeHTTP because ResponseRecorder is not a http.Hijacker.
test = func ( method string , reqhdrs map [ string ] string , expCode int , expHeaders map [ string ] string ) {
t . Helper ( )
req , err := http . NewRequest ( method , httpurl , nil )
2023-05-31 22:57:46 +03:00
tcheck ( t , err , "http newrequest" )
2023-05-30 23:11:31 +03:00
for k , v := range reqhdrs {
req . Header . Add ( k , v )
}
resp , err := http . DefaultClient . Do ( req )
tcheck ( t , err , "http transaction" )
if resp . StatusCode != expCode {
t . Fatalf ( "got statuscode %d, expected %d" , resp . StatusCode , expCode )
}
for k , v := range expHeaders {
if xv := resp . Header . Get ( k ) ; xv != v {
t . Fatalf ( "got %q for header %q, expected %q" , xv , k , v )
}
}
}
hdrs = clone ( wsreqhdrs )
hdrs [ "Sec-Websocket-Key" ] = "malformed"
test ( "GET" , hdrs , http . StatusBadRequest , nil )
hdrs = clone ( wsreqhdrs )
hdrs [ "Sec-Websocket-Key" ] = "c2hvcnQK" // "short"
test ( "GET" , hdrs , http . StatusBadRequest , nil )
// Not responding with a 101, but with regular 200 OK response.
handler = http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
http . Error ( w , "bad" , http . StatusOK )
} )
test ( "GET" , wsreqhdrs , http . StatusBadRequest , nil )
// Respond with 101, but other websocket response headers missing.
handler = http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
w . WriteHeader ( http . StatusSwitchingProtocols )
} )
test ( "GET" , wsreqhdrs , http . StatusBadRequest , nil )
// With Upgrade: websocket, without Connection: Upgrade
handler = http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
w . Header ( ) . Set ( "Upgrade" , "websocket" )
w . WriteHeader ( http . StatusSwitchingProtocols )
} )
test ( "GET" , wsreqhdrs , http . StatusBadRequest , nil )
// With malformed Sec-WebSocket-Accept response header.
handler = http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
h := w . Header ( )
h . Set ( "Upgrade" , "websocket" )
h . Set ( "Connection" , "Upgrade" )
h . Set ( "Sec-WebSocket-Accept" , "malformed" )
w . WriteHeader ( http . StatusSwitchingProtocols )
} )
test ( "GET" , wsreqhdrs , http . StatusBadRequest , nil )
// With malformed Sec-WebSocket-Accept response header.
handler = http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
h := w . Header ( )
h . Set ( "Upgrade" , "websocket" )
h . Set ( "Connection" , "Upgrade" )
h . Set ( "Sec-WebSocket-Accept" , "YmFk" ) // "bad"
w . WriteHeader ( http . StatusSwitchingProtocols )
} )
test ( "GET" , wsreqhdrs , http . StatusBadRequest , nil )
// All good.
wsresphdrs := map [ string ] string {
"Connection" : "Upgrade" ,
"Upgrade" : "websocket" ,
"Sec-Websocket-Accept" : "ICX+Yqv66kxgM0FcWaLWlFLwTAI=" ,
"X-Test" : "mox" ,
}
handler = http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
h := w . Header ( )
h . Set ( "Upgrade" , "websocket" )
h . Set ( "Connection" , "Upgrade" )
h . Set ( "Sec-WebSocket-Accept" , "ICX+Yqv66kxgM0FcWaLWlFLwTAI=" )
w . WriteHeader ( http . StatusSwitchingProtocols )
} )
test ( "GET" , wsreqhdrs , http . StatusSwitchingProtocols , wsresphdrs )
}