mirror of
https://github.com/LamGC/quickly-conf-sshd.git
synced 2026-11-26 20:55:49 +00:00
fix: bound source retries and distinguish explicit key revocation
This commit is contained in:
@@ -61,9 +61,10 @@ jobs:
|
||||
- run: npm test
|
||||
env:
|
||||
BROWSER_TESTS: '1'
|
||||
- name: Build production release (empty keys fail unless explicitly allowed)
|
||||
- name: Build production release (missing or unconfigured keys fail)
|
||||
run: npm run build
|
||||
- run: node scripts/verify-release.mjs
|
||||
- name: Preflight configured primary (fallback cannot mask failure)
|
||||
run: node scripts/verify-release.mjs
|
||||
- name: Deploy the validated production bundle
|
||||
id: deploy
|
||||
run: |
|
||||
|
||||
@@ -160,7 +160,7 @@ ON 客户端检查固定列表 ID、有效期和持久化的最高序号/摘要
|
||||
|
||||
更新使用锁、待提交记录、快照检查和原子替换来处理进程中断。待提交发布已过期时不会强行应用,保留其序号下限后允许有效的新发布继续;损坏且无法可信恢复的状态会停止并提示人工检查。不要删除或恢复旧版本的本地防回滚状态;整机快照回滚、本地管理员篡改或底层文件系统掉电持久性不由一个 POSIX 脚本保证。
|
||||
|
||||
下载/验签失败或清单过期会保留最后成功的密钥并报错,**不会自动清空密钥造成锁死**。攻击者仍可阻断更新;离线机器无法保证及时撤权。删除公钥不会终止已有会话,也不会移除管理区块外的手工重复钥匙。部署签名私钥或服务器本地管理员权限失陷超出这层保护范围。
|
||||
所有来源均下载失败、验证不通过或清单过期时,会保留最后成功的密钥并报错,**不会自动清空密钥造成锁死**。攻击者仍可阻断更新;离线机器无法保证及时撤权。删除公钥不会终止已有会话,也不会移除管理区块外的手工重复钥匙。部署签名私钥或服务器本地管理员权限失陷超出这层保护范围。
|
||||
|
||||
### 服务器本地验签审计
|
||||
|
||||
@@ -176,8 +176,8 @@ ON 客户端检查固定列表 ID、有效期和持久化的最高序号/摘要
|
||||
|
||||
有两份有意区分的配置:
|
||||
|
||||
1. Worker 部署的 `fallbackSources`:主来源不可用或普通主清单为空时,按顺序取首个有效集合,不合并多个来源。明确撤销阻止回退。
|
||||
2. 每台服务器本地保存的备用 URL:主 Worker 更新失败时,按本地顺序尝试,最多一个主源加五个备用源。每个端点单次请求最多 30 秒;由后续源或下次计划同步重试。只通过显式安装配置改变,远端响应不能覆盖。
|
||||
1. Worker 部署的 `fallbackSources`:主来源无法提供可用清单时,按顺序取首个有效集合,不合并多个来源。明确清空或签名撤销阻止回退,不会用备用密钥重新填充。
|
||||
2. 每台服务器本地保存的备用 URL:主 Worker 更新失败时,按本地顺序尝试,最多一个主源加五个备用源。每个源最多尝试 5 次;获取失败后依次等待 1、3、8、12 秒再试。每次尝试的正文与签名下载共用 30 秒预算。内容格式、签名、时效或防回滚验证失败则立即尝试下一源。只通过显式安装配置改变,远端响应不能覆盖。
|
||||
|
||||
### 如何准备备用源
|
||||
|
||||
@@ -191,7 +191,9 @@ Worker 的备用配置与每台服务器保存的备用 URL 是两层独立配
|
||||
|
||||
服务器本地备用 URL 必须返回本项目 v1 或 signed-v1 文档;普通原始公钥文件可通过 Worker 来源适配器发布。客户端 ON 时,备用 URL 和对应 `.sig` 必须满足相同指纹、列表 ID、签名、时效和防回滚策略。不能用另一来源的签名拼接,更不能在失败后接受未签名公钥。Worker 不能替未签名备用源伪造可信签名。
|
||||
|
||||
Worker 上游请求有时间、流式字节数、数量限制,并拒绝重定向。没有 Worker 陈旧公钥缓存,每个相关请求重新读取;API 响应 `Cache-Control: no-store`。Gist 的正文与签名取自同一修订。客户端两次 HTTP 请求之间若恰逢新发布,签名不匹配会安全拒绝,后续同步再重试。
|
||||
重试由客户端负责,Worker 不额外重试同一上游。这里的“每源 5 次”指客户端本地 URL;该 URL 若是 Worker,一次请求仍可能经过 Worker 的上游备用链。非 200 或网络获取失败可重试;Worker 明确报告全部上游均为内容验证失败时,客户端直接尝试下一 URL。六个本地源全部耗尽时,下载和等待预算最多约 17 分 24 秒,另加本地验证时间。有效空清单一旦被接受就停止回退;所有源均失败则保留已安装的密钥、审计和信任状态。
|
||||
|
||||
Worker 上游请求有时间、流式字节数、数量限制,并拒绝重定向。没有 Worker 陈旧公钥缓存,每个相关请求重新读取;API 响应 `Cache-Control: no-store`。Gist 的正文与签名取自同一修订。客户端两次 HTTP 请求之间若恰逢新发布,签名不匹配会拒绝该候选并尝试下一本地源;没有有效来源时保留旧钥匙,等待后续同步。
|
||||
|
||||
## 配置与部署
|
||||
|
||||
@@ -200,7 +202,7 @@ Worker 上游请求有时间、流式字节数、数量限制,并拒绝重定
|
||||
- `baseUrl`:正式 HTTPS origin,无路径、凭据或末尾斜杠。
|
||||
- `repositoryUrl`:项目 GitHub 地址。
|
||||
- `defaultCron`:新安装默认计划。
|
||||
- `allowEmpty`:普通 Git 模式明确允许撤销全部管理密钥;默认 false。
|
||||
- `allowEmpty`:保留兼容字段;不能把缺失文件或注释占位文件变成有效的清空指令。明确清空以实际存在的空文件或签名撤销文档为准。
|
||||
- `fallbackSources`:最多五个公开 HTTPS URL,不含凭据、query、fragment 或本地/IP 地址。
|
||||
- `keySource`:Git 或固定账号 Gist 配置。
|
||||
- `signedRelease`:签名列表身份和可公开发布的证书配置;不是私钥。
|
||||
@@ -215,6 +217,8 @@ npm run build
|
||||
node scripts/verify-release.mjs
|
||||
```
|
||||
|
||||
生产发布先检查配置的主来源,备用源不能掩盖主来源未配置或文件缺失。Git 模式保留所选密钥文件并清空内容,Gist 模式清空已配置文件的内容,表示有意移除全部管理密钥;仅含空格、制表符或换行也视为清空。缺失文件、获取失败、只含注释的示例占位文件均不表示清空。开启验签的客户端仍要求带有效签名、序号和有效期的撤销文档,不能接受未签名空文件。多种发布格式并存且空文件与旧签名内容冲突时会报错,须先明确唯一的发布形式。
|
||||
|
||||
正式上线前配置自己的域名、Worker 名称、正式公钥/签名和最小权限 Cloudflare Secrets。将仓库 `ENABLE_WORKER_DEPLOY=true` 才启用 main 发布;默认关闭。PR 测试不部署。
|
||||
|
||||
### 可选 Git 提交签名门禁
|
||||
@@ -262,7 +266,7 @@ GitHub 的通用 Verified 标记不是本项目授权名单。最终 merge/squas
|
||||
|
||||
普通部署会区分缺少 sshd 程序与现有配置无效。root 可按需安装 openssh-server,`-c` 时可按需安装 cron/crontabs;`-n` 跳过服务端检查/安装,`-o` 不执行这类系统操作。脚本不会主动执行服务 reload/restart,但发行版软件包的安装钩子可能启动服务或生成主机密钥。包安装不是可整体回滚的事务;后续失败会报告,已有钥匙和策略在验证前不改写。
|
||||
|
||||
目标为 Linux dash、Bash POSIX 与 BusyBox ash。测试不等于真实服务器登录、SELinux、发行版服务管理或自定义 AuthorizedKeysFile 已验证。异常强制终止可能留下锁,人工确认原进程状态后再处理。
|
||||
目标为 Linux dash、Bash POSIX 与 BusyBox ash。测试不等于真实服务器登录、SELinux、发行版服务管理或自定义 AuthorizedKeysFile 已验证。任务通过原子创建的锁目录记录 PID;发现仍存活的 PID(包括 PID 被复用)时跳过本轮。只有能够确认原进程已退出、锁归属与内容安全时才自动回收。PID 缺失/损坏、进程状态无法确认或遗留回收标记会停止并要求人工检查,不会猜测后删除锁。
|
||||
|
||||
## 测试
|
||||
|
||||
|
||||
@@ -12,14 +12,22 @@ class SourceError extends Error {
|
||||
}
|
||||
export class FallbackUnavailableError extends Error {
|
||||
constructor(diagnostics = []) {
|
||||
super('No configured SSH key source returned a valid nonempty key set.');
|
||||
super('No configured SSH key source returned a valid key release.');
|
||||
this.name = 'FallbackUnavailableError';
|
||||
this.code = 'KEY_SOURCES_UNAVAILABLE';
|
||||
// A mixed failure is still worth retrying if any upstream could not be retrieved.
|
||||
// This hint can only affect retry timing; it never makes a response trustworthy.
|
||||
this.failureKind = diagnostics.some(({code}) => ['network-error', 'timeout', 'http-error', 'redirect'].includes(code)) ? 'retrieval' : 'validation';
|
||||
// Keep diagnostics safe to log or return: no response content, URL secrets, or exception text.
|
||||
this.diagnostics = diagnostics.slice(0, KEY_SOURCE_LIMITS.sources).map(({index, code, status}) => ({index, code, ...(status === undefined ? {} : {status})}));
|
||||
}
|
||||
}
|
||||
|
||||
/** Only an existing, deliberately blank primary file means revoke; comments do not. */
|
||||
export function isExplicitEmptyKeyFile(input) {
|
||||
return typeof input === 'string' && /^[\t\r\n ]*$/.test(input);
|
||||
}
|
||||
|
||||
export function validateFallbackSources(sources = []) {
|
||||
if (!Array.isArray(sources) || sources.length > KEY_SOURCE_LIMITS.sources) throw new Error('fallbackSources must contain at most five HTTPS URLs.');
|
||||
const seen = new Set();
|
||||
@@ -276,28 +284,53 @@ async function fetchGist(source, fetchImpl, limits, release, options) {
|
||||
const gistRevision = latest.history?.[0]?.version;
|
||||
if (typeof gistRevision !== 'string' || !/^[0-9a-f]{40}$/.test(gistRevision)) throw new SourceError('invalid-gist-revision');
|
||||
const pinned = await get(`/${gistRevision}`);
|
||||
const filename = Object.hasOwn(pinned.files, source.bundleFile) ? source.bundleFile : source.file;
|
||||
const readFile = filename => {
|
||||
const file = pinned.files[filename];
|
||||
if (!file || file.filename !== filename || file.truncated !== false || typeof file.content !== 'string' || (file.encoding !== undefined && file.encoding !== 'utf-8')) throw new SourceError('invalid-gist-file');
|
||||
if (filename === source.bundleFile && (!file.content.startsWith('# conf-sshd-signed-v1\n') || !file.content.includes(SIGNATURE_SEPARATOR))) throw new SourceError('invalid-signed-release');
|
||||
const size = encoder.encode(file.content).length;
|
||||
const max = filename === source.bundleFile ? SIGNED_BUNDLE_MAX_BYTES : limits.maxBytes;
|
||||
if (!Number.isSafeInteger(file.size) || file.size !== size || size > max) throw new SourceError('too-large');
|
||||
return file;
|
||||
};
|
||||
const filename = Object.hasOwn(pinned.files, source.bundleFile) ? source.bundleFile : source.file;
|
||||
if (filename === source.bundleFile && Object.hasOwn(pinned.files, source.file)) {
|
||||
// A cleared split file must never be silently replaced by an older bundle,
|
||||
// or vice versa. Validate the clear before trusting it, then fail closed if
|
||||
// the other format conflicts or is unreadable. Both blank express one intent.
|
||||
const validEmpty = name => {
|
||||
if (!isExplicitEmptyKeyFile(pinned.files[name]?.content)) return false;
|
||||
try { return isExplicitEmptyKeyFile(readFile(name).content); } catch { return false; }
|
||||
};
|
||||
const splitEmpty = validEmpty(source.file), bundleEmpty = validEmpty(source.bundleFile);
|
||||
if (splitEmpty !== bundleEmpty) {
|
||||
throw new SourceError('ambiguous-empty-primary');
|
||||
}
|
||||
}
|
||||
const file = readFile(filename);
|
||||
const provenance = {type: 'gist', id: source.id, ownerId: source.ownerId, ownerLogin: source.ownerLogin, gistRevision, file: filename, url: `https://gist.github.com/${source.ownerLogin}/${source.id}/${gistRevision}`};
|
||||
const explicitEmpty = isExplicitEmptyKeyFile(file.content);
|
||||
if (explicitEmpty) {
|
||||
if (options.requireSigned) throw new SourceError('unsigned-revocation');
|
||||
return {keys: [], signed: null, explicitEmpty: true, source: provenance};
|
||||
}
|
||||
if (filename === source.bundleFile && (!file.content.startsWith('# conf-sshd-signed-v1\n') || !file.content.includes(SIGNATURE_SEPARATOR))) throw new SourceError('invalid-signed-release');
|
||||
// Optional signature is read only from this same immutable revision, never from latest/raw URLs.
|
||||
let signature = null;
|
||||
const signatureFile = pinned.files[source.signatureFile];
|
||||
if (signatureFile && signatureFile.filename === source.signatureFile && signatureFile.truncated === false && typeof signatureFile.content === 'string' && (signatureFile.encoding === undefined || signatureFile.encoding === 'utf-8') && Number.isSafeInteger(signatureFile.size) && signatureFile.size === encoder.encode(signatureFile.content).length && signatureFile.size <= SIGNED_RELEASE_LIMITS.signatureBytes) signature = signatureFile.content;
|
||||
const result = await parseSourceText(file.content, release, limits, options, signal, signature);
|
||||
return {...result, source: {type: 'gist', id: source.id, ownerId: source.ownerId, ownerLogin: source.ownerLogin, gistRevision, file: filename, url: `https://gist.github.com/${source.ownerLogin}/${source.id}/${gistRevision}`}};
|
||||
return {...result, source: provenance};
|
||||
});
|
||||
}
|
||||
|
||||
/** Only release-configured sources are accepted. Worker checks structure, never claims OpenPGP verification. */
|
||||
/** Only release-configured sources are accepted. requirePrimary disables fallback for deployment preflight.
|
||||
* Worker checks structure, never claims OpenPGP verification. */
|
||||
export async function resolveKeys(release, fetchImpl = globalThis.fetch, internalOptions = {}) {
|
||||
if (!release || !Array.isArray(release.keys) || typeof release.allowEmpty !== 'boolean') throw new Error('Invalid deployed key release.');
|
||||
const keySource = validateKeySource(release.keySource);
|
||||
validateSignedReleaseConfig(release.signedRelease);
|
||||
if (internalOptions.requireSigned !== undefined && typeof internalOptions.requireSigned !== 'boolean') throw Error('requireSigned must be boolean.');
|
||||
if (internalOptions.requirePrimary !== undefined && typeof internalOptions.requirePrimary !== 'boolean') throw Error('requirePrimary must be boolean.');
|
||||
const limits = {timeoutMs: boundedOption(internalOptions, 'timeoutMs'), maxBytes: boundedOption(internalOptions, 'maxBytes'), maxKeys: boundedOption(internalOptions, 'maxKeys')};
|
||||
const sources = validateFallbackSources(release.fallbackSources);
|
||||
const diagnostics = [];
|
||||
@@ -315,12 +348,17 @@ export async function resolveKeys(release, fetchImpl = globalThis.fetch, interna
|
||||
}
|
||||
// An explicit unsigned empty primary cannot be replaced by signed fallback keys either.
|
||||
if (!release.signedDocument && !release.signedBundle && release.allowEmpty && !release.keys.length) throw new FallbackUnavailableError([{index: -1, code: 'unsigned-revocation'}]);
|
||||
if (internalOptions.requirePrimary && !diagnostics.length) diagnostics.push({index: -1, code: internalOptions.requireSigned && release.keys.length ? 'invalid-signed-release' : 'unconfigured-primary'});
|
||||
} else {
|
||||
try {
|
||||
const result = await fetchGist(keySource, fetchImpl, limits, release, internalOptions);
|
||||
return await snapshot(result.keys, release, result.source, result.signed);
|
||||
} catch (error) { diagnostics.push(diagnostic(error, -1)); }
|
||||
return await snapshot(result.keys, result.explicitEmpty ? {...release, allowEmpty: true} : release, result.source, result.signed);
|
||||
} catch (error) {
|
||||
diagnostics.push(diagnostic(error, -1));
|
||||
if (error instanceof SourceError && ['unsigned-revocation', 'ambiguous-empty-primary'].includes(error.code)) throw new FallbackUnavailableError(diagnostics);
|
||||
}
|
||||
}
|
||||
if (internalOptions.requirePrimary) throw new FallbackUnavailableError(diagnostics);
|
||||
for (const [index, url] of sources.entries()) {
|
||||
try {
|
||||
const result = await fetchSource(url, fetchImpl, limits, release, internalOptions);
|
||||
|
||||
@@ -38,6 +38,7 @@ export function createHandler(release, {fetchImpl = globalThis.fetch} = {}) {
|
||||
headers.set('X-Conf-Sshd-Key-Source', snapshot.source.type);
|
||||
} catch (error) {
|
||||
if (error.code !== 'KEY_SOURCES_UNAVAILABLE') throw error;
|
||||
headers.set('X-Conf-Sshd-Source-Failure', error.failureKind);
|
||||
if (url.pathname !== '/') return respond('No valid public key source is currently available. Existing server keys must be preserved.\n', 'text/plain; charset=utf-8', 503);
|
||||
snapshot = {...release,keys:[],keyCount:0,sha256:null,source:{type:'unavailable'}};
|
||||
}
|
||||
|
||||
+192
-22
@@ -30,6 +30,15 @@ cron_prepared=no
|
||||
auth_prepared=no
|
||||
temps=
|
||||
lock_owned=no
|
||||
lock_identity=
|
||||
lock_reclaim_owned=no
|
||||
lock_reclaim_identity=
|
||||
lock_reclaim_parent=
|
||||
retired_lock_parent=
|
||||
retired_parent_identity=
|
||||
retired_lock_identity=
|
||||
retired_lock_pid=
|
||||
retired_reclaim_identity=
|
||||
created_state=no
|
||||
created_ssh=no
|
||||
gpg_home=
|
||||
@@ -217,8 +226,10 @@ audit_dir=$state/audit
|
||||
# GNU/Linux and BSD/macOS stat. No filesystem changes precede ownership checks.
|
||||
if stat -c '%u %a %h' "$HOME" >/dev/null 2>&1; then
|
||||
stat_info() { stat -c '%u %a %h' "$1"; }
|
||||
path_identity() { stat -c '%d:%i' "$1"; }
|
||||
else
|
||||
stat_info() { stat -f '%u %Lp %l' "$1"; }
|
||||
path_identity() { stat -f '%d:%i' "$1"; }
|
||||
fi
|
||||
check_path() {
|
||||
checked=$1
|
||||
@@ -285,7 +296,17 @@ cleanup() {
|
||||
if command -v gpgconf >/dev/null 2>&1; then gpgconf --homedir "$gpg_home" --kill all >/dev/null 2>&1 || :; fi
|
||||
rm -rf "$gpg_home"
|
||||
fi
|
||||
if [ "$lock_owned" = yes ]; then rm -f "$state/lock/pid"; rmdir "$state/lock" 2>/dev/null || :; fi
|
||||
if [ -n "$retired_lock_parent" ]; then cleanup_retired_lock || :; fi
|
||||
# Never clean a replacement lock (or follow a replaced PID symlink).
|
||||
if [ "$lock_reclaim_owned" = yes ] && [ ! -L "$state/lock" ] &&
|
||||
[ "$(path_identity "$state/lock" 2>/dev/null)" = "$lock_reclaim_parent" ] &&
|
||||
[ ! -L "$state/lock/reclaim" ] && [ "$(path_identity "$state/lock/reclaim" 2>/dev/null)" = "$lock_reclaim_identity" ]; then
|
||||
rmdir "$state/lock/reclaim" 2>/dev/null || :
|
||||
fi
|
||||
if [ "$lock_owned" = yes ] && lock_matches "$$" 2>/dev/null; then
|
||||
rm -f "$state/lock/pid"
|
||||
rmdir "$state/lock" 2>/dev/null || :
|
||||
fi
|
||||
if [ "$dry_run" = yes ] || [ "$mode" = uninstall ]; then
|
||||
if [ "$created_ssh" = yes ]; then rmdir "$ssh_dir" 2>/dev/null || :; fi
|
||||
if [ "$created_state" = yes ] || [ "$mode" = uninstall ]; then rmdir "$state" 2>/dev/null || :; fi
|
||||
@@ -319,16 +340,117 @@ if [ "$mode" = status ]; then
|
||||
fi
|
||||
|
||||
[ -d "$state" ] || { mkdir "$state"; created_state=yes; }
|
||||
if [ "$dry_run" = no ]; then chmod 700 "$state"; fi
|
||||
trap cleanup 0
|
||||
trap 'exit 129' HUP
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
if mkdir "$state/lock" 2>/dev/null; then
|
||||
lock_owned=yes; printf '%s\n' "$$" > "$state/lock/pid"
|
||||
else
|
||||
fail "Another run holds $state/lock. If it is stale, verify the recorded process before removing that directory."
|
||||
fi
|
||||
read_lock_pid() {
|
||||
inspected_lock=${1:-$state/lock}
|
||||
check_path "$inspected_lock" dir
|
||||
[ -d "$inspected_lock" ] || return 1
|
||||
check_path "$inspected_lock/pid" file
|
||||
[ -f "$inspected_lock/pid" ] || return 1
|
||||
[ "$(wc -c < "$inspected_lock/pid" | tr -d ' ')" -le 11 ] || return 1
|
||||
# Accept legacy PID-only locks, including a missing final LF. Never signal
|
||||
# PID 0, a process group, or an unbounded/unvalidated integer.
|
||||
awk 'NR!=1 || $0 !~ /^[1-9][0-9]*$/ || length($0)>10 || $0+0>2147483647 {bad=1}
|
||||
END {exit(bad || NR!=1)}' "$inspected_lock/pid" || return 1
|
||||
cat "$inspected_lock/pid"
|
||||
}
|
||||
lock_matches() (
|
||||
matched_lock=${2:-$state/lock}
|
||||
matched_identity=${3:-$lock_identity}
|
||||
[ ! -L "$matched_lock" ] && [ -d "$matched_lock" ] || exit 1
|
||||
[ "$(path_identity "$matched_lock")" = "$matched_identity" ] || exit 1
|
||||
[ "$(read_lock_pid "$matched_lock")" = "$1" ]
|
||||
)
|
||||
cleanup_retired_lock() {
|
||||
[ ! -L "$retired_lock_parent" ] && [ -d "$retired_lock_parent" ] || return 1
|
||||
[ "$(path_identity "$retired_lock_parent")" = "$retired_parent_identity" ] || return 1
|
||||
if [ -e "$retired_lock_parent/lock" ] || [ -L "$retired_lock_parent/lock" ]; then
|
||||
lock_matches "$retired_lock_pid" "$retired_lock_parent/lock" "$retired_lock_identity" || return 1
|
||||
[ ! -L "$retired_lock_parent/lock/reclaim" ] || return 1
|
||||
[ "$(path_identity "$retired_lock_parent/lock/reclaim")" = "$retired_reclaim_identity" ] || return 1
|
||||
rm -f "$retired_lock_parent/lock/pid"
|
||||
rmdir "$retired_lock_parent/lock/reclaim" || return 1
|
||||
rmdir "$retired_lock_parent/lock" || return 1
|
||||
fi
|
||||
rmdir "$retired_lock_parent"
|
||||
}
|
||||
lock_process_state() {
|
||||
lock_process=unknown
|
||||
# A live reused PID is deliberately treated as occupied. Never kill an
|
||||
# owner or infer staleness from its executable name/start-time mismatch.
|
||||
if kill -0 "$lock_pid" 2>/dev/null; then lock_process=live; return; fi
|
||||
# kill -0 can fail for permissions. Require a working process query before
|
||||
# declaring absence; unavailable/unsupported ps fails closed.
|
||||
command -v ps >/dev/null 2>&1 || return 0
|
||||
self_pid=$(ps -p "$$" -o pid= 2>/dev/null | tr -d ' ') || return 0
|
||||
[ "$self_pid" = "$$" ] || return 0
|
||||
process_status=0
|
||||
process_pid=$(ps -p "$lock_pid" -o pid= 2>/dev/null) || process_status=$?
|
||||
process_pid=$(printf '%s' "$process_pid" | tr -d ' ')
|
||||
if [ "$process_status" = 0 ] && [ "$process_pid" = "$lock_pid" ]; then lock_process=live
|
||||
elif [ "$process_status" = 1 ] && [ -z "$process_pid" ]; then lock_process=dead; fi
|
||||
}
|
||||
acquire_lock() {
|
||||
lock_recovered=no
|
||||
while :; do
|
||||
if mkdir "$state/lock" 2>/dev/null; then
|
||||
lock_identity=$(path_identity "$state/lock") || fail 'Cannot inspect the new lock.'
|
||||
(set -C; printf '%s\n' "$$" > "$state/lock/pid") || fail 'Cannot publish the new lock PID.'
|
||||
lock_owned=yes
|
||||
return
|
||||
fi
|
||||
check_path "$state/lock" dir
|
||||
[ -d "$state/lock" ] || fail 'Cannot create the run lock.'
|
||||
lock_identity=$(path_identity "$state/lock") || fail 'Cannot inspect the run lock.'
|
||||
lock_pid=$(read_lock_pid) || fail "Lock PID is missing or invalid; leave $state/lock in place and inspect it before removal."
|
||||
lock_matches "$lock_pid" || fail 'Run lock changed while being inspected; try again later.'
|
||||
lock_process_state
|
||||
case $lock_process in
|
||||
live) say "Another run holds $state/lock (PID $lock_pid); skipping."; exit 0 ;;
|
||||
unknown) fail 'Cannot prove that the lock owner exited; leaving the lock untouched.' ;;
|
||||
esac
|
||||
[ "$lock_recovered" = no ] || fail 'Run lock changed during recovery; try again later.'
|
||||
# Serialize stale recovery inside the exact old directory. A second
|
||||
# reaper must not rename/remove a newer lock acquired in the meantime.
|
||||
if ! mkdir "$state/lock/reclaim" 2>/dev/null; then
|
||||
check_path "$state/lock/reclaim" dir
|
||||
say 'Another run is recovering the stale lock; skipping.'
|
||||
exit 0
|
||||
fi
|
||||
lock_reclaim_identity=$(path_identity "$state/lock/reclaim")
|
||||
lock_reclaim_parent=$(path_identity "$state/lock")
|
||||
lock_reclaim_owned=yes
|
||||
lock_matches "$lock_pid" || fail 'Run lock changed during recovery; leaving it untouched.'
|
||||
lock_process_state
|
||||
[ "$lock_process" = dead ] || fail 'Lock owner may still be running; leaving the lock untouched.'
|
||||
for lock_entry in "$state/lock/"* "$state/lock/".[!.]* "$state/lock/"..?*; do
|
||||
[ -e "$lock_entry" ] || [ -L "$lock_entry" ] || continue
|
||||
case $lock_entry in "$state/lock/pid"|"$state/lock/reclaim") : ;;
|
||||
*) fail 'Unexpected lock contents; refusing automatic stale recovery.' ;; esac
|
||||
done
|
||||
# Retire the guarded inode atomically. Removing the in-directory guard
|
||||
# before rmdir would let a delayed second reaper wedge the empty lock.
|
||||
# A private empty destination prevents mv from merging into another run.
|
||||
# This coordinates cooperating runs; arbitrary path replacement by the
|
||||
# same UID is outside this lock's protection (as with the local state).
|
||||
retired_lock_parent=$(mktemp -d "$state/.conf-sshd.lock.XXXXXX") || fail 'Cannot prepare stale-lock recovery.'
|
||||
retired_parent_identity=$(path_identity "$retired_lock_parent")
|
||||
retired_lock_identity=$lock_identity
|
||||
retired_lock_pid=$lock_pid
|
||||
retired_reclaim_identity=$lock_reclaim_identity
|
||||
lock_matches "$lock_pid" || fail 'Run lock changed during recovery; leaving it untouched.'
|
||||
mv "$state/lock" "$retired_lock_parent/lock" || fail 'Cannot retire the stale lock.'
|
||||
lock_reclaim_owned=no
|
||||
cleanup_retired_lock || fail 'Retired lock changed; inspect it before removal.'
|
||||
retired_lock_parent=
|
||||
lock_recovered=yes
|
||||
done
|
||||
}
|
||||
acquire_lock
|
||||
if [ "$dry_run" = no ]; then chmod 700 "$state"; fi
|
||||
|
||||
# Inputs are origin-only build constants; also reject unbuilt or corrupted scripts.
|
||||
validate_build() {
|
||||
@@ -344,12 +466,30 @@ validate_build() {
|
||||
download() {
|
||||
need curl
|
||||
download_limit=${3:-1048576}
|
||||
# No redirects. Partial/error bodies are never parsed as a successful source.
|
||||
download_timeout=${4:-30}
|
||||
download_failure=retrieval
|
||||
new_temp "$state"; download_headers=$TEMP
|
||||
# No redirects or curl retries. Caller owns the per-source attempt count.
|
||||
# Headers can only reject a failed candidate, never authorize its contents.
|
||||
curl_status=0
|
||||
http_status=$(curl --disable --fail --silent --show-error --proto '=https' --tlsv1.2 \
|
||||
--connect-timeout 10 --max-time 30 --retry 0 \
|
||||
--max-filesize "$download_limit" --output "$2" --write-out '%{http_code}' "$1") || return 1
|
||||
[ "$http_status" = 200 ] || return 1
|
||||
[ "$(wc -c < "$2" | tr -d ' ')" -le "$download_limit" ]
|
||||
--connect-timeout 10 --max-time "$download_timeout" --retry 0 \
|
||||
--max-filesize "$download_limit" --dump-header "$download_headers" \
|
||||
--output "$2" --write-out '%{http_code}' "$1") || curl_status=$?
|
||||
if [ "$http_status" = 503 ] && awk '
|
||||
{sub(/\r$/, "")}
|
||||
/^HTTP\// {count=0; validation=0; next}
|
||||
tolower($0) ~ /^x-conf-sshd-source-failure:/ {
|
||||
count++; value=$0; sub(/^[^:]*:[ \t]*/, "", value); sub(/[ \t]*$/, "", value)
|
||||
if(value=="validation") validation++
|
||||
}
|
||||
END {exit !(count==1 && validation==1)}' "$download_headers"; then
|
||||
download_failure=validation
|
||||
fi
|
||||
if [ "$curl_status" = 63 ]; then download_failure=validation; return 1; fi
|
||||
[ "$curl_status" = 0 ] && [ "$http_status" = 200 ] || return 1
|
||||
# An oversized response is deterministic invalid content, not transport.
|
||||
if [ "$(wc -c < "$2" | tr -d ' ')" -gt "$download_limit" ]; then download_failure=validation; return 1; fi
|
||||
}
|
||||
sha256() {
|
||||
if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'
|
||||
@@ -1423,20 +1563,50 @@ sync_keys() {
|
||||
new_temp "$state"; response=$TEMP
|
||||
new_temp "$state"; signature=$TEMP
|
||||
accepted=no
|
||||
# Full validation occurs per source. A failed mirror never permits a policy
|
||||
# downgrade; candidate-local temporaries are cleaned even when fail() exits.
|
||||
# Five total attempts per local endpoint. Each attempt shares one 30-second
|
||||
# body/signature budget; only retrieval failures use the 1/3/8/12s backoff.
|
||||
# Worker upstream fallback remains separate and does not multiply this loop.
|
||||
need date
|
||||
need sleep
|
||||
while IFS= read -r source_url; do
|
||||
if download "$source_url" "$response" 1048576; then
|
||||
if [ "$policy" = required ] && ! download "$source_url.sig" "$signature" 65536; then
|
||||
say "Signature unavailable from $source_url; trying next locally configured source." >&2
|
||||
continue
|
||||
fi
|
||||
if ( lock_owned=no; created_state=no; created_ssh=no; gpg_home_saved=$gpg_home; gpg_home=; temps=; child_result=0
|
||||
# Preserve the caller keyring but never delete it in this subshell.
|
||||
gpg_home=$gpg_home_saved
|
||||
source_attempt=1
|
||||
while [ "$source_attempt" -le 5 ]; do
|
||||
attempt_started=$(date +%s)
|
||||
attempt_deadline=$((attempt_started + 30))
|
||||
source_failure=retrieval
|
||||
if download "$source_url" "$response" 1048576 30; then
|
||||
# Reject malformed/replayed/expired bodies before a signature
|
||||
# retrieval failure could disguise them as retryable transport.
|
||||
if ! ( lock_owned=no; lock_reclaim_owned=no; created_state=no; created_ssh=no; temps=; child_result=0
|
||||
trap 'child_result=$?; gpg_home=; cleanup "$child_result"' 0
|
||||
if [ "$policy" = required ]; then validate_signed_document; check_replay
|
||||
elif [ "$(sed -n '1p' "$response")" = '# conf-sshd-signed-v1' ]; then validate_signed_document
|
||||
else validate_legacy_response; fi ); then
|
||||
source_failure=validation
|
||||
elif [ "$policy" = required ]; then
|
||||
remaining=$((attempt_deadline - $(date +%s)))
|
||||
# A backwards wall-clock adjustment must not extend this
|
||||
# request past the original maximum per-request timeout.
|
||||
if [ "$remaining" -gt 30 ]; then remaining=30; fi
|
||||
if [ "$remaining" -gt 0 ] && download "$source_url.sig" "$signature" 65536 "$remaining"; then
|
||||
source_failure=none
|
||||
elif [ "$remaining" -gt 0 ]; then source_failure=$download_failure; fi
|
||||
else source_failure=none; fi
|
||||
else source_failure=$download_failure; fi
|
||||
if [ "$source_failure" = none ]; then
|
||||
if ( lock_owned=no; lock_reclaim_owned=no; created_state=no; created_ssh=no; temps=; child_result=0
|
||||
# Preserve the caller keyring but never delete it here.
|
||||
trap 'child_result=$?; gpg_home=; cleanup "$child_result"' 0
|
||||
validate_response ); then accepted=yes; accepted_source=$source_url; break; fi
|
||||
source_failure=validation
|
||||
fi
|
||||
[ "$source_failure" = retrieval ] && [ "$source_attempt" -lt 5 ] || break
|
||||
case $source_attempt in 1) retry_delay=1 ;; 2) retry_delay=3 ;; 3) retry_delay=8 ;; 4) retry_delay=12 ;; esac
|
||||
say "Retrieval attempt $source_attempt/5 failed for $source_url; retrying in ${retry_delay}s." >&2
|
||||
sleep "$retry_delay"
|
||||
source_attempt=$((source_attempt + 1))
|
||||
done
|
||||
[ "$accepted" = no ] || break
|
||||
say "Rejected source $source_url; trying next locally configured source." >&2
|
||||
done < "$urls"
|
||||
[ "$accepted" = yes ] || fail 'No locally configured source passed the required policy; existing keys are unchanged.'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# Add independently managed SERVER public keys here, one ordinary OpenSSH key per line.
|
||||
# Do not copy private keys or automatically import GitHub account authentication keys.
|
||||
# Empty production releases are rejected unless deployment.json explicitly sets allowEmpty=true.
|
||||
# This comment-only template is unconfigured. To intentionally clear managed keys, keep this file but remove all content.
|
||||
# GPG-enabled clients still require a valid signed revocation document.
|
||||
|
||||
+19
-7
@@ -9,7 +9,7 @@ export const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
export const digest = data => createHash('sha256').update(data).digest('hex');
|
||||
import { escapeHTML, commandsFor, renderCommands, renderPage } from '../cf-worker/src/view.js';
|
||||
export { escapeHTML, commandsFor, renderCommands };
|
||||
import { validateFallbackSources, parsePublicKeys, validateKeySource, validateSignedReleaseConfig } from '../cf-worker/src/key-source.js';
|
||||
import { validateFallbackSources, parsePublicKeys, validateKeySource, validateSignedReleaseConfig, isExplicitEmptyKeyFile } from '../cf-worker/src/key-source.js';
|
||||
import {withoutKeyComments, parsePublishedSignedRelease, SIGNATURE_SEPARATOR} from '../cf-worker/src/signed-release.js';
|
||||
import {checkSigningCertificate, validatePublicCertificate} from './signature-tools.mjs';
|
||||
|
||||
@@ -83,19 +83,26 @@ export function makeKeysText(keys, revision, allowEmpty) {
|
||||
|
||||
export async function build({directory = root, outDirectory = join(directory,'cf-worker'), testFixture = false, revision, publishedAt} = {}) {
|
||||
const config = validateConfig(JSON.parse(await readFile(join(directory,'deployment.json'),'utf8')));
|
||||
const input = config.keySource?.type === 'gist' && !testFixture ? '' : await readFile(join(directory,testFixture ? 'tests/fixtures/keys.pub' : 'keys/authorized_keys'),'utf8').catch(error => {if (error.code === 'ENOENT' && !testFixture) return ''; throw error;});
|
||||
const optional = async path => { try { return await readFile(join(directory, path), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
|
||||
let input = testFixture ? await readFile(join(directory, 'tests/fixtures/keys.pub'), 'utf8') : config.keySource?.type === 'gist' ? null : await optional('keys/authorized_keys');
|
||||
let keys = [];
|
||||
revision ||= process.env.GITHUB_SHA || execFileSync('git',['rev-parse','HEAD'],{cwd:directory,encoding:'utf8'}).trim();
|
||||
if (!/^[0-9a-f]{40}$/.test(revision)) throw Error('Release revision must be a 40-character Git commit SHA.');
|
||||
publishedAt ||= new Date().toISOString();
|
||||
const fallbackSources = validateFallbackSources(config.fallbackSources ?? []);
|
||||
const keySource = validateKeySource(config.keySource), signedRelease = validateSignedReleaseConfig(config.signedRelease);
|
||||
const optional = async path => { try { return await readFile(join(directory, path), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } };
|
||||
let signed = null, publicCertificate = null;
|
||||
let signed = null, publicCertificate = null, primaryFile = null;
|
||||
if (keySource.type === 'git' && !testFixture) {
|
||||
const documentFile = await optional('keys/ssh.keys'), bundleFile = await optional('keys/release.bundle');
|
||||
if (documentFile !== null && bundleFile !== null) throw Error('Use keys/ssh.keys plus its optional signature OR keys/release.bundle, not both.');
|
||||
if (documentFile !== null || bundleFile !== null) {
|
||||
// Do not let a leftover signed artifact silently override an explicitly cleared raw file.
|
||||
if (isExplicitEmptyKeyFile(input)) throw Error('Ambiguous Git revocation: empty keys/authorized_keys conflicts with a signed publishing file. Keep only the intended publishing form.');
|
||||
const rawHasContent = input !== null && input.split(/\r?\n/).some(line => {const text = line.replace(/^[ \t]+|[ \t]+$/g, ''); return text !== '' && !text.startsWith('#');});
|
||||
if (isExplicitEmptyKeyFile(documentFile ?? bundleFile) && rawHasContent) throw Error('Ambiguous Git revocation: empty signed publishing file conflicts with nonempty keys/authorized_keys. Keep only the intended publishing form.');
|
||||
primaryFile = documentFile !== null ? 'keys/ssh.keys' : 'keys/release.bundle';
|
||||
input = documentFile ?? bundleFile;
|
||||
if (!isExplicitEmptyKeyFile(input)) {
|
||||
const separator = bundleFile?.indexOf(SIGNATURE_SEPARATOR) ?? -1;
|
||||
if (bundleFile !== null && separator < 0) throw Error('release.bundle lacks its detached-signature separator.');
|
||||
const document = documentFile ?? bundleFile.slice(0, separator);
|
||||
@@ -103,14 +110,19 @@ export async function build({directory = root, outDirectory = join(directory,'cf
|
||||
signed = await parsePublishedSignedRelease(document, signature, {listId: signedRelease?.listId, checkFreshness: false});
|
||||
keys = signed.keys;
|
||||
}
|
||||
} else primaryFile = 'keys/authorized_keys';
|
||||
if (input === null) throw Error(`No server public keys configured: ${primaryFile} is missing. Keep an existing empty file for an explicit revocation.`);
|
||||
}
|
||||
if (!signed) keys = withoutKeyComments(await parseKeys(input));
|
||||
// A blank file may use lone CR line endings; retain its byte count for parser limits.
|
||||
if (!signed) keys = withoutKeyComments(await parseKeys(isExplicitEmptyKeyFile(input) ? input.replace(/\r/g, '\n') : input ?? ''));
|
||||
const explicitEmpty = !testFixture && keySource.type === 'git' && isExplicitEmptyKeyFile(input);
|
||||
if (!testFixture && keySource.type === 'git' && !signed && !keys.length && !explicitEmpty) throw Error('No server public keys configured: a comments-only placeholder is not an explicit empty revocation.');
|
||||
if (signedRelease?.publicKeyFile) {
|
||||
publicCertificate = validatePublicCertificate(await readFile(join(directory, signedRelease.publicKeyFile), 'utf8'));
|
||||
if (signed && !signed.bundle) throw Error('Configured build signature verification requires a valid detached signature.');
|
||||
await checkSigningCertificate(publicCertificate, signedRelease.fingerprint, signed?.bundle);
|
||||
}
|
||||
const allowEmpty = signed ? signed.metadata.revoke : config.allowEmpty;
|
||||
const allowEmpty = signed ? signed.metadata.revoke : explicitEmpty || config.allowEmpty;
|
||||
const needsFallback = keySource.type === 'git' && keys.length === 0 && !allowEmpty && fallbackSources.length > 0;
|
||||
const needsSource = keySource.type === 'gist' || needsFallback;
|
||||
if (keySource.type === 'gist') keys = [];
|
||||
@@ -130,7 +142,7 @@ export async function build({directory = root, outDirectory = join(directory,'cf
|
||||
if (/@@[A-Z_]+@@/.test(script)) throw Error('Unresolved script template token.');
|
||||
if (!script.includes('# conf-sshd-script-v2')) throw Error('Missing script format marker.');
|
||||
execFileSync('sh',['-n'],{input:script,stdio:['pipe','pipe','pipe']});
|
||||
const release = {schema:1,revision,publishedAt,keyCount:keys.length,allowEmpty,sha256:bundle.sha256,keyRevision:signed?.metadata.documentSha256 ?? bundle.sha256,testFixture,baseUrl:config.baseUrl,repositoryUrl:config.repositoryUrl,fallbackSources,keySource,signedRelease,clientDefaults,publicCertificate,signedDocument:signed?.document ?? null,signature:signed?.signature ?? null,signatureAvailable:Boolean(signed?.signature),publicCertificateAvailable:Boolean(publicCertificate),signedBundle:signed?.bundle ?? null,signedMetadata:signed?.metadata ?? null,needsFallback,needsSource,keys,commands:commandsFor(config)};
|
||||
const release = {schema:1,revision,publishedAt,keyCount:keys.length,allowEmpty,sha256:bundle.sha256,keyRevision:signed?.metadata.documentSha256 ?? bundle.sha256,testFixture,baseUrl:config.baseUrl,repositoryUrl:config.repositoryUrl,fallbackSources,keySource,primaryFile,explicitEmpty,signedRelease,clientDefaults,publicCertificate,signedDocument:signed?.document ?? null,signature:signed?.signature ?? null,signatureAvailable:Boolean(signed?.signature),publicCertificateAvailable:Boolean(publicCertificate),signedBundle:signed?.bundle ?? null,signedMetadata:signed?.metadata ?? null,needsFallback,needsSource,keys,commands:commandsFor(config)};
|
||||
let html = await readFile(join(directory,'site/index.html'),'utf8');
|
||||
const publicDir = join(outDirectory,'public'), generatedDir = join(outDirectory,'generated');
|
||||
await rm(publicDir,{recursive:true,force:true});
|
||||
|
||||
@@ -2,12 +2,31 @@ import {readFile} from 'node:fs/promises';
|
||||
import {resolve} from 'node:path';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
import {createHash} from 'node:crypto';
|
||||
import {parsePublicKeys} from '../cf-worker/src/key-source.js';
|
||||
import {parsePublicKeys, resolveKeys, validateKeySource} from '../cf-worker/src/key-source.js';
|
||||
import {parseSignedDocument, SIGNATURE_SEPARATOR, SIGNED_RELEASE_LIMITS, withoutKeyComments, validateSignature} from '../cf-worker/src/signed-release.js';
|
||||
import {checkSigningCertificate} from './signature-tools.mjs';
|
||||
const hash = text => createHash('sha256').update(text).digest('hex');
|
||||
const root = new URL('../', import.meta.url);
|
||||
|
||||
/** Deployment checks the primary itself; a healthy fallback cannot hide an unconfigured primary. */
|
||||
export async function verifyProduction(release, fetchImpl = fetch, {now, timeoutMs} = {}) {
|
||||
if (!release || release.testFixture) throw Error('Refusing to deploy a test-fixture or missing build. Run the production build with real server public keys.');
|
||||
if (!/^[0-9a-f]{40}$/.test(release.revision)) throw Error('Production release revision is invalid.');
|
||||
const keySource = validateKeySource(release.keySource);
|
||||
if (keySource.type === 'git' && !['keys/authorized_keys', 'keys/ssh.keys', 'keys/release.bundle'].includes(release.primaryFile)) throw Error('Production Git release has no configured primary file. Rebuild with an existing key file.');
|
||||
if (keySource.type === 'git' && !release.signedDocument && !release.signedBundle && !release.keys?.length && release.explicitEmpty !== true) throw Error('Production Git revocation lacks an explicitly empty primary file. Rebuild with an existing empty key file.');
|
||||
const requireSigned = release.clientDefaults?.gpgVerification === 'on';
|
||||
const snapshot = await resolveKeys(release, fetchImpl, {requirePrimary: true, requireSigned, ...(now === undefined ? {} : {now}), ...(timeoutMs === undefined ? {} : {timeoutMs})});
|
||||
if (requireSigned && snapshot.signedMetadata?.listId !== release.clientDefaults.listId) throw Error('Client default list ID differs from the primary signed document.');
|
||||
if (requireSigned && release.signedRelease?.fingerprint && release.clientDefaults.pinMode === 'primary' && release.clientDefaults.fingerprint !== release.signedRelease.fingerprint) throw Error('Client primary fingerprint differs from the configured signing certificate.');
|
||||
if (snapshot.signedDocument && release.signedRelease?.publicKeyFile) {
|
||||
if (!snapshot.signedBundle) throw Error('Configured build signature verification requires a valid detached signature.');
|
||||
await checkSigningCertificate(release.publicCertificate, release.signedRelease.fingerprint, snapshot.signedBundle);
|
||||
}
|
||||
const cryptoNote = snapshot.signedDocument && !release.signedRelease?.publicKeyFile ? ' OpenPGP not checked: no build verification certificate configured.' : '';
|
||||
return `Production primary checked: ${release.revision}; ${snapshot.keyCount} key(s) from ${snapshot.source.type}.${cryptoNote}`;
|
||||
}
|
||||
|
||||
async function remoteText(url, maxBytes, {allowMissing = false, fetchImpl = fetch} = {}) {
|
||||
const signal = AbortSignal.timeout(20000);
|
||||
const response = await fetchImpl(url, {cache: 'no-store', redirect: 'error', signal});
|
||||
@@ -29,7 +48,7 @@ async function remoteText(url, maxBytes, {allowMissing = false, fetchImpl = fetc
|
||||
} finally { await reader.cancel().catch(() => {}); reader.releaseLock(); }
|
||||
}
|
||||
|
||||
export async function verifyRemote(manifest, fetchImpl = fetch) {
|
||||
export async function verifyRemote(manifest, fetchImpl = fetch, {now} = {}) {
|
||||
const read = (path, maxBytes, allowMissing = false) => remoteText(manifest.baseUrl + path, maxBytes, {allowMissing, fetchImpl});
|
||||
const metadata = JSON.parse(await read('/release.json', 64 * 1024));
|
||||
if (metadata.revision !== manifest.revision || metadata.testFixture) throw Error('Remote release does not match this build.');
|
||||
@@ -59,6 +78,7 @@ export async function verifyRemote(manifest, fetchImpl = fetch) {
|
||||
if (signature !== null) validateSignature(signature);
|
||||
cryptoNote = ' OpenPGP not checked: no build verification certificate configured.';
|
||||
}
|
||||
if (manifest.clientDefaults?.gpgVerification === 'on') await parseSignedDocument(document, {listId: manifest.clientDefaults.listId, ...(now === undefined ? {} : {now})});
|
||||
} else {
|
||||
const match = /^# conf-sshd-v1\n# revision ([0-9a-f]{40})\n# key-count (0|[1-9][0-9]*)\n# allow-empty (yes|no)\n# sha256 ([0-9a-f]{64})\n# end-metadata\n([\s\S]*)$/.exec(document);
|
||||
if (!match || match[1] !== manifest.revision) throw Error('Remote key manifest invalid.');
|
||||
@@ -66,7 +86,9 @@ export async function verifyRemote(manifest, fetchImpl = fetch) {
|
||||
if (hash(payload) !== digest) throw Error('Remote key body does not match its response digest.');
|
||||
const keys = await parsePublicKeys(payload);
|
||||
count = keys.length; payloadHash = digest;
|
||||
if (keys.length !== Number(countText) || (!keys.length && (!manifest.allowEmpty || empty !== 'yes')) || withoutKeyComments(keys).map(key => key.text + '\n').join('') !== payload) throw Error('Remote key count/empty/canonical policy invalid.');
|
||||
// A pinned Gist may be intentionally cleared after this code build, without changing allowEmpty.
|
||||
const gistRevocation = manifest.keySource?.type === 'gist' && metadata.source?.type === 'gist' && metadata.allowEmpty === true && metadata.keyCount === 0;
|
||||
if (keys.length !== Number(countText) || (!keys.length && ((!manifest.allowEmpty && !gistRevocation) || empty !== 'yes')) || withoutKeyComments(keys).map(key => key.text + '\n').join('') !== payload) throw Error('Remote key count/empty/canonical policy invalid.');
|
||||
if (manifest.clientDefaults?.gpgVerification === 'on') throw Error('Verification-enabled clients require a signed-format document.');
|
||||
}
|
||||
if (!dynamic && payloadHash !== manifest.sha256) throw Error('Remote repository payload differs from this build.');
|
||||
@@ -75,8 +97,14 @@ export async function verifyRemote(manifest, fetchImpl = fetch) {
|
||||
}
|
||||
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const args = process.argv.slice(2);
|
||||
if (args.some(arg => arg !== '--remote') || args.length > 1) throw Error('Usage: node scripts/verify-release.mjs [--remote]');
|
||||
if (args.includes('--remote')) {
|
||||
const manifest = JSON.parse(await readFile(new URL('cf-worker/generated/manifest.json', root), 'utf8'));
|
||||
if (manifest.testFixture) throw Error('Refusing to deploy a test-fixture build. Run the production build with real server public keys.');
|
||||
if (!process.argv.includes('--remote')) console.log(`Production release checked: ${manifest.revision}`);
|
||||
else console.log(await verifyRemote(manifest));
|
||||
if (manifest.testFixture) throw Error('Refusing to verify a test-fixture deployment.');
|
||||
console.log(await verifyRemote(manifest));
|
||||
} else {
|
||||
const {default: release} = await import(new URL('cf-worker/generated/release.js', root));
|
||||
console.log(await verifyProduction(release));
|
||||
}
|
||||
}
|
||||
|
||||
+50
-4
@@ -5,6 +5,7 @@ import {tmpdir} from 'node:os';
|
||||
import {join} from 'node:path';
|
||||
import {renderPage} from '../cf-worker/src/view.js';
|
||||
import {validateConfig,parseKeys,makeKeysText,commandsFor,build,root,digest} from '../scripts/build.mjs';
|
||||
import {verifyProduction} from '../scripts/verify-release.mjs';
|
||||
const config = {baseUrl:'https://ssh.example.com',repositoryUrl:'https://github.com/example/keys',defaultCron:'*/15 * * * *',allowEmpty:false};
|
||||
const fixture = await readFile(new URL('./fixtures/keys.pub',import.meta.url),'utf8');
|
||||
const canonicalFixture=fixture.trim().split(/ +/).slice(0,2).join(' ')+'\n';
|
||||
@@ -63,7 +64,7 @@ test('build creates consistent assets/release; production empty is blocked',asyn
|
||||
} finally {await rm(directory,{recursive:true,force:true});}
|
||||
});
|
||||
|
||||
test('fallback configuration allows an empty primary only with explicit bounded HTTPS sources',async()=>{
|
||||
test('fallback URLs cannot bypass the unconfigured-primary deployment gate',async()=>{
|
||||
assert.throws(()=>validateConfig({...config,fallbackSources:['http://keys.example.com']}));
|
||||
assert.throws(()=>validateConfig({...config,fallbackSources:['https://user:[email protected]']}));
|
||||
assert.throws(()=>validateConfig({...config,fallbackSources:Array(6).fill('https://keys.example.com')}));
|
||||
@@ -72,9 +73,54 @@ test('fallback configuration allows an empty primary only with explicit bounded
|
||||
for(const path of ['site','tests/fixtures','keys']) {await mkdir(join(directory,path),{recursive:true});await cp(join(root,path),join(directory,path),{recursive:true});}
|
||||
await cp(join(root,'conf-sshd.sh'),join(directory,'conf-sshd.sh'));
|
||||
await writeFile(join(directory,'deployment.json'),JSON.stringify({...config,fallbackSources:['https://keys.example.com/server.keys']}));
|
||||
const release=await build({directory,revision:'d'.repeat(40)});
|
||||
assert.equal(release.needsFallback,true);assert.equal(release.sha256,null);assert.equal(release.keyCount,0);
|
||||
assert.ok((await readFile(join(directory,'cf-worker/public/index.html'),'utf8')).includes('未发布撤销指令'));
|
||||
await assert.rejects(build({directory,revision:'d'.repeat(40)}),/No server public keys configured/);
|
||||
} finally {await rm(directory,{recursive:true,force:true});}
|
||||
});
|
||||
|
||||
test('production distinguishes missing/comment-only files from deliberate blank revocations',async()=>{
|
||||
const directory=await mkdtemp(join(tmpdir(),'conf-sshd-primary-build-'));
|
||||
try {
|
||||
for(const path of ['site','tests/fixtures','keys']) await cp(join(root,path),join(directory,path),{recursive:true});
|
||||
await cp(join(root,'conf-sshd.sh'),join(directory,'conf-sshd.sh'));
|
||||
const keyPath=join(directory,'keys/authorized_keys'), options={directory,revision:'e'.repeat(40)};
|
||||
for(const allowEmpty of [false,true]) for(const fallbackSources of [[],['https://keys.example.com/server.keys']]) {
|
||||
await writeFile(join(directory,'deployment.json'),JSON.stringify({...config,allowEmpty,fallbackSources}));
|
||||
for(const content of [null,'# Add server keys here.\n','# placeholder\n \t\n']) {
|
||||
if(content===null) await rm(keyPath,{force:true}); else await writeFile(keyPath,content);
|
||||
await assert.rejects(build(options),/No server public keys configured/);
|
||||
}
|
||||
for(const content of ['',' ','\n','\r',' \t\r\n\t ']) {
|
||||
await writeFile(keyPath,content);
|
||||
const release=await build(options);
|
||||
assert.equal(release.primaryFile,'keys/authorized_keys');assert.equal(release.allowEmpty,true);assert.equal(release.explicitEmpty,true);
|
||||
assert.equal(release.needsFallback,false);assert.equal(release.needsSource,false);assert.equal(release.keyCount,0);
|
||||
assert.equal(release.sha256,digest(''));assert.equal(release.signatureAvailable,false);
|
||||
assert.match(await readFile(join(directory,'cf-worker/public/ssh.keys'),'utf8'),/# key-count 0\n# allow-empty yes\n/);
|
||||
assert.match(await verifyProduction(release,()=>assert.fail('Git revocation must not fetch fallback')),/0 key\(s\) from explicit-empty/);
|
||||
}
|
||||
await writeFile(keyPath,fixture);
|
||||
const release=await build(options);assert.equal(release.keyCount,1);
|
||||
assert.match(await verifyProduction(release,()=>assert.fail('Git primary must not fetch fallback')),/1 key\(s\) from repository/);
|
||||
}
|
||||
for(const content of ['\u00a0','\v','\0','\r'.repeat(1024*1024+1)]) {
|
||||
await writeFile(keyPath,content);
|
||||
await assert.rejects(build(options));
|
||||
}
|
||||
await rm(keyPath);
|
||||
const fixtureRelease=await build({...options,testFixture:true});
|
||||
assert.equal(fixtureRelease.testFixture,true);assert.equal(fixtureRelease.keyCount,1);
|
||||
await assert.rejects(verifyProduction(fixtureRelease),/test-fixture/);
|
||||
} finally {await rm(directory,{recursive:true,force:true});}
|
||||
});
|
||||
|
||||
test('ON builds never turn a blank unsigned Git file into a signed revoke',async()=>{
|
||||
const directory=await mkdtemp(join(tmpdir(),'conf-sshd-on-empty-'));
|
||||
try {
|
||||
await cp(join(root,'site'),join(directory,'site'),{recursive:true});await mkdir(join(directory,'keys'));
|
||||
await cp(join(root,'conf-sshd.sh'),join(directory,'conf-sshd.sh'));
|
||||
await writeFile(join(directory,'deployment.json'),JSON.stringify({...config,allowEmpty:true,fallbackSources:['https://keys.example.com/server.keys'],clientDefaults:{gpgVerification:'on',fingerprint:'A'.repeat(40),listId:'production'}}));
|
||||
await writeFile(join(directory,'keys/authorized_keys'),'\n');
|
||||
await assert.rejects(build({directory,revision:'f'.repeat(40)}),/require a signed document/);
|
||||
} finally {await rm(directory,{recursive:true,force:true});}
|
||||
});
|
||||
|
||||
|
||||
+187
-1
@@ -2,7 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import {createHash, generateKeyPairSync} from 'node:crypto';
|
||||
import {FallbackUnavailableError, KEY_SOURCE_LIMITS, makeKeyBundle, parsePublicKeys, resolveKeys, validateFallbackSources} from '../cf-worker/src/key-source.js';
|
||||
import {FallbackUnavailableError, KEY_SOURCE_LIMITS, isExplicitEmptyKeyFile, makeKeyBundle, parsePublicKeys, resolveKeys, validateFallbackSources} from '../cf-worker/src/key-source.js';
|
||||
import {SIGNED_BUNDLE_MAX_BYTES, makeSignedDocument, SIGNATURE_SEPARATOR} from '../cf-worker/src/signed-release.js';
|
||||
|
||||
const fixture = await readFile(new URL('./fixtures/keys.pub', import.meta.url), 'utf8');
|
||||
@@ -471,3 +471,189 @@ test('named Gist bundles cannot silently downgrade to raw key files', async () =
|
||||
assert.equal(result.source.type,'fallback');
|
||||
}
|
||||
});
|
||||
|
||||
test('only an existing ASCII-whitespace-empty primary file expresses unsigned revocation', () => {
|
||||
for (const input of ['', ' \t\r\n\n ']) assert.equal(isExplicitEmptyKeyFile(input), true);
|
||||
for (const input of [null, undefined, 0, '# initial placeholder\n', '\u00a0', '\u0000', '\u000b', fixture]) assert.equal(isExplicitEmptyKeyFile(input), false);
|
||||
});
|
||||
|
||||
for (const filename of ['ssh.keys', 'release.bundle']) {
|
||||
for (const input of ['', ' \t\r\n\n ']) {
|
||||
test(`blank pinned Gist ${filename} revokes without any fallback (${JSON.stringify(input)})`, async () => {
|
||||
const visited = [];
|
||||
const result = await resolveKeys(gistRelease, async url => {
|
||||
visited.push(url);
|
||||
assert.ok(url === gistUrl || url === gistUrl + '/' + gistRevision);
|
||||
return jsonResponse(gistData({[filename]: gistFile(filename, input)}));
|
||||
}, {requirePrimary: true});
|
||||
assert.deepEqual(visited, [gistUrl, gistUrl + '/' + gistRevision]);
|
||||
assert.equal(result.keyCount, 0); assert.equal(result.allowEmpty, true);
|
||||
assert.equal(result.source.type, 'gist'); assert.equal(result.source.file, filename);
|
||||
assert.equal(result.source.gistRevision, gistRevision);
|
||||
assert.equal(result.sha256, hash(''));
|
||||
assert.match(result.keysText, /# key-count 0\n# allow-empty yes\n/);
|
||||
assert.equal(result.signedDocument, null); assert.equal(result.signature, null);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('blank Gist primary and Git primary cannot be replaced with a strict signed fallback', async () => {
|
||||
for (const filename of ['ssh.keys', 'release.bundle']) {
|
||||
const visited = [];
|
||||
const error = await unavailable(async url => {
|
||||
visited.push(url);
|
||||
if (!url.startsWith(gistUrl)) return response(signedBundleFixture);
|
||||
return jsonResponse(gistData({[filename]: gistFile(filename, '')}));
|
||||
}, {requireSigned: true, now: 200}, gistRelease);
|
||||
assert.deepEqual(visited, [gistUrl, gistUrl + '/' + gistRevision]);
|
||||
assert.deepEqual(error.diagnostics, [{index: -1, code: 'unsigned-revocation'}]);
|
||||
assert.equal(error.failureKind, 'validation');
|
||||
}
|
||||
const error = await unavailable(() => assert.fail('Unsigned Git revocation must not fetch fallback'), {requireSigned: true}, {...emptyRelease, allowEmpty: true});
|
||||
assert.equal(error.diagnostics[0].code, 'unsigned-revocation');
|
||||
});
|
||||
|
||||
test('conflicting blank and nonblank Gist formats fail closed without fallback', async () => {
|
||||
for (const [split, bundle] of [['', signedBundleFixture], [fixture, ''], ['# placeholder\n', ''], ['', 'invalid bundle']]) {
|
||||
for (const options of [{}, {requireSigned: true, now: 200}, {requirePrimary: true}]) {
|
||||
const visited = [];
|
||||
const error = await unavailable(async url => {
|
||||
visited.push(url);
|
||||
if (!url.startsWith(gistUrl)) return response(fixture);
|
||||
return jsonResponse(gistData({'ssh.keys': gistFile('ssh.keys', split), 'release.bundle': gistFile('release.bundle', bundle)}));
|
||||
}, options, gistRelease);
|
||||
assert.deepEqual(visited, [gistUrl, gistUrl + '/' + gistRevision]);
|
||||
assert.deepEqual(error.diagnostics, [{index: -1, code: 'ambiguous-empty-primary'}]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('a validated Gist clear still blocks fallback when the competing format is malformed', async () => {
|
||||
for (const emptyName of ['ssh.keys', 'release.bundle']) {
|
||||
const otherName = emptyName === 'ssh.keys' ? 'release.bundle' : 'ssh.keys';
|
||||
const error = await unavailable(async url => {
|
||||
assert.ok(url.startsWith(gistUrl), 'Known clear must not fetch a fallback');
|
||||
return jsonResponse(gistData({[emptyName]: gistFile(emptyName, ''), [otherName]: {...gistFile(otherName, fixture), truncated: true}}));
|
||||
}, {}, gistRelease);
|
||||
assert.equal(error.diagnostics[0].code, 'ambiguous-empty-primary');
|
||||
}
|
||||
});
|
||||
|
||||
test('both validated blank Gist formats express the same clear', async () => {
|
||||
const result = await resolveKeys(gistRelease, async url => {
|
||||
assert.ok(url.startsWith(gistUrl));
|
||||
return jsonResponse(gistData({'ssh.keys': gistFile('ssh.keys', ''), 'release.bundle': gistFile('release.bundle', '\n')}));
|
||||
});
|
||||
assert.equal(result.keyCount, 0); assert.equal(result.allowEmpty, true);
|
||||
});
|
||||
|
||||
test('empty latest Gist contents never override its pinned nonempty revision', async () => {
|
||||
const result = await resolveKeys(gistRelease, async url => {
|
||||
assert.ok(url.startsWith(gistUrl));
|
||||
return jsonResponse(gistData({'ssh.keys': gistFile('ssh.keys', url === gistUrl ? '' : fixture)}));
|
||||
});
|
||||
assert.equal(result.keyCount, 1); assert.equal(result.allowEmpty, false);
|
||||
});
|
||||
|
||||
test('missing, comments-only and untrusted Gist primaries never synthesize a clear', async () => {
|
||||
const cases = [
|
||||
() => gistData(),
|
||||
() => gistData({'ssh.keys': gistFile('ssh.keys', '# initial placeholder\n\n')}),
|
||||
() => ({...gistData({'ssh.keys': gistFile('ssh.keys', '')}), owner: {id: 999}}),
|
||||
() => ({...gistData({'ssh.keys': gistFile('ssh.keys', '')}), history: [{version: '../invalid'}]}),
|
||||
() => gistData({'ssh.keys': {...gistFile('ssh.keys', ''), size: 1}}),
|
||||
() => gistData({'ssh.keys': {...gistFile('ssh.keys', ''), truncated: true}}),
|
||||
];
|
||||
for (const data of cases) {
|
||||
const result = await resolveKeys(gistRelease, async url => url.startsWith(gistUrl) ? jsonResponse(data()) : response(fixture));
|
||||
assert.equal(result.source.type, 'fallback'); assert.equal(result.keyCount, 1); assert.equal(result.allowEmpty, false);
|
||||
const error = await unavailable(async url => {
|
||||
assert.ok(url.startsWith(gistUrl), 'Primary preflight cannot fetch fallback');
|
||||
return jsonResponse(data());
|
||||
}, {requirePrimary: true}, gistRelease);
|
||||
assert.equal(error.failureKind, 'validation');
|
||||
}
|
||||
});
|
||||
|
||||
test('owner validation also precedes clear at the pinned Gist revision', async () => {
|
||||
const error = await unavailable(async url => {
|
||||
assert.ok(url.startsWith(gistUrl));
|
||||
const data = gistData({'ssh.keys': gistFile('ssh.keys', '')});
|
||||
if (url !== gistUrl) data.owner.id = 999;
|
||||
return jsonResponse(data);
|
||||
}, {requirePrimary: true}, gistRelease);
|
||||
assert.deepEqual(error.diagnostics, [{index: -1, code: 'gist-owner-mismatch'}]);
|
||||
});
|
||||
|
||||
test('Gist HTTP and network failure never clear and cannot be hidden by preflight fallback', async () => {
|
||||
for (const mode of ['404', '503', 'network']) {
|
||||
const fetcher = async url => {
|
||||
if (!url.startsWith(gistUrl)) return response(fixture);
|
||||
if (mode === 'network') throw Error('SECRET network information');
|
||||
return new Response('', {status: Number(mode)});
|
||||
};
|
||||
const result = await resolveKeys(gistRelease, fetcher);
|
||||
assert.equal(result.source.type, 'fallback'); assert.equal(result.allowEmpty, false);
|
||||
const visited = [];
|
||||
const error = await unavailable(async url => {visited.push(url); return fetcher(url);}, {requirePrimary: true}, gistRelease);
|
||||
assert.deepEqual(visited, [gistUrl]); assert.equal(error.failureKind, 'retrieval');
|
||||
assert.doesNotMatch(JSON.stringify(error), /SECRET|https:/);
|
||||
}
|
||||
});
|
||||
|
||||
test('primary-only preflight accepts signed revocation and rejects missing, malformed or unsigned Git primary', async () => {
|
||||
const document = await makeSignedDocument('', {...signedPolicy, revoke: true});
|
||||
const signed = {...emptyRelease, signedDocument: document, signature: signatureFixture};
|
||||
const result = await resolveKeys(signed, () => assert.fail('No fetch'), {requirePrimary: true, requireSigned: true, now: 200});
|
||||
assert.equal(result.keyCount, 0); assert.equal(result.allowEmpty, true);
|
||||
for (const [release, options, code] of [
|
||||
[emptyRelease, {}, 'unconfigured-primary'],
|
||||
[{...emptyRelease, signedDocument: 'invalid'}, {}, 'invalid-signed-release'],
|
||||
[{...emptyRelease, keys: fixtureKeys}, {requireSigned: true}, 'invalid-signed-release'],
|
||||
[{...emptyRelease, allowEmpty: true}, {requireSigned: true}, 'unsigned-revocation'],
|
||||
]) {
|
||||
const error = await unavailable(() => assert.fail('Preflight must not fetch'), {requirePrimary: true, ...options}, release);
|
||||
assert.equal(error.diagnostics[0].code, code);
|
||||
}
|
||||
await assert.rejects(resolveKeys(emptyRelease, () => assert.fail('Invalid option must not fetch'), {requirePrimary: 'yes'}), /requirePrimary must be boolean/);
|
||||
});
|
||||
|
||||
test('empty arbitrary fallback remains unavailable, including whitespace and comments', async () => {
|
||||
for (const body of ['', ' \t\r\n', '# placeholder\n']) {
|
||||
const error = await unavailable(async () => response(body), {}, {...emptyRelease, fallbackSources: [urls[0]]});
|
||||
assert.equal(error.diagnostics[0].code, 'empty'); assert.equal(error.failureKind, 'validation');
|
||||
}
|
||||
});
|
||||
|
||||
test('failed-source retry classification retains any retrieval error even beyond bounded diagnostics', async () => {
|
||||
for (const code of ['network-error', 'timeout', 'http-error', 'redirect']) {
|
||||
const error = new FallbackUnavailableError([...Array.from({length: 5}, (_, index) => ({index, code: 'invalid-keys'})), {index: 5, code, status: 404}]);
|
||||
assert.equal(error.failureKind, 'retrieval'); assert.equal(error.diagnostics.length, 5);
|
||||
}
|
||||
assert.equal(new FallbackUnavailableError([{index: -1, code: 'invalid-signed-release'}, {index: 0, code: 'empty'}]).failureKind, 'validation');
|
||||
});
|
||||
|
||||
test('a stale detached signature does not turn a blank Gist file into a key-bearing conflict', async () => {
|
||||
for (const signature of [signatureFixture, 'bad old signature']) {
|
||||
const fetcher = async url => {
|
||||
assert.ok(url.startsWith(gistUrl), 'Blank primary must not fetch fallback');
|
||||
return jsonResponse(gistData({'ssh.keys': gistFile('ssh.keys', ''), 'ssh.keys.sig': gistFile('ssh.keys.sig', signature)}));
|
||||
};
|
||||
const result = await resolveKeys(gistRelease, fetcher, {requirePrimary: true});
|
||||
assert.equal(result.keyCount, 0); assert.equal(result.allowEmpty, true);
|
||||
assert.equal(result.signature, null); assert.equal(result.signedDocument, null);
|
||||
const error = await unavailable(fetcher, {requirePrimary: true, requireSigned: true, now: 200}, gistRelease);
|
||||
assert.equal(error.diagnostics[0].code, 'unsigned-revocation');
|
||||
}
|
||||
});
|
||||
|
||||
test('strict primary-only Gist preflight accepts an existing signed-format revocation unchanged', async () => {
|
||||
const document = await makeSignedDocument('', {...signedPolicy, revoke: true});
|
||||
const result = await resolveKeys(gistRelease, async url => {
|
||||
assert.ok(url.startsWith(gistUrl));
|
||||
return jsonResponse(gistData({'ssh.keys': gistFile('ssh.keys', document), 'ssh.keys.sig': gistFile('ssh.keys.sig', signatureFixture)}));
|
||||
}, {requirePrimary: true, requireSigned: true, now: 200});
|
||||
assert.equal(result.keyCount, 0); assert.equal(result.allowEmpty, true);
|
||||
assert.equal(result.keysText, document); assert.equal(result.signature, signatureFixture);
|
||||
assert.equal(result.signedMetadata.sequence, signedPolicy.sequence);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFile} from 'node:fs/promises';
|
||||
import {verifyProduction, verifyRemote} from '../scripts/verify-release.mjs';
|
||||
import {makeKeyBundle} from '../cf-worker/src/key-source.js';
|
||||
import {makeSignedDocument, SIGNATURE_SEPARATOR} from '../cf-worker/src/signed-release.js';
|
||||
import {openPgpFixture} from './helpers/openpgp-fixture.mjs';
|
||||
|
||||
const fixture = await readFile(new URL('./fixtures/keys.pub', import.meta.url), 'utf8');
|
||||
const revision = 'a'.repeat(40), gistRevision = 'b'.repeat(40);
|
||||
const source = {type:'gist',id:'c'.repeat(32),ownerId:7,ownerLogin:'example',file:'ssh.keys',signatureFile:'ssh.keys.sig',bundleFile:'release.bundle'};
|
||||
const fallback = 'https://keys.example.com/fallback';
|
||||
const release = {revision,testFixture:false,keys:[],allowEmpty:false,needsSource:true,keySource:source,fallbackSources:[fallback],baseUrl:'https://ssh.example.com',clientDefaults:{gpgVerification:'off'}};
|
||||
const policy = {listId:'production',sequence:1,issuedAt:100,expiresAt:300};
|
||||
// Armor-shape fixture only. Crypto tests below generate and verify a real detached signature.
|
||||
const signature = '-----BEGIN PGP SIGNATURE-----\n\nYWJj\n-----END PGP SIGNATURE-----\n';
|
||||
const strict = {...release,clientDefaults:{gpgVerification:'on',listId:'production',fingerprint:'A'.repeat(40),pinMode:'primary'}};
|
||||
const gistFile = (name,content) => ({filename:name,content,size:Buffer.byteLength(content),truncated:false});
|
||||
function gistFetcher(content, {files, mutate = data => data} = {}) {
|
||||
const visited = [];
|
||||
const fetcher = async (url, init) => {
|
||||
visited.push(url);
|
||||
assert.notEqual(url,fallback,'Deployment preflight must never use fallback to mask the primary');
|
||||
assert.equal(init.redirect,'manual');assert.equal(init.cache,'no-store');
|
||||
assert.ok(init.signal instanceof AbortSignal);
|
||||
assert.ok([`https://api.github.com/gists/${source.id}`,`https://api.github.com/gists/${source.id}/${gistRevision}`].includes(url));
|
||||
const data = {id:source.id,owner:{id:source.ownerId},public:true,truncated:false,history:[{version:gistRevision}],files:files ?? {'ssh.keys':gistFile('ssh.keys',content)}};
|
||||
return new Response(JSON.stringify(mutate(data)));
|
||||
};
|
||||
return {fetcher,visited};
|
||||
}
|
||||
|
||||
test('preflight rejects fixture/legacy unconfigured Git builds before any network request',async()=>{
|
||||
const noFetch=()=>assert.fail('Unconfigured builds must not make network requests');
|
||||
await assert.rejects(verifyProduction({...release,testFixture:true},noFetch),/test-fixture/);
|
||||
await assert.rejects(verifyProduction({...release,keySource:{type:'git'},allowEmpty:true},noFetch),/no configured primary file/);
|
||||
await assert.rejects(verifyProduction({...release,keySource:{type:'git'},primaryFile:'keys/authorized_keys',allowEmpty:true},noFetch),/explicitly empty primary/);
|
||||
});
|
||||
|
||||
test('Gist preflight pins both reads and accepts valid keys or an existing blank OFF file',async()=>{
|
||||
for(const content of [fixture,'',' ','\n',' \t\r\n']) {
|
||||
const {fetcher,visited}=gistFetcher(content);
|
||||
assert.match(await verifyProduction(release,fetcher),new RegExp(`${content===fixture?1:0} key\\(s\\) from gist`));
|
||||
assert.deepEqual(visited,[`https://api.github.com/gists/${source.id}`,`https://api.github.com/gists/${source.id}/${gistRevision}`]);
|
||||
}
|
||||
});
|
||||
|
||||
test('Gist preflight fails absent, comments-only, invalid and wrong-owner primary despite a configured fallback',async()=>{
|
||||
for(const options of [
|
||||
{files:{}},
|
||||
{files:{'ssh.keys':gistFile('ssh.keys','# Add keys here.\n')}},
|
||||
{files:{'ssh.keys':gistFile('ssh.keys','ssh-ed25519 not-a-key')}},
|
||||
{mutate:data=>({...data,owner:{id:8}})},
|
||||
{mutate:data=>({...data,history:[]})},
|
||||
{mutate:data=>({...data,public:false})},
|
||||
]) {
|
||||
const {fetcher}=gistFetcher(fixture,options);
|
||||
await assert.rejects(verifyProduction({...release,allowEmpty:true},fetcher),/source|primary/i);
|
||||
}
|
||||
});
|
||||
|
||||
test('Gist preflight cannot hide a primary HTTP/network failure or timeout behind fallback keys',async()=>{
|
||||
for(const failure of ['404','503','network','timeout']) {
|
||||
const visited=[];
|
||||
const fetcher=async url=>{
|
||||
visited.push(url);assert.notEqual(url,fallback);
|
||||
if(failure==='network') throw Error('network failure');
|
||||
if(failure==='timeout') return new Promise(()=>{});
|
||||
return new Response('',{status:Number(failure)});
|
||||
};
|
||||
await assert.rejects(verifyProduction(release,fetcher,{timeoutMs:5}),/source|primary/i);
|
||||
assert.ok(visited.length>0);
|
||||
}
|
||||
});
|
||||
|
||||
test('Gist ON preflight requires a current signed release and explicit signed revoke',async()=>{
|
||||
for(const content of ['', ' \t\n',fixture]) await assert.rejects(verifyProduction(strict,gistFetcher(content).fetcher,{now:200}),/source|primary/i);
|
||||
const revoke=await makeSignedDocument('',{...policy,revoke:true});
|
||||
const populated=await makeSignedDocument(fixture,policy);
|
||||
for(const document of [revoke,populated]) {
|
||||
const files={'ssh.keys':gistFile('ssh.keys',document),'ssh.keys.sig':gistFile('ssh.keys.sig',signature)};
|
||||
const result=await verifyProduction(strict,gistFetcher(null,{files}).fetcher,{now:200});
|
||||
assert.match(result,new RegExp(`${document===revoke?0:1} key\\(s\\) from gist`));
|
||||
assert.match(result,/OpenPGP not checked/);
|
||||
await assert.rejects(verifyProduction(strict,gistFetcher(null,{files}).fetcher,{now:300}),/source|primary/i);
|
||||
await assert.rejects(verifyProduction(strict,gistFetcher(document).fetcher,{now:200}),/source|primary/i);
|
||||
files['ssh.keys.sig']=gistFile('ssh.keys.sig','bad signature');
|
||||
await assert.rejects(verifyProduction(strict,gistFetcher(null,{files}).fetcher,{now:200}),/source|primary/i);
|
||||
}
|
||||
const wrong=await makeSignedDocument('',{...policy,listId:'wrong',revoke:true});
|
||||
const files={'release.bundle':gistFile('release.bundle',wrong+SIGNATURE_SEPARATOR+signature)};
|
||||
await assert.rejects(verifyProduction(strict,gistFetcher(null,{files}).fetcher,{now:200}),/list ID differs/);
|
||||
});
|
||||
|
||||
test('configured Gist public certificate verifies the exact signed revoke before deployment',async()=>{
|
||||
const signer=openPgpFixture();
|
||||
const now=Math.floor(Date.now()/1000);
|
||||
const document=await makeSignedDocument('',{...policy,revoke:true,issuedAt:now-10,expiresAt:now+600});
|
||||
const releaseWithCertificate={...strict,publicCertificate:signer.publicKey,signedRelease:{listId:'production',publicKeyFile:'keys/certificate.asc',fingerprint:signer.primaryFingerprint},clientDefaults:{...strict.clientDefaults,fingerprint:signer.primaryFingerprint}};
|
||||
const files={'release.bundle':gistFile('release.bundle',document+SIGNATURE_SEPARATOR+signer.sign(document))};
|
||||
assert.doesNotMatch(await verifyProduction(releaseWithCertificate,gistFetcher(null,{files}).fetcher),/OpenPGP not checked/);
|
||||
files['release.bundle']=gistFile('release.bundle',document.replace('sequence 1','sequence 2')+SIGNATURE_SEPARATOR+signer.sign(document));
|
||||
await assert.rejects(verifyProduction(releaseWithCertificate,gistFetcher(null,{files}).fetcher),/signature verification failed/);
|
||||
});
|
||||
|
||||
test('remote verification accepts an explicit empty pinned Gist with OFF but preserves ON rejection',async()=>{
|
||||
const empty=await makeKeyBundle([],revision,true);
|
||||
const metadata={revision,sha256:empty.sha256,keyCount:0,allowEmpty:true,source:{...source,gistRevision}};
|
||||
const fetcher=async url=>new Response(url.endsWith('/release.json')?JSON.stringify(metadata):empty.text);
|
||||
assert.match(await verifyRemote(release,fetcher),/\(0 keys\)/);
|
||||
await assert.rejects(verifyRemote(strict,fetcher),/signed-format/);
|
||||
metadata.allowEmpty=false;
|
||||
await assert.rejects(verifyRemote(release,fetcher),/empty\/canonical/);
|
||||
metadata.allowEmpty=true;metadata.source={type:'fallback',url:fallback};
|
||||
await assert.rejects(verifyRemote(release,fetcher),/empty\/canonical/);
|
||||
});
|
||||
|
||||
test('remote verification ON checks signed-revoke freshness without claiming crypto when no certificate exists',async()=>{
|
||||
const document=await makeSignedDocument('',{...policy,revoke:true});
|
||||
const empty=await makeKeyBundle([],revision,true);
|
||||
const metadata={revision,sha256:empty.sha256,keyCount:0,allowEmpty:true,source:{...source,gistRevision}};
|
||||
const fetcher=async url=>new Response(url.endsWith('/release.json')?JSON.stringify(metadata):url.endsWith('/ssh.keys.sig')?signature:document);
|
||||
assert.match(await verifyRemote(strict,fetcher,{now:200}),/OpenPGP not checked/);
|
||||
await assert.rejects(verifyRemote(strict,fetcher,{now:300}),/expired/);
|
||||
});
|
||||
@@ -10,7 +10,7 @@ for (const [label, shell] of candidates) {
|
||||
const available = spawnSync(executable, executable === 'busybox' ? ['sh', '-c', ':'] : ['-c', ':']).status === 0;
|
||||
test(`isolated installer regression suite (${label})`, { skip: !available }, () => {
|
||||
const result = spawnSync('python3', ['tests/shell.test.py'], {
|
||||
cwd: root, encoding: 'utf8', timeout: 90_000,
|
||||
cwd: root, encoding: 'utf8', timeout: 240_000,
|
||||
env: { ...process.env, CONF_SSHD_TEST_SHELL: shell },
|
||||
});
|
||||
assert.equal(result.error, undefined, result.error?.message);
|
||||
|
||||
+446
-10
@@ -57,13 +57,23 @@ class ShellTests(unittest.TestCase):
|
||||
self.cron.write_text('[email protected]\n17 * * * * echo untouched\n')
|
||||
self.calls = self.root / 'calls'
|
||||
self.calls.write_text('')
|
||||
self.clock = self.root / 'clock'
|
||||
self.clock.write_text(str(int(time.time())))
|
||||
self.env = dict(os.environ, HOME=str(self.home), PATH=f'{self.bin}:/usr/bin:/bin',
|
||||
TEST_ROOT=str(self.root), TEST_RESPONSE=str(self.payload),
|
||||
TEST_UPDATE=str(self.update), TEST_CRONTAB=str(self.cron),
|
||||
TEST_CALLS=str(self.calls))
|
||||
TEST_CALLS=str(self.calls), TEST_CLOCK=str(self.clock))
|
||||
real_id = shutil.which('id')
|
||||
self.assertIsNotNone(real_id)
|
||||
self.mock('id', f'#!/bin/sh\nexec {shlex.quote(real_id)} "$@"\n')
|
||||
self.mock('date', '''#!/bin/sh
|
||||
if [ "$*" = +%s ]; then cat "$TEST_CLOCK"; else exec /bin/date "$@"; fi
|
||||
''')
|
||||
self.mock('sleep', '''#!/bin/sh
|
||||
case $1 in *.*) exec /bin/sleep "$@" ;; esac
|
||||
printf 'sleep %s\\n' "$1" >> "$TEST_CALLS"
|
||||
printf '%s\\n' "$(($(cat "$TEST_CLOCK") + $1))" > "$TEST_CLOCK"
|
||||
''')
|
||||
self.mock('curl', '''#!/bin/sh
|
||||
printf 'curl %s\\n' "$*" >> "$TEST_CALLS"
|
||||
[ "${TEST_CURL_ERROR:-0}" = 0 ] || exit "$TEST_CURL_ERROR"
|
||||
@@ -71,12 +81,22 @@ if [ "${TEST_CURL_WAIT:-0}" = 1 ]; then
|
||||
: > "$TEST_ROOT/waiting"
|
||||
while [ ! -f "$TEST_ROOT/release" ]; do sleep 0.02; done
|
||||
fi
|
||||
out=
|
||||
out=; headers=; max_time=30
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in --output) shift; out=$1 ;; https://*) url=$1 ;; esac
|
||||
case "$1" in --output) shift; out=$1 ;; --dump-header) shift; headers=$1 ;; --max-time) shift; max_time=$1 ;; https://*) url=$1 ;; esac
|
||||
shift
|
||||
done
|
||||
status=${TEST_HTTP_STATUS:-200}
|
||||
source_failure=${TEST_SOURCE_FAILURE:-}
|
||||
case $url in */mirror/*) source_failure=${TEST_FALLBACK_SOURCE_FAILURE:-} ;; esac
|
||||
case $url in
|
||||
*/mirror/*) duration=${TEST_MIRROR_SECONDS:-0} ;;
|
||||
*/ssh.keys.sig) duration=${TEST_SIGNATURE_SECONDS:-0} ;;
|
||||
*/ssh.keys) duration=${TEST_BODY_SECONDS:-0} ;;
|
||||
*) duration=0 ;;
|
||||
esac
|
||||
elapsed=$duration; [ "$elapsed" -le "$max_time" ] || elapsed=$max_time
|
||||
printf '%s\\n' "$(($(cat "$TEST_CLOCK") + elapsed))" > "$TEST_CLOCK"
|
||||
case $url in
|
||||
*/script.sh) cp "$TEST_UPDATE" "$out" ;;
|
||||
*/public-key.gpg) cp "${TEST_CERTIFICATE:-/nonexistent}" "$out" || exit 22; status=${TEST_CERT_STATUS:-$status} ;;
|
||||
@@ -86,6 +106,21 @@ case $url in
|
||||
*/ssh.keys) cp "$TEST_RESPONSE" "$out"; status=${TEST_KEY_STATUS:-$status} ;;
|
||||
*) exit 99 ;;
|
||||
esac
|
||||
case $url in
|
||||
*/mirror/*) failures=0; count_file="$TEST_ROOT/mirror-count" ;;
|
||||
*/ssh.keys.sig) failures=${TEST_SIGNATURE_FAILURES:-0}; count_file="$TEST_ROOT/signature-count" ;;
|
||||
*/ssh.keys) failures=${TEST_PRIMARY_FAILURES:-0}; count_file="$TEST_ROOT/primary-count" ;;
|
||||
*) failures=0; count_file="$TEST_ROOT/other-count" ;;
|
||||
esac
|
||||
count=0; [ ! -f "$count_file" ] || count=$(cat "$count_file")
|
||||
count=$((count + 1)); printf '%s\\n' "$count" > "$count_file"
|
||||
[ "$count" -gt "$failures" ] || status=503
|
||||
if [ -n "$headers" ]; then
|
||||
printf 'HTTP/1.1 %s fixture\\r\\n' "$status" > "$headers"
|
||||
[ -z "$source_failure" ] || printf 'X-Conf-Sshd-Source-Failure: %s\\r\\n' "$source_failure" >> "$headers"
|
||||
printf '\\r\\n' >> "$headers"
|
||||
fi
|
||||
if [ "$duration" -gt "$max_time" ]; then printf 000; exit 28; fi
|
||||
printf '%s' "$status"
|
||||
''')
|
||||
self.mock('crontab', '''#!/bin/sh
|
||||
@@ -252,6 +287,77 @@ fi
|
||||
self.assertIn(option, calls)
|
||||
self.assertNotIn('--location', calls)
|
||||
|
||||
def fetch_calls(self, suffix='/ssh.keys'):
|
||||
return [line for line in self.calls.read_text().splitlines()
|
||||
if line.startswith('curl ') and line.endswith(ORIGIN + suffix)]
|
||||
|
||||
def sleeps(self):
|
||||
return [line for line in self.calls.read_text().splitlines() if line.startswith('sleep ')]
|
||||
|
||||
def test_five_total_retrieval_attempts_exact_backoff(self):
|
||||
original = self.old_auth()
|
||||
for status in ('301', '401', '403', '404', '408', '429', '500', '503'):
|
||||
with self.subTest(status=status):
|
||||
self.calls.write_text('')
|
||||
self.run_script('-o', ok=False, env={'TEST_KEY_STATUS': status})
|
||||
self.assertEqual(len(self.fetch_calls()), 5)
|
||||
self.assertEqual(self.sleeps(), ['sleep 1', 'sleep 3', 'sleep 8', 'sleep 12'])
|
||||
self.assertEqual(self.auth.read_bytes(), original)
|
||||
self.assert_clean()
|
||||
|
||||
def test_fifth_retrieval_attempt_can_succeed(self):
|
||||
self.run_script('-o', env={'TEST_PRIMARY_FAILURES': '4'})
|
||||
self.assertEqual(len(self.fetch_calls()), 5)
|
||||
self.assertEqual(self.sleeps(), ['sleep 1', 'sleep 3', 'sleep 8', 'sleep 12'])
|
||||
self.assert_clean()
|
||||
|
||||
def test_invalid_body_skips_retries_and_reaches_valid_local_fallback(self):
|
||||
fallback = self.root / 'fallback-response'
|
||||
fallback.write_bytes(self.payload.read_bytes())
|
||||
fallbacks = self.root / 'fallbacks'
|
||||
fallbacks.write_text(ORIGIN + '/mirror/ssh.keys\n')
|
||||
self.payload.write_bytes(b'invalid key list\n')
|
||||
self.run_script('-o', '--fallback-urls-file', str(fallbacks),
|
||||
env={'TEST_FALLBACK_RESPONSE': str(fallback)})
|
||||
self.assertEqual(len(self.fetch_calls()), 1)
|
||||
self.assertEqual(len(self.fetch_calls('/mirror/ssh.keys')), 1)
|
||||
self.assertEqual(self.sleeps(), [])
|
||||
self.assert_clean()
|
||||
|
||||
def test_oversized_curl_response_is_validation_without_backoff(self):
|
||||
original = self.old_auth()
|
||||
self.run_script('-o', ok=False, env={'TEST_CURL_ERROR': '63'})
|
||||
self.assertEqual(len(self.fetch_calls()), 1)
|
||||
self.assertEqual(self.sleeps(), [])
|
||||
self.assertEqual(self.auth.read_bytes(), original)
|
||||
self.assert_clean()
|
||||
|
||||
def test_worker_validation_hint_only_skips_failed_response(self):
|
||||
self.old_auth()
|
||||
for hint, expected in [('validation', 1), ('retrieval', 5), ('unknown', 5),
|
||||
('validation\r\nX-Conf-Sshd-Source-Failure: retrieval', 5)]:
|
||||
with self.subTest(hint=hint):
|
||||
self.calls.write_text('')
|
||||
self.run_script('-o', ok=False, env={'TEST_KEY_STATUS': '503', 'TEST_SOURCE_FAILURE': hint})
|
||||
self.assertEqual(len(self.fetch_calls()), expected)
|
||||
self.calls.write_text('')
|
||||
self.payload.write_bytes(b'invalid body\n')
|
||||
self.run_script('-o', ok=False, env={'TEST_SOURCE_FAILURE': 'retrieval'})
|
||||
self.assertEqual(len(self.fetch_calls()), 1)
|
||||
self.assertEqual(self.sleeps(), [])
|
||||
|
||||
def test_each_local_source_has_independent_five_attempt_budget(self):
|
||||
fallbacks = self.root / 'fallbacks'
|
||||
fallbacks.write_text(ORIGIN + '/mirror/ssh.keys\n')
|
||||
self.old_auth()
|
||||
self.run_script('-o', '--fallback-urls-file', str(fallbacks), ok=False,
|
||||
env={'TEST_KEY_STATUS': '503', 'TEST_FALLBACK_KEY_STATUS': '503'})
|
||||
self.assertEqual(len(self.fetch_calls()), 5)
|
||||
self.assertEqual(len(self.fetch_calls('/mirror/ssh.keys')), 5)
|
||||
self.assertEqual(self.sleeps(), ['sleep 1', 'sleep 3', 'sleep 8', 'sleep 12'] * 2)
|
||||
self.assertFalse((self.home / '.conf-sshd/local.conf').exists())
|
||||
self.assert_clean()
|
||||
|
||||
def test_empty_set_requires_explicit_permission(self):
|
||||
original = self.old_auth(BEGIN + KEY + END + b'# keep\n')
|
||||
self.payload.write_bytes(response(b''))
|
||||
@@ -261,6 +367,18 @@ fi
|
||||
self.run_script('-o')
|
||||
self.assertEqual(self.auth.read_bytes(), BEGIN + END + b'# keep\n')
|
||||
|
||||
def test_valid_empty_primary_stops_before_local_fallback(self):
|
||||
fallbacks = self.root / 'fallbacks'
|
||||
fallbacks.write_text(ORIGIN + '/mirror/ssh.keys\n')
|
||||
self.old_auth(b'# unmanaged before\n' + BEGIN + KEY + END + b'# unmanaged after\n')
|
||||
self.payload.write_bytes(response(b'', allow='yes'))
|
||||
self.run_script('-o', '--fallback-urls-file', str(fallbacks))
|
||||
self.assertEqual(self.auth.read_bytes(), b'# unmanaged before\n' + BEGIN + END + b'# unmanaged after\n')
|
||||
self.assertEqual(len(self.fetch_calls()), 1)
|
||||
self.assertEqual(self.fetch_calls('/mirror/ssh.keys'), [])
|
||||
self.assertEqual(self.sleeps(), [])
|
||||
self.assert_clean()
|
||||
|
||||
def test_metadata_and_payload_corruption(self):
|
||||
original = self.old_auth()
|
||||
good = response()
|
||||
@@ -452,7 +570,7 @@ fi
|
||||
self.assertEqual(state.stat().st_mode & 0o777, 0o755)
|
||||
self.assertEqual(self.auth.read_bytes(), b'# unmanaged\n')
|
||||
|
||||
def test_concurrent_run_refuses_and_signal_cleanup(self):
|
||||
def test_concurrent_run_skips_and_reclaims_stale_pid(self):
|
||||
env = self.env | {'TEST_CURL_WAIT': '1'}
|
||||
first = subprocess.Popen(self.script_command('-o'), env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
@@ -461,8 +579,10 @@ fi
|
||||
while not (self.root / 'waiting').exists() and time.monotonic() < deadline:
|
||||
time.sleep(0.02)
|
||||
self.assertTrue((self.root / 'waiting').exists())
|
||||
completed = self.run_script('-o', ok=False)
|
||||
self.assertIn('Another run holds', completed.stderr)
|
||||
before = self.calls.read_text()
|
||||
completed = self.run_script('-o')
|
||||
self.assertIn('Another run holds', completed.stdout)
|
||||
self.assertEqual(self.calls.read_text(), before)
|
||||
(self.root / 'release').touch()
|
||||
stdout, stderr = first.communicate(timeout=10)
|
||||
self.assertEqual(first.returncode, 0, stdout + stderr)
|
||||
@@ -472,12 +592,227 @@ fi
|
||||
first.terminate()
|
||||
first.communicate(timeout=10)
|
||||
self.assert_clean()
|
||||
# A stale/foreign lock is never auto-removed.
|
||||
# A safe legacy PID-only lock with a demonstrably absent owner recovers.
|
||||
lock = self.home / '.conf-sshd/lock'
|
||||
lock.mkdir()
|
||||
(lock / 'pid').write_text('999999')
|
||||
lock.mkdir(mode=0o700)
|
||||
(lock / 'pid').write_text('2147483647')
|
||||
self.run_script('-o')
|
||||
self.assert_clean()
|
||||
|
||||
def make_lock(self, pid='2147483647'):
|
||||
state = self.home / '.conf-sshd'
|
||||
state.mkdir(mode=0o700, exist_ok=True)
|
||||
lock = state / 'lock'
|
||||
lock.mkdir(mode=0o700)
|
||||
if pid is not None:
|
||||
(lock / 'pid').write_text(pid)
|
||||
return lock
|
||||
|
||||
def wait_for_file(self, path, seconds=5):
|
||||
deadline = time.monotonic() + seconds
|
||||
while not path.exists() and time.monotonic() < deadline:
|
||||
time.sleep(0.02)
|
||||
self.assertTrue(path.exists(), str(path))
|
||||
|
||||
def test_live_unrelated_or_reused_pid_is_conservatively_skipped(self):
|
||||
original = self.old_auth()
|
||||
lock = self.make_lock(str(os.getpid()))
|
||||
lock.parent.chmod(0o750)
|
||||
result = self.run_script('-o')
|
||||
self.assertIn('skipping', result.stdout)
|
||||
self.assertEqual((lock / 'pid').read_text(), str(os.getpid()))
|
||||
self.assertEqual(lock.parent.stat().st_mode & 0o777, 0o750)
|
||||
self.assertEqual(self.auth.read_bytes(), original)
|
||||
self.assertEqual(self.calls.read_text(), '')
|
||||
|
||||
def test_missing_malformed_or_uncertain_lock_owner_is_never_reaped(self):
|
||||
for pid in (None, '', '0', '-1', 'abc', '2147483648', '1\n2\n', '2147483647\n\n'):
|
||||
with self.subTest(pid=pid):
|
||||
lock = self.make_lock(pid)
|
||||
self.run_script('-o', ok=False)
|
||||
self.assertTrue(lock.exists())
|
||||
self.assertTrue(lock.is_dir())
|
||||
if pid is not None:
|
||||
self.assertEqual((lock / 'pid').read_text(), pid)
|
||||
shutil.rmtree(lock)
|
||||
lock = self.make_lock()
|
||||
self.mock('ps', '#!/bin/sh\nexit 2\n')
|
||||
self.run_script('-o', ok=False)
|
||||
self.assertEqual((lock / 'pid').read_text(), '2147483647')
|
||||
self.assertEqual(self.calls.read_text(), '')
|
||||
|
||||
def test_malicious_lock_paths_are_rejected_without_touching_targets(self):
|
||||
outside = self.root / 'outside-lock'
|
||||
outside.mkdir(mode=0o700)
|
||||
(outside / 'pid').write_text('2147483647')
|
||||
state = self.home / '.conf-sshd'
|
||||
state.mkdir(mode=0o700)
|
||||
lock = state / 'lock'
|
||||
lock.symlink_to(outside, target_is_directory=True)
|
||||
self.run_script('-o', ok=False)
|
||||
self.assertEqual((outside / 'pid').read_text(), '2147483647')
|
||||
lock.unlink()
|
||||
lock.mkdir(mode=0o700)
|
||||
(lock / 'pid').symlink_to(outside / 'pid')
|
||||
self.run_script('-o', ok=False)
|
||||
self.assertTrue((lock / 'pid').is_symlink())
|
||||
(lock / 'pid').unlink()
|
||||
os.link(outside / 'pid', lock / 'pid')
|
||||
self.run_script('-o', ok=False)
|
||||
(lock / 'pid').unlink()
|
||||
(lock / 'pid').write_text('2147483647')
|
||||
for path in (lock, lock / 'pid'):
|
||||
mode = path.stat().st_mode & 0o777
|
||||
path.chmod(0o777 if path.is_dir() else 0o666)
|
||||
self.run_script('-o', ok=False)
|
||||
path.chmod(mode)
|
||||
(lock / 'reclaim').symlink_to(outside, target_is_directory=True)
|
||||
self.run_script('-o', ok=False)
|
||||
self.assertEqual((outside / 'pid').read_text(), '2147483647')
|
||||
self.assertEqual(self.calls.read_text(), '')
|
||||
|
||||
def test_stale_lock_with_unexpected_files_is_not_partially_deleted(self):
|
||||
lock = self.make_lock()
|
||||
(lock / 'unexpected').write_text('preserve')
|
||||
self.run_script('-o', ok=False)
|
||||
self.assertEqual((lock / 'pid').read_text(), '2147483647')
|
||||
self.assertEqual((lock / 'unexpected').read_text(), 'preserve')
|
||||
self.assertFalse((lock / 'reclaim').exists())
|
||||
|
||||
def test_concurrent_stale_reclaimers_have_one_fetching_owner(self):
|
||||
lock = self.make_lock()
|
||||
self.mock('mkdir', '''#!/bin/sh
|
||||
/bin/mkdir "$@" || exit $?
|
||||
case "$*" in
|
||||
*/lock/reclaim)
|
||||
if [ "${TEST_HOLD_RECLAIM:-0}" = 1 ]; then
|
||||
: > "$TEST_ROOT/reclaim-waiting"
|
||||
while [ ! -f "$TEST_ROOT/reclaim-release" ]; do /bin/sleep 0.02; done
|
||||
fi ;;
|
||||
esac
|
||||
''')
|
||||
first = subprocess.Popen(self.script_command('-o'),
|
||||
env=self.env | {'TEST_HOLD_RECLAIM': '1'},
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
self.wait_for_file(self.root / 'reclaim-waiting')
|
||||
second = self.run_script('-o')
|
||||
self.assertIn('recovering the stale lock', second.stdout)
|
||||
self.assertEqual((lock / 'pid').read_text(), '2147483647')
|
||||
self.assertEqual(self.fetch_calls(), [])
|
||||
(self.root / 'reclaim-release').touch()
|
||||
stdout, stderr = first.communicate(timeout=10)
|
||||
self.assertEqual(first.returncode, 0, stdout + stderr)
|
||||
self.assertEqual(len(self.fetch_calls()), 1)
|
||||
self.assert_clean()
|
||||
finally:
|
||||
(self.root / 'reclaim-release').touch()
|
||||
if first.poll() is None:
|
||||
first.terminate()
|
||||
first.communicate(timeout=10)
|
||||
|
||||
def test_delayed_reaper_cannot_retire_or_delete_a_new_live_lock(self):
|
||||
lock = self.make_lock()
|
||||
self.mock('mkdir', '''#!/bin/sh
|
||||
case "$*" in
|
||||
*/lock/reclaim)
|
||||
if [ "${TEST_DELAY_RECLAIM:-0}" = 1 ]; then
|
||||
: > "$TEST_ROOT/delayed-reaper"
|
||||
while [ ! -f "$TEST_ROOT/delayed-release" ]; do /bin/sleep 0.02; done
|
||||
fi ;;
|
||||
esac
|
||||
exec /bin/mkdir "$@"
|
||||
''')
|
||||
delayed = subprocess.Popen(self.script_command('-o'),
|
||||
env=self.env | {'TEST_DELAY_RECLAIM': '1'},
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
owner = None
|
||||
try:
|
||||
self.wait_for_file(self.root / 'delayed-reaper')
|
||||
owner = subprocess.Popen(self.script_command('-o'),
|
||||
env=self.env | {'TEST_CURL_WAIT': '1'},
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
self.wait_for_file(self.root / 'waiting')
|
||||
owner_pid = (lock / 'pid').read_bytes()
|
||||
owner_inode = lock.stat().st_ino
|
||||
(self.root / 'delayed-release').touch()
|
||||
stdout, stderr = delayed.communicate(timeout=10)
|
||||
self.assertNotEqual(delayed.returncode, 0, stdout + stderr)
|
||||
self.assertIn('changed during recovery', stderr)
|
||||
self.assertEqual((lock / 'pid').read_bytes(), owner_pid)
|
||||
self.assertEqual(lock.stat().st_ino, owner_inode)
|
||||
self.assertFalse((lock / 'reclaim').exists())
|
||||
(self.root / 'release').touch()
|
||||
stdout, stderr = owner.communicate(timeout=10)
|
||||
self.assertEqual(owner.returncode, 0, stdout + stderr)
|
||||
self.assertEqual(len(self.fetch_calls()), 1)
|
||||
self.assert_clean()
|
||||
finally:
|
||||
(self.root / 'delayed-release').touch()
|
||||
(self.root / 'release').touch()
|
||||
for process in (delayed, owner):
|
||||
if process is not None and process.poll() is None:
|
||||
process.terminate()
|
||||
process.communicate(timeout=10)
|
||||
|
||||
def test_unpublished_pid_is_never_assumed_stale(self):
|
||||
self.mock('mkdir', '''#!/bin/sh
|
||||
/bin/mkdir "$@" || exit $?
|
||||
case "$*" in
|
||||
*/lock)
|
||||
: > "$TEST_ROOT/pid-waiting"
|
||||
while [ ! -f "$TEST_ROOT/pid-release" ]; do /bin/sleep 0.02; done ;;
|
||||
esac
|
||||
''')
|
||||
first = subprocess.Popen(self.script_command('-o'), env=self.env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
self.wait_for_file(self.root / 'pid-waiting')
|
||||
second = self.run_script('-o', ok=False)
|
||||
self.assertIn('PID is missing or invalid', second.stderr)
|
||||
self.assertTrue((self.home / '.conf-sshd/lock').is_dir())
|
||||
(self.root / 'pid-release').touch()
|
||||
stdout, stderr = first.communicate(timeout=10)
|
||||
self.assertEqual(first.returncode, 0, stdout + stderr)
|
||||
self.assertEqual(len(self.fetch_calls()), 1)
|
||||
self.assert_clean()
|
||||
finally:
|
||||
(self.root / 'pid-release').touch()
|
||||
if first.poll() is None:
|
||||
first.terminate()
|
||||
first.communicate(timeout=10)
|
||||
|
||||
def test_cleanup_does_not_remove_a_replacement_lock_or_pid_symlink(self):
|
||||
for replace_directory in (True, False):
|
||||
with self.subTest(replace_directory=replace_directory):
|
||||
for barrier in ('waiting', 'release'):
|
||||
(self.root / barrier).unlink(missing_ok=True)
|
||||
first = subprocess.Popen(self.script_command('-o'),
|
||||
env=self.env | {'TEST_CURL_WAIT': '1'},
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
self.wait_for_file(self.root / 'waiting')
|
||||
lock = self.home / '.conf-sshd/lock'
|
||||
outside = self.root / 'replacement-pid'
|
||||
outside.write_text(str(os.getpid()))
|
||||
if replace_directory:
|
||||
lock.rename(self.root / 'old-lock')
|
||||
lock.mkdir(mode=0o700)
|
||||
(lock / 'pid').write_text(str(os.getpid()))
|
||||
else:
|
||||
(lock / 'pid').unlink()
|
||||
(lock / 'pid').symlink_to(outside)
|
||||
(self.root / 'release').touch()
|
||||
stdout, stderr = first.communicate(timeout=10)
|
||||
self.assertEqual(first.returncode, 0, stdout + stderr)
|
||||
self.assertTrue(lock.is_dir())
|
||||
self.assertEqual((lock / 'pid').read_text(), str(os.getpid()))
|
||||
self.assertEqual(outside.read_text(), str(os.getpid()))
|
||||
finally:
|
||||
(self.root / 'release').touch()
|
||||
if first.poll() is None:
|
||||
first.terminate()
|
||||
first.communicate(timeout=10)
|
||||
shutil.rmtree(self.home / '.conf-sshd/lock')
|
||||
|
||||
def test_update_self_is_explicit_atomic_and_fail_closed(self):
|
||||
self.run_script('-c')
|
||||
@@ -1157,6 +1492,107 @@ exec "{real_gpg}" "$@"
|
||||
self.run_script('-o', ok=False, env={'TEST_SIG_STATUS':'404', 'TEST_FALLBACK_SIG_STATUS':'404'})
|
||||
self.assertEqual(self.auth.read_bytes(), original)
|
||||
|
||||
def persistent_snapshot(self):
|
||||
paths = [self.auth, *sorted((self.home / '.conf-sshd').rglob('*'))]
|
||||
return {str(path.relative_to(self.home)): path.read_bytes()
|
||||
for path in paths if path.is_file()}
|
||||
|
||||
def test_signature_fetch_uses_remaining_attempt_budget_and_retries_pair(self):
|
||||
self.enroll()
|
||||
original = self.persistent_snapshot()
|
||||
self.calls.write_text('')
|
||||
started = int(self.clock.read_text())
|
||||
self.run_script('-o', ok=False,
|
||||
env={'TEST_BODY_SECONDS': '20', 'TEST_SIGNATURE_SECONDS': '11'})
|
||||
self.assertEqual(len(self.fetch_calls()), 5)
|
||||
signatures = self.fetch_calls('/ssh.keys.sig')
|
||||
self.assertEqual(len(signatures), 5)
|
||||
self.assertTrue(all('--max-time 10 ' in line for line in signatures))
|
||||
self.assertTrue(all('--connect-timeout 10 ' in line for line in signatures))
|
||||
self.assertEqual(int(self.clock.read_text()) - started, 5 * 30 + 24)
|
||||
self.assertEqual(self.sleeps(), ['sleep 1', 'sleep 3', 'sleep 8', 'sleep 12'])
|
||||
self.assertEqual(self.persistent_snapshot(), original)
|
||||
self.assert_clean()
|
||||
|
||||
def test_exhausted_body_budget_never_starts_a_signature_request(self):
|
||||
self.enroll()
|
||||
original = self.persistent_snapshot()
|
||||
self.calls.write_text('')
|
||||
started = int(self.clock.read_text())
|
||||
self.run_script('-o', ok=False, env={'TEST_BODY_SECONDS': '30'})
|
||||
self.assertEqual(len(self.fetch_calls()), 5)
|
||||
self.assertEqual(self.fetch_calls('/ssh.keys.sig'), [])
|
||||
self.assertEqual(int(self.clock.read_text()) - started, 174)
|
||||
self.assertEqual(self.persistent_snapshot(), original)
|
||||
|
||||
def test_signature_failure_counts_as_one_pair_attempt(self):
|
||||
self.enroll()
|
||||
self.calls.write_text('')
|
||||
(self.root / 'signature-count').unlink()
|
||||
self.run_script('-o', env={'TEST_SIGNATURE_FAILURES': '2'})
|
||||
self.assertEqual(len(self.fetch_calls()), 3)
|
||||
self.assertEqual(len(self.fetch_calls('/ssh.keys.sig')), 3)
|
||||
self.assertEqual(self.sleeps(), ['sleep 1', 'sleep 3'])
|
||||
self.assert_clean()
|
||||
|
||||
def test_strict_validation_failures_go_directly_to_next_source(self):
|
||||
fallbacks = self.root / 'fallbacks'
|
||||
fallbacks.write_text(ORIGIN + '/mirror/ssh.keys\n')
|
||||
self.enroll(extra=('--fallback-urls-file', str(fallbacks)))
|
||||
fallback = self.root / 'fallback-response'
|
||||
fallback_signature = self.root / 'fallback-signature'
|
||||
fallback.write_text(self.fixtures['releases']['next']['data'])
|
||||
fallback_signature.write_text(self.fixtures['releases']['next']['sig'])
|
||||
for release in ('old', 'expired', 'wronglist', 'comment', 'wrongsigner'):
|
||||
with self.subTest(release=release):
|
||||
self.calls.write_text('')
|
||||
self.set_release(release)
|
||||
self.run_script('-o', env={'TEST_FALLBACK_RESPONSE': str(fallback),
|
||||
'TEST_FALLBACK_SIGNATURE': str(fallback_signature)})
|
||||
self.assertEqual(len(self.fetch_calls()), 1)
|
||||
self.assertEqual(len(self.fetch_calls('/ssh.keys.sig')), int(release == 'wrongsigner'))
|
||||
self.assertEqual(len(self.fetch_calls('/mirror/ssh.keys')), 1)
|
||||
self.assertEqual(len(self.fetch_calls('/mirror/ssh.keys.sig')), 1)
|
||||
self.assertEqual(self.sleeps(), [])
|
||||
self.assert_clean()
|
||||
|
||||
def test_valid_signed_revocation_stops_before_local_fallback(self):
|
||||
fallbacks = self.root / 'fallbacks'
|
||||
fallbacks.write_text(ORIGIN + '/mirror/ssh.keys\n')
|
||||
self.old_auth(b'# keep unmanaged\n')
|
||||
self.enroll(extra=('--fallback-urls-file', str(fallbacks)))
|
||||
self.calls.write_text('')
|
||||
self.set_release('revoke')
|
||||
self.run_script('-o')
|
||||
self.assertEqual(self.auth.read_bytes(), b'# keep unmanaged\n' + BEGIN + END)
|
||||
self.assertEqual(len(self.fetch_calls()), 1)
|
||||
self.assertEqual(len(self.fetch_calls('/ssh.keys.sig')), 1)
|
||||
self.assertEqual(self.fetch_calls('/mirror/ssh.keys'), [])
|
||||
self.assertEqual(self.sleeps(), [])
|
||||
self.assertIn('sequence 6\n', self.replay.read_text())
|
||||
|
||||
def test_all_sources_fail_preserve_keys_audit_trust_and_replay(self):
|
||||
fallbacks = self.root / 'fallbacks'
|
||||
fallbacks.write_text(ORIGIN + '/mirror/ssh.keys\n')
|
||||
self.enroll(extra=('--fallback-urls-file', str(fallbacks)))
|
||||
original = self.persistent_snapshot()
|
||||
self.calls.write_text('')
|
||||
self.run_script('-o', ok=False,
|
||||
env={'TEST_KEY_STATUS': '503', 'TEST_FALLBACK_SIG_STATUS': '404'})
|
||||
self.assertEqual(len(self.fetch_calls()), 5)
|
||||
self.assertEqual(len(self.fetch_calls('/mirror/ssh.keys')), 5)
|
||||
self.assertEqual(len(self.fetch_calls('/mirror/ssh.keys.sig')), 5)
|
||||
self.assertEqual(self.persistent_snapshot(), original)
|
||||
self.assert_clean()
|
||||
self.calls.write_text('')
|
||||
self.payload.write_bytes(response(b'', allow='yes'))
|
||||
self.run_script('-o', ok=False)
|
||||
self.assertEqual(len(self.fetch_calls()), 1)
|
||||
self.assertEqual(len(self.fetch_calls('/mirror/ssh.keys')), 1)
|
||||
self.assertEqual(self.fetch_calls('/ssh.keys.sig'), [])
|
||||
self.assertEqual(self.sleeps(), [])
|
||||
self.assertEqual(self.persistent_snapshot(), original)
|
||||
|
||||
def test_persisted_config_is_strict_data_never_executed(self):
|
||||
self.enroll()
|
||||
original = self.auth.read_bytes()
|
||||
|
||||
@@ -8,7 +8,7 @@ import {execFileSync} from 'node:child_process';
|
||||
import {makeSignedDocument, parseSignedDocument, parseSignedBundle, parsePublishedSignedRelease, SIGNATURE_SEPARATOR, SIGNED_RELEASE_LIMITS, validateSignature} from '../cf-worker/src/signed-release.js';
|
||||
import {prepare} from '../scripts/prepare-key-release.mjs';
|
||||
import {openPgpFixture} from './helpers/openpgp-fixture.mjs';
|
||||
import {verifyRemote} from '../scripts/verify-release.mjs';
|
||||
import {verifyProduction, verifyRemote} from '../scripts/verify-release.mjs';
|
||||
import {validateConfig, validateClientDefaults, build, root} from '../scripts/build.mjs';
|
||||
import {validatePublicCertificate, checkSigningCertificate, validatePayloadSignatureStatus} from '../scripts/signature-tools.mjs';
|
||||
|
||||
@@ -144,6 +144,54 @@ test('Git revocation bundle overrides legacy empty policy without falling back',
|
||||
});
|
||||
});
|
||||
|
||||
test('an explicitly cleared authorized_keys cannot be repopulated by leftover signed artifacts',async()=>{
|
||||
for(const filename of ['ssh.keys','release.bundle']) await buildFixture({},async(dir,buildNow)=>{
|
||||
await writeFile(join(dir,'keys',filename),filename==='ssh.keys'?document:document+SIGNATURE_SEPARATOR+signature);
|
||||
for(const content of ['',' \t\r\n']) {
|
||||
await writeFile(join(dir,'keys/authorized_keys'),content);
|
||||
await assert.rejects(buildNow(),/Ambiguous Git revocation/);
|
||||
}
|
||||
await rm(join(dir,'keys/authorized_keys'));
|
||||
const result=await buildNow();assert.equal(result.keyCount,1);assert.equal(result.primaryFile,`keys/${filename}`);
|
||||
});
|
||||
});
|
||||
|
||||
test('clearing the selected signed publishing file is an OFF revocation, never a synthetic signed release',async()=>{
|
||||
for(const filename of ['ssh.keys','release.bundle']) for(const content of ['',' \t\r\n']) await buildFixture({fallbackSources:['https://keys.example.com/fallback']},async(dir,buildNow)=>{
|
||||
await writeFile(join(dir,'keys',filename),content);
|
||||
await writeFile(join(dir,'keys/ssh.keys.sig'),signature);
|
||||
for(const raw of [fixture,'invalid stale raw content']) {
|
||||
await writeFile(join(dir,'keys/authorized_keys'),raw);
|
||||
await assert.rejects(buildNow(),/Ambiguous Git revocation/);
|
||||
}
|
||||
// The shipped comments-only placeholder has never configured raw keys.
|
||||
await writeFile(join(dir,'keys/authorized_keys'),'# Add server public keys here.\n');
|
||||
const result=await buildNow();assert.equal(result.keyCount,0);assert.equal(result.allowEmpty,true);assert.equal(result.needsFallback,false);
|
||||
assert.equal(result.primaryFile,`keys/${filename}`);assert.equal(result.signedDocument,null);assert.equal(result.signature,null);
|
||||
await assert.rejects(readFile(join(dir,'cf-worker/public/ssh.keys.sig')),{code:'ENOENT'});
|
||||
assert.match(await readFile(join(dir,'cf-worker/public/ssh.keys'),'utf8'),/# conf-sshd-v1\n/);
|
||||
await rm(join(dir,'keys/authorized_keys'));
|
||||
assert.equal((await buildNow()).allowEmpty,true);
|
||||
});
|
||||
for(const filename of ['ssh.keys','release.bundle']) await buildFixture({clientDefaults:{gpgVerification:'on',fingerprint:'A'.repeat(40),listId:'production'}},async(dir,buildNow)=>{
|
||||
await writeFile(join(dir,'keys',filename),'');
|
||||
await assert.rejects(buildNow(),/require a signed document/);
|
||||
});
|
||||
});
|
||||
|
||||
test('ON Git preflight accepts only a current signed revoke without falling back',async()=>{
|
||||
await buildFixture({fallbackSources:['https://keys.example.com/fallback'],clientDefaults:{gpgVerification:'on',fingerprint:'A'.repeat(40),listId:'production'}},async(dir,buildNow)=>{
|
||||
const revoke=await makeSignedDocument('',{...policy,revoke:true});
|
||||
await writeFile(join(dir,'keys/release.bundle'),revoke+SIGNATURE_SEPARATOR+signature);
|
||||
const release=await buildNow(), noFetch=()=>assert.fail('Git preflight must not fall back');
|
||||
assert.equal(release.explicitEmpty,false);assert.equal(release.signedMetadata.revoke,true);
|
||||
assert.match(await verifyProduction(release,noFetch,{now:200}),/0 key\(s\) from explicit-empty/);
|
||||
await assert.rejects(verifyProduction(release,noFetch,{now:300}),/source|primary/i);
|
||||
await assert.rejects(verifyProduction({...release,signature:null},noFetch,{now:200}),/source|primary/i);
|
||||
await assert.rejects(verifyProduction({...release,signedDocument:revoke.replace('sequence 1','sequence 0')},noFetch,{now:200}),/source|primary/i);
|
||||
});
|
||||
});
|
||||
|
||||
test('dynamic Gist builds need no local keys and must not publish stale static key placeholders', async () => {
|
||||
await buildFixture({keySource:{type:'gist',id:'a'.repeat(32),ownerId:7,ownerLogin:'example'}},async (dir,buildNow)=>{
|
||||
await writeFile(join(dir,'keys/authorized_keys'),fixture);
|
||||
|
||||
@@ -109,3 +109,84 @@ test('signature endpoint pairs with exact signed document, never the legacy wrap
|
||||
assert.equal(await(await unsigned(request('/ssh.keys'),env)).text(),document);
|
||||
assert.equal((await unsigned(request('/ssh.keys.sig'),env)).status,404);
|
||||
});
|
||||
|
||||
const gistSource={type:'gist',id:'b'.repeat(32),ownerId:123,ownerLogin:'example'};
|
||||
const gistRevision='c'.repeat(40);
|
||||
const gistUrl=`https://api.github.com/gists/${gistSource.id}`;
|
||||
const gistFile=(filename,content)=>({filename,content,size:Buffer.byteLength(content),truncated:false});
|
||||
const gistData=files=>({id:gistSource.id,owner:{id:gistSource.ownerId},public:true,history:[{version:gistRevision}],files});
|
||||
const gistRelease={...release,keys:[],keyCount:0,allowEmpty:false,keySource:gistSource,fallbackSources:['https://keys.example.com/server.keys']};
|
||||
|
||||
test('blank Gist publishes a legacy revocation consistently across page, metadata and keys',async()=>{
|
||||
const visited=[];
|
||||
const handler=createHandler(gistRelease,{fetchImpl:async url=>{
|
||||
visited.push(url);
|
||||
assert.ok(url===gistUrl||url===gistUrl+'/'+gistRevision,'Clear must not fetch fallback');
|
||||
return new Response(JSON.stringify(gistData({'ssh.keys':gistFile('ssh.keys',' \t\r\n')})));
|
||||
}});
|
||||
const keysResponse=await handler(request('/ssh.keys'),env);
|
||||
assert.equal(keysResponse.status,200);assert.equal(keysResponse.headers.get('X-Conf-Sshd-Source-Failure'),null);
|
||||
assert.equal(keysResponse.headers.get('X-Conf-Sshd-Key-Source'),'gist');
|
||||
assert.match(await keysResponse.text(),/# key-count 0\n# allow-empty yes\n/);
|
||||
const metadata=await(await handler(request('/release.json'),env)).json();
|
||||
assert.equal(metadata.keyCount,0);assert.equal(metadata.allowEmpty,true);
|
||||
assert.equal(metadata.source.type,'gist');assert.equal(metadata.source.gistRevision,gistRevision);
|
||||
assert.equal(metadata.signatureAvailable,false);assert.equal(metadata.signedMetadata,null);
|
||||
const html=await(await handler(request('/'),env)).text();
|
||||
assert.match(html,/明确撤销/);assert.doesNotMatch(html,/未发布撤销指令/);
|
||||
assert.equal((await handler(request('/ssh.keys.sig'),env)).status,404);
|
||||
assert.equal(visited.length,8);
|
||||
});
|
||||
|
||||
test('ambiguous Gist clear produces validation-only 503 and never serves fallback keys',async()=>{
|
||||
const handler=createHandler(gistRelease,{fetchImpl:async url=>{
|
||||
assert.ok(url.startsWith(gistUrl),'Conflicting clear must not fetch fallback');
|
||||
return new Response(JSON.stringify(gistData({'ssh.keys':gistFile('ssh.keys',''),'release.bundle':gistFile('release.bundle',fixture)})));
|
||||
}});
|
||||
for(const path of ['/ssh.keys','/ssh.keys.sig','/release.json','/']) {
|
||||
const response=await handler(request(path),env);
|
||||
assert.equal(response.status,503);
|
||||
assert.equal(response.headers.get('X-Conf-Sshd-Source-Failure'),'validation');
|
||||
const text=await response.text();
|
||||
assert.doesNotMatch(text,/TEST-ONLY|BEGIN PGP|# allow-empty yes/);
|
||||
if(path==='/')assert.match(text,/未发布撤销指令/);
|
||||
}
|
||||
});
|
||||
|
||||
test('source-failure header classifies exhausted validation, retrieval and mixed failures without details',async()=>{
|
||||
const fallback={...release,keys:[],keyCount:0,fallbackSources:['https://keys.example.com/first','https://keys.example.com/second']};
|
||||
const cases=[
|
||||
['validation',async()=>new Response('SECRET invalid content')],
|
||||
['retrieval',async()=>new Response('SECRET upstream error',{status:404})],
|
||||
['retrieval',async()=>{throw Error('SECRET network error');}],
|
||||
['retrieval',async url=>url.endsWith('first')?new Response('SECRET invalid content'):new Response('SECRET overloaded',{status:503})],
|
||||
['retrieval',async url=>url.endsWith('first')?new Response('SECRET denied',{status:403}):new Response('SECRET invalid content')],
|
||||
];
|
||||
for(const [kind,fetchImpl] of cases) {
|
||||
const handler=createHandler(fallback,{fetchImpl});
|
||||
for(const method of ['GET','HEAD'])for(const path of ['/ssh.keys','/ssh.keys.sig','/release.json','/']) {
|
||||
const response=await handler(request(path,{method}),env);
|
||||
assert.equal(response.status,503);assert.equal(response.headers.get('X-Conf-Sshd-Source-Failure'),kind);
|
||||
assert.equal(response.headers.get('Cache-Control'),'no-store');
|
||||
assert.doesNotMatch(JSON.stringify([...response.headers]),/SECRET|keys\.example/);
|
||||
const text=await response.text();assert.doesNotMatch(text,/SECRET/);
|
||||
if(method==='HEAD')assert.equal(text,'');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('missing and comment-only Gist files are validation failures while HTTP 404 is retrieval',async()=>{
|
||||
for(const [files,kind] of [[{},'validation'],[{'ssh.keys':gistFile('ssh.keys','# placeholder\n')},'validation'],[null,'retrieval']]) {
|
||||
const handler=createHandler({...gistRelease,fallbackSources:[]},{fetchImpl:async()=>files===null?new Response('',{status:404}):new Response(JSON.stringify(gistData(files)))});
|
||||
const response=await handler(request('/ssh.keys'),env);
|
||||
assert.equal(response.status,503);assert.equal(response.headers.get('X-Conf-Sshd-Source-Failure'),kind);
|
||||
assert.doesNotMatch(await response.text(),/# allow-empty yes/);
|
||||
}
|
||||
});
|
||||
|
||||
test('successful fallback does not retain failed-source retry hints',async()=>{
|
||||
const handler=createHandler({...release,keys:[],keyCount:0,fallbackSources:['https://keys.example.com/first','https://keys.example.com/second']},{fetchImpl:async url=>url.endsWith('first')?new Response('',{status:503}):new Response(fixture)});
|
||||
const response=await handler(request('/ssh.keys'),env);
|
||||
assert.equal(response.status,200);assert.equal(response.headers.get('X-Conf-Sshd-Source-Failure'),null);
|
||||
assert.equal(await response.text(),bundle.text);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user