Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ All notable changes to this project will be documented in this file. The format

- [#290](https://github.com/mohanagy/miftah/issues/290) Redesigned the README as a concise product front door: first-screen fit guidance, one connector with named profiles, one safe GitHub first-success path, distinct secret/native-OAuth/upstream-owned-OAuth routes, visible client/wizard/Console choices, and progressively disclosed security, architecture, reference, and troubleshooting links. External evaluator acceptance remains open and is not claimed by this documentation change.

### Fixed

- [#255](https://github.com/mohanagy/miftah/issues/255) Isolated logical audit, Console, and OAuth profile-rename contracts from host-dependent file-flush latency while retaining dedicated real-sync audit and OAuth transaction integration tests and the broader durability suites. Process-tree tests now stop at their real containment boundary, drain bounded restart work, and use a minimal MCP fixture for the shutdown-timing contract. Production audit writes, fail-closed locking, transactional recovery, containment, test timeouts, coverage, and platform gates are unchanged.

## [0.5.0] - 2026-07-28

### Added
Expand Down
31 changes: 31 additions & 0 deletions tests/audit-integrity-durability.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { AuditLogger } from "../src/audit/audit-logger.js";
import { verifyAuditJournal } from "../src/audit/audit-journal.js";

describe("audit integrity durability integration", () => {
it("persists one verifiable integrity record through the real file sync boundary", async () => {
const directory = await mkdtemp(join(tmpdir(), "miftah-audit-integrity-durability-"));
const path = join(directory, "audit.jsonl");
try {
const logger = new AuditLogger(path, {
integrity: { algorithm: "sha256-chain" }
});
await logger.log({
wrapper: "github",
profile: "work",
operation: "tools/call",
name: "real-durability-integrity-event",
status: "success",
durationMs: 1
});

expect(await verifyAuditJournal(path)).toEqual({ ok: true });
expect(await readFile(path, "utf8")).toContain("real-durability-integrity-event");
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});
7 changes: 6 additions & 1 deletion tests/audit-integrity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import { createServer, Socket } from "node:net";
import type { Server } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AuditLogger } from "../src/audit/audit-logger.js";
import { verifyAuditJournal } from "../src/audit/audit-journal.js";
import { stubFileSyncForLogicalTest } from "./helpers/logical-file-sync.js";

type BufferWrite = (
this: FileHandle,
Expand Down Expand Up @@ -41,6 +42,10 @@ interface DelayedLocalRefusalDiagnosticState {
readonly bindOutcome: DelayedLocalRefusalBindOutcome;
}

beforeEach(async () => {
await stubFileSyncForLogicalTest();
});

// Vitest's current default test timeout is 5 seconds; emit evidence before the runner cuts it off.
const HARD_LINK_FIXTURE_DIAGNOSTIC_DELAY_MS = 4_500;

Expand Down
7 changes: 6 additions & 1 deletion tests/audit-log-reader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import { randomUUID } from "node:crypto";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { afterAll, describe, expect, it } from "vitest";
import { afterAll, beforeEach, describe, expect, it } from "vitest";
import {
AUDIT_READ_CHUNK_BYTES,
MALFORMED_AUDIT_RECORD,
Expand All @@ -29,6 +29,7 @@ import { runLogsCommand } from "../src/cli/logs.js";
import { createRuntime } from "../src/runtime/create-runtime.js";
import { resolveRuntimeConfig } from "../src/runtime/resolve-runtime-config.js";
import { SecretRedactor } from "../src/secrets/redact.js";
import { stubFileSyncForLogicalTest } from "./helpers/logical-file-sync.js";

const testRoot = join(process.cwd(), ".miftah-audit-log-reader-tests");
const pollIntervalMs = 10;
Expand All @@ -37,6 +38,10 @@ afterAll(async () => {
await rm(testRoot, { recursive: true, force: true });
});

beforeEach(async () => {
await stubFileSyncForLogicalTest();
});

async function inSandbox<T>(run: (directory: string) => Promise<T>): Promise<T> {
const directory = join(testRoot, randomUUID());
await mkdir(directory, { recursive: true });
Expand Down
36 changes: 36 additions & 0 deletions tests/audit-logical-suite-contract.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";

describe("audit logical suite durability boundary", () => {
it("isolates logical filesystem assertions from host sync latency without weakening durability coverage", async () => {
const logicalSyncHook =
/beforeEach\s*\(\s*async\s*\(\)\s*=>\s*\{\s*await\s+stubFileSyncForLogicalTest\(\);\s*\}\s*\);/s;
const [
integritySuite,
readerSuite,
consoleApplicationSuite,
auditDurabilitySuite,
integrityDurabilitySuite,
oauthRenameSuite,
oauthRenameDurabilitySuite
] = await Promise.all([
readFile(new URL("./audit-integrity.test.ts", import.meta.url), "utf8"),
readFile(new URL("./audit-log-reader.test.ts", import.meta.url), "utf8"),
readFile(new URL("./console-application-service.test.ts", import.meta.url), "utf8"),
readFile(new URL("./audit.test.ts", import.meta.url), "utf8"),
readFile(new URL("./audit-integrity-durability.test.ts", import.meta.url), "utf8"),
readFile(new URL("./oauth-profile-rename-transaction.test.ts", import.meta.url), "utf8"),
readFile(new URL("./oauth-profile-rename-durability.test.ts", import.meta.url), "utf8")
]);

expect(integritySuite).toMatch(logicalSyncHook);
expect(readerSuite).toMatch(logicalSyncHook);
expect(consoleApplicationSuite).toMatch(logicalSyncHook);
expect(auditDurabilitySuite).not.toContain("stubFileSyncForLogicalTest");
expect(integrityDurabilitySuite).toContain('algorithm: "sha256-chain"');
expect(integrityDurabilitySuite).not.toContain("stubFileSyncForLogicalTest");
expect(oauthRenameSuite).toMatch(logicalSyncHook);
expect(oauthRenameDurabilitySuite).toContain("runOAuthProfileRenameTransaction");
expect(oauthRenameDurabilitySuite).not.toContain("stubFileSyncForLogicalTest");
});
});
7 changes: 6 additions & 1 deletion tests/console-application-service.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { ConsoleApplicationService, consoleAuditPath } from "../src/console/console-application-service.js";
import { buildPresetConfig } from "../src/config/presets.js";
import {
Expand All @@ -21,6 +21,7 @@ import { MiftahError } from "../src/utils/errors.js";
import { createPrivateConsoleDirectory } from "./helpers/private-console-directory.js";
import { environmentProfileConfig } from "./helpers/environment-profile-config.js";
import { createMemoryProfileRenameOAuthDependencies } from "./helpers/profile-rename-oauth-dependencies.js";
import { stubFileSyncForLogicalTest } from "./helpers/logical-file-sync.js";
import {
startOAuthCompatibilityProbe,
type OAuthCompatibilityProbe
Expand All @@ -31,6 +32,10 @@ const oauthUpstreams: OAuthCompatibilityProbe[] = [];
const connectionRef = "oauthconn:31cb3ef5-22cb-4bf7-9ebf-e4a2d32bf18c";
const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");

beforeEach(async () => {
await stubFileSyncForLogicalTest();
});

function supportedKnownConnectorOptions(): {
readonly preset: string;
readonly credentialEnv: string;
Expand Down
36 changes: 36 additions & 0 deletions tests/fixtures/shutdown-delay-upstream.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { writeFileSync } from "node:fs";
import { setTimeout } from "node:timers";

let input = "";

process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const newline = input.indexOf("\n");
if (newline === -1) break;
const line = input.slice(0, newline).replace(/\r$/, "");
input = input.slice(newline + 1);
if (line.length === 0) continue;
const message = JSON.parse(line);
if (message.method !== "initialize" || message.id === undefined) continue;
process.stdout.write(`${JSON.stringify({
jsonrpc: "2.0",
id: message.id,
result: {
protocolVersion: message.params?.protocolVersion ?? "2025-06-18",
capabilities: {},
serverInfo: { name: "shutdown-delay-upstream", version: "1.0.0" }
}
})}\n`);
}
});

process.stdin.on("end", () => {
const markerPath = process.env.TEST_SHUTDOWN_END_PATH;
if (markerPath !== undefined) writeFileSync(markerPath, "ended", { mode: 0o600 });
const delayMs = Number(process.env.TEST_SHUTDOWN_DELAY_MS ?? "0");
setTimeout(() => process.exit(0), Number.isFinite(delayMs) ? Math.max(0, delayMs) : 0);
});

process.stdin.resume();
33 changes: 33 additions & 0 deletions tests/helpers/logical-file-sync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { mkdtemp, open, rm, type FileHandle } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { vi } from "vitest";

type FileHandlePrototype = {
sync: FileHandle["sync"];
};

let fileHandlePrototype: FileHandlePrototype | undefined;

async function resolveFileHandlePrototype(): Promise<FileHandlePrototype> {
if (fileHandlePrototype !== undefined) return fileHandlePrototype;
const directory = await mkdtemp(join(tmpdir(), "miftah-logical-sync-probe-"));
const probe = await open(join(directory, "probe"), "w", 0o600);
try {
fileHandlePrototype = Object.getPrototypeOf(probe) as FileHandlePrototype;
return fileHandlePrototype;
} finally {
await probe.close();
await rm(directory, { recursive: true, force: true });
}
}

/**
* Logical filesystem suites exercise production transaction and reader behavior
* without benchmarking host disk-flush latency. Dedicated audit and OAuth rename
* durability suites intentionally retain real sync integration coverage.
*/
export async function stubFileSyncForLogicalTest(): Promise<void> {
const prototype = await resolveFileHandlePrototype();
vi.spyOn(prototype, "sync").mockResolvedValue(undefined);
}
16 changes: 8 additions & 8 deletions tests/helpers/upstream-manager-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ const retainedStdioDescendantFixture = join(
"fixtures",
"retained-stdio-descendant.mjs"
);
const shutdownDelayFixture = join(
dirname(fileURLToPath(import.meta.url)),
"..",
"fixtures",
"shutdown-delay-upstream.mjs"
);
const backToBackProgressFixture = join(
dirname(fileURLToPath(import.meta.url)),
"..",
Expand Down Expand Up @@ -878,7 +884,7 @@ function registerTeardown(): void {
{
transport: "stdio",
command: process.execPath,
args: [fixture],
args: [shutdownDelayFixture],
env: {
TEST_SHUTDOWN_DELAY_MS: "500",
TEST_SHUTDOWN_END_PATH: shutdownEndPath
Expand Down Expand Up @@ -1002,14 +1008,8 @@ function registerTeardown(): void {
() => fixtureProcessIsAlive(recordedFirstDescendantPid),
(alive) => alive === false
);
await waitFor(
() => countStarts(startCountPath),
(starts) => starts === 2
);
expect(replacementStartedBeforeFirstDescendantReaped).toBe(false);

descendantPid = Number(await readFile(descendantPidPath, "utf8"));
expect(Number.isSafeInteger(descendantPid)).toBe(true);
await expect(restarting).resolves.toBeDefined();
} finally {
if (descendantPid !== undefined) {
terminateFixtureProcess(descendantPid);
Expand Down
97 changes: 97 additions & 0 deletions tests/oauth-profile-rename-durability.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { readConfigMigrationSource } from "../src/cli/migrate-config.js";
import { OAuthConnectionRegistry } from "../src/oauth/connection-registry.js";
import {
createOAuthConfigIdentity,
createOAuthConnectionBinding,
parseOAuthConnectionRef
} from "../src/oauth/connection-types.js";
import {
canonicalOAuthProfileRenameConfigPath,
oauthProfileRenameJournalPath,
runOAuthProfileRenameTransaction
} from "../src/oauth/profile-rename-transaction.js";
import { planProfileRename } from "../src/setup/profile-rename-onboarding.js";
import {
MemoryProfileRenameCredentialStore,
MemoryProfileRenameMetadataStore
} from "./helpers/profile-rename-oauth-dependencies.js";

const connectionRef = "oauthconn:11111111-1111-4111-8111-111111111111";

describe("native OAuth profile-rename durability", () => {
it("commits one exact binding migration through the real filesystem sync boundary", async () => {
const directory = await mkdtemp(join(tmpdir(), "miftah-oauth-profile-rename-durability-"));
const configPath = join(directory, "remote-analytics.json");
try {
const config = {
version: "3",
name: "remote-analytics",
defaultProfile: "work",
upstream: { transport: "streamable-http", url: "https://mcp.example.com/mcp" },
profiles: { work: {}, personal: {} },
oauth: {
connections: {
[connectionRef]: {
profile: "work",
upstream: "default",
resource: "https://mcp.example.com/mcp",
issuer: "https://auth.example.com",
clientRegistration: "dynamic",
scopes: ["openid"]
}
}
}
} as const;
await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
const source = await readConfigMigrationSource(configPath);
const candidate = planProfileRename(config, {
configPath,
profile: "work",
newProfile: "studio"
}).config;
const canonicalConfigPath = await canonicalOAuthProfileRenameConfigPath(configPath);
const binding = (profile: string) =>
createOAuthConnectionBinding({
configIdentity: createOAuthConfigIdentity(canonicalConfigPath),
connectionRef: parseOAuthConnectionRef(connectionRef),
profile,
upstream: "default",
resource: "https://mcp.example.com/mcp",
issuer: "https://auth.example.com",
clientRegistration: "dynamic",
scopes: ["openid"]
});
const from = binding("work");
const to = binding("studio");
const credentials = new MemoryProfileRenameCredentialStore();
const registry = new OAuthConnectionRegistry(
new MemoryProfileRenameMetadataStore(),
() => "2030-01-02T03:04:05.000Z"
);
await credentials.save(from, { accessToken: "fixture-access-token" });
await registry.create(from);

await expect(
runOAuthProfileRenameTransaction(
{ configPath, source, candidate, bindings: [{ from, to }] },
{ credentialStore: credentials, registry }
)
).resolves.toMatchObject({ backupPath: expect.any(String) });

expect(JSON.parse(await readFile(configPath, "utf8"))).toMatchObject({
defaultProfile: "studio",
profiles: { studio: {}, personal: {} },
oauth: { connections: { [connectionRef]: { profile: "studio" } } }
});
await expect(readFile(oauthProfileRenameJournalPath(canonicalConfigPath), "utf8")).rejects.toMatchObject({
code: "ENOENT"
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});
7 changes: 6 additions & 1 deletion tests/oauth-profile-rename-transaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
import { lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { OAuthConnectionRegistry } from "../src/oauth/connection-registry.js";
import {
createOAuthConfigIdentity,
Expand All @@ -24,6 +24,7 @@ import {
MemoryProfileRenameCredentialStore as MemoryCredentialStore,
MemoryProfileRenameMetadataStore as MemoryMetadataStore
} from "./helpers/profile-rename-oauth-dependencies.js";
import { stubFileSyncForLogicalTest } from "./helpers/logical-file-sync.js";

type ProfileRenameTimeoutDiagnosticPhase =
| "test-setup"
Expand Down Expand Up @@ -83,6 +84,10 @@ const directories: string[] = [];
const connectionRef = "oauthconn:11111111-1111-4111-8111-111111111111";
let profileRenameTimeoutDiagnosticStop: (() => void) | undefined;

beforeEach(async () => {
await stubFileSyncForLogicalTest();
});

afterEach(async () => {
const stopTimeoutDiagnostic = profileRenameTimeoutDiagnosticStop;
if (stopTimeoutDiagnostic !== undefined) profileRenameTimeoutDiagnostic.phase = "test-cleanup";
Expand Down