Skip to content
106 changes: 106 additions & 0 deletions src/frameworks/rust/rust-wizard-agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/* Rust wizard using posthog-agent with PostHog MCP */
import * as fs from 'node:fs';
import * as path from 'node:path';
import type { WizardRunOptions } from '@utils/types';
import type { FrameworkConfig } from '@lib/framework-config';
import { cargoPackageManager } from '@lib/detection/package-manager';
import { Integration } from '@lib/constants';

type RustContext = {
asyncRuntime?: boolean;
};

function readCargoToml(installDir: string): string | undefined {
const cargoTomlPath = path.join(installDir, 'Cargo.toml');
if (!fs.existsSync(cargoTomlPath)) {
return undefined;
}
return fs.readFileSync(cargoTomlPath, 'utf-8');
}

/** posthog-rs defaults to its async client; projects without an async runtime need the blocking one. */
function hasAsyncRuntime(installDir: string): boolean {
const cargoToml = readCargoToml(installDir);
return !!cargoToml && /^\s*(tokio|async-std|smol)\s*[=.]/m.test(cargoToml);
}

export const RUST_AGENT_CONFIG: FrameworkConfig<RustContext> = {
metadata: {
name: 'Rust',
integration: Integration.rust,
docsUrl: 'https://posthog.com/docs/libraries/rust',
gatherContext: (options: WizardRunOptions) => {
const asyncRuntime = hasAsyncRuntime(options.installDir);
return Promise.resolve({ asyncRuntime });
},
},

detection: {
packageName: 'posthog-rs',
packageDisplayName: 'Rust',
usesPackageJson: false,
getVersion: () => undefined,
// A Cargo.toml with a [package] section marks a crate root. A
// workspace-root-only manifest ([workspace], no [package]) falls
// through — the agentic monorepo scan finds the nested crates.
detect: (options) => {
const cargoToml = readCargoToml(options.installDir);
return Promise.resolve(!!cargoToml && /^\s*\[package\]/m.test(cargoToml));
},
detectPackageManager: cargoPackageManager,
},

environment: {
uploadToHosting: false,
getEnvVars: (apiKey: string, host: string) => ({
POSTHOG_API_KEY: apiKey,
POSTHOG_HOST: host,
}),
},

analytics: {
getTags: (context) => ({
asyncRuntime: context.asyncRuntime ? 'true' : 'false',
}),
},

prompts: {
projectTypeDetection:
'This is a Rust project. Look for Cargo.toml with a [package] section, src/main.rs or src/lib.rs, and Cargo.lock to confirm.',
packageInstallation:
'Install the PostHog Rust SDK with `cargo add posthog-rs`. Do not manually edit Cargo.toml; cargo updates it automatically.',
getAdditionalContextLines: (context) => {
const lines = [
`Framework docs ID: rust (use posthog://docs/frameworks/rust for documentation)`,
'capture() hands events to a background worker — the client must flush() or shutdown() before the process exits or buffered events are lost.',
];
if (context.asyncRuntime) {
lines.push(
'An async runtime is present — use the default async posthog-rs client.',
);
} else {
lines.push(
'No async runtime detected — install with `cargo add posthog-rs --no-default-features` and use the blocking client.',
);
}
return lines;
},
},

ui: {
successMessage: 'PostHog integration complete',
estimatedDurationMinutes: 5,
getOutroChanges: () => [
'Analyzed your Rust project structure',
'Installed the posthog-rs crate via cargo add',
'Initialized a shared PostHog client configured from environment variables',
'Instrumented meaningful events with client.capture',
],
getOutroNextSteps: () => [
'Run your Rust application and trigger the instrumented code paths',
'Visit your PostHog dashboard to see incoming events',
'Use Event::new(event_name, distinct_id) and client.capture to track custom events',
'Keep flush()/shutdown() in your exit path so queued events are sent',
],
},
};
17 changes: 16 additions & 1 deletion src/lib/__tests__/wizard-can-use-tool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,21 @@ describe('bash fence — allows real toolchain commands (from skills + field log
expect(allow('xcodegen dump')).toBe('deny');
});

it('rust ecosystem', () => {
expect(allow('cargo add posthog-rs')).toBe('allow');
expect(allow('cargo add posthog-rs --no-default-features')).toBe('allow');
expect(allow('cargo build')).toBe('allow');
expect(allow('cargo check --all-targets')).toBe('allow');
expect(allow('cargo fmt')).toBe('allow');
expect(allow('cargo clippy')).toBe('allow');
expect(allow('cargo metadata --format-version 1')).toBe('allow');
// run/test execute project code; install/publish are outward-facing.
expect(allow('cargo run')).toBe('deny');
expect(allow('cargo test')).toBe('deny');
expect(allow('cargo install evil-tool')).toBe('deny');
expect(allow('cargo publish')).toBe('deny');
});

