快速入門:使用 MXC SDK 執行工作負載

使用 .NET、TypeScript 或 Rust SDK 在 Windows 行程隔離中執行指令。 每個範例會產生一個範例輸入,允許工作負載讀取,並授權寫入獨立的輸出資料夾。 網路和使用者介面權限仍遭拒絕。

你的主機應用程式會建立原則並處理結果。 指令執行於 MXC 內部;主機應用程式的其他部分則沒有。

範例使用 MXC 1.0 V1 SDK API。 V1 SDK 內部使用穩定的 1.0.0 結構描述,因此你不需要在請求中指定結構描述版本。 請參見 選擇相容的結構描述。

Prerequisites

您需要:

  • Windows 11,版本為 24H2 或更新版本,並支援 ProcessContainer 環境。
  • 針對 C#,需要 .NET 8 SDK 或更新版本,以及 Microsoft.Mxc.Sdk NuGet 套件。
  • 對於 TypeScript、npm、套件 @microsoft/mxc-sdk,以及 Node.js 24 發行線中的 24.21.0 或更新版本,或 Node.js 26.8.0 或更新版本。
  • Rust 則是穩定的 Rust 工具鏈,搭配 MSVC 建構工具和 mxc-sdk crate。 請參見「在 Windows 上設定你的 Rust 開發環境」。
  • 一個可寫的工作目錄和用於安裝/設定所需命令的 PowerShell。

這些說明書使用 NuGet.org、npm 和 crates.io 的 MXC 1.0 套件。 不需要 MXC 原始碼建置。

在執行範例前先確認 平台支援 。 支援的 Windows 版本並不保證所有可選功能都能使用。

在某些主機上,MXC 會在基於 AppContainer 的後備層執行程序隔離。 該層需要一次性準備系統磁碟機與空裝置,且空裝置設定會在每次重啟時重置。 當缺少準備時,MXC 的主機探針會回傳警告,指出要執行的 wxc-host-prep.exe 子指令。 TypeScript 範例會從 getPlatformSupport() 列印這些警告,你也可以透過執行 wxc-exec.exe --probe 來檢查主機。 因為 wxc-host-prep.exe 需要管理員核准,建議由管理員執行建議的指令,而不是從你的應用程式執行該指令。 詳情請參閱 主機準備。

1. 建立專案

建立一個主控台應用程式,並從 NuGet.org 新增 MXC 套件:

dotnet new console -n MxcQuickstart
Set-Location MxcQuickstart
dotnet add package Microsoft.Mxc.Sdk

2. 定義並執行工作負載

程序隔離適合這種短暫執行的命令,因為它需要選取的主機檔案,且不需要保留的環境。 其他工作負載可能需要不同的 容器類型。

主機在專案目錄下方建立 workspace\input 和 workspace\output。 包含的指令會 input.txt 讀取並寫入 result.txt。 它不會獲得對輸入目錄或其他專案檔案的寫入權限。

主機提供一個小型、明確的環境,而非繼承自身的變數。 當你提供 Windows ProcessContainer 工作負載的環境時,請同時包含 SystemRoot 和 LOCALAPPDATA。 如果缺少其中一項,MXC 會在啟動前拒絕該請求。 範例將 LOCALAPPDATA、TEMP 和 TMP 指向已授權的輸出目錄,使得暫存及每位使用者檔案仍保留在政策範圍內。

替換 Program.cs 為:

using Microsoft.Mxc.Sdk.V1;

if (!OperatingSystem.IsWindows())
{
    Console.Error.WriteLine("This example requires Windows.");
    return 1;
}

