obsidian-mcp: 初次落地 Obsidian Vault MCP Server (.NET 10, read+write)
把 Obsidian vault 通过 MCP 暴露给 Claude.ai,OAuth 走 nas-auth。 设计文档见 vault Coding/obsidian-mcp/obsidian-mcp 设计.md。 代码层落地参考 vault Coding/obsidian-mcp/MCP 实现指南.md。 V1+V2 同时实现(用户要求跳过分阶段直接全部): 读 Tools(需 scope=read:obsidian): - list_vault_tree(一次性 vault 地图,限制深度) - list_files / read_file(含 offset/limit 大文件分页) - search(子串匹配 + glob 过滤,最多 50 hits) - get_metadata(size / modified_at / has_frontmatter) 写 Tools(需 scope=write:obsidian): - write_file / append_file - 多重门禁:scope 校验 + 路径黑名单 + 写入白名单 + 永禁文件 - 永禁写:任意目录的 AGENTS.md / PROFILE.md / README.md / CLAUDE.md / 01-Secret/** - 白名单:02-ShengquGames/logs/ + Coding/ + NAS/NAS 待办清单.md - 写入审计日志按天 rotate(JSON line) 安全: - VaultPathResolver chroot:path traversal + symlink 双拒绝 - JwtBearer (HS256, Current+Previous fallback, MapInboundClaims=false) - aud=obsidian, iss=https://auth.zhengchentao.win - 黑名单:01-Secret / .obsidian / .trash / .git 技术栈: - .NET 10 + ModelContextProtocol SDK 1.0 - Streamable HTTP transport (POST /mcp) - JwtBearer 10.0 + IdentityModel.Tokens 8.x 部署: - Dockerfile multi-stage,runtime 装 ripgrep(V3 备用),non-root user - .gitea/workflows/build-image.yml:build + deploy 双 job,buildkit v0.13.2 - 容器内 :8080,宿主端口 9090 - 子域名 obs.zhengchentao.win - vault 挂载 /volume1/docker/webdav/data/Zhengchen:/vault:rw(V2 写入需要 rw) 测试:35/35 单测过(VaultPathResolver path traversal/blacklist/symlink + VaultWriteGuard whitelist/forbidden) Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ObsidianMcp.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 写操作审计日志(JSON lines 格式,按天 rotate)。
|
||||
/// 输出到 /app/logs/audit-YYYY-MM-DD.log。
|
||||
/// 注册为 Singleton,内部用 lock 保证多线程写入安全。
|
||||
/// </summary>
|
||||
public class AuditLogger
|
||||
{
|
||||
private readonly string _logDir;
|
||||
private readonly object _lock = new();
|
||||
|
||||
public AuditLogger(IConfiguration config)
|
||||
{
|
||||
// 允许通过配置覆盖日志目录,默认 /app/logs
|
||||
_logDir = config["AuditLog:Directory"] ?? "/app/logs";
|
||||
Directory.CreateDirectory(_logDir);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 记录一次写操作审计条目。
|
||||
/// </summary>
|
||||
public void LogWrite(
|
||||
string user,
|
||||
string clientId,
|
||||
string tool,
|
||||
string path,
|
||||
long bytes,
|
||||
bool ok,
|
||||
string? error = null)
|
||||
{
|
||||
var entry = new
|
||||
{
|
||||
timestamp = DateTime.UtcNow.ToString("O"),
|
||||
user,
|
||||
tool,
|
||||
path,
|
||||
bytes,
|
||||
client_id = clientId,
|
||||
ok,
|
||||
error,
|
||||
};
|
||||
|
||||
var line = JsonSerializer.Serialize(entry);
|
||||
var fileName = $"audit-{DateTime.UtcNow:yyyy-MM-dd}.log";
|
||||
var filePath = Path.Combine(_logDir, fileName);
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
File.AppendAllText(filePath, line + Environment.NewLine);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
using ObsidianMcp.Config;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ObsidianMcp.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Vault 路径安全守卫(chroot 语义)。
|
||||
///
|
||||
/// 职责:
|
||||
/// - 把相对路径拼接到 VaultRoot,防止路径穿越(../)
|
||||
/// - 拒绝绝对路径输入
|
||||
/// - 拒绝命中黑名单的路径段
|
||||
///
|
||||
/// 线程安全,注册为 Singleton。
|
||||
/// </summary>
|
||||
public class VaultPathResolver
|
||||
{
|
||||
// hardcode 黑名单路径段(任意路径段命中即拒)
|
||||
private static readonly HashSet<string> HardcodeBlacklist =
|
||||
new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"01-Secret",
|
||||
".obsidian",
|
||||
".trash",
|
||||
".git",
|
||||
};
|
||||
|
||||
private readonly string _root;
|
||||
private readonly HashSet<string> _blacklist;
|
||||
|
||||
public VaultPathResolver(IOptions<VaultOptions> opts)
|
||||
{
|
||||
var o = opts.Value;
|
||||
_root = Path.GetFullPath(o.Root);
|
||||
|
||||
// 合并 hardcode + env 配置的黑名单,去重
|
||||
_blacklist = new HashSet<string>(HardcodeBlacklist, StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var b in o.Blacklist)
|
||||
if (!string.IsNullOrWhiteSpace(b))
|
||||
_blacklist.Add(b.Trim());
|
||||
}
|
||||
|
||||
/// <summary>返回 vault 根目录的绝对路径(规范化后)。</summary>
|
||||
public string VaultRoot => _root;
|
||||
|
||||
/// <summary>
|
||||
/// 将相对路径解析为 vault 内的绝对路径。
|
||||
///
|
||||
/// 可能抛出:
|
||||
/// UnauthorizedAccessException — 路径穿越、绝对路径、命中黑名单、目标是 symlink
|
||||
/// ArgumentException — relativePath 为空
|
||||
/// </summary>
|
||||
public string Resolve(string relativePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(relativePath))
|
||||
throw new ArgumentException("路径不能为空。", nameof(relativePath));
|
||||
|
||||
// 拒绝绝对路径输入(防止容器外访问;包括 Linux /etc/... 与 Windows C:\... / UNC \\server)
|
||||
if (Path.IsPathRooted(relativePath))
|
||||
throw new UnauthorizedAccessException(
|
||||
$"拒绝绝对路径输入:{relativePath}");
|
||||
|
||||
// 把 Windows 反斜杠归一化成 Unix 分隔符,避免 Linux 容器上把 "..\\.." 当成单段不消解。
|
||||
// 注意:仅对相对路径输入做归一化;root 路径已经由 Path.GetFullPath 处理过。
|
||||
var normalizedRel = relativePath.Replace('\\', '/');
|
||||
|
||||
// 拼接并规范化(自动消解 .. 和 .)
|
||||
var target = Path.GetFullPath(Path.Combine(_root, normalizedRel));
|
||||
|
||||
// 确认解析后的路径仍在 vault root 内
|
||||
if (!IsUnderRoot(target))
|
||||
throw new UnauthorizedAccessException(
|
||||
$"路径穿越 vault 根目录:{relativePath}");
|
||||
|
||||
// 逐段检查黑名单
|
||||
CheckBlacklist(target, relativePath);
|
||||
|
||||
// 拒绝 symlink(无论指向 vault 内外,统一禁;vault 真实内容应是普通文件 / 目录)。
|
||||
// 这是兜底防线:万一 WebDAV / 操作失误把 symlink 落到 vault 里,避免 Tool 跟随到容器外。
|
||||
RejectSymlink(target, relativePath);
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查路径自身(以及任一父级路径段)是否是 symlink。是 → 拒绝。
|
||||
/// 防御链外文件 leak(例如有人在 vault 里建一个指向 /etc/passwd 的软链)。
|
||||
/// </summary>
|
||||
private void RejectSymlink(string absPath, string original)
|
||||
{
|
||||
// 从 absPath 一直向上检查到 _root(不含 root 本体;root 是已知信任的挂载点)
|
||||
var current = absPath;
|
||||
while (current != null && current.Length > _root.Length)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(current);
|
||||
if (info.Exists && info.LinkTarget != null)
|
||||
throw new UnauthorizedAccessException($"拒绝 symlink 路径:{original}");
|
||||
if (!info.Exists)
|
||||
{
|
||||
var di = new DirectoryInfo(current);
|
||||
if (di.Exists && di.LinkTarget != null)
|
||||
throw new UnauthorizedAccessException($"拒绝 symlink 路径:{original}");
|
||||
}
|
||||
}
|
||||
catch (UnauthorizedAccessException) { throw; }
|
||||
catch
|
||||
{
|
||||
// I/O 异常不在这里阻断;后续真正读文件时会自然抛
|
||||
}
|
||||
var parent = Path.GetDirectoryName(current);
|
||||
if (parent == null || parent == current) break;
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>检查绝对路径是否在 vault root 下(含等于 root)。</summary>
|
||||
private bool IsUnderRoot(string absPath)
|
||||
{
|
||||
return absPath == _root
|
||||
|| absPath.StartsWith(_root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>逐个路径段检查黑名单。</summary>
|
||||
private void CheckBlacklist(string absPath, string original)
|
||||
{
|
||||
// 把 absPath 中 root 之后的部分按分隔符拆分,逐段比对
|
||||
var relative = absPath[_root.Length..].TrimStart(Path.DirectorySeparatorChar);
|
||||
var segments = relative.Split(
|
||||
[Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar],
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
foreach (var seg in segments)
|
||||
{
|
||||
if (_blacklist.Contains(seg))
|
||||
throw new UnauthorizedAccessException(
|
||||
$"路径命中黑名单段 '{seg}':{original}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using Microsoft.Extensions.FileSystemGlobbing;
|
||||
using Microsoft.Extensions.FileSystemGlobbing.Abstractions;
|
||||
|
||||
namespace ObsidianMcp.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Vault 全文搜索服务。
|
||||
/// 纯 C# 实现,大小写不敏感子串匹配(不支持 regex)。
|
||||
/// V3 可替换为 ripgrep 调用。
|
||||
/// </summary>
|
||||
public class VaultSearchService
|
||||
{
|
||||
private readonly VaultPathResolver _resolver;
|
||||
|
||||
public VaultSearchService(VaultPathResolver resolver)
|
||||
{
|
||||
_resolver = resolver;
|
||||
}
|
||||
|
||||
/// <param name="query">大小写不敏感的子串</param>
|
||||
/// <param name="glob">glob 过滤,例如 "NAS/**/*.md",为 null 时搜全 vault</param>
|
||||
/// <param name="limit">最多返回条数</param>
|
||||
/// <param name="ct">CancellationToken</param>
|
||||
public async Task<List<SearchHit>> SearchAsync(
|
||||
string query,
|
||||
string? glob,
|
||||
int limit,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var root = _resolver.VaultRoot;
|
||||
var files = GetFilesToSearch(root, glob);
|
||||
|
||||
var hits = new List<SearchHit>();
|
||||
foreach (var file in files)
|
||||
{
|
||||
if (ct.IsCancellationRequested) break;
|
||||
if (hits.Count >= limit) break;
|
||||
|
||||
await SearchFileAsync(file, root, query, limit, hits, ct);
|
||||
}
|
||||
|
||||
return hits;
|
||||
}
|
||||
|
||||
private static IEnumerable<string> GetFilesToSearch(string root, string? glob)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(glob))
|
||||
{
|
||||
// 全 vault 搜索,只搜 .md 文件(.json/.yaml 通常不需要全文检索)
|
||||
return Directory.EnumerateFiles(root, "*.md", SearchOption.AllDirectories);
|
||||
}
|
||||
|
||||
// 用 Microsoft.Extensions.FileSystemGlobbing 做 glob 过滤
|
||||
var matcher = new Matcher(StringComparison.OrdinalIgnoreCase);
|
||||
matcher.AddInclude(glob);
|
||||
var dirInfo = new DirectoryInfoWrapper(new DirectoryInfo(root));
|
||||
var result = matcher.Execute(dirInfo);
|
||||
return result.Files.Select(f => Path.Combine(root, f.Path));
|
||||
}
|
||||
|
||||
private static async Task SearchFileAsync(
|
||||
string filePath,
|
||||
string root,
|
||||
string query,
|
||||
int limit,
|
||||
List<SearchHit> hits,
|
||||
CancellationToken ct)
|
||||
{
|
||||
// 跳过过大的文件(>5MB),避免 OOM
|
||||
var fi = new FileInfo(filePath);
|
||||
if (!fi.Exists || fi.Length > 5 * 1024 * 1024) return;
|
||||
|
||||
try
|
||||
{
|
||||
int lineNumber = 0;
|
||||
await foreach (var line in File.ReadLinesAsync(filePath, ct))
|
||||
{
|
||||
lineNumber++;
|
||||
if (hits.Count >= limit) break;
|
||||
|
||||
if (line.Contains(query, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
hits.Add(new SearchHit
|
||||
{
|
||||
File = Path.GetRelativePath(root, filePath).Replace('\\', '/'),
|
||||
Line = lineNumber,
|
||||
Preview = line.Length > 200 ? line[..200] + "..." : line,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// 文件读取失败(权限、锁定等),跳过不影响其他结果
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SearchHit
|
||||
{
|
||||
public string File { get; set; } = "";
|
||||
public int Line { get; set; }
|
||||
public string Preview { get; set; } = "";
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using ObsidianMcp.Config;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ObsidianMcp.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 写入门禁——在路径安全(VaultPathResolver)之上再加写入白名单控制。
|
||||
///
|
||||
/// 规则优先级(从高到低):
|
||||
/// 1. 永禁写入:AGENTS.md / PROFILE.md / README.md / CLAUDE.md(任何路径下的同名文件)
|
||||
/// 2. 永禁前缀:01-Secret/
|
||||
/// 3. 必须命中写入白名单之一才允许
|
||||
///
|
||||
/// 白名单(hardcode):
|
||||
/// - 前缀 02-ShengquGames/logs/
|
||||
/// - 前缀 Coding/
|
||||
/// - 精确匹配 NAS/NAS 待办清单.md
|
||||
///
|
||||
/// 白名单可通过 env Vault__WriteWhitelist__N 扩展。
|
||||
/// </summary>
|
||||
public class VaultWriteGuard
|
||||
{
|
||||
// 永禁写入的文件名(不含路径,任何目录下的同名文件都禁写)
|
||||
private static readonly HashSet<string> ForbiddenFileNames =
|
||||
new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"AGENTS.md",
|
||||
"PROFILE.md",
|
||||
"README.md",
|
||||
"CLAUDE.md",
|
||||
};
|
||||
|
||||
// 永禁写入的路径前缀(相对路径)
|
||||
private static readonly string[] ForbiddenPrefixes =
|
||||
[
|
||||
"01-Secret/",
|
||||
"01-Secret\\",
|
||||
];
|
||||
|
||||
// hardcode 写入白名单
|
||||
// 前缀匹配:以 / 或 \ 结尾表示前缀;精确匹配:其他
|
||||
private static readonly string[] HardcodeWhitelist =
|
||||
[
|
||||
"02-ShengquGames/logs/",
|
||||
"02-ShengquGames\\logs\\",
|
||||
"Coding/",
|
||||
"Coding\\",
|
||||
"NAS/NAS 待办清单.md",
|
||||
"NAS\\NAS 待办清单.md",
|
||||
];
|
||||
|
||||
private readonly VaultPathResolver _resolver;
|
||||
private readonly string[] _extraWhitelist;
|
||||
|
||||
public VaultWriteGuard(VaultPathResolver resolver, IOptions<VaultOptions> opts)
|
||||
{
|
||||
_resolver = resolver;
|
||||
_extraWhitelist = opts.Value.WriteWhitelist ?? [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 校验相对路径是否允许写入。
|
||||
/// 通过则返回规范化后的绝对路径;不通过则抛 UnauthorizedAccessException。
|
||||
/// </summary>
|
||||
public string EnsureWritable(string relativePath)
|
||||
{
|
||||
// 先过路径安全守卫(防穿越 + 黑名单)
|
||||
var absPath = _resolver.Resolve(relativePath);
|
||||
|
||||
// 规范化相对路径(用于白名单匹配),统一用 /
|
||||
var normalized = NormalizeRelative(relativePath);
|
||||
|
||||
// 1. 永禁文件名
|
||||
var fileName = Path.GetFileName(absPath);
|
||||
if (ForbiddenFileNames.Contains(fileName))
|
||||
throw new UnauthorizedAccessException(
|
||||
$"禁止写入保护文件:{relativePath}");
|
||||
|
||||
// 2. 永禁前缀
|
||||
foreach (var prefix in ForbiddenPrefixes)
|
||||
{
|
||||
if (normalized.StartsWith(NormalizeRelative(prefix), StringComparison.OrdinalIgnoreCase))
|
||||
throw new UnauthorizedAccessException(
|
||||
$"禁止写入 01-Secret/ 目录:{relativePath}");
|
||||
}
|
||||
|
||||
// 3. 白名单(hardcode + env 扩展)
|
||||
if (!IsInWhitelist(normalized))
|
||||
throw new UnauthorizedAccessException(
|
||||
$"路径不在写入白名单内:{relativePath}");
|
||||
|
||||
return absPath;
|
||||
}
|
||||
|
||||
private bool IsInWhitelist(string normalized)
|
||||
{
|
||||
var allWhitelist = HardcodeWhitelist.Concat(_extraWhitelist);
|
||||
foreach (var entry in allWhitelist)
|
||||
{
|
||||
var normalizedEntry = NormalizeRelative(entry);
|
||||
if (normalizedEntry.EndsWith('/'))
|
||||
{
|
||||
// 前缀匹配
|
||||
if (normalized.StartsWith(normalizedEntry, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 精确匹配
|
||||
if (string.Equals(normalized, normalizedEntry, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>统一用 / 作分隔符,用于白名单匹配。</summary>
|
||||
private static string NormalizeRelative(string path) =>
|
||||
path.Replace('\\', '/');
|
||||
}
|
||||
Reference in New Issue
Block a user