-
Notifications
You must be signed in to change notification settings - Fork 0
feat(audit): add terminal audit outcomes #53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
04d32bc
feat(audit): secure audit file permissions
mohanagy 3bf6a94
feat(audit): add shared redaction and resilient writes
mohanagy 14655e3
feat(audit): add terminal audit outcomes
mohanagy 3395a59
fix(audit): harden streamed redaction
mohanagy 66712f9
test(redaction): cover capped stream boundary
mohanagy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,29 +1,128 @@ | ||
| import { appendFile, mkdir } from "node:fs/promises"; | ||
| import { chmod, mkdir, open, type FileHandle } from "node:fs/promises"; | ||
| import { dirname } from "node:path"; | ||
| import type { AuditEvent } from "./audit-types.js"; | ||
| import { redactSecrets } from "../secrets/redact.js"; | ||
| import type { AuditEvent, AuditFailureMode, AuditHealth } from "./audit-types.js"; | ||
| import { SecretRedactor } from "../secrets/redact.js"; | ||
| import { MiftahError } from "../utils/errors.js"; | ||
|
|
||
| export interface AuditLoggerOptions { | ||
| secretValues?: readonly string[]; | ||
| redactor?: SecretRedactor; | ||
| includeArguments?: boolean; | ||
| failureMode?: AuditFailureMode; | ||
| } | ||
|
|
||
| export class AuditLogger { | ||
| private readonly options: { secretValues: readonly string[]; includeArguments: boolean }; | ||
| private static readonly writesByPath = new Map<string, Promise<void>>(); | ||
| private readonly options: { includeArguments: boolean; failureMode: AuditFailureMode }; | ||
| private readonly redactor: SecretRedactor; | ||
| private lastFailure?: AuditHealth["lastFailure"]; | ||
|
|
||
| constructor( | ||
| private readonly path: string, | ||
| options: { secretValues?: readonly string[]; includeArguments?: boolean } = {} | ||
| ) { | ||
| constructor(private readonly path: string, options: AuditLoggerOptions = {}) { | ||
| this.options = { | ||
| secretValues: options.secretValues ?? [], | ||
| includeArguments: options.includeArguments ?? false | ||
| includeArguments: options.includeArguments ?? false, | ||
| failureMode: options.failureMode ?? "fail-closed" | ||
| }; | ||
| this.redactor = options.redactor ?? new SecretRedactor(); | ||
| this.redactor.addAll(options.secretValues ?? []); | ||
| } | ||
|
|
||
| async log(event: AuditEvent): Promise<void> { | ||
| await mkdir(dirname(this.path), { recursive: true }); | ||
| const safeEvent = redactSecrets( | ||
| const timestamp = new Date().toISOString(); | ||
| const safeEvent = this.redactor.redactForAudit( | ||
| !this.options.includeArguments | ||
| ? { ...event, arguments: undefined } | ||
| : event, | ||
| this.options.secretValues ?? [] | ||
| : event | ||
| ); | ||
| try { | ||
| await this.enqueue(() => this.writeLine(`${JSON.stringify({ timestamp, ...safeEvent })}\n`)); | ||
| this.lastFailure = undefined; | ||
| } catch (error) { | ||
| const failure = this.recordFailure(error); | ||
| if (this.options.failureMode === "fail-closed") throw failure; | ||
| } | ||
| } | ||
|
|
||
| /** Verifies that a fail-closed sink is writable before an operation can make a side effect. */ | ||
| async ensureWritable(): Promise<void> { | ||
| if (this.options.failureMode !== "fail-closed") return; | ||
| try { | ||
| await this.enqueue(() => this.prepareFile()); | ||
| } catch (error) { | ||
| throw this.recordFailure(error); | ||
| } | ||
| } | ||
|
mohanagy marked this conversation as resolved.
|
||
|
|
||
| health(): AuditHealth { | ||
| return this.lastFailure ? { state: "failed", lastFailure: structuredClone(this.lastFailure) } : { state: "healthy" }; | ||
| } | ||
|
|
||
| private enqueue<Result>(operation: () => Promise<Result>): Promise<Result> { | ||
| const prior = AuditLogger.writesByPath.get(this.path) ?? Promise.resolve(); | ||
| const write = prior.catch(() => undefined).then(operation); | ||
| const tail = write.then( | ||
| () => undefined, | ||
| () => undefined | ||
| ); | ||
| await appendFile(this.path, `${JSON.stringify({ timestamp: new Date().toISOString(), ...safeEvent })}\n`, "utf8"); | ||
| AuditLogger.writesByPath.set(this.path, tail); | ||
| void tail.then(() => { | ||
| if (AuditLogger.writesByPath.get(this.path) === tail) AuditLogger.writesByPath.delete(this.path); | ||
| }); | ||
| return write; | ||
| } | ||
|
|
||
| private async writeLine(line: string): Promise<void> { | ||
| const file = await this.openAuditFile(); | ||
| try { | ||
| await file.writeFile(line, "utf8"); | ||
| } finally { | ||
| await file.close(); | ||
| } | ||
| } | ||
|
|
||
| private async prepareFile(): Promise<void> { | ||
| const file = await this.openAuditFile(); | ||
| await file.close(); | ||
| } | ||
|
|
||
| private async openAuditFile(): Promise<FileHandle> { | ||
| const directory = dirname(this.path); | ||
| await mkdir(directory, { recursive: true, mode: 0o700 }); | ||
| const file = await open(this.path, "a", 0o600); | ||
| try { | ||
| await setRestrictiveMode(this.path, 0o600); | ||
| return file; | ||
| } catch (error) { | ||
| await file.close(); | ||
| throw error; | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| private recordFailure(error: unknown): MiftahError { | ||
| const failure = this.asWriteFailure(error); | ||
| this.lastFailure = { | ||
| timestamp: new Date().toISOString(), | ||
| errorCode: "AUDIT_WRITE_FAILED", | ||
| message: failure.message | ||
| }; | ||
| return failure; | ||
| } | ||
|
|
||
| private asWriteFailure(error: unknown): MiftahError { | ||
| const message = this.redactor.redactText(error instanceof Error ? error.message : String(error)); | ||
| return new MiftahError("AUDIT_WRITE_FAILED", `AUDIT_WRITE_FAILED: unable to write audit record: ${message}`); | ||
| } | ||
| } | ||
|
|
||
| async function setRestrictiveMode(path: string, mode: number): Promise<void> { | ||
| try { | ||
| await chmod(path, mode); | ||
| } catch (error) { | ||
| if ( | ||
| !(error instanceof Error) || | ||
| !("code" in error) || | ||
| (error.code !== "ENOSYS" && error.code !== "ENOTSUP" && error.code !== "EOPNOTSUPP") | ||
| ) { | ||
| throw error; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| import { randomUUID } from "node:crypto"; | ||
| import { AuditLogger } from "./audit-logger.js"; | ||
| import type { AuditEvent, AuditHealth, AuditRoutingSource, AuditStatus } from "./audit-types.js"; | ||
|
|
||
| export interface AuditOperationInput { | ||
| operation: string; | ||
| name: string; | ||
| sourceProfile: string; | ||
| profile?: string; | ||
| arguments?: Record<string, unknown>; | ||
| } | ||
|
|
||
| export interface AuditScopeUpdate { | ||
| name?: string; | ||
| profile?: string; | ||
| upstream?: string; | ||
| routingReason?: string; | ||
| routingSource?: AuditRoutingSource; | ||
| policyName?: string; | ||
| policyDecision?: AuditEvent["policyDecision"]; | ||
| risk?: AuditEvent["risk"]; | ||
| } | ||
|
|
||
| export interface AuditScopeResult { | ||
| status: AuditStatus; | ||
| errorCode?: string; | ||
| } | ||
|
|
||
| export interface AuditLifecycleInput { | ||
| operation: string; | ||
| name: string; | ||
| profile: string; | ||
| upstream?: string; | ||
| lockToProfile?: string; | ||
| status: AuditStatus; | ||
| errorCode?: string; | ||
| } | ||
|
|
||
| /** Creates one final audit record per MCP request when audit logging is configured. */ | ||
| export class AuditTrail { | ||
| readonly sessionId = randomUUID(); | ||
|
|
||
| constructor( | ||
| private readonly wrapperName: string, | ||
| private readonly logger?: AuditLogger | ||
| ) {} | ||
|
|
||
| beginOperation(input: AuditOperationInput): AuditScope { | ||
| return new AuditScope(this, input); | ||
| } | ||
|
|
||
| health(): { enabled: boolean; state?: AuditHealth["state"]; lastFailure?: AuditHealth["lastFailure"] } { | ||
| if (!this.logger) return { enabled: false }; | ||
| return { enabled: true, ...this.logger.health() }; | ||
| } | ||
|
|
||
| async ensureWritable(): Promise<void> { | ||
| await this.logger?.ensureWritable(); | ||
| } | ||
|
|
||
| async write(event: AuditEvent): Promise<void> { | ||
| await this.logger?.log(event); | ||
| } | ||
|
|
||
| async writeLifecycle(input: AuditLifecycleInput): Promise<void> { | ||
| await this.write({ | ||
| wrapper: this.wrapperName, | ||
| kind: "lifecycle", | ||
| eventId: randomUUID(), | ||
| sessionId: this.sessionId, | ||
| sourceProfile: input.profile, | ||
| profile: input.profile, | ||
| operation: input.operation, | ||
| name: input.name, | ||
| status: input.status, | ||
| durationMs: 0, | ||
| ...(input.upstream === undefined ? {} : { upstream: input.upstream }), | ||
| ...(input.lockToProfile === undefined ? {} : { lockToProfile: input.lockToProfile }), | ||
| ...(input.errorCode === undefined ? {} : { errorCode: input.errorCode }) | ||
| }); | ||
| } | ||
|
|
||
| /** Records a background lifecycle event without letting audit I/O disrupt process management. */ | ||
| recordLifecycle(input: AuditLifecycleInput): void { | ||
| void this.writeLifecycle(input).catch(() => undefined); | ||
| } | ||
|
|
||
| wrapper(): string { | ||
| return this.wrapperName; | ||
| } | ||
| } | ||
|
|
||
| /** Accumulates request context and prevents duplicate terminal records. */ | ||
| export class AuditScope { | ||
| private readonly requestId = randomUUID(); | ||
| private readonly startedAt = Date.now(); | ||
| private readonly event: AuditOperationInput & AuditScopeUpdate; | ||
| private finalized = false; | ||
|
|
||
| constructor( | ||
| private readonly trail: AuditTrail, | ||
| input: AuditOperationInput | ||
| ) { | ||
| this.event = { ...input, profile: input.profile ?? input.sourceProfile }; | ||
| } | ||
|
|
||
| get isFinalized(): boolean { | ||
| return this.finalized; | ||
| } | ||
|
|
||
| update(update: AuditScopeUpdate): void { | ||
| Object.assign(this.event, update); | ||
| } | ||
|
|
||
| async finish(result: AuditScopeResult): Promise<void> { | ||
| if (this.finalized) throw new Error("Audit scope already has a terminal event"); | ||
| this.finalized = true; | ||
| await this.trail.write({ | ||
| wrapper: this.trail.wrapper(), | ||
| kind: "operation", | ||
| eventId: this.requestId, | ||
| requestId: this.requestId, | ||
| sessionId: this.trail.sessionId, | ||
| sourceProfile: this.event.sourceProfile, | ||
| profile: this.event.profile ?? this.event.sourceProfile, | ||
| operation: this.event.operation, | ||
| name: this.event.name, | ||
| status: result.status, | ||
| durationMs: Date.now() - this.startedAt, | ||
| ...(this.event.upstream === undefined ? {} : { upstream: this.event.upstream }), | ||
| ...(this.event.routingReason === undefined ? {} : { routingReason: this.event.routingReason }), | ||
| ...(this.event.routingSource === undefined ? {} : { routingSource: this.event.routingSource }), | ||
| ...(this.event.policyName === undefined ? {} : { policyName: this.event.policyName }), | ||
| ...(this.event.policyDecision === undefined ? {} : { policyDecision: this.event.policyDecision }), | ||
| ...(this.event.risk === undefined ? {} : { risk: this.event.risk }), | ||
| ...(this.event.arguments === undefined ? {} : { arguments: this.event.arguments }), | ||
| ...(result.errorCode === undefined ? {} : { errorCode: result.errorCode }) | ||
| }); | ||
| } | ||
|
mohanagy marked this conversation as resolved.
|
||
|
|
||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.