it('elixir ecosystem', () => {
expect(allow('mix deps.get')).toBe('allow');
expect(allow('mix deps.update posthog')).toBe('allow');
Expand Down Expand Up @@ -249,7 +264,7 @@ describe('bash fence — attack corpus (one test per bypass vector)', () => {
expect(allow('xcodebuild test-without-building')).toBe('deny');
expect(allow('bundle exec rspec')).toBe('deny');
expect(allow('composer run-script evil')).toBe('deny');
expect(allow('cargo run')).toBe('deny'); // no rust framework -> whole binary denied
expect(allow('cargo run')).toBe('deny'); // arbitrary code execution
expect(allow('go run main.go')).toBe('deny'); // arbitrary code execution
});

Expand Down
16 changes: 16 additions & 0 deletions src/lib/agent/bash-fence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,21 @@ const SIMPLE_MANAGERS: Record<string, readonly string[]> = {
swift: ['package', 'build'],
pod: ['install', 'update', 'search'],
carthage: ['bootstrap', 'update'],
// cargo build/check also execute code (build.rs build scripts + proc-macros),
// accepted under the "builds are equivalent risk" model in the file header.
// run/test are denied so the finished binary/tests aren't run; install/publish
// are outward-facing.
cargo: [
'add',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High: Repository-controlled Cargo credential provider execution

Cargo loads .cargo/config.toml from the current project, and authenticated registries can configure credential providers as external executables. An attacker can commit a provider script and registry configuration, then cause the agent to run an allowed cargo add or cargo fetch; Cargo executes the script without exposing its command to this fence or the pre-execution scan. Deny these Cargo operations in the unsandboxed harness, or run them through a trusted wrapper that rejects repository-local executable configuration. (doc.rust-lang.org)

'remove',
'build',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High: Cargo build scripts bypass the execution fence

An attacker can execute arbitrary commands on a developer's machine by placing a malicious build.rs or procedural macro in a repository and inducing the agent to run cargo build, cargo check, or cargo clippy. These entries are global, and the unsandboxed harness treats this fence as its execution boundary; scanning the benign Cargo command does not inspect the code Cargo executes. Remove these verbs from that path or run them inside an OS sandbox that prevents host access, network access, and writes outside the workspace.

'check',
'fmt',
'clippy',
'metadata',
'tree',
'fetch',
],
// mix runs arbitrary project-defined tasks, so only the dependency + build
// tasks are listed. compile also executes code (compile-time macros), accepted
// under the "builds are equivalent risk" model in the file header; run/test/
Expand Down Expand Up @@ -138,6 +153,7 @@ const ALLOWED_TOOLS_SUMMARY =
'xcodegen (generate), xcodebuild (build/clean/archive actions), gradle/gradlew (build|clean|dependencies|assemble*/compile*/bundle*/lint* tasks), ' +
'mvn (install|compile|package|verify|dependency:tree), ' +
'flutter/dart (pub add/remove/get/upgrade/outdated/deps, analyze, build, clean, doctor), ' +
'cargo (add|remove|build|check|fmt|clippy|metadata|tree|fetch), ' +
'mix (deps.get|deps.update|deps.tree|compile|format|hex.info), ' +
'go (get|build|vet|fmt|version|list, mod tidy/download/verify/graph/why).';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const INTEGRATION_ENTRIES = [
{ id: 'integration-ruby', framework: 'ruby' },
{ id: 'integration-elixir', framework: 'elixir' },
{ id: 'integration-go', framework: 'go' },
{ id: 'integration-rust', framework: 'rust' },
{ id: 'integration-swift', framework: 'swift' },
{ id: 'integration-kmp', framework: 'kmp' },
{ id: 'integration-flutter', framework: 'flutter' },
Expand Down
1 change: 1 addition & 0 deletions src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ export enum Integration {
rails = 'rails',
elixir = 'elixir',
go = 'go',
rust = 'rust',

// Language fallbacks. Keep javascriptNode last: it matches any package.json.
python = 'python',
Expand Down
34 changes: 34 additions & 0 deletions src/lib/detection/__tests__/framework.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ANDROID_AGENT_CONFIG } from '../../../frameworks/android/android-wizard
import { KMP_AGENT_CONFIG } from '../../../frameworks/kmp/kmp-wizard-agent';
import { ELIXIR_AGENT_CONFIG } from '../../../frameworks/elixir/elixir-wizard-agent';
import { GO_AGENT_CONFIG } from '../../../frameworks/go/go-wizard-agent';
import { RUST_AGENT_CONFIG } from '../../../frameworks/rust/rust-wizard-agent';
import { FLUTTER_AGENT_CONFIG } from '../../../frameworks/flutter/flutter-wizard-agent';

/** A throwaway project dir seeded with the given files. */
Expand Down Expand Up @@ -151,6 +152,16 @@ describe('detectFramework (end-to-end over real project dirs)', () => {
);
});

test('a Rust crate resolves to rust', async () => {
const opts = project({
'Cargo.toml': '[package]\nname = "my-app"\nedition = "2021"\n',
'src/main.rs': 'fn main() {}',
});
await expect(detectFramework(opts.installDir)).resolves.toBe(
Integration.rust,
);
});

test('a Phoenix project resolves to elixir', async () => {
const opts = project({
'mix.exs':
Expand Down Expand Up @@ -262,6 +273,29 @@ describe('android detect', () => {
});
});

describe('rust detect', () => {
const detect = RUST_AGENT_CONFIG.detection.detect;

test('claims a crate with a [package] section', async () => {
const opts = project({
'Cargo.toml': '[package]\nname = "my-app"\nedition = "2021"\n',
});
await expect(detect(opts)).resolves.toBe(true);
});

test('does not claim a workspace-root-only manifest', async () => {
const opts = project({
'Cargo.toml': '[workspace]\nmembers = ["crates/*"]\n',
});
await expect(detect(opts)).resolves.toBe(false);
});

test('does not claim a project without a Cargo.toml', async () => {
const opts = project({ 'src/main.rs': 'fn main() {}' });
await expect(detect(opts)).resolves.toBe(false);
});
});

describe('elixir detect', () => {
const detect = ELIXIR_AGENT_CONFIG.detection.detect;

Expand Down
2 changes: 2 additions & 0 deletions src/lib/detection/__tests__/package-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
composerPackageManager,
swiftPackageManager,
gradlePackageManager,
cargoPackageManager,
mixPackageManager,
goModulesPackageManager,
pubPackageManager,
Expand Down Expand Up @@ -191,6 +192,7 @@ describe('static package manager helpers', () => {
{ fn: composerPackageManager, name: 'composer' },
{ fn: swiftPackageManager, name: 'spm' },
{ fn: gradlePackageManager, name: 'gradle' },
{ fn: cargoPackageManager, name: 'cargo' },
{ fn: mixPackageManager, name: 'mix' },
{ fn: goModulesPackageManager, name: 'go' },
{ fn: pubPackageManager, name: 'pub' },
Expand Down
5 changes: 3 additions & 2 deletions src/lib/detection/agentic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,14 @@ export const PROJECT_MANIFESTS: readonly string[] = [
// Ruby / PHP
'Gemfile',
'composer.json',
// Rust
'Cargo.toml',
// Elixir
'mix.exs',
// Go
'go.mod',
// Rust / JVM / .NET: no framework targets yet, but found so
// JVM / .NET: no framework targets yet, but found so
// an existing PostHog SDK is reported (feeds self-driving's "continue" path).
'Cargo.toml',
'pom.xml',
'*.csproj',
// Mobile / native
Expand Down
18 changes: 18 additions & 0 deletions src/lib/detection/package-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,24 @@ export function bundlerPackageManager(): Promise<PackageManagerInfo> {
});
}

// ---------------------------------------------------------------------------
// Rust (Cargo) helper
// ---------------------------------------------------------------------------

const CARGO: DetectedPackageManager = {
name: 'cargo',
label: 'Cargo',
installCommand: 'cargo add',
};

export function cargoPackageManager(): Promise<PackageManagerInfo> {
return Promise.resolve({
detected: [CARGO],
primary: CARGO,
recommendation: 'Use Cargo (cargo add).',
});
}

// ---------------------------------------------------------------------------
// Elixir (Mix) helper
// ---------------------------------------------------------------------------
Expand Down
2 changes: 2 additions & 0 deletions src/lib/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { ANDROID_AGENT_CONFIG } from '@frameworks/android/android-wizard-agent';
import { RAILS_AGENT_CONFIG } from '@frameworks/rails/rails-wizard-agent';
import { ELIXIR_AGENT_CONFIG } from '@frameworks/elixir/elixir-wizard-agent';
import { GO_AGENT_CONFIG } from '@frameworks/go/go-wizard-agent';
import { RUST_AGENT_CONFIG } from '@frameworks/rust/rust-wizard-agent';
import { PYTHON_AGENT_CONFIG } from '@frameworks/python/python-wizard-agent';
import { RUBY_AGENT_CONFIG } from '@frameworks/ruby/ruby-wizard-agent';
import { JAVASCRIPT_NODE_AGENT_CONFIG } from '@frameworks/javascript-node/javascript-node-wizard-agent';
Expand Down Expand Up @@ -48,6 +49,7 @@ export const FRAMEWORK_REGISTRY: Record<Integration, FrameworkConfig> = {
[Integration.rails]: RAILS_AGENT_CONFIG,
[Integration.elixir]: ELIXIR_AGENT_CONFIG,
[Integration.go]: GO_AGENT_CONFIG,
[Integration.rust]: RUST_AGENT_CONFIG,
[Integration.python]: PYTHON_AGENT_CONFIG,
[Integration.ruby]: RUBY_AGENT_CONFIG,
[Integration.javascriptNode]: JAVASCRIPT_NODE_AGENT_CONFIG,
Expand Down
Loading