π A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!
Vue awesomedashboarddockerhomelabhomepagemitnodejsorganizationproductivitypwaself-hostedstartpagevue
β»οΈ Moves YAML serving into one auth gate, replacing the static guard
Alicia Sykes63afcc6c3274
diff --git a/services/app.js b/services/app.jsindex 25acb704..94432249 100644--- a/services/app.js+++ b/services/app.js@@ -30,16 +30,16 @@ let config = require('./utils/config-validator'); // Validate config file and loconst statusCheck = require('./endpoints/status-check'); // Used by the status check feature, uses GETconst pingCheck = require('./endpoints/ping-check'); // Used by the ping check feature, uses GETconst saveConfig = require('./endpoints/save-config'); // Saves users new conf.yml to file-system+const serveConfig = require('./endpoints/serve-config'); // Serves conf.yml and other YAML, behind authconst systemInfo = require('./endpoints/system-info'); // Basic system info, for resource widgetconst sslServer = require('./utils/ssl-server'); // TLS-enabled web server-const blockStaticYaml = require('./utils/block-static-yaml'); // Keeps YAML out of static servingconst corsProxy = require('./endpoints/cors-proxy'); // Enables API requests to CORS-blocked servicesconst getUser = require('./endpoints/get-user'); // Enables server side user lookupconst openSearch = require('./endpoints/opensearch'); // Descriptor for browser keyword searchconst aliasTarget = require('./endpoints/alias-target'); // Resolves /<alias> to an item's URLconst { apiEnabledGate, apiErrorHandler, createApiRouter } = require('./endpoints/api'); // Opt-in REST API-const { loadOidcSettings, createOidcMiddleware, maybeBootstrapConfig } = require('./utils/auth-oidc');+const { loadOidcSettings, createOidcMiddleware } = require('./utils/auth-oidc');/* Service endpoint URL paths (see also serviceEndpoints in src/utils/config/defaults.js) */const ENDPOINTS = {@@ -346,36 +346,9 @@ const app = express()safeEnd(res, errBody(e), 500);}})- // Middleware to serve any .yml/.yaml files in USER_DATA_DIR with optional protection- // Note: returns stripped version if auth configured but not yet authenticated- .get(/\.ya?ml$/i, bootstrapAuth, (req, res) => {- const ymlFile = req.path.split('/').pop();- const userDataDir = path.resolve(rootDir, process.env.USER_DATA_DIR || 'user-data');- const filePath = path.resolve(userDataDir, ymlFile);- if (authIsConfigured) {- res.set('Cache-Control', 'private, no-store').set('Vary', 'Authorization');- try {- const stripped = maybeBootstrapConfig(filePath, {- isRootConfig: ymlFile === 'conf.yml',- isAuthenticated: Boolean(req.auth),- guestAccessOn,- });- if (stripped) return res.type('text/yaml').send(stripped);- } catch (e) {- printWarning(`Failed to read or parse ${ymlFile}`, e);- return safeEnd(res, errBody('Could not read config'), 500);- }- // Not authenticated, not main conf.yml- if (!req.auth && !guestAccessOn) {- return res.status(401).json({ success: false, message: 'Unauthorized' });- }- }- res.sendFile(ymlFile, { root: userDataDir }, (err) => {- if (err) safeEnd(res, errBody(`Could not read ${ymlFile}`), 404);- });- })- // Serves up static files, except YAML (handled above)- .use(blockStaticYaml)+ // Serves .yml/.yaml files in USER_DATA_DIR, with optional protection+ .use(serveConfig({ bootstrapAuth, authIsConfigured, guestAccessOn }))+ // Serves up static files.use(express.static(path.resolve(rootDir, process.env.USER_DATA_DIR || 'user-data'))).use(express.static(path.join(rootDir, 'dist'))).use(express.static(path.join(rootDir, 'public'), { index: 'initialization.html' }))diff --git a/services/endpoints/serve-config.js b/services/endpoints/serve-config.jsnew file mode 100644index 00000000..d83c3675--- /dev/null+++ b/services/endpoints/serve-config.js@@ -0,0 +1,51 @@+/**+ * Serves YAML config files from the user data directory, behind auth if enabled+ */+const path = require('path');+const { maybeBootstrapConfig } = require('../utils/auth-oidc');++const rootDir = path.join(__dirname, '..', '..');++/* Returns the YAML file a request is for (including Windows aliases), or null */+const yamlFilename = (req) => {+ if (req.method !== 'GET' && req.method !== 'HEAD') return null;+ let file;+ try { file = path.normalize(decodeURIComponent(req.path)); } catch (e) { return null; }+ return /\.(ya?ml|yam)(:|$)/i.test(file) ? path.basename(file) : null;+};++module.exports = ({ bootstrapAuth, authIsConfigured, guestAccessOn }) => {+ const userDataDir = path.resolve(rootDir, process.env.USER_DATA_DIR || 'user-data');++ const serve = (req, res, file) => {+ if (authIsConfigured) {+ res.set('Cache-Control', 'private, no-store').set('Vary', 'Authorization');+ try {+ const stripped = maybeBootstrapConfig(path.resolve(userDataDir, file), {+ isRootConfig: file === 'conf.yml',+ isAuthenticated: Boolean(req.auth),+ guestAccessOn,+ });+ if (stripped) return res.type('text/yaml').send(stripped);+ } catch (e) {+ console.warn(`Failed to read or parse ${file}`, e);+ return res.status(500).json({ success: false, message: 'Could not read config' });+ }+ // Not authenticated, not main conf.yml+ if (!req.auth && !guestAccessOn) {+ return res.status(401).json({ success: false, message: 'Unauthorized' });+ }+ }+ return res.sendFile(file, { root: userDataDir }, (err) => {+ if (err && !res.headersSent) {+ res.status(404).json({ success: false, message: `Could not read ${file}` });+ }+ });+ };++ return (req, res, next) => {+ const file = yamlFilename(req);+ if (!file) return next();+ return bootstrapAuth(req, res, (err) => (err ? next(err) : serve(req, res, file)));+ };+};diff --git a/services/utils/block-static-yaml.js b/services/utils/block-static-yaml.jsdeleted file mode 100644index 5ee6927d..00000000--- a/services/utils/block-static-yaml.js+++ /dev/null@@ -1,11 +0,0 @@-/**- * Express middleware function which stope static from serving YAML paths- */-const path = require('path');--module.exports = (req, res, next) => {- let file;- try { file = path.normalize(decodeURIComponent(req.path)); } catch (e) { return next(); }- if (!/\.(ya?ml|yam)(:|$)/i.test(file)) return next();- return res.status(404).json({ success: false, message: 'Not Found' });-};diff --git a/tests/server/conf-no-server-check.test.js b/tests/server/conf-no-server-check.test.jsindex ab23841d..4225088d 100644--- a/tests/server/conf-no-server-check.test.js+++ b/tests/server/conf-no-server-check.test.js@@ -29,6 +29,7 @@ beforeAll(() => {tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dashy-no-check-test-'));fs.writeFileSync(path.join(tmpDir, 'conf.yml'), CONF);fs.writeFileSync(path.join(tmpDir, 'sub.yml'), 'pageInfo:\n title: Sub\n');+ fs.writeFileSync(path.join(tmpDir, 'my page.yml'), 'pageInfo:\n title: Sub\n');process.env.USER_DATA_DIR = tmpDir;delete require.cache[require.resolve('../../services/app')];delete require.cache[require.resolve('../../services/utils/auth-oidc')];@@ -50,6 +51,10 @@ describe('OIDC with disableServerSideCheck', () => {expect(res.status).toBe(200);});+ it('serves yml files with encoded characters in the name', async () => {+ expect((await request(app).get('/my%20page.yml')).status).toBe(200);+ });+it('does not reject API routes on an invalid Bearer token', async () => {const res = await request(app).get('/status-check')diff --git a/tests/server/conf-strip.test.js b/tests/server/conf-strip.test.jsindex 95144144..30df4f97 100644--- a/tests/server/conf-strip.test.js+++ b/tests/server/conf-strip.test.js@@ -78,8 +78,14 @@ describe('OIDC strip behaviour for /conf.yml', () => {expect(res.status).toBe(401);});- it.each(['/conf%2Eyml', '/sub.ya%6Dl', '/sub.yml%2F.'])('does not serve %s via static', async (url) => {- expect((await request(app).get(url)).status).toBe(404);+ it.each(['/sub%2Eyml', '/sub.ya%6Dl', '/sub.yml%2F.'])('requires auth for encoded path %s', async (url) => {+ expect((await request(app).get(url)).status).toBe(401);+ });++ it('strips conf.yml requested via an encoded path', async () => {+ const body = yamlLoad((await request(app).get('/conf%2Eyml')).text);+ expect(body._bootstrap.authenticated).toBe(false);+ expect(body.sections).toBeUndefined();});it('falls through to bootstrap on conf.yml when Bearer fails to verify', async () => {