fix: redact secrets in instance settings reads unless explicitly revealed (#12682)

* fix: redact secrets in instance settings reads unless explicitly revealed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): compare redacted remote settings against unchanged local secrets

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: redact nuget, maven, cargo, webhook and otel header credentials too

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): mask get-config secrets from servers that do not redact

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): refuse a masked get-config export from a server that cannot restore it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): word the get-config prompt for servers that do not redact

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-11-26 15:45:42 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent c689d74505
commit cc855e6fd9
15 changed files with 402 additions and 74 deletions
@@ -204,6 +204,7 @@ async fn test_alert_job_queue_waiting_in_global_settings(db: Pool<Postgres>) ->
async fn read_secret_surfaces(
base: &str,
names: &[&str],
reveal: bool,
) -> anyhow::Result<Vec<(String, u16, String)>> {
let mut paths = vec![
"instance_config".to_string(),
@@ -214,9 +215,13 @@ async fn read_secret_surfaces(
paths.extend(names.iter().map(|n| format!("global/{n}")));
let mut out = vec![];
for path in paths {
let resp = authed(client().get(format!("{base}/{path}")))
.send()
.await?;
let resp = authed(
client()
.get(format!("{base}/{path}"))
.query(&[("dangerously_reveal_secrets", reveal)]),
)
.send()
.await?;
let status = resp.status().as_u16();
out.push((path, status, resp.text().await?));
}
@@ -252,9 +257,17 @@ async fn test_server_secrets_follow_export_flag(db: Pool<Postgres>) -> anyhow::R
let server = ApiServer::start(db.clone()).await?;
let base = format!("http://localhost:{}/api/settings", server.addr.port());
// Default: a full export, so `get-config` and `pull` can migrate an instance.
std::env::remove_var("EXPORT_SERVER_SECRETS");
for (path, status, body) in read_secret_surfaces(&base, &names).await? {
// A read that does not ask for secrets gets them redacted.
for (path, status, body) in read_secret_surfaces(&base, &names, false).await? {
assert_2xx(status, &body, &path);
assert!(
!body.contains("planted-"),
"{path} returned a secret without dangerously_reveal_secrets: {body}"
);
}
// Asked for, a full export, so `get-config` and `pull` can migrate an instance.
for (path, status, body) in read_secret_surfaces(&base, &names, true).await? {
assert_2xx(status, &body, &path);
assert!(
body.contains("planted-"),
@@ -263,7 +276,7 @@ async fn test_server_secrets_follow_export_flag(db: Pool<Postgres>) -> anyhow::R
}
std::env::set_var("EXPORT_SERVER_SECRETS", "0");
let withheld = read_secret_surfaces(&base, &names).await;
let withheld = read_secret_surfaces(&base, &names, true).await;
std::env::remove_var("EXPORT_SERVER_SECRETS");
for (path, status, body) in withheld? {
if path.starts_with("global/") {
+42 -5
View File
@@ -878,8 +878,18 @@ async fn audit_instance_action(
pub async fn set_global_setting_internal(
db: &DB,
key: String,
value: serde_json::Value,
mut value: serde_json::Value,
) -> error::Result<()> {
if instance_config::contains_redacted_secret(&value) {
let current = sqlx::query_scalar::<_, serde_json::Value>(
"SELECT value FROM global_settings WHERE name = $1",
)
.bind(&key)
.fetch_optional(db)
.await?;
instance_config::restore_redacted_secrets(&key, &mut value, current.as_ref())
.map_err(error::Error::BadRequest)?;
}
let should_bump_instance_ai_revision = key == AI_CONFIG_SETTING;
let value = if key == "retention_period_secs" {
instance_config::clamp_retention_period(value)
@@ -1348,12 +1358,22 @@ async fn run_setting_pre_write_hook(
// Bulk instance config endpoints
// ---------------------------------------------------------------------------
/// Secrets are redacted on every settings read unless asked for by name, so that a superadmin
/// token used to inspect the configuration (by a script, a CLI run or an AI assistant) does not
/// copy every instance credential into its output.
#[derive(Deserialize)]
pub struct RevealSecrets {
#[serde(default)]
pub dangerously_reveal_secrets: bool,
}
async fn get_instance_config(
Extension(db): Extension<DB>,
authed: ApiAuthed,
Query(reveal): Query<RevealSecrets>,
) -> JsonResult<InstanceConfig> {
require_super_admin(&db, &authed).await?;
let config = InstanceConfig::from_db_for_api(&db)
let config = InstanceConfig::from_db_for_api(&db, reveal.dangerously_reveal_secrets)
.await
.map_err(|e| error::Error::internal_err(e.to_string()))?;
Ok(Json(config))
@@ -1362,9 +1382,10 @@ async fn get_instance_config(
async fn get_instance_config_yaml(
Extension(db): Extension<DB>,
authed: ApiAuthed,
Query(reveal): Query<RevealSecrets>,
) -> error::Result<Response> {
require_super_admin(&db, &authed).await?;
let config = InstanceConfig::from_db_for_api(&db)
let config = InstanceConfig::from_db_for_api(&db, reveal.dangerously_reveal_secrets)
.await
.map_err(|e| error::Error::internal_err(e.to_string()))?;
let yaml = config
@@ -1387,9 +1408,13 @@ async fn set_instance_config(
.await
.map_err(|e| error::Error::internal_err(e.to_string()))?;
let desired_map = desired.global_settings.to_settings_map();
let mut desired_map = desired.global_settings.to_settings_map();
if !desired_map.is_empty() {
let current_map = current.global_settings.to_settings_map();
for (key, value) in desired_map.iter_mut() {
instance_config::restore_redacted_secrets(key, value, current_map.get(key))
.map_err(error::Error::BadRequest)?;
}
let mut settings_diff =
instance_config::diff_global_settings(&current_map, &desired_map, ApplyMode::Merge);
let ai_config_changed = settings_diff
@@ -1495,6 +1520,7 @@ pub async fn get_global_setting(
Extension(db): Extension<DB>,
authed: ApiAuthed,
Path(key): Path<String>,
Query(reveal): Query<RevealSecrets>,
) -> JsonResult<serde_json::Value> {
if !key.starts_with("default_error_handler_")
&& !key.starts_with("default_recovery_handler_")
@@ -1539,7 +1565,11 @@ pub async fn get_global_setting(
.await?
.map(|x| x.value);
Ok(Json(value.unwrap_or_else(|| serde_json::Value::Null)))
let mut value = value.unwrap_or(serde_json::Value::Null);
if !reveal.dangerously_reveal_secrets {
instance_config::redact_setting_secrets(&key, &mut value);
}
Ok(Json(value))
}
#[cfg(feature = "enterprise")]
@@ -1572,6 +1602,7 @@ async fn github_app_stale_webhooks(
async fn list_global_settings(
Extension(db): Extension<DB>,
authed: ApiAuthed,
Query(reveal): Query<RevealSecrets>,
) -> JsonResult<Vec<GlobalSetting>> {
require_super_admin(&db, &authed).await?;
let settings = sqlx::query_as!(GlobalSetting, "SELECT name, value FROM global_settings")
@@ -1579,6 +1610,12 @@ async fn list_global_settings(
.await?
.into_iter()
.filter(|s| !instance_config::is_withheld_server_secret(&s.name))
.map(|mut s| {
if !reveal.dangerously_reveal_secrets {
instance_config::redact_setting_secrets(&s.name, &mut s.value);
}
s
})
.collect();
Ok(Json(settings))
+14
View File
@@ -1903,6 +1903,7 @@ paths:
- setting
parameters:
- $ref: "#/components/parameters/Key"
- $ref: "#/components/parameters/DangerouslyRevealSecrets"
responses:
"200":
description: status
@@ -2717,6 +2718,8 @@ paths:
operationId: listGlobalSettings
tags:
- setting
parameters:
- $ref: "#/components/parameters/DangerouslyRevealSecrets"
responses:
"200":
description: list of settings
@@ -2760,6 +2763,8 @@ paths:
operationId: getInstanceConfig
tags:
- setting
parameters:
- $ref: "#/components/parameters/DangerouslyRevealSecrets"
responses:
"200":
description: full instance configuration
@@ -29911,6 +29916,15 @@ components:
required: true
schema:
type: string
DangerouslyRevealSecrets:
name: dangerously_reveal_secrets
description: >
Return stored secrets in clear. Without it, every secret is replaced by a
placeholder, which a write sending it back unchanged keeps as the stored value.
in: query
required: false
schema:
type: boolean
WorkspaceId:
name: workspace
in: path
+194 -36
View File
@@ -1200,6 +1200,11 @@ const SENSITIVE_SETTINGS: &[&str] = &[
"powershell_repo_pat",
"workspace_registries",
"sandbox_registry_auth",
"nuget_config",
"maven_settings_xml",
"cargo_registries",
// A webhook URL is commonly its own credential.
"instance_events_webhook",
];
/// Object-valued settings that contain sensitive sub-fields.
@@ -1224,8 +1229,52 @@ const NESTED_SENSITIVE_FIELDS: &[(&str, &[&str])] = &[
("custom_instance_pg_databases", &["user_pwd"]),
("external_instance_pg", &["password"]),
("github_enterprise_app", &["private_key"]),
("otel", &["otel_exporter_otlp_headers"]),
];
/// Settings that are maps-of-objects where each child has sensitive sub-fields.
const NESTED_MAP_SENSITIVE: &[(&str, &[&str])] = &[
("oauths", &["secret", "signing_secret"]),
("external_secrets", &["token", "approle_secret_id"]),
];
/// Calls `f` on every part of setting `key`'s value that holds a secret, as listed in
/// [`SENSITIVE_SETTINGS`], [`NESTED_SENSITIVE_FIELDS`] and [`NESTED_MAP_SENSITIVE`]. Logs
/// and API reads both redact through it, so a new secret is listed once, there.
fn visit_secrets(
key: &str,
value: &mut serde_json::Value,
f: &mut dyn FnMut(&mut serde_json::Value),
) {
if SENSITIVE_SETTINGS.contains(&key) {
f(value);
return;
}
if let Some((_, fields)) = NESTED_SENSITIVE_FIELDS.iter().find(|(k, _)| *k == key) {
if let Some(obj) = value.as_object_mut() {
for field in *fields {
if let Some(v) = obj.get_mut(*field) {
f(v);
}
}
}
return;
}
if let Some((_, fields)) = NESTED_MAP_SENSITIVE.iter().find(|(k, _)| *k == key) {
if let Some(entries) = value.as_object_mut() {
for entry in entries.values_mut() {
if let Some(obj) = entry.as_object_mut() {
for field in *fields {
if let Some(v) = obj.get_mut(*field) {
f(v);
}
}
}
}
}
}
}
fn redact_json_value(value: &serde_json::Value) -> serde_json::Value {
match value {
serde_json::Value::String(s) => serde_json::json!(redact_string(s)),
@@ -1234,42 +1283,89 @@ fn redact_json_value(value: &serde_json::Value) -> serde_json::Value {
}
fn mask_nested_sensitive(key: &str, value: &serde_json::Value) -> serde_json::Value {
for &(parent_key, sub_fields) in NESTED_SENSITIVE_FIELDS {
if key == parent_key {
if let serde_json::Value::Object(map) = value {
let mut masked = map.clone();
for &field in sub_fields {
if let Some(v) = masked.get(field) {
masked.insert(field.to_string(), redact_json_value(v));
}
}
return serde_json::Value::Object(masked);
}
let mut masked = value.clone();
visit_secrets(key, &mut masked, &mut |v| *v = redact_json_value(v));
masked
}
/// What the settings read endpoints return in place of a stored secret unless the caller
/// passes `dangerously_reveal_secrets=true`. A write carrying it back keeps the stored value
/// at that spot ([`restore_redacted_secrets`]), so a redacted read round-trips through a write.
pub const REDACTED_SECRET: &str =
"__REDACTED__ (read it with dangerously_reveal_secrets=true; send this back unchanged to keep the stored value)";
/// Replaces every secret in setting `key`'s value with [`REDACTED_SECRET`]. Only non-empty
/// strings are replaced, recursing into objects and arrays, so the value keeps the shape its
/// typed config field parses, and an unset secret still reads as unset.
pub fn redact_setting_secrets(key: &str, value: &mut serde_json::Value) {
fn redact_leaves(v: &mut serde_json::Value) {
match v {
serde_json::Value::String(s) if !s.is_empty() => *s = REDACTED_SECRET.to_string(),
serde_json::Value::Array(items) => items.iter_mut().for_each(redact_leaves),
serde_json::Value::Object(obj) => obj.values_mut().for_each(redact_leaves),
_ => {}
}
}
// Settings that are maps-of-objects where each child has a sensitive sub-field.
const NESTED_MAP_SENSITIVE: &[(&str, &[&str])] = &[
("oauths", &["secret", "signing_secret"]),
("external_secrets", &["token", "approle_secret_id"]),
];
for &(parent_key, child_fields) in NESTED_MAP_SENSITIVE {
if key == parent_key {
if let serde_json::Value::Object(entries) = value {
let mut masked = entries.clone();
for (_entry_key, entry_val) in masked.iter_mut() {
if let serde_json::Value::Object(ref mut obj) = entry_val {
for &child_field in child_fields {
if let Some(v) = obj.get(child_field) {
obj.insert(child_field.to_string(), redact_json_value(v));
}
}
}
visit_secrets(key, value, &mut redact_leaves);
}
pub fn contains_redacted_secret(value: &serde_json::Value) -> bool {
match value {
serde_json::Value::String(s) => s == REDACTED_SECRET,
serde_json::Value::Array(items) => items.iter().any(contains_redacted_secret),
serde_json::Value::Object(obj) => obj.values().any(contains_redacted_secret),
_ => false,
}
}
/// Puts the stored value back wherever `desired` carries [`REDACTED_SECRET`], matched by JSON
/// path against `current`. Fails rather than store the placeholder when nothing is stored there.
pub fn restore_redacted_secrets(
key: &str,
desired: &mut serde_json::Value,
current: Option<&serde_json::Value>,
) -> Result<(), String> {
fn walk(
path: &mut String,
desired: &mut serde_json::Value,
current: Option<&serde_json::Value>,
) -> Result<(), String> {
match desired {
serde_json::Value::String(s) if s == REDACTED_SECRET => match current {
Some(c) if !c.is_null() => {
*desired = c.clone();
Ok(())
}
return serde_json::Value::Object(masked);
_ => Err(format!(
"{path} is the redacted placeholder, but no value is stored there to keep"
)),
},
serde_json::Value::Object(obj) => {
for (k, v) in obj.iter_mut() {
let len = path.len();
path.push('.');
path.push_str(k);
walk(path, v, current.and_then(|c| c.get(k.as_str())))?;
path.truncate(len);
}
Ok(())
}
serde_json::Value::Array(items) => {
for (i, v) in items.iter_mut().enumerate() {
let len = path.len();
path.push_str(&format!("[{i}]"));
walk(path, v, current.and_then(|c| c.get(i)))?;
path.truncate(len);
}
Ok(())
}
_ => Ok(()),
}
}
value.clone()
if !contains_redacted_secret(desired) {
return Ok(());
}
walk(&mut key.to_string(), desired, current)
}
fn redact_string(s: &str) -> String {
@@ -1518,6 +1614,15 @@ pub async fn sync_global_settings_declarative(
desired: &BTreeMap<String, serde_json::Value>,
observer: &impl ConfigWriteObserver,
) -> anyhow::Result<()> {
let mut restored = None;
if desired.values().any(contains_redacted_secret) {
let mut copy = desired.clone();
for (key, value) in copy.iter_mut() {
restore_redacted_secrets(key, value, current.get(key)).map_err(anyhow::Error::msg)?;
}
restored = Some(copy);
}
let desired = restored.as_ref().unwrap_or(desired);
for url_key in [
crate::global_settings::GITHUB_APP_WEBHOOK_BASE_URL_SETTING,
crate::global_settings::API_BASE_URL_SETTING,
@@ -1786,20 +1891,24 @@ pub fn resolve_env_refs(settings: &mut GlobalSettings) -> Result<(), String> {
impl InstanceConfig {
/// Read the full instance configuration from the database.
pub async fn from_db(db: &sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<Self> {
Self::read_from_db(db, true).await
Self::read_from_db(db, true, true).await
}
/// The instance configuration as an API response may carry it: `from_db` without
/// `SERVER_SECRET_SETTINGS` unless `server_secrets_exported()`. It holds admin-entered
/// credentials (`license_key`, `scim_token`, SMTP and OAuth secrets), so callers must
/// have checked superadmin.
pub async fn from_db_for_api(db: &sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<Self> {
Self::read_from_db(db, server_secrets_exported()).await
/// `SERVER_SECRET_SETTINGS` unless `server_secrets_exported()`, and with every secret
/// replaced by [`REDACTED_SECRET`] unless `reveal_secrets`. Callers must have checked
/// superadmin.
pub async fn from_db_for_api(
db: &sqlx::Pool<sqlx::Postgres>,
reveal_secrets: bool,
) -> anyhow::Result<Self> {
Self::read_from_db(db, server_secrets_exported(), reveal_secrets).await
}
async fn read_from_db(
db: &sqlx::Pool<sqlx::Postgres>,
include_server_secrets: bool,
reveal_secrets: bool,
) -> anyhow::Result<Self> {
// Read global_settings table → flat map → deserialize into GlobalSettings
let rows: Vec<(String, serde_json::Value)> =
@@ -1812,6 +1921,12 @@ impl InstanceConfig {
.filter(|(name, _)| {
include_server_secrets || !SERVER_SECRET_SETTINGS.contains(&name.as_str())
})
.map(|(name, mut value)| {
if !reveal_secrets {
redact_setting_secrets(&name, &mut value);
}
(name, value)
})
.collect();
let global_settings: GlobalSettings =
serde_json::from_value(serde_json::Value::Object(map))?;
@@ -2835,6 +2950,49 @@ mod tests {
);
}
#[test]
fn redacted_settings_parse_and_restore_on_write() {
let stored = serde_json::json!({
"custom_instance_pg_databases": {
"user_pwd": "pg-secret",
"databases": { "mydb": { "success": true, "tag": "t" } }
},
"custom_instance_replication_pwd": "repl-secret",
"workspace_registries": { "ws": { "npm": { "token": "reg-secret" } } },
"oauths": { "google": { "id": "client-id", "secret": "oauth-secret" } },
"nuget_config": "<add key=\"ClearTextPassword\" value=\"nuget-secret\" />",
"otel": { "otel_exporter_otlp_endpoint": "https://otel", "otel_exporter_otlp_headers": "authorization=otel-secret" },
"base_url": "https://example.com",
});
let mut read = stored.clone();
for (key, value) in read.as_object_mut().unwrap().iter_mut() {
redact_setting_secrets(key, value);
}
let text = read.to_string();
for secret in [
"pg-secret",
"repl-secret",
"reg-secret",
"oauth-secret",
"nuget-secret",
"otel-secret",
] {
assert!(!text.contains(secret), "{secret} leaked: {text}");
}
assert_eq!(read["oauths"]["google"]["id"], "client-id");
assert_eq!(read["base_url"], "https://example.com");
// The redacted read still parses into the typed config the API returns.
serde_json::from_value::<GlobalSettings>(read.clone()).unwrap();
for (key, value) in read.as_object_mut().unwrap().iter_mut() {
restore_redacted_secrets(key, value, stored.get(key)).unwrap();
}
assert_eq!(read, stored);
let mut orphan = serde_json::json!({ "smtp_password": REDACTED_SECRET });
assert!(restore_redacted_secrets("smtp_settings", &mut orphan, None).is_err());
}
#[test]
fn db_oversize_alert_defaults() {
let alert: DbOversizeAlert = serde_json::from_str("{}").unwrap();
+1
View File
@@ -54,6 +54,7 @@ export async function pull(opts: GlobalOptions) {
if (hubBaseUrl !== DEFAULT_HUB_BASE_URL) {
const hubSecret = (await wmill.getGlobal({
key: "hub_api_secret",
dangerouslyRevealSecrets: true,
})) as string | undefined;
log.info("Fetching resource types from private hub: " + hubBaseUrl);
if (hubSecret) {
+38 -15
View File
@@ -38,6 +38,7 @@ import {
pullInstanceSettings,
pushInstanceConfigs,
pushInstanceSettings,
REDACTED_SECRET_PREFIX,
type SimplifiedSettings,
} from "../../core/settings.ts";
import { deepEqual, readTextFile } from "../../utils/utils.ts";
@@ -183,6 +184,7 @@ export type InstanceSyncOptions = {
yes?: boolean;
prefix?: string;
prefixSettings?: boolean;
showSecrets?: boolean;
};
export async function pickInstance(
@@ -667,25 +669,42 @@ export async function getActiveInstance(opts: {
async function getConfig(opts: InstanceSyncOptions & { outputFile?: string; showSecrets?: boolean }) {
await pickInstance(opts, false);
const config = await wmill.getInstanceConfig() as any;
// In interactive mode, mask secrets by default and prompt
const hasSecrets = config?.global_settings?.license_key || config?.global_settings?.jwt_secret;
let showSecrets = opts.showSecrets ?? false;
if (!showSecrets && hasSecrets && process.stdout.isTTY && !opts.outputFile) {
log.warn("Config contains sensitive fields (license_key, jwt_secret). They are masked by default.");
log.warn("Use --show-secrets to include them, or press Y to show them now.");
showSecrets = await Confirm.prompt({ message: "Show secrets?", default: false });
} else if (!process.stdout.isTTY || opts.outputFile) {
// Non-interactive or writing to file: always include secrets
showSecrets = true;
}
let config = await wmill.getInstanceConfig({ dangerouslyRevealSecrets: showSecrets }) as any;
if (!showSecrets && config?.global_settings) {
const settings = config?.global_settings ?? {};
const serverRedacted = JSON.stringify(settings).includes(REDACTED_SECRET_PREFIX);
// A server without redaction ignores the parameter and returns its secrets in clear.
const clearFromOlderServer =
!showSecrets && !serverRedacted && Boolean(settings.license_key || settings.jwt_secret);
const interactive = process.stdout.isTTY && !opts.outputFile;
// Masking such an export is only safe on screen: applied back, that server would store the mask.
if (clearFromOlderServer && !interactive) {
throw new Error(
"This server does not redact secrets, so a redacted export would overwrite them when applied back. Pass --show-secrets to export them."
);
}
const redacted = !showSecrets && (serverRedacted || clearFromOlderServer);
if (redacted && interactive) {
log.warn(
clearFromOlderServer
? "Config contains sensitive fields (license_key, jwt_secret). They are masked by default. Use --show-secrets to include them, or press Y to show them now."
: "Secrets (license key, passwords, tokens) are redacted. Use --show-secrets to include them, or press Y to show them now."
);
showSecrets = await Confirm.prompt({ message: "Show secrets?", default: false });
if (showSecrets) {
config = await wmill.getInstanceConfig({ dangerouslyRevealSecrets: true }) as any;
}
} else if (redacted) {
log.infoStderr(
"Secrets are redacted: pass --show-secrets to include them. Pushing this export back keeps the stored secrets, but it cannot set up another instance."
);
}
if (!showSecrets && clearFromOlderServer) {
if (config.global_settings.license_key) config.global_settings.license_key = "***";
if (config.global_settings.jwt_secret) config.global_settings.jwt_secret = "***";
}
if (config?.global_settings && !config.global_settings.jwt_secret) {
if (showSecrets && config?.global_settings && !config.global_settings.jwt_secret) {
log.infoStderr(
"jwt_secret, rsa_keys and the instance database secrets are not part of the export: the server withholds them (EXPORT_SERVER_SECRETS=false). This export cannot fully restore or migrate the instance."
);
@@ -778,6 +797,10 @@ const command = new Command()
.option("--dry-run", "Perform a dry run without making changes")
.option("--skip-users", "Skip pulling users")
.option("--skip-settings", "Skip pulling settings")
.option(
"--show-secrets",
"Pull secrets (license key, passwords, tokens) in clear instead of redacted",
)
.option("--skip-configs", "Skip pulling configs (worker groups)")
.option("--skip-groups", "Skip pulling instance groups")
.option("--include-workspaces", "Also pull workspaces")
@@ -826,7 +849,7 @@ const command = new Command()
.command("get-config")
.description("Dump the current instance config (global settings + worker configs) as YAML")
.option("-o, --output-file <file:string>", "Write YAML to a file instead of stdout")
.option("--show-secrets", "Include sensitive fields (license key, JWT secret) without prompting")
.option("--show-secrets", "Include secrets (license key, passwords, tokens) in clear without prompting")
.option(
"--instance <instance:string>",
"Name of the instance, override the active instance",
+79 -4
View File
@@ -103,6 +103,60 @@ export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [
* so a file that still carries one must not show as differing from the workspace. */
export const RETIRED_SETTINGS = ["guest_access_enabled"] as const;
/** How the server's settings reads begin a secret they withheld (without `dangerouslyRevealSecrets`). */
export const REDACTED_SECRET_PREFIX = "__REDACTED__";
function keepUnchangedLocalSecrets(redacted: any, revealed: any, local: any): any {
if (typeof redacted === "string" && redacted.startsWith(REDACTED_SECRET_PREFIX)) {
return local !== undefined && deepEqual(local, revealed) ? local : redacted;
}
if (Array.isArray(redacted)) {
return redacted.map((v, i) =>
keepUnchangedLocalSecrets(v, revealed?.[i], local?.[i])
);
}
if (redacted && typeof redacted === "object") {
return Object.fromEntries(
Object.entries(redacted).map(([k, v]) => [
k,
keepUnchangedLocalSecrets(v, revealed?.[k], local?.[k]),
])
);
}
return redacted;
}
/**
* The remote settings as pull and push compare them with the local file. Unless
* `showSecrets`, a remote secret stays redacted, except where the local file already holds
* that same value: comparing against the redacted value alone would flag every secret as
* changed on each sync, while the revealed one must not reach the printed diff or the file.
*/
async function remoteSettingsAgainstLocal(
opts: InstanceSyncOptions,
readLocal: () => Promise<GlobalSetting[]>
): Promise<GlobalSetting[]> {
if (opts.showSecrets) {
return await wmill.listGlobalSettings({ dangerouslyRevealSecrets: true });
}
const redacted = await wmill.listGlobalSettings();
if (!JSON.stringify(redacted).includes(REDACTED_SECRET_PREFIX)) {
return redacted;
}
const revealed = await wmill.listGlobalSettings({
dangerouslyRevealSecrets: true,
});
const local = await readLocal();
return redacted.map((s) => ({
...s,
value: keepUnchangedLocalSecrets(
s.value,
revealed.find((r) => r.name === s.name)?.value,
local.find((l) => l.name === s.name)?.value
),
}));
}
// Legacy settings interface for reading old settings.yaml files
interface LegacySimplifiedSettings {
auto_invite_enabled?: boolean;
@@ -708,7 +762,10 @@ export async function pushWorkspaceKey(
}
}
export async function readInstanceSettings(opts: InstanceSyncOptions) {
export async function readInstanceSettings(
opts: InstanceSyncOptions,
silent = false
) {
let localSettings: GlobalSetting[] = [];
await checkInstanceSettingsPath(opts);
@@ -718,7 +775,7 @@ export async function readInstanceSettings(opts: InstanceSyncOptions) {
instanceSettingsPath
)) as GlobalSetting[];
} catch {
log.warn(`No ${instanceSettingsPath} found`);
if (!silent) log.warn(`No ${instanceSettingsPath} found`);
}
return localSettings;
}
@@ -781,7 +838,22 @@ export async function pullInstanceSettings(
opts: InstanceSyncOptions,
preview = false
) {
const remoteSettings = await wmill.listGlobalSettings();
const remoteSettings = await remoteSettingsAgainstLocal(
opts,
async () =>
await processInstanceSettings(
await readInstanceSettings(opts, true),
"decode"
)
);
if (
!preview &&
JSON.stringify(remoteSettings).includes(REDACTED_SECRET_PREFIX)
) {
log.info(
"Secrets are redacted in the pulled settings: pass --show-secrets to include them. Pushing them back keeps the stored secrets."
);
}
await checkInstanceSettingsPath(opts);
@@ -818,9 +890,12 @@ export async function pushInstanceSettings(
opts: InstanceSyncOptions,
preview: boolean = false
) {
const remoteSettings = await wmill.listGlobalSettings();
let localSettings: GlobalSetting[] = await readInstanceSettings(opts);
localSettings = await processInstanceSettings(localSettings, "decode");
const remoteSettings = await remoteSettingsAgainstLocal(
opts,
async () => localSettings
);
if (opts.baseUrl) {
localSettings = localSettings.filter((s) => s.name !== "base_url");
+2 -1
View File
@@ -9205,6 +9205,7 @@ sync local with a remote instance or the opposite (push or pull)
- \`--dry-run\` - Perform a dry run without making changes
- \`--skip-users\` - Skip pulling users
- \`--skip-settings\` - Skip pulling settings
- \`--show-secrets\` - Pull secrets (license key, passwords, tokens) in clear instead of redacted
- \`--skip-configs\` - Skip pulling configs (worker groups)
- \`--skip-groups\` - Skip pulling instance groups
- \`--include-workspaces\` - Also pull workspaces
@@ -9227,7 +9228,7 @@ sync local with a remote instance or the opposite (push or pull)
- \`instance whoami\` - Display information about the currently logged-in user
- \`instance get-config\` - Dump the current instance config (global settings + worker configs) as YAML
- \`-o, --output-file <file:string>\` - Write YAML to a file instead of stdout
- \`--show-secrets\` - Include sensitive fields (license key, JWT secret) without prompting
- \`--show-secrets\` - Include secrets (license key, passwords, tokens) in clear without prompting
- \`--instance <instance:string>\` - Name of the instance, override the active instance
- \`instance connect-slack\` - Non-interactively connect Slack at the instance level using a pre-minted bot token (xoxb-...). Produces the same artifacts as the UI OAuth flow: global_settings 'slack' row + encrypted f/slack_bot/global_bot_token variable and resource in the admins workspace.
- \`--bot-token <bot_token:string>\` - Slack bot token (xoxb-...)
@@ -325,7 +325,8 @@
loadFilePreviewRequest={HelpersService.loadGitRepoFilePreview}
testConnectionRequest={(async (_d) => {
const bucketConfig: any = await SettingService.getGlobal({
key: 'object_store_cache_config'
key: 'object_store_cache_config',
dangerouslyRevealSecrets: true
})
return SettingService.testObjectStorageConfig({
requestBody: bucketConfig
@@ -128,7 +128,8 @@
async function reloadLicenseKey() {
$values['license_key'] = await SettingService.getGlobal({
key: 'license_key'
key: 'license_key',
dangerouslyRevealSecrets: true
})
}
@@ -135,7 +135,7 @@
loading = true
// Bulk-load all settings in a single API call
const config = await SettingService.getInstanceConfig()
const config = await SettingService.getInstanceConfig({ dangerouslyRevealSecrets: true })
const gs = (config.global_settings ?? {}) as Record<string, any>
initialOauths = gs['oauths'] ?? {}
@@ -228,7 +228,8 @@
try {
const licenseKey = (await SettingService.getGlobal({
key: 'license_key'
key: 'license_key',
dangerouslyRevealSecrets: true
})) as string
if (!licenseKey) {
@@ -325,6 +325,7 @@ sync local with a remote instance or the opposite (push or pull)
- `--dry-run` - Perform a dry run without making changes
- `--skip-users` - Skip pulling users
- `--skip-settings` - Skip pulling settings
- `--show-secrets` - Pull secrets (license key, passwords, tokens) in clear instead of redacted
- `--skip-configs` - Skip pulling configs (worker groups)
- `--skip-groups` - Skip pulling instance groups
- `--include-workspaces` - Also pull workspaces
@@ -347,7 +348,7 @@ sync local with a remote instance or the opposite (push or pull)
- `instance whoami` - Display information about the currently logged-in user
- `instance get-config` - Dump the current instance config (global settings + worker configs) as YAML
- `-o, --output-file <file:string>` - Write YAML to a file instead of stdout
- `--show-secrets` - Include sensitive fields (license key, JWT secret) without prompting
- `--show-secrets` - Include secrets (license key, passwords, tokens) in clear without prompting
- `--instance <instance:string>` - Name of the instance, override the active instance
- `instance connect-slack` - Non-interactively connect Slack at the instance level using a pre-minted bot token (xoxb-...). Produces the same artifacts as the UI OAuth flow: global_settings 'slack' row + encrypted f/slack_bot/global_bot_token variable and resource in the admins workspace.
- `--bot-token <bot_token:string>` - Slack bot token (xoxb-...)
+2 -1
View File
@@ -4439,6 +4439,7 @@ sync local with a remote instance or the opposite (push or pull)
- \`--dry-run\` - Perform a dry run without making changes
- \`--skip-users\` - Skip pulling users
- \`--skip-settings\` - Skip pulling settings
- \`--show-secrets\` - Pull secrets (license key, passwords, tokens) in clear instead of redacted
- \`--skip-configs\` - Skip pulling configs (worker groups)
- \`--skip-groups\` - Skip pulling instance groups
- \`--include-workspaces\` - Also pull workspaces
@@ -4461,7 +4462,7 @@ sync local with a remote instance or the opposite (push or pull)
- \`instance whoami\` - Display information about the currently logged-in user
- \`instance get-config\` - Dump the current instance config (global settings + worker configs) as YAML
- \`-o, --output-file <file:string>\` - Write YAML to a file instead of stdout
- \`--show-secrets\` - Include sensitive fields (license key, JWT secret) without prompting
- \`--show-secrets\` - Include secrets (license key, passwords, tokens) in clear without prompting
- \`--instance <instance:string>\` - Name of the instance, override the active instance
- \`instance connect-slack\` - Non-interactively connect Slack at the instance level using a pre-minted bot token (xoxb-...). Produces the same artifacts as the UI OAuth flow: global_settings 'slack' row + encrypted f/slack_bot/global_bot_token variable and resource in the admins workspace.
- \`--bot-token <bot_token:string>\` - Slack bot token (xoxb-...)
@@ -330,6 +330,7 @@ sync local with a remote instance or the opposite (push or pull)
- `--dry-run` - Perform a dry run without making changes
- `--skip-users` - Skip pulling users
- `--skip-settings` - Skip pulling settings
- `--show-secrets` - Pull secrets (license key, passwords, tokens) in clear instead of redacted
- `--skip-configs` - Skip pulling configs (worker groups)
- `--skip-groups` - Skip pulling instance groups
- `--include-workspaces` - Also pull workspaces
@@ -352,7 +353,7 @@ sync local with a remote instance or the opposite (push or pull)
- `instance whoami` - Display information about the currently logged-in user
- `instance get-config` - Dump the current instance config (global settings + worker configs) as YAML
- `-o, --output-file <file:string>` - Write YAML to a file instead of stdout
- `--show-secrets` - Include sensitive fields (license key, JWT secret) without prompting
- `--show-secrets` - Include secrets (license key, passwords, tokens) in clear without prompting
- `--instance <instance:string>` - Name of the instance, override the active instance
- `instance connect-slack` - Non-interactively connect Slack at the instance level using a pre-minted bot token (xoxb-...). Produces the same artifacts as the UI OAuth flow: global_settings 'slack' row + encrypted f/slack_bot/global_bot_token variable and resource in the admins workspace.
- `--bot-token <bot_token:string>` - Slack bot token (xoxb-...)