try
{
    var support = MxcPlatform.GetPlatformSupport();
    if (!support.IsSupported ||
        !support.AvailableMethods.Contains(ContainmentBackend.ProcessContainer))
    {
        Console.Error.WriteLine(support.Reason ?? "Windows ProcessContainer is unavailable.");
        return 1;
    }

    string inputDirectory = Path.GetFullPath(@"workspace\input");
    string outputDirectory = Path.GetFullPath(@"workspace\output");
    string outputFile = Path.Combine(outputDirectory, "result.txt");
    string commandInterpreter = Path.Combine(Environment.SystemDirectory, "cmd.exe");

    Directory.CreateDirectory(inputDirectory);
    Directory.CreateDirectory(outputDirectory);
    File.WriteAllText(Path.Combine(inputDirectory, "input.txt"), "Hello from MXC!\n");

    var request = new ContainerRequest(
        $"\"{commandInterpreter}\" /d /c type input.txt > \"{outputFile}\"")
    {
        Containment = new Containment.Process(),
        Filesystem = new FilesystemPolicy
        {
            ReadonlyPaths = { inputDirectory, commandInterpreter },
            ReadwritePaths = { outputDirectory },
        },
        // Omitted network and UI permissions remain denied.
        WorkingDirectory = inputDirectory,
        Environment = new()
        {
            ["SystemRoot"] = Environment.GetFolderPath(Environment.SpecialFolder.Windows),
            ["LOCALAPPDATA"] = outputDirectory,
            ["TEMP"] = outputDirectory,
            ["TMP"] = outputDirectory,
        },
        TimeoutMs = 30_000,
    };

    ExecutionResult result = await MxcContainer.RunAsync(request);
    Console.Write(result.Stdout);
    Console.Error.Write(result.Stderr);
    foreach (string warning in result.Warnings)
    {
        Console.Error.WriteLine(warning);
    }

    if (result.TimedOut)
    {
        Console.Error.WriteLine("The workload exceeded its timeout.");
        return 1;
    }

    Console.WriteLine($"Sandbox exited with code {result.ExitCode}");
    if (result.ExitCode == 0)
    {
        Console.Write(File.ReadAllText(outputFile));
    }
    return result.ExitCode;
}
catch (MxcException ex)
{
    Console.Error.WriteLine(ex);
    if (ex.Remediation is not null)
    {
        Console.Error.WriteLine(ex.Remediation);
    }
    return 1;
}

執行應用程式:

dotnet run

每個版本都會列印:

Sandbox exited with code 0
Hello from MXC!

你也可以檢查 workspace\output\result.txt。

3. 驗證被拒絕的操作

只更改輸出檔案宣告,使指令嘗試寫入唯讀輸入目錄:

string outputFile = Path.Combine(inputDirectory, "blocked.txt");

在不更改政策的情況下,重新執行應用程式。 預期會出現存取被拒絕錯誤和非零的退出碼,且沒有新的 workspace\input\blocked.txt 檔案。 還原原始輸出檔案宣告,並確認允許的操作仍可成功執行。

若獲准執行失敗,應將主機設定或組態錯誤與資源遭拒區分開來。 使用 學習模式 來探討前者;不要自動擴大原則範圍。

4. 修改此範例

將 sample 指令和輸入替換成可信的代表性工作負載。 檢視所需的工具二進位檔、函式庫、暫存檔和輸出。 只有在任務需要時,才授予網路或使用者介面存取權限,且所選後端能強制執行預期的限制。

測試每個目標主機上允許與拒絕的操作。 當你使用學習模式來精煉政策時,請檢視每一項觀察,最後執行一次未啟用學習或審核設定的強制模式執行。

可選:使用程式設計代理

給你的代理程式提供目標平台、SDK 語言與版本、指令、所需資源、生命週期及隔離目標。 你可以改編這個提示:

Use the MXC Learn quickstart and the documentation for my installed SDK release.
Integrate this workload through the .NET, TypeScript, or Rust SDK used by this project.

First identify the command, target platforms, input and output paths, network
and UI requirements, and whether state must persist between commands.
Explain the containment choice and create the narrowest policy that fits.
Run both permitted and denied cases and report the effective permissions.

Do not execute the workload outside MXC to get around a failure. Ask for my
approval before expanding access, changing host settings, or using permissive
Learning Mode. Treat observed resource access as evidence, not automatic grants.

檢視代理人的假設及後續原則。 代理可以協助整合,但必須由受信任的主機程式碼或人員核准工作負載權限的變更。

下一步