diff --git a/docs/Platforms/Webserver/HTTPS-without-proxy.md b/docs/Platforms/Webserver/HTTPS-without-proxy.md new file mode 100644 index 0000000000..9c6898ec0a --- /dev/null +++ b/docs/Platforms/Webserver/HTTPS-without-proxy.md @@ -0,0 +1,54 @@ +# HTTPS in WeKan itself, without a proxy + +WeKan can serve HTTPS itself (#916). A proxy in front of it (Caddy, nginx, +Apache, Traefik) remains the recommendation for production: it renews +certificates, compresses, and can serve several sites. For a small install, a +test setup or a closed network, the certificate can go to WeKan directly. + +| Variable | What it does | +| --- | --- | +| `HTTPS_PORT` | the port to serve HTTPS on, e.g. `8443` or `443`; HTTPS is off without it | +| `HTTPS_CERT_FILE` | the certificate, with its chain: a file path, or the PEM text itself | +| `HTTPS_KEY_FILE` | its private key: a file path, or the PEM text itself | +| `HTTPS_BIND_IP` | the address to listen on; default `BIND_IP`, else all | +| `HTTPS_REDIRECT` | `true`: plain-HTTP requests get a redirect to HTTPS instead of the page | + +Set `ROOT_URL` to the `https://` address too, so links in emails use it. + +WeKan keeps serving plain HTTP on `PORT`. With `HTTPS_REDIRECT=true`, every +request there is redirected to `ROOT_URL` when that is an `https://` address, +otherwise to the same host on `HTTPS_PORT`. To serve HTTPS only, bind `PORT` to +`127.0.0.1` with `BIND_IP`. + +A port below 1024, such as 443, needs the right to bind it, for example +`setcap 'cap_net_bind_service=+ep'` on the `node` binary, or a container that +publishes it. + +**Renewing the certificate.** When the files at `HTTPS_CERT_FILE` or +`HTTPS_KEY_FILE` change, WeKan loads them within a minute, without a restart. +So `certbot renew` or `acme.sh` can renew them in place. If the new files +cannot be read, WeKan keeps serving the old certificate and logs why. + +Example, Let's Encrypt with certbot: + +``` +HTTPS_PORT=443 +HTTPS_CERT_FILE=/etc/letsencrypt/live/wekan.example.com/fullchain.pem +HTTPS_KEY_FILE=/etc/letsencrypt/live/wekan.example.com/privkey.pem +HTTPS_REDIRECT=true +ROOT_URL=https://wekan.example.com +``` + +Snap: `snap set wekan https-port=443 https-cert-file=… https-key-file=…`. The +snap's own Caddy (`caddy-enabled`) is the alternative, and only one of them +can use port 443. + +**How it works.** Meteor's HTTP server is what pages, DDP and its websockets +attach to. WeKan does not replace it: a TLS listener accepts encrypted +connections and gives each decrypted connection to that same server. Everything +works the same over HTTPS as over HTTP, including the live updates. + +Code: `models/lib/httpsConfig.js`, `server/lib/httpsBridge.js`, +`server/httpsServer.js`. Test: `tests/httpsServer.test.cjs`. It runs with a +real certificate, checks a page and a websocket upgrade, swaps the certificate +without a restart, and covers the refusals. diff --git a/models/lib/httpsConfig.js b/models/lib/httpsConfig.js new file mode 100644 index 0000000000..fb28938917 --- /dev/null +++ b/models/lib/httpsConfig.js @@ -0,0 +1,73 @@ +'use strict'; + +// Optional HTTPS in WeKan's own server (#916, maintainer decision 2026-10-14). +// Pure: which settings turn it on and what they mean, tested without a server +// (tests/httpsServer.test.cjs). server/httpsServer.js does the listening. +// +// HTTPS_PORT the port to serve HTTPS on; HTTPS is off without it +// HTTPS_CERT_FILE the certificate (chain) - a path, or the PEM itself +// HTTPS_KEY_FILE its private key - a path, or the PEM itself +// HTTPS_BIND_IP the address to listen on (default: BIND_IP, else all) +// HTTPS_REDIRECT true: answer plain-HTTP requests with a redirect to HTTPS +// +// Without HTTPS_PORT nothing changes: WeKan serves HTTP on PORT, as always, +// and a proxy (Caddy, nginx) stays the recommendation for production. + +function pemOrPath(value, readFile) { + const v = String(value || '').trim(); + if (!v) return null; + if (v.includes('-----BEGIN ')) return v; + return readFile(v); +} + +/** + * @return {null | {port: number, host: string|undefined, cert: string|Buffer, + * key: string|Buffer, redirect: boolean, certPath: string|null, keyPath: string|null}} + */ +function httpsConfig(env = process.env, readFile = path => require('fs').readFileSync(path)) { + const portText = String(env.HTTPS_PORT || '').trim(); + if (!portText) return null; + const port = Number(portText); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`HTTPS_PORT must be a port number (got "${portText}")`); + } + if (!env.HTTPS_CERT_FILE || !env.HTTPS_KEY_FILE) { + throw new Error('HTTPS_PORT is set, so HTTPS_CERT_FILE and HTTPS_KEY_FILE are needed too'); + } + const cert = pemOrPath(env.HTTPS_CERT_FILE, readFile); + const key = pemOrPath(env.HTTPS_KEY_FILE, readFile); + const isPath = v => !String(v).includes('-----BEGIN '); + return { + port, + host: (env.HTTPS_BIND_IP || env.BIND_IP || '').trim() || undefined, + cert, + key, + redirect: String(env.HTTPS_REDIRECT || '').trim() === 'true', + certPath: isPath(env.HTTPS_CERT_FILE) ? String(env.HTTPS_CERT_FILE).trim() : null, + keyPath: isPath(env.HTTPS_KEY_FILE) ? String(env.HTTPS_KEY_FILE).trim() : null, + }; +} + +const HTTPS_SCHEME = 'https:'; + +/** + * Where a plain-HTTP request is redirected. ROOT_URL's host when ROOT_URL is + * an https:// address (it names the server); otherwise the host the browser + * asked for, on the HTTPS port. Only the path of the request is kept. + */ +function redirectLocation(hostHeader, url, httpsPort, rootUrl = '') { + let root = null; + try { + root = rootUrl ? new URL(rootUrl) : null; + } catch (e) { + root = null; + } + const path = String(url || '/').startsWith('/') && !String(url).startsWith('//') ? String(url || '/') : '/'; + if (root && root.protocol === HTTPS_SCHEME) return `${root.origin}${path}`; + const host = String(hostHeader || '').replace(/:\d+$/, ''); + if (!/^[A-Za-z0-9.-]+$|^\[[0-9A-Fa-f:.]+\]$/.test(host)) return null; + const port = Number(httpsPort) === 443 ? '' : `:${httpsPort}`; + return `${HTTPS_SCHEME}//${host}${port}${path}`; +} + +module.exports = { httpsConfig, redirectLocation }; diff --git a/server/httpsServer.js b/server/httpsServer.js new file mode 100644 index 0000000000..8fa0b9ce85 --- /dev/null +++ b/server/httpsServer.js @@ -0,0 +1,43 @@ +import { Meteor } from 'meteor/meteor'; +import { WebApp } from 'meteor/webapp'; + +// Optional HTTPS in WeKan's own server (#916; settings in +// models/lib/httpsConfig.js). Meteor's HTTP server is what DDP, its websockets +// and every route attach to, so it is not replaced: a TLS listener takes the +// encrypted connections and hands each decrypted socket to that same server. +// Everything WeKan serves over HTTP it then serves over HTTPS too. +// +// The certificate is read again when its file changes, so a renewal (certbot, +// acme.sh) needs no restart. With HTTPS_REDIRECT=true, a plain-HTTP request +// gets a redirect to HTTPS instead of the page. +const { httpsConfig, redirectLocation } = require('/models/lib/httpsConfig'); +const { startHttpsBridge } = require('/server/lib/httpsBridge'); + +let config = null; +try { + config = httpsConfig(); +} catch (error) { + console.error(`HTTPS is not started: ${error.message}`); +} + +if (config) { + if (config.redirect) { + WebApp.rawConnectHandlers.use((req, res, next) => { + if (req.socket && req.socket.encrypted) return next(); + const location = redirectLocation(req.headers.host, req.url, config.port, process.env.ROOT_URL); + if (!location) return next(); + res.writeHead(301, { Location: location, 'Cache-Control': 'no-store' }); + res.end(); + return undefined; + }); + } + + Meteor.startup(() => { + const { server } = startHttpsBridge(WebApp.httpServer, config, { readConfig: () => httpsConfig() }); + server.listen(config.port, config.host, () => { + console.log(`WeKan serves HTTPS on ${config.host || 'all addresses'}:${config.port}.`); + }); + }); +} + +export { config as httpsServerConfig }; diff --git a/server/imports.js b/server/imports.js index 7167294ab8..686bb74033 100644 --- a/server/imports.js +++ b/server/imports.js @@ -317,6 +317,8 @@ import '/server/recovery'; import '/server/publications/inviteToBoardRolesSettings'; // Custom board roles (#3022): the permission lookup, publication and methods. import '/server/customBoardRoles'; +// Optional HTTPS in WeKan's own server (#916). +import '/server/httpsServer'; import '/server/publications/lockoutSettings'; import '/server/publications/notifications'; import '/server/publications/org'; diff --git a/server/lib/httpsBridge.js b/server/lib/httpsBridge.js new file mode 100644 index 0000000000..0d7e8380f7 --- /dev/null +++ b/server/lib/httpsBridge.js @@ -0,0 +1,44 @@ +'use strict'; + +// The TLS listener of optional HTTPS (#916): encrypted connections in, each +// decrypted socket handed to an existing HTTP server - Meteor's, in WeKan - +// which serves it exactly as a plain connection, websocket upgrades included. +// No Meteor here, so tests/httpsServer.test.cjs runs it with a real +// certificate and a plain http.Server. +const fs = require('fs'); +const tls = require('tls'); + +function startHttpsBridge(httpServer, config, { readConfig = null, log = console } = {}) { + const server = tls.createServer({ cert: config.cert, key: config.key, ALPNProtocols: ['http/1.1'] }, socket => { + httpServer.emit('connection', socket); + }); + server.on('tlsClientError', () => { /* a client that cannot speak TLS: its problem */ }); + server.on('error', error => log.error(`HTTPS server: ${error.message}`)); + + // Renewed certificates are picked up without a restart. + const watched = []; + if (readConfig) { + const reload = () => { + try { + const next = readConfig(); + if (next) server.setSecureContext({ cert: next.cert, key: next.key }); + log.log('HTTPS certificate reloaded.'); + } catch (error) { + log.error(`HTTPS certificate not reloaded, keeping the current one: ${error.message}`); + } + }; + for (const file of [config.certPath, config.keyPath].filter(Boolean)) { + fs.watchFile(file, { interval: 60000 }, (now, before) => { + if (now.mtimeMs !== before.mtimeMs) reload(); + }); + watched.push(file); + } + } + const close = () => { + for (const file of watched) fs.unwatchFile(file); + server.close(); + }; + return { server, close }; +} + +module.exports = { startHttpsBridge }; diff --git a/snap-src/bin/config b/snap-src/bin/config index c05ad63be9..1899a730cd 100755 --- a/snap-src/bin/config +++ b/snap-src/bin/config @@ -3,7 +3,7 @@ # All supported keys are defined here together with descriptions and default values # list of supported keys -keys="WEKAN_AUTOPICK WEKAN_AUTOPICK_TIMEOUT DEBUG BIND_IP MAIL_TLS_CA_CERT MAIL_TLS_SERVERNAME WEBHOOK_TLS_CA_CERT HTTP_PROXY HTTPS_PROXY NO_PROXY WEKAN_FERRETDB_OPLOG WEKAN_FERRETDB_HANDLER WEKAN_FERRETDB_URL DDP_TRANSPORT METEOR_REACTIVITY_ORDER MONGO_LOG_DESTINATION MONGO_URL MONGO_OPLOG_URL MONGODB_BIND_UNIX_SOCKET MONGODB_BIND_IP MONGODB_PORT MAIL_URL MAIL_FROM MAIL_SERVICE MAIL_SERVICE_USER MAIL_SERVICE_PASSWORD ROOT_URL PORT DISABLE_MONGODB CADDY_ENABLED CADDY_BIND_PORT WITH_API CARDS_LOADING CARD_OPENED_WEBHOOK_ENABLED ACCOUNTS_LOCKOUT_KNOWN_USERS_FAILURES_BEFORE ACCOUNTS_LOCKOUT_KNOWN_USERS_PERIOD ACCOUNTS_LOCKOUT_KNOWN_USERS_FAILURE_WINDOW ACCOUNTS_LOCKOUT_UNKNOWN_USERS_FAILURES_BERORE ACCOUNTS_LOCKOUT_UNKNOWN_USERS_LOCKOUT_PERIOD ACCOUNTS_LOCKOUT_UNKNOWN_USERS_FAILURE_WINDOW ACCOUNTS_COMMON_LOGIN_EXPIRATION_IN_DAYS ATTACHMENTS_UPLOAD_EXTERNAL_PROGRAM ATTACHMENTS_UPLOAD_MIME_TYPES ATTACHMENTS_UPLOAD_MAX_SIZE AVATARS_UPLOAD_EXTERNAL_PROGRAM AVATARS_UPLOAD_MIME_TYPES AVATARS_UPLOAD_MAX_SIZE DEFAULT_AVATAR_URL MAX_IMAGE_PIXEL IMAGE_COMPRESS_RATIO BIGEVENTS_PATTERN NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE NOTIFY_DUE_DAYS_BEFORE_AND_AFTER NOTIFY_DUE_AT_HOUR_OF_DAY DEFAULT_BOARD_ID EMAIL_NOTIFICATION_TIMEOUT CORS CORS_ALLOW_HEADERS CORS_EXPOSE_HEADERS MATOMO_ADDRESS MATOMO_SITE_ID MATOMO_DO_NOT_TRACK MATOMO_WITH_USERNAME METRICS_ALLOWED_IP_ADDRESSES BROWSER_POLICY_ENABLED TRUSTED_URL WEBHOOKS_ATTRIBUTES OAUTH2_ENABLED OIDC_REDIRECTION_ENABLED OAUTH2_CA_CERT OAUTH2_LOGIN_STYLE OAUTH2_CLIENT_ID OAUTH2_SECRET OAUTH2_SERVER_URL OAUTH2_AUTH_ENDPOINT OAUTH2_USERINFO_ENDPOINT OAUTH2_TOKEN_ENDPOINT OAUTH2_LOGOUT_ENDPOINT OAUTH2_ID_MAP OAUTH2_USERNAME_MAP OAUTH2_FULLNAME_MAP OAUTH2_ID_TOKEN_WHITELIST_FIELDS OAUTH2_EMAIL_MAP OAUTH2_REQUEST_PERMISSIONS OAUTH2_ADFS_ENABLED OAUTH2_B2C_ENABLED OAUTH2_MERGE_EXISTING_USERS LDAP_ENABLE LDAP_PORT LDAP_HOST LDAP_AD_SIMPLE_AUTH LDAP_BASEDN LDAP_LOGIN_FALLBACK LDAP_RECONNECT LDAP_TIMEOUT LDAP_IDLE_TIMEOUT LDAP_CONNECT_TIMEOUT LDAP_AUTHENTIFICATION LDAP_AUTHENTIFICATION_USERDN LDAP_AUTHENTIFICATION_PASSWORD LDAP_LOG_ENABLED LDAP_BACKGROUND_SYNC LDAP_BACKGROUND_SYNC_INTERVAL LDAP_BACKGROUND_SYNC_KEEP_EXISTANT_USERS_UPDATED LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS LDAP_ENCRYPTION LDAP_CA_CERT LDAP_REJECT_UNAUTHORIZED LDAP_USER_AUTHENTICATION LDAP_USER_AUTHENTICATION_FIELD LDAP_USER_SEARCH_FILTER LDAP_USER_SEARCH_SCOPE LDAP_USER_SEARCH_FIELD LDAP_SEARCH_PAGE_SIZE LDAP_SEARCH_SIZE_LIMIT LDAP_GROUP_FILTER_ENABLE LDAP_GROUP_FILTER_OBJECTCLASS LDAP_GROUP_FILTER_GROUP_ID_ATTRIBUTE LDAP_GROUP_FILTER_GROUP_MEMBER_ATTRIBUTE LDAP_GROUP_FILTER_GROUP_MEMBER_FORMAT LDAP_GROUP_FILTER_NESTED LDAP_GROUP_FILTER_GROUP_NAME LDAP_UNIQUE_IDENTIFIER_FIELD LDAP_UTF8_NAMES_SLUGIFY LDAP_USERNAME_FIELD LDAP_FULLNAME_FIELD LDAP_MERGE_EXISTING_USERS LDAP_SYNC_USER_DATA LDAP_SYNC_USER_DATA_FIELDMAP LDAP_SYNC_GROUP_ROLES LDAP_DEFAULT_DOMAIN LDAP_EMAIL_MATCH_ENABLE LDAP_EMAIL_MATCH_REQUIRE LDAP_EMAIL_MATCH_VERIFIED LDAP_EMAIL_FIELD LDAP_SYNC_ADMIN_STATUS LDAP_SYNC_ADMIN_GROUPS HEADER_LOGIN_ID HEADER_LOGIN_FIRSTNAME HEADER_LOGIN_LASTNAME HEADER_LOGIN_EMAIL HEADER_LOGIN_TRUSTED_IPS HEADER_LOGIN_TRUSTED_PROXIES LOGOUT_WITH_TIMER LOGOUT_IN LOGOUT_ON_HOURS LOGOUT_ON_MINUTES DEFAULT_AUTHENTICATION_METHOD PASSWORD_LOGIN_ENABLED CAS_ENABLED CAS_BASE_URL CAS_LOGIN_URL CAS_VALIDATE_URL SAML_ENABLED SAML_PROVIDER SAML_ENTRYPOINT SAML_ISSUER SAML_CERT SAML_IDPSLO_REDIRECTURL SAML_PRIVATE_KEYFILE SAML_PUBLIC_CERTFILE SAML_IDENTIFIER_FORMAT SAML_LOCAL_PROFILE_MATCH_ATTRIBUTE SAML_ATTRIBUTES SAML_MERGE_EXISTING_USERS SAML_IDP_PROFILE SAML_WANT_RESPONSE_SIGNED SAML_WANT_ASSERTIONS_SIGNED SAML_LOGIN_FLOW OAUTH_GOOGLE_ENABLED OAUTH_GOOGLE_CLIENT_ID OAUTH_GOOGLE_SECRET OAUTH_GOOGLE_SECRET_FILE OAUTH_GITHUB_ENABLED OAUTH_GITHUB_CLIENT_ID OAUTH_GITHUB_SECRET OAUTH_GITHUB_SECRET_FILE OAUTH_FACEBOOK_ENABLED OAUTH_FACEBOOK_APP_ID OAUTH_FACEBOOK_SECRET OAUTH_FACEBOOK_SECRET_FILE OAUTH_TWITTER_ENABLED OAUTH_TWITTER_CONSUMER_KEY OAUTH_TWITTER_SECRET OAUTH_TWITTER_SECRET_FILE OAUTH_METEOR_DEVELOPER_ENABLED OAUTH_METEOR_DEVELOPER_CLIENT_ID OAUTH_METEOR_DEVELOPER_SECRET OAUTH_METEOR_DEVELOPER_SECRET_FILE OAUTH_WEIBO_ENABLED OAUTH_WEIBO_CLIENT_ID OAUTH_WEIBO_SECRET OAUTH_WEIBO_SECRET_FILE OAUTH_MEETUP_ENABLED OAUTH_MEETUP_CLIENT_ID OAUTH_MEETUP_SECRET OAUTH_MEETUP_SECRET_FILE OAUTH_PROVIDERS_LOGIN_STYLE OAUTH_PROVIDERS_MERGE_EXISTING_USERS OAUTH_PROVIDERS_ALLOWED_EMAIL_DOMAINS PASSWORDLESS_ENABLED ORACLE_OIM_ENABLED RESULTS_PER_PAGE WAIT_SPINNER NODE_OPTIONS LDAP_AUTHENTIFICATION_PASSWORD_FILE OAUTH2_SECRET_FILE MAIL_URL_FILE MONGO_URL_FILE S3 S3_SECRET_KEY_FILE OAUTH2_AUTO_REGISTRATION OAUTH2_ADMIN_GROUPS NOTIFY_ON_ASSIGN LDAP_BACKGROUND_SYNC_DISABLE_NONEXISTANT_USERS LDAP_SYNC_ORGANIZATIONS LDAP_SYNC_ORGANIZATIONS_GROUPS LDAP_SYNC_TEAMS LDAP_SYNC_TEAMS_GROUPS LDAP_MIGRATION_ALLOW_PASSWORD_LOGIN LDAP_USER_ATTRIBUTES LDAP_GROUP_BASEDN OAUTH2_AVATAR_MAP OAUTH2_ALLOWED_EMAIL_DOMAINS OAUTH2_DEFAULT_ORGANIZATION PROPAGATE_OIDC_DATA OAUTH2_SECRET_JWT_KEY_PATH OAUTH2_SECRET_JWT_ISSUER OAUTH2_SECRET_JWT_KEY_ID OAUTH2_SECRET_JWT_AUDIENCE OAUTH2_SECRET_JWT_SUBJECT OAUTH2_SECRET_JWT_EXPIRES_IN CAS_MERGE_EXISTING_USERS" +keys="WEKAN_AUTOPICK WEKAN_AUTOPICK_TIMEOUT DEBUG BIND_IP MAIL_TLS_CA_CERT MAIL_TLS_SERVERNAME WEBHOOK_TLS_CA_CERT HTTP_PROXY HTTPS_PROXY NO_PROXY HTTPS_PORT HTTPS_CERT_FILE HTTPS_KEY_FILE HTTPS_BIND_IP HTTPS_REDIRECT WEKAN_FERRETDB_OPLOG WEKAN_FERRETDB_HANDLER WEKAN_FERRETDB_URL DDP_TRANSPORT METEOR_REACTIVITY_ORDER MONGO_LOG_DESTINATION MONGO_URL MONGO_OPLOG_URL MONGODB_BIND_UNIX_SOCKET MONGODB_BIND_IP MONGODB_PORT MAIL_URL MAIL_FROM MAIL_SERVICE MAIL_SERVICE_USER MAIL_SERVICE_PASSWORD ROOT_URL PORT DISABLE_MONGODB CADDY_ENABLED CADDY_BIND_PORT WITH_API CARDS_LOADING CARD_OPENED_WEBHOOK_ENABLED ACCOUNTS_LOCKOUT_KNOWN_USERS_FAILURES_BEFORE ACCOUNTS_LOCKOUT_KNOWN_USERS_PERIOD ACCOUNTS_LOCKOUT_KNOWN_USERS_FAILURE_WINDOW ACCOUNTS_LOCKOUT_UNKNOWN_USERS_FAILURES_BERORE ACCOUNTS_LOCKOUT_UNKNOWN_USERS_LOCKOUT_PERIOD ACCOUNTS_LOCKOUT_UNKNOWN_USERS_FAILURE_WINDOW ACCOUNTS_COMMON_LOGIN_EXPIRATION_IN_DAYS ATTACHMENTS_UPLOAD_EXTERNAL_PROGRAM ATTACHMENTS_UPLOAD_MIME_TYPES ATTACHMENTS_UPLOAD_MAX_SIZE AVATARS_UPLOAD_EXTERNAL_PROGRAM AVATARS_UPLOAD_MIME_TYPES AVATARS_UPLOAD_MAX_SIZE DEFAULT_AVATAR_URL MAX_IMAGE_PIXEL IMAGE_COMPRESS_RATIO BIGEVENTS_PATTERN NOTIFICATION_TRAY_AFTER_READ_DAYS_BEFORE_REMOVE NOTIFY_DUE_DAYS_BEFORE_AND_AFTER NOTIFY_DUE_AT_HOUR_OF_DAY DEFAULT_BOARD_ID EMAIL_NOTIFICATION_TIMEOUT CORS CORS_ALLOW_HEADERS CORS_EXPOSE_HEADERS MATOMO_ADDRESS MATOMO_SITE_ID MATOMO_DO_NOT_TRACK MATOMO_WITH_USERNAME METRICS_ALLOWED_IP_ADDRESSES BROWSER_POLICY_ENABLED TRUSTED_URL WEBHOOKS_ATTRIBUTES OAUTH2_ENABLED OIDC_REDIRECTION_ENABLED OAUTH2_CA_CERT OAUTH2_LOGIN_STYLE OAUTH2_CLIENT_ID OAUTH2_SECRET OAUTH2_SERVER_URL OAUTH2_AUTH_ENDPOINT OAUTH2_USERINFO_ENDPOINT OAUTH2_TOKEN_ENDPOINT OAUTH2_LOGOUT_ENDPOINT OAUTH2_ID_MAP OAUTH2_USERNAME_MAP OAUTH2_FULLNAME_MAP OAUTH2_ID_TOKEN_WHITELIST_FIELDS OAUTH2_EMAIL_MAP OAUTH2_REQUEST_PERMISSIONS OAUTH2_ADFS_ENABLED OAUTH2_B2C_ENABLED OAUTH2_MERGE_EXISTING_USERS LDAP_ENABLE LDAP_PORT LDAP_HOST LDAP_AD_SIMPLE_AUTH LDAP_BASEDN LDAP_LOGIN_FALLBACK LDAP_RECONNECT LDAP_TIMEOUT LDAP_IDLE_TIMEOUT LDAP_CONNECT_TIMEOUT LDAP_AUTHENTIFICATION LDAP_AUTHENTIFICATION_USERDN LDAP_AUTHENTIFICATION_PASSWORD LDAP_LOG_ENABLED LDAP_BACKGROUND_SYNC LDAP_BACKGROUND_SYNC_INTERVAL LDAP_BACKGROUND_SYNC_KEEP_EXISTANT_USERS_UPDATED LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS LDAP_ENCRYPTION LDAP_CA_CERT LDAP_REJECT_UNAUTHORIZED LDAP_USER_AUTHENTICATION LDAP_USER_AUTHENTICATION_FIELD LDAP_USER_SEARCH_FILTER LDAP_USER_SEARCH_SCOPE LDAP_USER_SEARCH_FIELD LDAP_SEARCH_PAGE_SIZE LDAP_SEARCH_SIZE_LIMIT LDAP_GROUP_FILTER_ENABLE LDAP_GROUP_FILTER_OBJECTCLASS LDAP_GROUP_FILTER_GROUP_ID_ATTRIBUTE LDAP_GROUP_FILTER_GROUP_MEMBER_ATTRIBUTE LDAP_GROUP_FILTER_GROUP_MEMBER_FORMAT LDAP_GROUP_FILTER_NESTED LDAP_GROUP_FILTER_GROUP_NAME LDAP_UNIQUE_IDENTIFIER_FIELD LDAP_UTF8_NAMES_SLUGIFY LDAP_USERNAME_FIELD LDAP_FULLNAME_FIELD LDAP_MERGE_EXISTING_USERS LDAP_SYNC_USER_DATA LDAP_SYNC_USER_DATA_FIELDMAP LDAP_SYNC_GROUP_ROLES LDAP_DEFAULT_DOMAIN LDAP_EMAIL_MATCH_ENABLE LDAP_EMAIL_MATCH_REQUIRE LDAP_EMAIL_MATCH_VERIFIED LDAP_EMAIL_FIELD LDAP_SYNC_ADMIN_STATUS LDAP_SYNC_ADMIN_GROUPS HEADER_LOGIN_ID HEADER_LOGIN_FIRSTNAME HEADER_LOGIN_LASTNAME HEADER_LOGIN_EMAIL HEADER_LOGIN_TRUSTED_IPS HEADER_LOGIN_TRUSTED_PROXIES LOGOUT_WITH_TIMER LOGOUT_IN LOGOUT_ON_HOURS LOGOUT_ON_MINUTES DEFAULT_AUTHENTICATION_METHOD PASSWORD_LOGIN_ENABLED CAS_ENABLED CAS_BASE_URL CAS_LOGIN_URL CAS_VALIDATE_URL SAML_ENABLED SAML_PROVIDER SAML_ENTRYPOINT SAML_ISSUER SAML_CERT SAML_IDPSLO_REDIRECTURL SAML_PRIVATE_KEYFILE SAML_PUBLIC_CERTFILE SAML_IDENTIFIER_FORMAT SAML_LOCAL_PROFILE_MATCH_ATTRIBUTE SAML_ATTRIBUTES SAML_MERGE_EXISTING_USERS SAML_IDP_PROFILE SAML_WANT_RESPONSE_SIGNED SAML_WANT_ASSERTIONS_SIGNED SAML_LOGIN_FLOW OAUTH_GOOGLE_ENABLED OAUTH_GOOGLE_CLIENT_ID OAUTH_GOOGLE_SECRET OAUTH_GOOGLE_SECRET_FILE OAUTH_GITHUB_ENABLED OAUTH_GITHUB_CLIENT_ID OAUTH_GITHUB_SECRET OAUTH_GITHUB_SECRET_FILE OAUTH_FACEBOOK_ENABLED OAUTH_FACEBOOK_APP_ID OAUTH_FACEBOOK_SECRET OAUTH_FACEBOOK_SECRET_FILE OAUTH_TWITTER_ENABLED OAUTH_TWITTER_CONSUMER_KEY OAUTH_TWITTER_SECRET OAUTH_TWITTER_SECRET_FILE OAUTH_METEOR_DEVELOPER_ENABLED OAUTH_METEOR_DEVELOPER_CLIENT_ID OAUTH_METEOR_DEVELOPER_SECRET OAUTH_METEOR_DEVELOPER_SECRET_FILE OAUTH_WEIBO_ENABLED OAUTH_WEIBO_CLIENT_ID OAUTH_WEIBO_SECRET OAUTH_WEIBO_SECRET_FILE OAUTH_MEETUP_ENABLED OAUTH_MEETUP_CLIENT_ID OAUTH_MEETUP_SECRET OAUTH_MEETUP_SECRET_FILE OAUTH_PROVIDERS_LOGIN_STYLE OAUTH_PROVIDERS_MERGE_EXISTING_USERS OAUTH_PROVIDERS_ALLOWED_EMAIL_DOMAINS PASSWORDLESS_ENABLED ORACLE_OIM_ENABLED RESULTS_PER_PAGE WAIT_SPINNER NODE_OPTIONS LDAP_AUTHENTIFICATION_PASSWORD_FILE OAUTH2_SECRET_FILE MAIL_URL_FILE MONGO_URL_FILE S3 S3_SECRET_KEY_FILE OAUTH2_AUTO_REGISTRATION OAUTH2_ADMIN_GROUPS NOTIFY_ON_ASSIGN LDAP_BACKGROUND_SYNC_DISABLE_NONEXISTANT_USERS LDAP_SYNC_ORGANIZATIONS LDAP_SYNC_ORGANIZATIONS_GROUPS LDAP_SYNC_TEAMS LDAP_SYNC_TEAMS_GROUPS LDAP_MIGRATION_ALLOW_PASSWORD_LOGIN LDAP_USER_ATTRIBUTES LDAP_GROUP_BASEDN OAUTH2_AVATAR_MAP OAUTH2_ALLOWED_EMAIL_DOMAINS OAUTH2_DEFAULT_ORGANIZATION PROPAGATE_OIDC_DATA OAUTH2_SECRET_JWT_KEY_PATH OAUTH2_SECRET_JWT_ISSUER OAUTH2_SECRET_JWT_KEY_ID OAUTH2_SECRET_JWT_AUDIENCE OAUTH2_SECRET_JWT_SUBJECT OAUTH2_SECRET_JWT_EXPIRES_IN CAS_MERGE_EXISTING_USERS" #-------------------- TWO COPIES OF THE DATA -------------------- # After a MongoDB -> FerretDB migration both copies stay on disk, and if both have @@ -160,6 +160,26 @@ DESCRIPTION_NO_PROXY="Destinations that do not use the proxy: comma-separated ho DEFAULT_NO_PROXY="" KEY_NO_PROXY="no-proxy" +DESCRIPTION_HTTPS_PORT="Serve HTTPS from WeKan itself on this port (off when empty). Needs https-cert-file and https-key-file. The snap's Caddy is the alternative" +DEFAULT_HTTPS_PORT="" +KEY_HTTPS_PORT="https-port" + +DESCRIPTION_HTTPS_CERT_FILE="Certificate (with chain) for https-port: a file path or the PEM itself. A renewed file is loaded without a restart" +DEFAULT_HTTPS_CERT_FILE="" +KEY_HTTPS_CERT_FILE="https-cert-file" + +DESCRIPTION_HTTPS_KEY_FILE="Private key for https-port: a file path or the PEM itself" +DEFAULT_HTTPS_KEY_FILE="" +KEY_HTTPS_KEY_FILE="https-key-file" + +DESCRIPTION_HTTPS_BIND_IP="Address https-port listens on (default: bind-ip, else all)" +DEFAULT_HTTPS_BIND_IP="" +KEY_HTTPS_BIND_IP="https-bind-ip" + +DESCRIPTION_HTTPS_REDIRECT="true: plain-HTTP requests get a redirect to HTTPS" +DEFAULT_HTTPS_REDIRECT="" +KEY_HTTPS_REDIRECT="https-redirect" + DESCRIPTION_BIND_IP="address WeKan listens on. Empty: Meteor default (0.0.0.0, IPv4 only). '::' for IPv6 (and IPv4 on a dual-stack host)" DEFAULT_BIND_IP="" KEY_BIND_IP="bind-ip" diff --git a/tests/httpsServer.test.cjs b/tests/httpsServer.test.cjs new file mode 100644 index 0000000000..65acceda94 --- /dev/null +++ b/tests/httpsServer.test.cjs @@ -0,0 +1,97 @@ +'use strict'; + +// Optional HTTPS in WeKan's own server (#916): off without HTTPS_PORT; with +// it, a TLS listener hands each decrypted connection to the existing HTTP +// server, so pages AND websocket upgrades (DDP) are served over TLS; a renewed +// certificate is used without a restart; and plain HTTP can be redirected. +// Run: node tests/httpsServer.test.cjs + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const http = require('node:http'); +const https = require('node:https'); +const path = require('node:path'); +const tls = require('node:tls'); +const { spawnSync } = require('node:child_process'); + +const ROOT = path.join(__dirname, '..'); +const { httpsConfig, redirectLocation } = require('../models/lib/httpsConfig'); +const { startHttpsBridge } = require('../server/lib/httpsBridge'); +const HAS_OPENSSL = spawnSync('openssl', ['version']).status === 0; + +function selfSigned(dir, cn) { + const cert = path.join(dir, `${cn}.crt`); + const key = path.join(dir, `${cn}.key`); + const r = spawnSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', `/CN=${cn}`, + '-addext', `subjectAltName=DNS:${cn},IP:127.0.0.1`, '-keyout', key, '-out', cert], { encoding: 'utf8' }); + assert.equal(r.status, 0, r.stderr); + return { cert, key }; +} + +test('settings: off without HTTPS_PORT; a port needs a certificate and a key (negative)', () => { + assert.equal(httpsConfig({}), null); + assert.equal(httpsConfig({ HTTPS_CERT_FILE: '/x', HTTPS_KEY_FILE: '/y' }), null, 'files alone change nothing'); + assert.throws(() => httpsConfig({ HTTPS_PORT: '8443' }), /HTTPS_CERT_FILE and HTTPS_KEY_FILE/); + assert.throws(() => httpsConfig({ HTTPS_PORT: 'https', HTTPS_CERT_FILE: 'a', HTTPS_KEY_FILE: 'b' }), /must be a port/); + const read = p => `content of ${p}`; + const c = httpsConfig({ HTTPS_PORT: '8443', HTTPS_CERT_FILE: '/etc/c.pem', HTTPS_KEY_FILE: '-----BEGIN PRIVATE KEY-----\nx', BIND_IP: '10.0.0.1', HTTPS_REDIRECT: 'true' }, read); + assert.deepEqual([c.port, c.host, c.cert, c.certPath, c.keyPath, c.redirect], [8443, '10.0.0.1', 'content of /etc/c.pem', '/etc/c.pem', null, true]); +}); + +test('the redirect keeps only the path, and names a host the browser asked for or ROOT_URL', () => { + assert.equal(redirectLocation('wekan.example.com:8080', '/b/x?y=1', 8443), 'https://wekan.example.com:8443/b/x?y=1'); + assert.equal(redirectLocation('wekan.example.com', '/', 443), 'https://wekan.example.com/'); + assert.equal(redirectLocation('anything', '/p', 8443, 'https://boards.example.com'), 'https://boards.example.com/p'); + // Negative: no injected host, and no scheme-relative path to another site. + assert.equal(redirectLocation('evil.com/@x', '/', 8443), null); + assert.equal(redirectLocation('wekan.example.com', '//evil.com/', 8443), 'https://wekan.example.com:8443/'); +}); + +test('pages and websocket upgrades over TLS, through the existing HTTP server; a renewed certificate without a restart', { skip: !HAS_OPENSSL && 'needs openssl' }, async () => { + const dir = fs.mkdtempSync(path.join(ROOT, '.tools', 'tmp', 'https-')); + const first = selfSigned(dir, 'first.example'); + const app = http.createServer((req, res) => res.end(`served ${req.url} encrypted=${!!req.socket.encrypted}`)); + let upgraded = false; + app.on('upgrade', (req, socket) => { upgraded = true; socket.end('HTTP/1.1 101 Switching Protocols\r\n\r\n'); }); + const env = { HTTPS_PORT: '1', HTTPS_CERT_FILE: first.cert, HTTPS_KEY_FILE: first.key }; + const config = httpsConfig(env); + const { server, close } = startHttpsBridge(app, config, { readConfig: () => httpsConfig(env), log: { log() {}, error() {} } }); + await new Promise(r => server.listen(0, '127.0.0.1', r)); + const port = server.address().port; + const get = (ca, servername = 'first.example') => new Promise((resolve, reject) => { + https.get({ host: '127.0.0.1', port, path: '/hello', ca, servername }, res => { + let body = ''; + res.on('data', d => { body += d; }); + res.on('end', () => resolve(body)); + }).on('error', reject); + }); + try { + assert.equal(await get(fs.readFileSync(first.cert)), 'served /hello encrypted=true'); + // Negative: without trusting the certificate, the client refuses it. + await assert.rejects(get(undefined), /self[- ]signed|unable to verify/i); + // A websocket upgrade (what DDP does) reaches the server's upgrade handler. + await new Promise((resolve, reject) => { + const socket = tls.connect({ host: '127.0.0.1', port, ca: fs.readFileSync(first.cert), servername: 'first.example' }, () => { + socket.write('GET /sockjs/websocket HTTP/1.1\r\nHost: x\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n'); + }); + socket.on('data', d => { if (String(d).startsWith('HTTP/1.1 101')) { socket.end(); resolve(); } }); + socket.on('error', reject); + }); + assert.equal(upgraded, true); + // A renewal is used without a restart (setSecureContext, as the file watch does). + const second = selfSigned(dir, 'second.example'); + server.setSecureContext({ cert: fs.readFileSync(second.cert), key: fs.readFileSync(second.key) }); + assert.equal(await get(fs.readFileSync(second.cert), 'second.example'), 'served /hello encrypted=true', 'the new certificate is the one served'); + } finally { + close(); + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test('WeKan starts the bridge on Meteor\'s own server, only when configured', () => { + const src = fs.readFileSync(path.join(ROOT, 'server/httpsServer.js'), 'utf8'); + assert.match(src, /startHttpsBridge\(WebApp\.httpServer, config,/); + assert.match(src, /if \(config\) \{/); + assert.match(fs.readFileSync(path.join(ROOT, 'server/imports.js'), 'utf8'), /import '\/server\/httpsServer';/); +});