mirror of
https://github.com/tale/headplane.git
synced 2026-08-20 01:42:17 +00:00
Revert "Implement path-based secret loading"
This reverts commit 8ea8c7195f.
This commit is contained in:
+63
-194
@@ -1,5 +1,5 @@
|
||||
import { constants, access, readFile } from 'node:fs/promises';
|
||||
import { env } from 'node:process';
|
||||
import { env, exit } from 'node:process';
|
||||
import { type } from 'arktype';
|
||||
import { configDotenv } from 'dotenv';
|
||||
import { parseDocument } from 'yaml';
|
||||
@@ -7,56 +7,10 @@ import log from '~/utils/log';
|
||||
import { EnvOverrides, envVariables } from './env';
|
||||
import {
|
||||
HeadplaneConfig,
|
||||
PartialHeadplaneConfig,
|
||||
headplaneConfig,
|
||||
partialHeadplaneConfig,
|
||||
} from './schema';
|
||||
|
||||
// A whitelist of known secret paths that should be processed
|
||||
// and loaded from files.
|
||||
const SECRET_PATHS = new Set([
|
||||
'server.cookie_secret_path',
|
||||
'server.agent.authkey_path',
|
||||
'oidc.client_secret_path',
|
||||
'oidc.headscale_api_key_path',
|
||||
'headscale.api_key_path',
|
||||
'headscale.tls_cert_path',
|
||||
'headscale.tls_key_path',
|
||||
]);
|
||||
|
||||
// Custom Error for configuration issues
|
||||
export class ConfigError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'ConfigError';
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function for environment variable interpolation in file paths
|
||||
function interpolateEnvVars(filePath: string): string {
|
||||
const interpolatedPath = filePath.replace(
|
||||
/\$\{(.*?)\}/g,
|
||||
(match, varName) => {
|
||||
const value = env[varName];
|
||||
if (value === undefined) {
|
||||
throw new ConfigError(
|
||||
`Environment variable "${varName}" not found for path interpolation in "${filePath}"`,
|
||||
);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
);
|
||||
if (interpolatedPath !== filePath) {
|
||||
log.debug(
|
||||
'config',
|
||||
'Interpolated path "%s" to "%s"',
|
||||
filePath,
|
||||
interpolatedPath,
|
||||
);
|
||||
}
|
||||
return interpolatedPath;
|
||||
}
|
||||
|
||||
// loadConfig is a has a lifetime of the entire application and is
|
||||
// used to load the configuration for Headplane. It is called once.
|
||||
//
|
||||
@@ -64,44 +18,35 @@ function interpolateEnvVars(filePath: string): string {
|
||||
// But this may not be necessary as a use-case anyways
|
||||
export async function loadConfig({ loadEnv, path }: EnvOverrides) {
|
||||
log.debug('config', 'Loading configuration file: %s', path);
|
||||
|
||||
const isValidPath = await validateConfigPath(path);
|
||||
if (!isValidPath) {
|
||||
throw new ConfigError(`Config file not accessible: "${path}"`);
|
||||
const valid = await validateConfigPath(path);
|
||||
if (!valid) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
const rawData = await loadConfigFile(path);
|
||||
if (typeof rawData !== 'object' || rawData === null) {
|
||||
throw new ConfigError('Loaded configuration data is not a valid object.');
|
||||
const data = await loadConfigFile(path);
|
||||
if (!data) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// Initial validation
|
||||
const initialValidatedConfig = validateConfig({
|
||||
...(rawData as Record<string, unknown>),
|
||||
debug: log.debugEnabled,
|
||||
});
|
||||
|
||||
// Deep clone before mutation by loadSecretsFromFiles
|
||||
let configObject = JSON.parse(JSON.stringify(initialValidatedConfig));
|
||||
|
||||
// Process *_path fields from the YAML file itself, regardless of env loading
|
||||
await loadSecretsFromFiles(configObject);
|
||||
let config = validateConfig({ ...data, debug: log.debugEnabled });
|
||||
if (!config) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (!loadEnv) {
|
||||
log.debug('config', 'Environment variable overrides are disabled');
|
||||
log.debug('config', 'This also disables the loading of a .env file');
|
||||
return validateConfig(configObject); // Re-validate after potential modifications by loadSecretsFromFiles
|
||||
return config;
|
||||
}
|
||||
|
||||
log.info('config', 'Loading a .env file (if available)');
|
||||
configDotenv({ override: true });
|
||||
config = coalesceEnv(config);
|
||||
if (!config) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
configObject = coalesceEnv(configObject);
|
||||
|
||||
// Processes any new or modified secret paths that came from environment variables
|
||||
await loadSecretsFromFiles(configObject);
|
||||
|
||||
return validateConfig(configObject);
|
||||
return config;
|
||||
}
|
||||
|
||||
export async function hp_loadConfig() {
|
||||
@@ -123,15 +68,14 @@ export async function hp_loadConfig() {
|
||||
// }
|
||||
}
|
||||
|
||||
async function validateConfigPath(path: string): Promise<boolean> {
|
||||
async function validateConfigPath(path: string) {
|
||||
try {
|
||||
await access(path, constants.F_OK | constants.R_OK);
|
||||
log.info('config', 'Found a valid configuration file at %s', path);
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
} catch (error) {
|
||||
log.error('config', 'Unable to read a configuration file at %s', path);
|
||||
log.error('config', '%s', message);
|
||||
log.error('config', '%s', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -143,14 +87,11 @@ async function loadConfigFile(path: string): Promise<unknown> {
|
||||
const configYaml = parseDocument(data);
|
||||
if (configYaml.errors.length > 0) {
|
||||
log.error('config', 'Cannot parse configuration file at %s', path);
|
||||
let errorMessages = '';
|
||||
for (const error of configYaml.errors) {
|
||||
log.error('config', ` - ${error.toString()}`);
|
||||
errorMessages += `${error.toString()}\n`;
|
||||
}
|
||||
throw new ConfigError(
|
||||
`YAML parsing error in "${path}":\n${errorMessages}`,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (configYaml.warnings.length > 0) {
|
||||
@@ -165,39 +106,47 @@ async function loadConfigFile(path: string): Promise<unknown> {
|
||||
}
|
||||
|
||||
return configYaml.toJSON() as unknown;
|
||||
} catch (e: unknown) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
} catch (e) {
|
||||
log.error('config', 'Error reading configuration file at %s', path);
|
||||
log.error('config', '%s', message);
|
||||
if (e instanceof ConfigError) throw e;
|
||||
throw new ConfigError(`File read error for "${path}": ${message}`);
|
||||
log.error('config', '%s', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function validateConfig(config: unknown): HeadplaneConfig {
|
||||
export function validateConfig(config: unknown) {
|
||||
log.debug('config', 'Validating Headplane configuration');
|
||||
const result = headplaneConfig(config);
|
||||
|
||||
if (result instanceof type.errors) {
|
||||
log.error('config', 'Error validating Headplane configuration:');
|
||||
let errorSummary = '';
|
||||
for (const [number, error] of result.entries()) {
|
||||
log.error('config', ` - (${number}): ${error.toString()}`);
|
||||
errorSummary += `(${number}): ${error.toString()}\n`;
|
||||
}
|
||||
throw new ConfigError(`Configuration validation failed:\n${errorSummary}`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function coalesceEnv(config: HeadplaneConfig): HeadplaneConfig {
|
||||
function coalesceEnv(config: HeadplaneConfig) {
|
||||
const envConfig: Record<string, unknown> = {};
|
||||
const rootKeys: string[] = Object.values(envVariables);
|
||||
|
||||
// Typescript is still insanely stupid at nullish filtering
|
||||
const vars = Object.entries(env).filter(([key, value]) => {
|
||||
if (!value) return false;
|
||||
if (!key.startsWith('HEADPLANE_')) return false;
|
||||
if (rootKeys.includes(key)) return false;
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!key.startsWith('HEADPLANE_')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Filter out the rootEnv configurations
|
||||
if (rootKeys.includes(key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}) as [string, string][];
|
||||
|
||||
@@ -208,125 +157,45 @@ function coalesceEnv(config: HeadplaneConfig): HeadplaneConfig {
|
||||
'config',
|
||||
` - ${key}=${new Array(value.length).fill('*').join('')}`,
|
||||
);
|
||||
|
||||
let current = envConfig;
|
||||
while (configPath.length > 1) {
|
||||
const pathPart = configPath.shift() as string;
|
||||
if (!(pathPart in current)) current[pathPart] = {};
|
||||
current = current[pathPart] as Record<string, unknown>;
|
||||
const path = configPath.shift() as string;
|
||||
if (!(path in current)) {
|
||||
current[path] = {};
|
||||
}
|
||||
|
||||
current = current[path] as Record<string, unknown>;
|
||||
}
|
||||
|
||||
current[configPath[0]] = value;
|
||||
}
|
||||
|
||||
// coalesceConfig will throw ConfigError if validation of env vars fails.
|
||||
// If it succeeds, toMerge will be a valid PartialHeadplaneConfig.
|
||||
const toMerge = coalesceConfig(envConfig);
|
||||
if (!toMerge) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If coalesceConfig did not throw, proceed to merge.
|
||||
return deepMerge(config, toMerge as DeepPartial<HeadplaneConfig>);
|
||||
// Deep merge the environment variables into the configuration
|
||||
// This will overwrite any existing values in the configuration
|
||||
return deepMerge(config, toMerge);
|
||||
}
|
||||
|
||||
export function coalesceConfig(config: unknown): PartialHeadplaneConfig {
|
||||
export function coalesceConfig(config: unknown) {
|
||||
log.debug('config', 'Revalidating config after coalescing variables');
|
||||
const out = partialHeadplaneConfig(config);
|
||||
|
||||
if (out instanceof type.errors) {
|
||||
log.error(
|
||||
'config',
|
||||
'Error parsing environment variables into partial config:',
|
||||
);
|
||||
let errorSummary = '';
|
||||
log.error('config', 'Error parsing variables:');
|
||||
for (const [number, error] of out.entries()) {
|
||||
log.error('config', ` - (${number}): ${error.toString()}`);
|
||||
errorSummary += `(${number}): ${error.toString()}\n`;
|
||||
}
|
||||
throw new ConfigError(
|
||||
`Environment variable validation failed:\n${errorSummary}`,
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
// Safely interpolates environment variables with error handling
|
||||
function safeInterpolateEnvVars(value: string, fullKeyPath: string): string {
|
||||
try {
|
||||
return interpolateEnvVars(value);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof ConfigError) throw e;
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
log.error('config', 'Interpolation error for %s: %s', fullKeyPath, message);
|
||||
throw new ConfigError(`Interpolation error for ${fullKeyPath}: ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Processes a secret path field by reading the file and setting the value
|
||||
async function processSecretPath(
|
||||
configObject: Record<string, unknown>,
|
||||
key: string,
|
||||
value: string,
|
||||
fullKeyPath: string,
|
||||
): Promise<void> {
|
||||
const valueKey = key.substring(0, key.length - '_path'.length);
|
||||
const processedPath = safeInterpolateEnvVars(value, fullKeyPath);
|
||||
|
||||
log.debug(
|
||||
'config',
|
||||
'Loading value for "%s" from file (via %s): %s',
|
||||
valueKey,
|
||||
fullKeyPath,
|
||||
processedPath,
|
||||
);
|
||||
|
||||
try {
|
||||
const secretContent = await readFile(processedPath, 'utf8');
|
||||
configObject[valueKey] = secretContent.trim();
|
||||
delete configObject[key];
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
log.error(
|
||||
'config',
|
||||
'Failed to read file "%s" for %s: %s',
|
||||
processedPath,
|
||||
fullKeyPath,
|
||||
message,
|
||||
);
|
||||
throw new ConfigError(
|
||||
`File read error for ${fullKeyPath} (path: ${processedPath}): ${message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively processes the config tree to find and evaluate secret paths
|
||||
// and loads their file contents into the config.
|
||||
async function loadSecretsFromFiles(
|
||||
currentConfigLevel: Record<string, unknown>,
|
||||
currentPathPrefix = '',
|
||||
): Promise<void> {
|
||||
for (const key in currentConfigLevel) {
|
||||
if (!Object.prototype.hasOwnProperty.call(currentConfigLevel, key)) {
|
||||
continue; // Skip inherited properties
|
||||
}
|
||||
|
||||
const value = currentConfigLevel[key];
|
||||
const fullKeyPath = currentPathPrefix ? `${currentPathPrefix}.${key}` : key;
|
||||
|
||||
if (typeof value === 'string') {
|
||||
if (SECRET_PATHS.has(fullKeyPath)) {
|
||||
await processSecretPath(currentConfigLevel, key, value, fullKeyPath);
|
||||
} else {
|
||||
currentConfigLevel[key] = safeInterpolateEnvVars(value, fullKeyPath);
|
||||
}
|
||||
}
|
||||
// Recurse through the nested object
|
||||
else if (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
!Array.isArray(value)
|
||||
) {
|
||||
await loadSecretsFromFiles(value as Record<string, unknown>, fullKeyPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type DeepPartial<T> =
|
||||
| {
|
||||
[P in keyof T]?: DeepPartial<T[P]>;
|
||||
|
||||
+35
-408
@@ -1,275 +1,45 @@
|
||||
import { Type, type } from 'arktype';
|
||||
|
||||
// Configuration Schema for Headplane
|
||||
//
|
||||
// For OIDC client secret, Headplane supports two ways to provide it:
|
||||
// 1. Directly in the config file or environment variable (client_secret)
|
||||
// 2. As a path to a file containing the secret (client_secret_path)
|
||||
//
|
||||
// Only one of these should be set. If client_secret_path is provided,
|
||||
// Headplane will read the secret from that file during startup.
|
||||
|
||||
/**
|
||||
* Generates an ArkType schema for a field that can be provided either as a direct value
|
||||
* or via a file path. Enforces mutual exclusivity and optional overall mandatoriness.
|
||||
*
|
||||
* @param key The base name for the field (e.g., "client_secret").
|
||||
* @param options Configuration options:
|
||||
* - mandatory: If true, ensures either the direct value or the path is provided.
|
||||
* - valueType: ArkType string for the direct value (e.g., "string", "32 <= string <= 32"). Defaults to "string".
|
||||
* @returns An ArkType Type definition for the value/path pair.
|
||||
*/
|
||||
function valueOrPath<Key extends string>(
|
||||
key: Key,
|
||||
options?: { mandatory?: boolean; valueType?: string },
|
||||
) {
|
||||
const pathKey = `${key}_path` as const;
|
||||
const valueTypeString = options?.valueType || 'string';
|
||||
|
||||
return type({
|
||||
[key]: valueTypeString,
|
||||
[pathKey]: 'string',
|
||||
}).narrow((obj: unknown, ctx) => {
|
||||
if (typeof obj !== 'object' || obj === null) {
|
||||
return ctx.reject('Expected an object');
|
||||
}
|
||||
|
||||
const valProperty = (obj as Record<string, unknown>)[key];
|
||||
const pathProperty = (obj as Record<string, unknown>)[pathKey];
|
||||
|
||||
const hasVal =
|
||||
valProperty !== undefined &&
|
||||
valProperty !== null &&
|
||||
(typeof valProperty === 'string' ? valProperty !== '' : true);
|
||||
const hasPath =
|
||||
pathProperty !== undefined &&
|
||||
pathProperty !== null &&
|
||||
typeof pathProperty === 'string' &&
|
||||
pathProperty !== '';
|
||||
|
||||
if (hasVal && hasPath) {
|
||||
return ctx.reject(`Only one of "${key}" or "${pathKey}" may be set.`);
|
||||
}
|
||||
if (options?.mandatory && !hasVal && !hasPath) {
|
||||
return ctx.reject(
|
||||
`Either "${key}" or "${pathKey}" must be provided for ${key}.`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
import { type } from 'arktype';
|
||||
|
||||
const stringToBool = type('string | boolean').pipe((v) => Boolean(v));
|
||||
|
||||
// --- Agent Config (defined separately for clarity in partial) ---
|
||||
const agentObjectDefinition = type({
|
||||
'authkey?': '(string | null)',
|
||||
'authkey_path?': '(string | null)',
|
||||
ttl: 'number.integer = 180000',
|
||||
cache_path: 'string = "/var/lib/headplane/agent_cache.json"',
|
||||
})
|
||||
// biome-ignore lint/suspicious/noExplicitAny: ArkType context object
|
||||
.narrow((obj, ctx: any) => {
|
||||
const key = 'authkey';
|
||||
const pathKey = 'authkey_path';
|
||||
const valProperty = obj[key];
|
||||
const pathProperty = obj[pathKey];
|
||||
|
||||
const hasVal =
|
||||
valProperty !== undefined &&
|
||||
valProperty !== null &&
|
||||
(typeof valProperty === 'string' ? valProperty !== '' : true);
|
||||
const hasPath =
|
||||
pathProperty !== undefined &&
|
||||
pathProperty !== null &&
|
||||
typeof pathProperty === 'string' &&
|
||||
pathProperty !== '';
|
||||
|
||||
console.log(
|
||||
`Agent Narrow Check: authkey="${valProperty}", authkey_path="${pathProperty}", hasVal=${hasVal}, hasPath=${hasPath}`,
|
||||
);
|
||||
|
||||
if (hasVal && hasPath) {
|
||||
return ctx.reject(
|
||||
`Only one of agent "${key}" or "${pathKey}" may be set.`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.onDeepUndeclaredKey('reject');
|
||||
|
||||
const partialAgentConfig = type({
|
||||
'authkey??': '(string | null)',
|
||||
'authkey_path??': '(string | null)',
|
||||
'ttl??': 'number.integer',
|
||||
'cache_path??': 'string',
|
||||
})
|
||||
// biome-ignore lint/suspicious/noExplicitAny: ArkType context object
|
||||
.narrow((obj, ctx: any) => {
|
||||
const key = 'authkey?';
|
||||
const pathKey = 'authkey_path?';
|
||||
const valProperty = obj[key];
|
||||
const pathProperty = obj[pathKey];
|
||||
if (valProperty !== undefined && pathProperty !== undefined) {
|
||||
const hasVal =
|
||||
valProperty !== null &&
|
||||
(typeof valProperty === 'string' ? valProperty !== '' : true);
|
||||
const hasPath =
|
||||
pathProperty !== null &&
|
||||
typeof pathProperty === 'string' &&
|
||||
pathProperty !== '';
|
||||
if (hasVal && hasPath) {
|
||||
return ctx.reject(
|
||||
`Only one of agent "${key}" or "${pathKey}" may be set in partial config.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.onDeepUndeclaredKey('reject');
|
||||
|
||||
const agentConfig = agentObjectDefinition.default(() => ({
|
||||
authkey: null,
|
||||
ttl: 180000,
|
||||
cache_path: '/var/lib/headplane/agent_cache.json',
|
||||
}));
|
||||
|
||||
// --- Main Configurations ---
|
||||
const serverConfig = type({
|
||||
host: 'string.ip',
|
||||
port: type('string | number.integer').pipe((v) => Number(v)),
|
||||
'cookie_secret?': '((32 <= string <= 32) | null)',
|
||||
'cookie_secret_path?': 'string',
|
||||
cookie_secret: '32 <= string <= 32',
|
||||
cookie_secure: stringToBool,
|
||||
agent: agentConfig,
|
||||
}).narrow((obj, ctx: any) => {
|
||||
const key = 'cookie_secret';
|
||||
const pathKey = 'cookie_secret_path';
|
||||
const valProperty = obj[key];
|
||||
const pathProperty = obj[pathKey];
|
||||
|
||||
const hasVal =
|
||||
valProperty !== undefined &&
|
||||
valProperty !== null &&
|
||||
(typeof valProperty === 'string' ? valProperty !== '' : true);
|
||||
const hasPath =
|
||||
pathProperty !== undefined &&
|
||||
pathProperty !== null &&
|
||||
typeof pathProperty === 'string' &&
|
||||
pathProperty !== '';
|
||||
|
||||
if (hasVal && hasPath) {
|
||||
return ctx.reject(`Only one of "${key}" or "${pathKey}" may be set.`);
|
||||
}
|
||||
if (!hasVal && !hasPath) {
|
||||
return ctx.reject(
|
||||
`Either "${key}" or "${pathKey}" must be provided for ${key}.`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
agent: type({
|
||||
authkey: 'string = ""',
|
||||
ttl: 'number.integer = 180000', // Default to 3 minutes
|
||||
cache_path: 'string = "/var/lib/headplane/agent_cache.json"',
|
||||
})
|
||||
.onDeepUndeclaredKey('reject')
|
||||
.default(() => ({
|
||||
authkey: '',
|
||||
ttl: 180000,
|
||||
cache_path: '/var/lib/headplane/agent_cache.json',
|
||||
})),
|
||||
});
|
||||
|
||||
const oidcConfig = type({
|
||||
issuer: 'string.url',
|
||||
client_id: 'string',
|
||||
'client_secret?': '(string | null)',
|
||||
'client_secret_path?': 'string',
|
||||
'headscale_api_key?': '(string | null)',
|
||||
'headscale_api_key_path?': 'string',
|
||||
client_secret: 'string?',
|
||||
client_secret_path: 'string?',
|
||||
token_endpoint_auth_method:
|
||||
'"client_secret_basic" | "client_secret_post" | "client_secret_jwt"',
|
||||
'redirect_uri?': 'string.url',
|
||||
user_storage_file: type('string').default('/var/lib/headplane/users.json'),
|
||||
redirect_uri: 'string.url?',
|
||||
user_storage_file: 'string = "/var/lib/headplane/users.json"',
|
||||
disable_api_key_login: stringToBool,
|
||||
headscale_api_key: 'string',
|
||||
strict_validation: stringToBool.default(true),
|
||||
})
|
||||
.narrow((obj, ctx: any) => {
|
||||
const clientSecretKey = 'client_secret';
|
||||
const clientSecretPathKey = 'client_secret_path';
|
||||
const clientSecretVal = obj[clientSecretKey];
|
||||
const clientSecretPathVal = obj[clientSecretPathKey];
|
||||
const hasClientSecretVal =
|
||||
clientSecretVal !== undefined &&
|
||||
clientSecretVal !== null &&
|
||||
(typeof clientSecretVal === 'string' ? clientSecretVal !== '' : true);
|
||||
const hasClientSecretPath =
|
||||
clientSecretPathVal !== undefined &&
|
||||
clientSecretPathVal !== null &&
|
||||
typeof clientSecretPathVal === 'string' &&
|
||||
clientSecretPathVal !== '';
|
||||
|
||||
if (hasClientSecretVal && hasClientSecretPath) {
|
||||
return ctx.reject(
|
||||
`Only one of "${clientSecretKey}" or "${clientSecretPathKey}" may be set.`,
|
||||
);
|
||||
}
|
||||
if (obj.issuer && obj.client_id) {
|
||||
if (!hasClientSecretVal && !hasClientSecretPath) {
|
||||
return ctx.reject(
|
||||
`Either "${clientSecretKey}" or "${clientSecretPathKey}" must be provided for client_secret if OIDC is configured.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const hsApiKey = 'headscale_api_key';
|
||||
const hsApiKeyPath = 'headscale_api_key_path';
|
||||
const hsApiVal = obj[hsApiKey];
|
||||
const hsApiPathVal = obj[hsApiKeyPath];
|
||||
const hasHsApiVal =
|
||||
hsApiVal !== undefined &&
|
||||
hsApiVal !== null &&
|
||||
(typeof hsApiVal === 'string' ? hsApiVal !== '' : true);
|
||||
const hasHsApiPath =
|
||||
hsApiPathVal !== undefined &&
|
||||
hsApiPathVal !== null &&
|
||||
typeof hsApiPathVal === 'string' &&
|
||||
hsApiPathVal !== '';
|
||||
|
||||
if (hasHsApiVal && hasHsApiPath) {
|
||||
return ctx.reject(
|
||||
`Only one of "${hsApiKey}" or "${hsApiKeyPath}" may be set.`,
|
||||
);
|
||||
}
|
||||
if (obj.issuer && obj.client_id) {
|
||||
if (!hasHsApiVal && !hasHsApiPath) {
|
||||
return ctx.reject(
|
||||
`Either "${hsApiKey}" or "${hsApiKeyPath}" must be provided for oidc.headscale_api_key if OIDC is configured.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.onDeepUndeclaredKey('reject');
|
||||
}).onDeepUndeclaredKey('reject');
|
||||
|
||||
const headscaleConfig = type({
|
||||
url: type('string.url').pipe((v) => (v.endsWith('/') ? v.slice(0, -1) : v)),
|
||||
'api_key?': 'string',
|
||||
'api_key_path?': 'string',
|
||||
'tls_cert_path?': '(string | null)',
|
||||
'public_url?': 'string.url',
|
||||
'config_path?': 'string',
|
||||
tls_cert_path: 'string?',
|
||||
public_url: 'string.url?',
|
||||
config_path: 'string?',
|
||||
config_strict: stringToBool,
|
||||
})
|
||||
.narrow((obj, ctx: any) => {
|
||||
const key = 'api_key';
|
||||
const pathKey = 'api_key_path';
|
||||
const valProperty = obj[key];
|
||||
const pathProperty = obj[pathKey];
|
||||
const hasVal =
|
||||
valProperty !== undefined &&
|
||||
valProperty !== null &&
|
||||
(typeof valProperty === 'string' ? valProperty !== '' : true);
|
||||
const hasPath =
|
||||
pathProperty !== undefined &&
|
||||
pathProperty !== null &&
|
||||
typeof pathProperty === 'string' &&
|
||||
pathProperty !== '';
|
||||
if (hasVal && hasPath) {
|
||||
return ctx.reject(`Only one of "${key}" or "${pathKey}" may be set.`);
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.onDeepUndeclaredKey('reject');
|
||||
}).onDeepUndeclaredKey('reject');
|
||||
|
||||
const containerLabel = type({
|
||||
name: 'string',
|
||||
@@ -299,169 +69,26 @@ const integrationConfig = type({
|
||||
'proc?': procConfig,
|
||||
}).onDeepUndeclaredKey('reject');
|
||||
|
||||
const partialIntegrationConfig = type({
|
||||
'docker?': dockerConfig.partial(),
|
||||
'kubernetes?': kubernetesConfig.partial(),
|
||||
'proc?': procConfig.partial(),
|
||||
}).partial();
|
||||
|
||||
export const headplaneConfig = type({
|
||||
debug: stringToBool.default(false),
|
||||
debug: stringToBool,
|
||||
server: serverConfig,
|
||||
'oidc?': oidcConfig,
|
||||
'integration?': integrationConfig,
|
||||
headscale: headscaleConfig,
|
||||
}).onDeepUndeclaredKey('delete');
|
||||
|
||||
// --- Partial Configurations (Explicitly defined field by field) ---
|
||||
|
||||
const partialServerConfig = type({
|
||||
'host?': 'string.ip',
|
||||
'port?': type('string | number.integer').pipe((v) => Number(v)),
|
||||
'cookie_secret?': '((32 <= string <= 32) | null)',
|
||||
'cookie_secret_path?': 'string',
|
||||
'cookie_secure?': stringToBool,
|
||||
'agent?': partialAgentConfig,
|
||||
}).narrow((obj, ctx: any) => {
|
||||
const key = 'cookie_secret';
|
||||
const pathKey = 'cookie_secret_path';
|
||||
const valProperty = obj[key];
|
||||
const pathProperty = obj[pathKey];
|
||||
const hasVal =
|
||||
valProperty !== undefined &&
|
||||
valProperty !== null &&
|
||||
(typeof valProperty === 'string' ? valProperty !== '' : true);
|
||||
const hasPath =
|
||||
pathProperty !== undefined &&
|
||||
pathProperty !== null &&
|
||||
typeof pathProperty === 'string' &&
|
||||
pathProperty !== '';
|
||||
if (hasVal && hasPath) {
|
||||
return ctx.reject(`Only one of "${key}" or "${pathKey}" may be set.`);
|
||||
}
|
||||
if (Object.keys(obj).length > 0 && !obj.agent && !obj.cookie_secure) {
|
||||
if (!hasVal && !hasPath) {
|
||||
return ctx.reject(
|
||||
`Either "${key}" or "${pathKey}" must be provided for cookie_secret if server section is present.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const partialOidcConfig = type({
|
||||
'issuer?': 'string.url',
|
||||
'client_id?': 'string',
|
||||
'client_secret?': '(string | null)',
|
||||
'client_secret_path?': 'string',
|
||||
'token_endpoint_auth_method?':
|
||||
'"client_secret_basic" | "client_secret_post" | "client_secret_jwt"',
|
||||
'redirect_uri?': 'string.url',
|
||||
'user_storage_file?': 'string',
|
||||
'disable_api_key_login?': stringToBool,
|
||||
'headscale_api_key?': '(string | null)',
|
||||
'headscale_api_key_path?': 'string',
|
||||
'strict_validation?': stringToBool,
|
||||
})
|
||||
.narrow((obj, ctx: any) => {
|
||||
const clientSecretKey = 'client_secret';
|
||||
const clientSecretPathKey = 'client_secret_path';
|
||||
const clientSecretVal = obj[clientSecretKey];
|
||||
const clientSecretPathVal = obj[clientSecretPathKey];
|
||||
const hasClientSecretVal =
|
||||
clientSecretVal !== undefined &&
|
||||
clientSecretVal !== null &&
|
||||
(typeof clientSecretVal === 'string' ? clientSecretVal !== '' : true);
|
||||
const hasClientSecretPath =
|
||||
clientSecretPathVal !== undefined &&
|
||||
clientSecretPathVal !== null &&
|
||||
typeof clientSecretPathVal === 'string' &&
|
||||
clientSecretPathVal !== '';
|
||||
if (hasClientSecretVal && hasClientSecretPath) {
|
||||
return ctx.reject(
|
||||
`Only one of "${clientSecretKey}" or "${clientSecretPathKey}" may be set.`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
obj.issuer &&
|
||||
obj.client_id &&
|
||||
!hasClientSecretVal &&
|
||||
!hasClientSecretPath
|
||||
) {
|
||||
return ctx.reject(
|
||||
`Either "${clientSecretKey}" or "${clientSecretPathKey}" must be provided if issuer and client_id are set in partial OIDC config.`,
|
||||
);
|
||||
}
|
||||
|
||||
const hsApiKey = 'headscale_api_key';
|
||||
const hsApiKeyPath = 'headscale_api_key_path';
|
||||
const hsApiVal = obj[hsApiKey];
|
||||
const hsApiPathVal = obj[hsApiKeyPath];
|
||||
const hasHsApiVal =
|
||||
hsApiVal !== undefined &&
|
||||
hsApiVal !== null &&
|
||||
(typeof hsApiVal === 'string' ? hsApiVal !== '' : true);
|
||||
const hasHsApiPath =
|
||||
hsApiPathVal !== undefined &&
|
||||
hsApiPathVal !== null &&
|
||||
typeof hsApiPathVal === 'string' &&
|
||||
hsApiPathVal !== '';
|
||||
if (hasHsApiVal && hasHsApiPath) {
|
||||
return ctx.reject(
|
||||
`Only one of "${hsApiKey}" or "${hsApiKeyPath}" may be set.`,
|
||||
);
|
||||
}
|
||||
if (obj.issuer && obj.client_id && !hasHsApiVal && !hasHsApiPath) {
|
||||
return ctx.reject(
|
||||
`Either "${hsApiKey}" or "${hsApiKeyPath}" must be provided for headscale_api_key if issuer and client_id are set in partial OIDC config.`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.onDeepUndeclaredKey('reject');
|
||||
|
||||
const partialHeadscaleConfig = type({
|
||||
'url?': type('string.url').pipe((v) =>
|
||||
v.endsWith('/') ? v.slice(0, -1) : v,
|
||||
),
|
||||
'api_key?': 'string',
|
||||
'api_key_path?': 'string',
|
||||
'tls_cert_path?': '(string | null)',
|
||||
'public_url?': 'string.url',
|
||||
'config_path?': 'string',
|
||||
'config_strict?': stringToBool,
|
||||
})
|
||||
.narrow((obj, ctx: any) => {
|
||||
const key = 'api_key';
|
||||
const pathKey = 'api_key_path';
|
||||
const valProperty = obj[key];
|
||||
const pathProperty = obj[pathKey];
|
||||
const hasVal =
|
||||
valProperty !== undefined &&
|
||||
valProperty !== null &&
|
||||
(typeof valProperty === 'string' ? valProperty !== '' : true);
|
||||
const hasPath =
|
||||
pathProperty !== undefined &&
|
||||
pathProperty !== null &&
|
||||
typeof pathProperty === 'string' &&
|
||||
pathProperty !== '';
|
||||
if (hasVal && hasPath) {
|
||||
return ctx.reject(`Only one of "${key}" or "${pathKey}" may be set.`);
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.onDeepUndeclaredKey('reject');
|
||||
|
||||
const partialDockerConfig = dockerConfig.partial();
|
||||
const partialKubernetesConfig = kubernetesConfig.partial();
|
||||
const partialProcConfig = procConfig.partial();
|
||||
|
||||
const partialIntegrationConfig = type({
|
||||
'docker?': partialDockerConfig,
|
||||
'kubernetes?': partialKubernetesConfig,
|
||||
'proc?': partialProcConfig,
|
||||
}).partial();
|
||||
|
||||
export const partialHeadplaneConfig = type({
|
||||
'debug?': stringToBool,
|
||||
'server?': partialServerConfig,
|
||||
'oidc?': partialOidcConfig,
|
||||
'integration?': integrationConfig.partial(),
|
||||
'headscale?': partialHeadscaleConfig,
|
||||
debug: stringToBool,
|
||||
server: serverConfig.partial(),
|
||||
'oidc?': oidcConfig.partial(),
|
||||
'integration?': partialIntegrationConfig,
|
||||
headscale: headscaleConfig.partial(),
|
||||
}).partial();
|
||||
|
||||
export type HeadplaneConfig = typeof headplaneConfig.infer;
|
||||
|
||||
@@ -10,16 +10,12 @@ import { HostInfo } from '~/types';
|
||||
import log from '~/utils/log';
|
||||
|
||||
export async function loadAgentSocket(
|
||||
authkey: string | null,
|
||||
authkey: string,
|
||||
path: string,
|
||||
ttl: number,
|
||||
) {
|
||||
if (authkey === null || authkey.length === 0) {
|
||||
log.warn(
|
||||
'agent',
|
||||
'Agent authkey is not configured or is empty, agent support will be disabled.',
|
||||
);
|
||||
return undefined;
|
||||
if (authkey.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user