diff --git a/backend/certbot/dns-plugins.json b/backend/certbot/dns-plugins.json index 4467a27af..f22da5af7 100644 --- a/backend/certbot/dns-plugins.json +++ b/backend/certbot/dns-plugins.json @@ -224,12 +224,12 @@ "version": "~=0.1.2" }, "edgedns": { - "credentials": "edgedns_client_secret = as3d1asd5d1a32sdfsdfs2d1asd5=\nedgedns_host = sdflskjdf-dfsdfsdf-sdfsdfsdf.luna.akamaiapis.net\nedgedns_access_token = kjdsi3-34rfsdfsdf-234234fsdfsdf\nedgedns_client_token = dkfjdf-342fsdfsd-23fsdfsdfsdf", - "dependencies": "", - "full_plugin_name": "edgedns", - "name": "Akamai Edge DNS", - "package_name": "certbot-plugin-edgedns", - "version": "~=0.1.0" + "credentials": "client_token = YOUR_CLIENT_TOKEN\naccess_token = YOUR_ACCESS_TOKEN\nclient_secret = YOUR_CLIENT_SECRET\nhost = YOUR_HOST.luna.akamaiapis.net\n# Optional: account_key = YOUR_ACCOUNT_KEY", + "dependencies": "", + "full_plugin_name": "edgedns", + "name": "Akamai Edge DNS", + "package_name": "certbot-plugin-edgedns", + "version": "==0.3.0" }, "edgeone": { "credentials": "dns_edgeone_secret_id = YOUR_TENCENTCLOUD_SECRET_ID\ndns_edgeone_secret_key = YOUR_TENCENTCLOUD_SECRET_KEY", diff --git a/backend/internal/certificate.js b/backend/internal/certificate.js index 9a14f5893..9f81b764d 100644 --- a/backend/internal/certificate.js +++ b/backend/internal/certificate.js @@ -545,13 +545,15 @@ const internalCertificate = { /** * Validates that the certs provided are good. - * No access required here, nothing is changed or stored. + * Nothing is changed or stored, but the files go through openssl, so it needs the same access as creating one. * + * @param {Access} access * @param {Object} data * @param {Object} data.files * @returns {Promise} */ - validate: (data) => { + validate: async (access, data) => { + await access.can("certificates:create"); // Put file contents into an object const files = {}; _.map(data.files, (file, name) => { @@ -600,7 +602,7 @@ const internalCertificate = { throw new error.ValidationError("Cannot upload certificates for this type of provider"); } - const validations = await internalCertificate.validate(data); + const validations = await internalCertificate.validate(access, data); if (typeof validations.certificate === "undefined") { throw new error.ValidationError("Certificate file was not provided"); } diff --git a/backend/internal/host.js b/backend/internal/host.js index 748716262..81efe160e 100644 --- a/backend/internal/host.js +++ b/backend/internal/host.js @@ -79,15 +79,18 @@ const internalHost = { redirection_hosts: [], }; - const proxyRes = await proxyHostModel.query().where("is_deleted", 0); + const proxyRes = await proxyHostModel + .query() + .where("is_deleted", 0) + .withGraphFetched("[certificate, access_list.[clients,items]]"); responseObject.proxy_hosts = internalHost._getHostsWithDomains(proxyRes, domainNames); responseObject.total_count += responseObject.proxy_hosts.length; - const redirRes = await redirectionHostModel.query().where("is_deleted", 0); + const redirRes = await redirectionHostModel.query().where("is_deleted", 0).withGraphFetched("[certificate]"); responseObject.redirection_hosts = internalHost._getHostsWithDomains(redirRes, domainNames); responseObject.total_count += responseObject.redirection_hosts.length; - const deadRes = await deadHostModel.query().where("is_deleted", 0); + const deadRes = await deadHostModel.query().where("is_deleted", 0).withGraphFetched("[certificate]"); responseObject.dead_hosts = internalHost._getHostsWithDomains(deadRes, domainNames); responseObject.total_count += responseObject.dead_hosts.length; diff --git a/backend/internal/nginx.js b/backend/internal/nginx.js index a50e0780d..378b53591 100644 --- a/backend/internal/nginx.js +++ b/backend/internal/nginx.js @@ -7,6 +7,7 @@ import errs from "../lib/error.js"; import utils from "../lib/utils.js"; import { debug, nginx as logger } from "../logger.js"; import accessListModel from "../models/access_list.js"; +import certificateModel from "../models/certificate.js"; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -209,11 +210,13 @@ const internalNginx = { * @param {Object} host * @returns {Promise} */ - generateConfig: (host_type, host_row) => { + generateConfig: async (host_type, host_row) => { // Prevent modifying the original object: const host = JSON.parse(JSON.stringify(host_row)); const nice_host_type = internalNginx.getFileFriendlyHostType(host_type); + await internalNginx.loadRenderRelations(nice_host_type, host); + debug(logger, `Generating ${nice_host_type} Config:`, JSON.stringify(host, null, 2)); const renderEngine = utils.getRenderEngine(); @@ -299,6 +302,53 @@ const internalNginx = { }); }, + /** + * The templates rely on the certificate and access list relations being loaded. + * Not every caller fetches them (or fetches them fully), and when they're missing + * the config silently renders without SSL or without any access rules (#5919). + * Load anything that is referenced but not loaded onto the given host object. + * + * @param {String} host_type + * @param {Object} host + * @returns {Promise} + */ + loadRenderRelations: async (host_type, host) => { + if (host.certificate_id > 0 && host.certificate?.id !== host.certificate_id) { + const certificate = await certificateModel + .query() + .where("is_deleted", 0) + .andWhere("id", host.certificate_id) + .first(); + host.certificate = certificate ? JSON.parse(JSON.stringify(certificate)) : null; + } + + if (host_type === "proxy_host" && host.access_list_id > 0) { + if ( + host.access_list?.id !== host.access_list_id || + !Array.isArray(host.access_list.clients) || + !Array.isArray(host.access_list.items) + ) { + const accessList = await accessListModel + .query() + .where("is_deleted", 0) + .andWhere("id", host.access_list_id) + .withGraphFetched("[clients,items]") + .first(); + host.access_list = accessList ? JSON.parse(JSON.stringify(accessList)) : null; + } + + if (!host.access_list) { + logger.warn( + `Proxy Host #${host.id} references Access List #${host.access_list_id} which does not exist`, + ); + } else if (!host.access_list.clients.length && !host.access_list.items.length) { + logger.warn( + `Proxy Host #${host.id} uses Access List #${host.access_list_id} which has no clients or authorizations, no access restrictions will apply`, + ); + } + } + }, + /** * This generates a temporary nginx config listening on port 80 for the domain names listed * in the certificate setup. It allows the letsencrypt acme challenge to be requested by letsencrypt diff --git a/backend/internal/proxy-host.js b/backend/internal/proxy-host.js index eac0c148a..f079dab02 100644 --- a/backend/internal/proxy-host.js +++ b/backend/internal/proxy-host.js @@ -323,7 +323,7 @@ const internalProxyHost = { .then(() => { return internalProxyHost.get(access, { id: data.id, - expand: ["certificate", "owner", "access_list"], + expand: ["certificate", "owner", "access_list.[clients,items]"], }); }) .then(async (row) => { diff --git a/backend/routes/nginx/certificates.js b/backend/routes/nginx/certificates.js index dea809423..90f279c37 100644 --- a/backend/routes/nginx/certificates.js +++ b/backend/routes/nginx/certificates.js @@ -161,7 +161,7 @@ router } try { - const result = await internalCertificate.validate({ + const result = await internalCertificate.validate(res.locals.access, { files: req.files, }); res.status(200).send(result); diff --git a/docker/docker-compose.ci.yml b/docker/docker-compose.ci.yml index be6f517d3..2aef4e8ff 100644 --- a/docker/docker-compose.ci.yml +++ b/docker/docker-compose.ci.yml @@ -37,6 +37,7 @@ services: - website1.example.com - website2.example.com - website3.example.com + - website4.example.com examplesite: image: "${IMAGE}-examplesite:ci-${BUILD_NUMBER}" diff --git a/docker/docker-compose.dev.yml b/docker/docker-compose.dev.yml index d6b07ec01..20e01e6be 100644 --- a/docker/docker-compose.dev.yml +++ b/docker/docker-compose.dev.yml @@ -16,6 +16,7 @@ services: - website1.example.com - website2.example.com - website3.example.com + - website4.example.com environment: TZ: "${TZ:-Australia/Brisbane}" PUID: 1000 diff --git a/frontend/src/locale/src/fr.json b/frontend/src/locale/src/fr.json index 0911eedc3..88add74bd 100644 --- a/frontend/src/locale/src/fr.json +++ b/frontend/src/locale/src/fr.json @@ -1,6 +1,6 @@ { "2fa.backup-codes-remaining": { - "defaultMessage": "Codes de secours restants : {count}" + "defaultMessage": "Codes de secours restants : {count}" }, "2fa.backup-warning": { "defaultMessage": "Sauvegardez ces codes de secours dans un endroit sûr. Chaque code ne peut être utilisé qu'une seule fois." @@ -71,6 +71,12 @@ "access-list.help.rules-order": { "defaultMessage": "Notez que les directives autoriser et refuser seront appliquées dans l'ordre où elles sont définies." }, + "access-list.inherit": { + "defaultMessage": "Hériter de l'hôte proxy" + }, + "access-list.inherit.subtitle": { + "defaultMessage": "Utilise la liste d'accès de l'hôte proxy" + }, "access-list.pass-auth": { "defaultMessage": "Transmettre l'authentification au serveur en amont" }, @@ -84,10 +90,10 @@ "defaultMessage": "192.168.1.100 ou 192.168.1.0/24 ou 2001:0db8::/32" }, "access-list.satisfy-any": { - "defaultMessage": "Valide n'importe quelle règle" + "defaultMessage": "Satisfaire au moins une condition" }, "access-list.subtitle": { - "defaultMessage": "{utilisateurs} {utilisateurs, plural, one {Utilisateur} other {Utilisateurs}}, {règles} {règles, plural, one {Règle} other {Règles}} - Crée : {date}" + "defaultMessage": "{users} {users, plural, one {Utilisateur} other {Utilisateurs}}, {rules} {rules, plural, one {Règle} other {Règles}} - Créée le {date}" }, "access-lists": { "defaultMessage": "Listes d'accès" @@ -96,11 +102,14 @@ "defaultMessage": "Ajouter" }, "action.add-location": { - "defaultMessage": "Ajouter localisation" + "defaultMessage": "Ajouter un emplacement" }, "action.allow": { "defaultMessage": "Autoriser" }, + "action.clear": { + "defaultMessage": "Effacer" + }, "action.close": { "defaultMessage": "Fermer" }, @@ -122,6 +131,9 @@ "action.enable": { "defaultMessage": "Activer" }, + "action.logs": { + "defaultMessage": "Journaux" + }, "action.permissions": { "defaultMessage": "Permissions" }, @@ -129,7 +141,7 @@ "defaultMessage": "Renouveler" }, "action.view-details": { - "defaultMessage": "Voir les Détails" + "defaultMessage": "Voir les détails" }, "auditlogs": { "defaultMessage": "Journaux d'audit" @@ -147,7 +159,7 @@ "defaultMessage": "Certificat" }, "certificate.custom-certificate-key": { - "defaultMessage": "Clé du Certificat" + "defaultMessage": "Clé du certificat" }, "certificate.custom-intermediate": { "defaultMessage": "Certificat intermédiaire" @@ -168,7 +180,7 @@ "defaultMessage": "Non utilisé" }, "certificate.renew": { - "defaultMessage": "Renouveler Certificat" + "defaultMessage": "Renouveler le certificat" }, "certificates": { "defaultMessage": "Certificats" @@ -189,7 +201,7 @@ "defaultMessage": "Ces données seront stockées en clair dans la base de données et dans un fichier !" }, "certificates.dns.propagation-seconds": { - "defaultMessage": "Propagation Seconds" + "defaultMessage": "Délai de propagation (secondes)" }, "certificates.dns.propagation-seconds-note": { "defaultMessage": "Laisser vide pour utiliser la valeur par défaut du plugin. Nombre de secondes à attendre pour la propagation DNS." @@ -216,10 +228,10 @@ "defaultMessage": "Votre serveur est accessible et la création de certificats devrait être possible." }, "certificates.http.reachability-other": { - "defaultMessage": "Un serveur a été trouvé sur ce domaine, mais il a renvoyé un code d'état inattendu {code}. S'agit-il du serveur NPM ? Veuillez vérifier que votre domaine pointe bien vers l'adresse IP où votre instance NPM est exécutée." + "defaultMessage": "Un serveur a été trouvé sur ce domaine, mais il a renvoyé un code d'état inattendu {code}. S'agit-il du serveur NPM ? Veuillez vérifier que votre domaine pointe bien vers l'adresse IP où votre instance NPM est exécutée." }, "certificates.http.reachability-wrong-data": { - "defaultMessage": "Un serveur a été trouvé sur ce domaine, mais il a renvoyé des données inattendues. S'agit-il du serveur NPM ? Veuillez vérifier que votre domaine pointe bien vers l'adresse IP où votre instance NPM est exécutée." + "defaultMessage": "Un serveur a été trouvé sur ce domaine, mais il a renvoyé des données inattendues. S'agit-il du serveur NPM ? Veuillez vérifier que votre domaine pointe bien vers l'adresse IP où votre instance NPM est exécutée." }, "certificates.http.test-results": { "defaultMessage": "Résultats du test" @@ -255,7 +267,7 @@ "defaultMessage": "Autorisations" }, "column.custom-locations": { - "defaultMessage": "Emplacement personnalisé" + "defaultMessage": "Emplacements personnalisés" }, "column.destination": { "defaultMessage": "Destination" @@ -266,6 +278,9 @@ "column.email": { "defaultMessage": "e-mail" }, + "column.error": { + "defaultMessage": "Erreurs" + }, "column.event": { "defaultMessage": "Évènement" }, @@ -294,13 +309,13 @@ "defaultMessage": "Règles" }, "column.satisfy": { - "defaultMessage": "Valide" + "defaultMessage": "Conditions requises" }, "column.satisfy-all": { - "defaultMessage": "All" + "defaultMessage": "Toutes" }, "column.satisfy-any": { - "defaultMessage": "Any" + "defaultMessage": "Au moins une" }, "column.scheme": { "defaultMessage": "Schéma" @@ -315,7 +330,7 @@ "defaultMessage": "Statut" }, "created-on": { - "defaultMessage": "Créé : {date}" + "defaultMessage": "Création : {date}" }, "dashboard": { "defaultMessage": "Tableau de bord" @@ -342,10 +357,10 @@ "defaultMessage": "Commencez à écrire pour ajouter un domaine…" }, "domain-names.wildcards-not-permitted": { - "defaultMessage": "Les Wildcards ne sont pas permises dans ce cas" + "defaultMessage": "Les wildcards ne sont pas permises dans ce cas" }, "domain-names.wildcards-not-supported": { - "defaultMessage": "Les Wildcards ne sont pas prises en charge par cette autorité de certification." + "defaultMessage": "Les wildcards ne sont pas prises en charge par cette autorité de certification." }, "domains.advanced": { "defaultMessage": "Avancé" @@ -375,7 +390,7 @@ "defaultMessage": "Aucun résultat trouvé" }, "empty-subtitle": { - "defaultMessage": "Pourquoi n'en créez-vous pas un ?" + "defaultMessage": "Pourquoi n'en créez-vous pas un ?" }, "enabled": { "defaultMessage": "Activé" @@ -390,7 +405,7 @@ "defaultMessage": "Adresse e-mail ou mot de passe invalide" }, "error.invalid-domain": { - "defaultMessage": "Domaine invalide : {domain}" + "defaultMessage": "Domaine invalide : {domain}" }, "error.invalid-email": { "defaultMessage": "Adresse e-mail invalide" @@ -417,16 +432,16 @@ "defaultMessage": "Ceci est obligatoire" }, "expires.on": { - "defaultMessage": "Expire : {date}" + "defaultMessage": "Expire le {date}" }, "footer.github-fork": { - "defaultMessage": "Forkez-moi sur Github" + "defaultMessage": "Forkez-moi sur GitHub" }, "host.flags.block-exploits": { "defaultMessage": "Bloquer les exploits courants" }, "host.flags.cache-assets": { - "defaultMessage": "Ressources du cache" + "defaultMessage": "Mise en cache des ressources" }, "host.flags.preserve-path": { "defaultMessage": "Préserver le chemin" @@ -435,10 +450,10 @@ "defaultMessage": "Protocoles" }, "host.flags.websockets-upgrade": { - "defaultMessage": "Prise en charge de Websockets" + "defaultMessage": "Prise en charge de WebSockets" }, "host.forward-port": { - "defaultMessage": "Port de redirection" + "defaultMessage": "Port de destination" }, "host.forward-scheme": { "defaultMessage": "Schéma" @@ -461,6 +476,12 @@ "loading": { "defaultMessage": "Chargement…" }, + "location.advanced-config": { + "defaultMessage": "Configuration Nginx personnalisée" + }, + "location.filter": { + "defaultMessage": "Filtrer par chemin ou destination" + }, "login.2fa-code": { "defaultMessage": "Code de vérification" }, @@ -479,11 +500,56 @@ "login.title": { "defaultMessage": "Connectez-vous à votre compte" }, + "logs": { + "defaultMessage": "Journaux" + }, + "logs.channel.access": { + "defaultMessage": "Accès" + }, + "logs.channel.error": { + "defaultMessage": "Erreurs" + }, + "logs.download": { + "defaultMessage": "Télécharger" + }, + "logs.empty": { + "defaultMessage": "Aucune entrée pour le moment." + }, + "logs.level": { + "defaultMessage": "Niveau" + }, + "logs.level.all": { + "defaultMessage": "Tous les niveaux" + }, + "logs.lines": { + "defaultMessage": "Lignes" + }, + "logs.live": { + "defaultMessage": "En direct" + }, + "logs.paused": { + "defaultMessage": "En pause" + }, + "logs.refresh": { + "defaultMessage": "Actualiser" + }, + "logs.search-placeholder": { + "defaultMessage": "Rechercher dans les journaux…" + }, + "logs.source": { + "defaultMessage": "Source" + }, + "logs.source.system": { + "defaultMessage": "Système" + }, + "logs.truncated-warning": { + "defaultMessage": "Seule la partie la plus récente de ce fichier est affichée." + }, "nginx-config.label": { "defaultMessage": "Configuration Nginx personnalisée" }, "nginx-config.placeholder": { - "defaultMessage": "# Mettez ici votre configuration Nginx personnalisé à vos risques et périls !" + "defaultMessage": "# Mettez ici votre configuration Nginx personnalisée à vos risques et périls !" }, "no-permission-error": { "defaultMessage": "Vous n'avez pas la permission de voir ce contenu." @@ -597,7 +663,7 @@ "defaultMessage": "Hôte proxy" }, "proxy-host.forward-host": { - "defaultMessage": "Nom d'hôte de redirection / IP" + "defaultMessage": "Nom d'hôte / IP de destination" }, "proxy-hosts": { "defaultMessage": "Hôtes proxy" @@ -606,7 +672,7 @@ "defaultMessage": "{count} {count, plural, one {Hôte proxy} other {Hôtes proxy}}" }, "public": { - "defaultMessage": "Publique" + "defaultMessage": "Public" }, "redirection-host": { "defaultMessage": "Hôte de redirection" @@ -669,7 +735,7 @@ "defaultMessage": "Page de félicitations" }, "settings.default-site.description": { - "defaultMessage": "ce qu'il faut afficher lorsqu'un hôte inconnu est détecté par Nginx" + "defaultMessage": "Ce qu'il faut afficher lorsqu'un hôte inconnu est détecté par Nginx" }, "settings.default-site.html": { "defaultMessage": "HTML personnalisé" @@ -696,7 +762,7 @@ "defaultMessage": "Stream" }, "stream.forward-host": { - "defaultMessage": "Hôte destinataire" + "defaultMessage": "Hôte de destination" }, "stream.forward-host.placeholder": { "defaultMessage": "example.com ou 10.0.0.1 ou 2001:db8:3333:4444:5555:6666:7777:8888" @@ -720,7 +786,7 @@ "defaultMessage": "Test" }, "update-available": { - "defaultMessage": "Mise à jour disponible : {latestVersion}" + "defaultMessage": "Mise à jour disponible : {latestVersion}" }, "user": { "defaultMessage": "Utilisateur" @@ -759,10 +825,10 @@ "defaultMessage": "Définir les autorisations pour {name}" }, "user.switch-dark": { - "defaultMessage": "Passer au mode Sombre" + "defaultMessage": "Passer au mode sombre" }, "user.switch-light": { - "defaultMessage": "Passer au mode Lumineux" + "defaultMessage": "Passer au mode clair" }, "user.two-factor": { "defaultMessage": "Auth. à deux facteurs" diff --git a/test/cypress/e2e/api/AccessListHostToggle.cy.js b/test/cypress/e2e/api/AccessListHostToggle.cy.js new file mode 100644 index 000000000..ee1bee0dc --- /dev/null +++ b/test/cypress/e2e/api/AccessListHostToggle.cy.js @@ -0,0 +1,210 @@ +/// + +// Regression tests for #5919, #4286 and #5710: access list rules must survive +// every path that re-renders a proxy host config, not just the initial save. +describe('Access Lists across Proxy Host disable/enable', () => { + const domain = 'website4.example.com'; + + const creds = { + username: 'toggle-user', + password: 'toggle-pass', + }; + + let token; + let authListId; + let clientListId; + let hostId; + + /** + * Requests a path on the proxy host directly (bypassing squid) + * and yields the HTTP status code + * + * @param {object} [auth] + * @param {string} auth.username + * @param {string} auth.password + */ + const request = (auth) => { + const authArg = auth ? `-u '${auth.username}:${auth.password}'` : ''; + return cy.exec(`curl --noproxy '*' -s -o /dev/null -w '%{http_code}' ${authArg} http://${domain}/`) + .then((result) => { + expect(result.exitCode).to.eq(0); + return result.stdout.trim(); + }); + }; + + // nginx reloads are signalled and return immediately, so the old + // config can still be served for a moment after an API change. + // Retry until the expected status is seen. + const expectStatus = (auth, status) => { + let last = null; + cy.waitUntil(() => request(auth).then((res) => { + last = res; + return res === status; + }), { + timeout: 15000, + interval: 500, + errorMsg: () => `${domain} did not return ${status}, last status: ${last}`, + }); + }; + + const createAccessList = (data) => { + return cy.task('backendApiPost', { + token: token, + path: '/api/nginx/access-lists', + data: { + satisfy_any: false, + pass_auth: false, + items: [], + clients: [], + ...data, + } + }).then((res) => { + cy.validateSwaggerSchema('post', 201, '/nginx/access-lists', res); + expect(res).to.have.property('id'); + expect(res.id).to.be.greaterThan(0); + return cy.wrap(res.id); + }); + }; + + const setHostAccessList = (accessListId) => { + cy.task('backendApiPut', { + token: token, + path: `/api/nginx/proxy-hosts/${hostId}`, + data: { + access_list_id: accessListId, + } + }).then((data) => { + // No swagger validation here: with a host access list set, the expanded + // access_list in the response has no proxy_host_count, which the schema requires + expect(data).to.have.property('access_list_id', accessListId); + }); + }; + + const toggleHost = () => { + cy.task('backendApiPost', { + token: token, + path: `/api/nginx/proxy-hosts/${hostId}/disable`, + }).then((data) => { + cy.validateSwaggerSchema('post', 200, '/nginx/proxy-hosts/{hostID}/disable', data); + expect(data).to.be.equal(true); + }); + + cy.task('backendApiPost', { + token: token, + path: `/api/nginx/proxy-hosts/${hostId}/enable`, + }).then((data) => { + cy.validateSwaggerSchema('post', 200, '/nginx/proxy-hosts/{hostID}/enable', data); + expect(data).to.be.equal(true); + }); + }; + + before(() => { + cy.resetUsers(); + cy.getToken().then((tok) => { + token = tok; + }); + }); + + it('Should be able to create an auth access list and a client access list', () => { + createAccessList({ + name: 'Toggle Auth', + items: [creds], + }).then((id) => { + authListId = id; + }); + + // The test runner is never in this range, so it must always be denied + createAccessList({ + name: 'Toggle Clients', + clients: [ + { + directive: 'allow', + address: '203.0.113.0/24', + } + ], + }).then((id) => { + clientListId = id; + }); + }); + + it('Should be able to create a proxy host without an access list', () => { + cy.task('backendApiPost', { + token: token, + path: '/api/nginx/proxy-hosts', + data: { + domain_names: [domain], + forward_scheme: 'http', + forward_host: 'examplesite', + forward_port: 80, + access_list_id: 0, + certificate_id: 0, + meta: { + dns_challenge: false + }, + advanced_config: '', + locations: [], + block_exploits: false, + caching_enabled: false, + allow_websocket_upgrade: false, + http2_support: false, + hsts_enabled: false, + hsts_subdomains: false, + ssl_forced: false + } + }).then((data) => { + cy.validateSwaggerSchema('post', 201, '/nginx/proxy-hosts', data); + expect(data).to.have.property('id'); + expect(data.id).to.be.greaterThan(0); + hostId = data.id; + }); + + expectStatus(null, '200'); + }); + + it('Should enforce an auth access list applied to an existing host', () => { + setHostAccessList(authListId); + expectStatus(null, '401'); + expectStatus(creds, '200'); + }); + + it('Should still enforce the auth access list after the host is disabled and enabled', () => { + toggleHost(); + expectStatus(null, '401'); + expectStatus(creds, '200'); + }); + + it('Should enforce a client access list applied to an existing host', () => { + setHostAccessList(clientListId); + expectStatus(null, '403'); + }); + + it('Should still enforce the client access list after the host is disabled and enabled', () => { + toggleHost(); + expectStatus(null, '403'); + }); + + it('Should be able to delete the proxy host and access lists', () => { + cy.task('backendApiDelete', { + token: token, + path: `/api/nginx/proxy-hosts/${hostId}`, + }).then((data) => { + cy.validateSwaggerSchema('delete', 200, '/nginx/proxy-hosts/{hostID}', data); + expect(data).to.be.equal(true); + }); + + // Each delete signals an nginx reload and returns immediately. A request + // made while the workers are being swapped can be reset by the nginx + // serving the API (502 from squid), so let each reload settle first. + [authListId, clientListId].forEach((id) => { + cy.wait(1500); + cy.task('backendApiDelete', { + token: token, + path: `/api/nginx/access-lists/${id}`, + }).then((data) => { + cy.validateSwaggerSchema('delete', 200, '/nginx/access-lists/{listID}', data); + expect(data).to.be.equal(true); + }); + }); + }); + +}); diff --git a/test/cypress/e2e/api/Certificates.cy.js b/test/cypress/e2e/api/Certificates.cy.js index 7d75d40cf..cc197bc36 100644 --- a/test/cypress/e2e/api/Certificates.cy.js +++ b/test/cypress/e2e/api/Certificates.cy.js @@ -35,6 +35,63 @@ describe('Certificates endpoints', () => { }); }); + it('Unauthenticated user cannot validate custom certificate', () => { + cy.task('backendApiPostFiles', { + path: '/api/nginx/certificates/validate', + files: { + certificate: certFile, + certificate_key: keyFile, + }, + returnOnError: true, + }).then((data) => { + expect(data.error.code).to.equal(403); + }); + }); + + it('User with certificates view permission cannot validate custom certificate', () => { + const viewer = { + email: 'viewer@example.com', + secret: 'changeme', + }; + + cy.task('backendApiPost', { + token: token, + path: '/api/users', + data: { + name: 'Certificate Viewer', + nickname: 'Viewer', + email: viewer.email, + roles: ['user'], + auth: { + type: 'password', + secret: viewer.secret, + }, + }, + }).then((user) => { + cy.task('backendApiPut', { + token: token, + path: `/api/users/${user.id}/permissions`, + data: { + certificates: 'view', + }, + }); + + cy.getToken(null, {identity: viewer.email, secret: viewer.secret}).then((viewerToken) => { + cy.task('backendApiPostFiles', { + token: viewerToken, + path: '/api/nginx/certificates/validate', + files: { + certificate: certFile, + certificate_key: keyFile, + }, + returnOnError: true, + }).then((data) => { + expect(data.error.code).to.equal(403); + }); + }); + }); + }); + it('Custom certificate lifecycle', () => { // Create custom cert cy.task('backendApiPost', { diff --git a/test/cypress/plugins/backendApi/client.mjs b/test/cypress/plugins/backendApi/client.mjs index 78618abb2..5c0daa5c0 100644 --- a/test/cypress/plugins/backendApi/client.mjs +++ b/test/cypress/plugins/backendApi/client.mjs @@ -1,3 +1,4 @@ +import http from "node:http"; import axios from "axios"; import logger from "./logger.mjs"; @@ -8,6 +9,10 @@ const BackendApi = function (config, token) { this.axios = axios.create({ baseURL: config.baseUrl, timeout: 90000, + // Don't reuse sockets: a pooled keep-alive connection that squid or the + // backend has since closed fails with a 502 (ERR_READ_ERROR 104), which + // made tests flaky. + httpAgent: new http.Agent({ keepAlive: false }), }); }; diff --git a/test/docker/nginx/conf.d/website123.conf b/test/docker/nginx/conf.d/website123.conf index 656f3ade4..eefb233bc 100644 --- a/test/docker/nginx/conf.d/website123.conf +++ b/test/docker/nginx/conf.d/website123.conf @@ -1,6 +1,6 @@ server { listen 80; - server_name website1.example.com website2.example.com website3.example.com; + server_name website1.example.com website2.example.com website3.example.com website4.example.com; root /www; index index.html;