Skip to content

armgit / dashy

Public Imported from GitHub
0

πŸš€ A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!

πŸ›‚ Stricter config access for OIDC/Keycloak

Alicia Sykes85e1ce73a68c
diff --git a/services/app.js b/services/app.js
index da68f39e..d2991267 100644
--- a/services/app.js
+++ b/services/app.js
@@ -30,7 +30,8 @@ const systemInfo = require('./system-info'); // Basic system info, for resource
const sslServer = require('./ssl-server'); // TLS-enabled web server
const corsProxy = require('./cors-proxy'); // Enables API requests to CORS-blocked services
const getUser = require('./get-user'); // Enables server side user lookup
-const { loadOidcSettings, createOidcMiddleware } = require('./auth-oidc'); // Server-side OIDC/Keycloak token verification
+
+const { loadOidcSettings, createOidcMiddleware, maybeBootstrapConfig } = require('./auth-oidc');
/* Service endpoint URL paths (see also serviceEndpoints in src/utils/config/defaults.js) */
const ENDPOINTS = {
@@ -178,6 +179,7 @@ const authIsConfigured = Boolean(
|| (process.env.BASIC_AUTH_USERNAME && process.env.BASIC_AUTH_PASSWORD)
|| (initialAuthConfig.enableHeaderAuth && initialAuthConfig.headerAuth),
);
+const guestAccessOn = Boolean(initialAuthConfig?.enableGuestAccess);
/* Require an authenticated identity on this request. No-op for zero-auth deploys. */
function requireAuth(req, res, next) {
@@ -276,9 +278,24 @@ const app = express()
}
}))
// Middleware to serve any .yml files in USER_DATA_DIR with optional protection
+ // Note: returns stripped version if auth configured but not yet authenticated
.get('/*.yml', protectConfig, (req, res) => {
const ymlFile = req.path.split('/').pop();
const filePath = path.resolve(rootDir, process.env.USER_DATA_DIR || 'user-data', 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);
+ }
+ }
res.sendFile(filePath, (err) => {
if (err) safeEnd(res, errBody(`Could not read ${ymlFile}`), 404);
});
diff --git a/services/auth-oidc.js b/services/auth-oidc.js
index c41747af..6d8c4fe3 100644
--- a/services/auth-oidc.js
+++ b/services/auth-oidc.js
@@ -12,6 +12,8 @@
* A present-but-invalid token is always rejected.
*/
+const fs = require('fs');
+const yaml = require('js-yaml');
const { createRemoteJWKSet, jwtVerify } = require('jose');
/* Normalise the OIDC / Keycloak block from conf.yml into a unified shape.
@@ -133,8 +135,28 @@ function createOidcMiddleware(settings) {
};
}
+/* Prevent unauthenticated access to config, by making stripped version of conf.yml
+ * When auth is configured AND guest access disabled AND user not yet authenticated
+ * Otherwise, returns null, and the parent proceeds to use full config
+ * Has just enough info (the auth config) to initiate the auth process
+*/
+function maybeBootstrapConfig(filePath, opts) {
+ const { isRootConfig, isAuthenticated, guestAccessOn } = opts;
+ // Pass through, if already authenticated / auth not configured
+ if (!isRootConfig || isAuthenticated || guestAccessOn) return null;
+ const full = yaml.load(fs.readFileSync(filePath, 'utf8')) || {};
+ return yaml.dump({
+ appConfig: {
+ auth: full.appConfig?.auth || {},
+ enableServiceWorker: full.appConfig?.enableServiceWorker,
+ },
+ pageInfo: { title: `Login | ${full.pageInfo?.title || 'Dashy'}` },
+ });
+}
+
module.exports = {
loadOidcSettings,
createOidcMiddleware,
deriveIsAdmin,
+ maybeBootstrapConfig,
};
diff --git a/src/assets/locales/en.json b/src/assets/locales/en.json
index 311de5b6..4f607886 100644
--- a/src/assets/locales/en.json
+++ b/src/assets/locales/en.json
@@ -48,6 +48,7 @@
"error-no-user-configured": "Authentication is not enabled, or no users have been configured",
"error-go-home-button": "Go Home",
"logged-in-guest": "Logged in as Guest, Redirecting...",
+ "authenticated-redirecting": "Authenticated, Redirecting...",
"error-guest-access": "Guest Access Not Allowed"
},
"app-info": {
diff --git a/src/utils/auth/KeycloakAuth.js b/src/utils/auth/KeycloakAuth.js
index 99492ac8..6083066d 100644
--- a/src/utils/auth/KeycloakAuth.js
+++ b/src/utils/auth/KeycloakAuth.js
@@ -1,6 +1,9 @@
import ConfigAccumulator from '@/utils/config/ConfigAccumalator';
import { localStorageKeys } from '@/utils/config/defaults';
import ErrorHandler from '@/utils/logging/ErrorHandler';
+import getApiAuthHeader from '@/utils/auth/getApiAuthHeader';
+import i18n from '@/utils/i18n';
+import { toast } from '@/utils/Toast';
const getAppConfig = () => {
const Accumulator = new ConfigAccumulator();
@@ -37,11 +40,19 @@ class KeycloakAuth {
}
login() {
+ const hadValidToken = Boolean(getApiAuthHeader());
return new Promise((resolve, reject) => {
this.keycloakClient.init({ onLoad: 'check-sso', responseMode: 'query' })
.then((auth) => {
if (auth) {
this.storeKeycloakInfo();
+ // We've returned back from Keycloak login, and a fresh token has landed
+ // Validate, then hard redirect home to fetch to (now fully readable) config
+ if (!hadValidToken && getApiAuthHeader()) {
+ toast(i18n.global.t('login.authenticated-redirecting'), { type: 'success' });
+ setTimeout(() => window.location.replace('/'), 500);
+ return undefined;
+ }
return resolve();
} else if (isKeycloakGuestAccessEnabled()) {
// Don't redirect, allow guest access
diff --git a/src/utils/auth/OidcAuth.js b/src/utils/auth/OidcAuth.js
index aa99485a..c0e6e0f0 100644
--- a/src/utils/auth/OidcAuth.js
+++ b/src/utils/auth/OidcAuth.js
@@ -2,6 +2,9 @@ import ConfigAccumulator from '@/utils/config/ConfigAccumalator';
import { localStorageKeys } from '@/utils/config/defaults';
import ErrorHandler from '@/utils/logging/ErrorHandler';
import { statusMsg, statusErrorMsg } from '@/utils/logging/CoolConsole';
+import getApiAuthHeader from '@/utils/auth/getApiAuthHeader';
+import i18n from '@/utils/i18n';
+import { toast } from '@/utils/Toast';
// Session storage config for storing last sign-in attempt
const SIGNIN_GUARD_KEY = 'dashy.oidc.signin-attempt';
@@ -61,6 +64,7 @@ class OidcAuth {
}
async login() {
+ const hadValidToken = Boolean(getApiAuthHeader());
const url = new URL(window.location.href);
const code = url.searchParams.get('code');
const providerError = url.searchParams.get('error');
@@ -82,7 +86,8 @@ class OidcAuth {
);
}
this.persistUserInfo(callbackUser);
- window.location.href = '/';
+ toast(i18n.global.t('login.authenticated-redirecting'), { type: 'success' });
+ setTimeout(() => window.location.replace('/'), 600);
return;
}
@@ -103,6 +108,11 @@ class OidcAuth {
}
} else {
this.persistUserInfo(user);
+ // Fresh token established this run: reload to refetch config with Bearer
+ if (!hadValidToken && getApiAuthHeader()) {
+ toast(i18n.global.t('login.authenticated-redirecting'), { type: 'success' });
+ setTimeout(() => window.location.replace('/'), 500);
+ }
}
}
diff --git a/tests/server/conf-strip.test.js b/tests/server/conf-strip.test.js
new file mode 100644
index 00000000..6b4aa805
--- /dev/null
+++ b/tests/server/conf-strip.test.js
@@ -0,0 +1,73 @@
+// @vitest-environment node
+import fs from 'fs';
+import os from 'os';
+import path from 'path';
+import { load as yamlLoad } from 'js-yaml';
+import { describe, it, expect, beforeAll } from 'vitest';
+import request from 'supertest';
+
+const FULL_CONF = `appConfig:
+ enableServiceWorker: true
+ theme: dark
+ customCss: '.secret { color: red }'
+ auth:
+ enableOidc: true
+ oidc:
+ endpoint: https://example.test/
+ clientId: dashy-test
+ adminGroup: admins
+pageInfo:
+ title: My Dashboard
+sections:
+ - name: Internal Services
+ items:
+ - title: secret-host
+ url: http://10.0.0.5
+`;
+
+let app;
+let tmpDir;
+
+beforeAll(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dashy-strip-test-'));
+ fs.writeFileSync(path.join(tmpDir, 'conf.yml'), FULL_CONF);
+ fs.writeFileSync(path.join(tmpDir, 'sub.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/auth-oidc')];
+ app = require('../../services/app');
+});
+
+describe('OIDC strip behaviour for /conf.yml', () => {
+ it('returns only auth + minimal pageInfo when unauthenticated', async () => {
+ const res = await request(app).get('/conf.yml');
+ expect(res.status).toBe(200);
+ const body = yamlLoad(res.text);
+ expect(body.appConfig.auth.enableOidc).toBe(true);
+ expect(body.appConfig.auth.oidc.clientId).toBe('dashy-test');
+ expect(body.appConfig.enableServiceWorker).toBe(true);
+ expect(body.pageInfo.title).toBe('Login | My Dashboard');
+ expect(body.sections).toBeUndefined();
+ expect(body.appConfig.customCss).toBeUndefined();
+ expect(body.appConfig.theme).toBeUndefined();
+ });
+
+ it('sets cache headers to prevent cross-auth-state caching', async () => {
+ const res = await request(app).get('/conf.yml');
+ expect(res.headers['cache-control']).toContain('no-store');
+ expect(res.headers['vary']).toContain('Authorization');
+ });
+
+ it('does not strip non-root yml files', async () => {
+ const res = await request(app).get('/sub.yml');
+ expect(res.status).toBe(200);
+ expect(res.text).toContain('Sub');
+ });
+
+ it('rejects invalid Bearer tokens with 401 from the OIDC middleware', async () => {
+ const res = await request(app)
+ .get('/conf.yml')
+ .set('Authorization', 'Bearer not-a-real-token');
+ expect(res.status).toBe(401);
+ });
+});