diff --git a/CHANGELOG.md b/CHANGELOG.md index ed29152..1572790 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,13 @@ All notable changes to this project are documented here. The format is based on ### Added +- `--bearer-env ` and `--header-env 'Name: VAR'` on the CLI: HTTP authentication read from environment variables, so tokens are not on the command line. Later sources win for the same header name (`--header`, then `--header-env`, then `--bearer-env`). A missing or empty variable is exit 2 and names the variable, not the value. GitHub Action inputs `bearer-env` and `header-env`, and Azure Pipelines parameters `bearerEnv` and `headerEnv`, pass the variable names through. They need a CLI that has these flags. - `McpProbeHostOptions.IncludeServerExceptions` (default `true`): in the in-memory host, when a tool throws an exception that is not an `McpException`, the tool error result shows the exception type and message (for example `An error occurred invoking 'update_todo_item': FormatException: ...`) instead of the SDK's generic message, `An error occurred invoking 'update_todo_item'.` Prompts and resources that throw are reported the same way. Set it to `false` for the generic text a remote client would see. - `ToolSurfaceChange.Before` and `After` hold the previous and current title or description when that is what changed. Other change kinds leave them unset. ### Changed +- A 401 now says `The credentials were rejected.` (it used to say `The credentials in --header were rejected.`), and the hint for a missing token also mentions `--bearer-env`. - Title and description changes in a tool-surface diff now include a short before and after (truncated and escaped), in the CLI, the HTML report, and snapshot check messages. - Package tags now include `mcp-server`, `dotnet` and `csharp`. The README opening line describes McpProbe as a .NET test kit for C# MCP server testing. - The README GitHub Action section now has an inputs and outputs table, a warning not to log `header` or `env`, and pinning guidance (exact tags only; no `@main` or floating major tag until 1.0). diff --git a/README.md b/README.md index 1fd31da..ecb3029 100644 --- a/README.md +++ b/README.md @@ -212,10 +212,12 @@ dotnet tool install --global McpProbe.Cli --version 0.5.0-preview mcpprobe snapshot --stdio "dotnet run --project src/MyServer" --out mcp-tools.json mcpprobe diff --stdio "dotnet run --project src/MyServer" --baseline mcp-tools.json -mcpprobe lint --http https://localhost:5001/mcp --header "Authorization: Bearer $TOKEN" -mcpprobe lint --http http://localhost:5000/sse --transport sse --header "Authorization: Bearer $TOKEN" +mcpprobe lint --http https://localhost:5001/mcp --bearer-env MCP_TOKEN +mcpprobe lint --http http://localhost:5000/sse --transport sse --bearer-env MCP_TOKEN ``` +For authenticated HTTP servers, `--bearer-env ` sends `Authorization: Bearer ` with the value read from the environment variable `VAR`, and `--header-env 'Name: VAR'` does the same for any header. Unlike `--header "Authorization: Bearer $TOKEN"`, the token is not on the command line, so it doesn't end up in shell history or in a log that prints the command. If the same header comes from more than one of these, the order is `--header`, then `--header-env`, then `--bearer-env`, and the last one wins. A missing or empty variable is a usage error (exit `2`) that names the variable, never its value. The variable name is matched the way the operating system does (case-insensitive on Windows). + The `mcpprobe` tool is packed for net8.0 and net10.0 (`RollForward=Major`), so a .NET 8 or .NET 10 runtime must be installed. An SDK is also needed if the `--stdio` command is `dotnet run`. If the apphost errors with "You must install .NET to run this application" even though `dotnet` works, set `DOTNET_ROOT` to that install's root (the directory that contains `dotnet` and the `shared` folder). `--http` already tries Streamable HTTP and falls back to legacy SSE. Use `--transport streamable-http` or `--transport sse` to pin a mode (`auto` is the default). Legacy SSE servers usually listen at `/sse` (and `/message`), not at the Streamable HTTP path. If the server maps MCP at a prefix such as `/mcp` and enables legacy SSE, the C# SDK places those endpoints under the prefix (`/mcp/sse` and `/mcp/message`). There is no WebSocket transport. @@ -282,7 +284,17 @@ jobs: Pass exactly one of `stdio`, `http`, or `from-file`. Both `diff` and `lint` are on by default. The Action fails the step on a breaking change or a lint finding at or above `--fail-on` (default `warning`, or `failOn` from [`mcpprobe.json`](#config-file-and-ignore-rules) when `fail-on` is empty). -`header` and `env` often carry tokens. Do not log these values. +`header` and `env` often carry tokens. Do not log these values. To authenticate an HTTP server, pass the **name** of an environment variable in `bearer-env` or `header-env`, and set that variable from a secret. The token never appears in the Action's inputs or in the `mcpprobe` command line: + +```yaml + - name: Check MCP tool surface + uses: ShmueLior/mcpprobe@v0.5.0-preview + with: + http: https://example.test/mcp + bearer-env: MCP_TOKEN + env: + MCP_TOKEN: ${{ secrets.MCP_TOKEN }} +``` #### Inputs @@ -293,6 +305,8 @@ Pass exactly one of `stdio`, `http`, or `from-file`. Both `diff` and `lint` are | `from-file` | empty | Read the current tool surface from a snapshot file instead of a server. | | `baseline` | `mcp-tools.json` | The committed snapshot to compare against (diff only). | | `header` | empty | HTTP headers as 'Name: value', one per line. Only used with http. Do not log these values; they often carry tokens. | +| `bearer-env` | empty | Name of an environment variable that holds a bearer token for the http server. Sends 'Authorization: Bearer '. The input is the variable name, not the token, so the token never appears in the command line. Requires a CLI that has --bearer-env. | +| `header-env` | empty | HTTP headers whose values are read from environment variables, as 'Name: VAR', one per line. Only used with http. Requires a CLI that has --header-env. | | `env` | empty | Environment variables for the stdio server as NAME=value, one per line. | | `cwd` | empty | Working directory for the stdio server. | | `timeout` | `60` | Seconds to wait for the server to start and list its tools. | @@ -323,6 +337,8 @@ None of the inputs is marked required in `action.yml`. The wrapper still needs e | `lint-report` | Path to lint.html if that file was written. Empty otherwise. | | `diff-report` | Path to diff.html if that file was written. Empty otherwise. | +`bearer-env` and `header-env` need a CLI that has `--bearer-env` / `--header-env`. If you set them and the installed tool lacks the flags, the Action fails fast with a message instead of a generic "unrecognized option". + `strict`, `transport`, and `report` are off by default, so an unchanged workflow runs the same commands as before. `strict` is lint-only. `transport` is only used with `http`. `report` is a directory, not a file: the Action writes `lint.html` and/or `diff.html` there (both checks run by default, so a single file path would overwrite one report with the other). The job summary stays the plain-text report. Upload is left to your workflow. `config` is the path of a [`mcpprobe.json`](#config-file-and-ignore-rules) for lint. Leave it empty and lint finds one on its own, starting in the step's working directory (the repository root after `actions/checkout`), so a committed `mcpprobe.json` is used without any input. `config` needs a CLI that has `--config`, which is 0.5.0-preview or later; the Action fails fast with a message if the installed tool lacks it. @@ -372,7 +388,7 @@ steps: baseline: mcp-tools.json ``` -The template needs bash (Git Bash on Windows). It also accepts `strict`, `transport`, `report` (a directory, as in the Action), `config` and `lintBaseline`. Do not add those parameters to a pipeline that pins `refs/tags/v0.3.0-preview`; that tag's template does not have them. `config` and `lintBaseline` need `refs/tags/v0.5.0-preview` or later. Upload is a separate step; the template does not publish an artifact: +The template needs bash (Git Bash on Windows). It also accepts `strict`, `transport`, `report` (a directory, as in the Action), `config`, `lintBaseline`, `bearerEnv` and `headerEnv`. Do not add those parameters to a pipeline that pins `refs/tags/v0.3.0-preview`; that tag's template does not have them. `config` and `lintBaseline` need `refs/tags/v0.5.0-preview` or later. `bearerEnv` and `headerEnv` need a CLI that has `--bearer-env` / `--header-env`. Upload is a separate step; the template does not publish an artifact: ```yaml - task: PublishPipelineArtifact@1 diff --git a/action.yml b/action.yml index 4f6a4cb..33ccd3d 100644 --- a/action.yml +++ b/action.yml @@ -36,6 +36,21 @@ inputs: log these values; they often carry tokens. required: false default: '' + bearer-env: + description: >- + Name of an environment variable that holds a bearer token for the http + server. Sends 'Authorization: Bearer '. The input is the variable + name, not the token, so the token never appears in the command line. + Requires a CLI that has --bearer-env. + required: false + default: '' + header-env: + description: >- + HTTP headers whose values are read from environment variables, as + 'Name: VAR', one per line. Only used with http. Requires a CLI that has + --header-env. + required: false + default: '' env: description: Environment variables for the stdio server as NAME=value, one per line. required: false @@ -151,6 +166,8 @@ runs: MCPPROBE_FROM_FILE: ${{ inputs.from-file }} MCPPROBE_BASELINE: ${{ inputs.baseline }} MCPPROBE_HEADER: ${{ inputs.header }} + MCPPROBE_BEARER_ENV: ${{ inputs.bearer-env }} + MCPPROBE_HEADER_ENV: ${{ inputs.header-env }} MCPPROBE_ENV: ${{ inputs.env }} MCPPROBE_CWD: ${{ inputs.cwd }} MCPPROBE_TIMEOUT: ${{ inputs.timeout }} diff --git a/action/run.sh b/action/run.sh index 5e2a652..35805b7 100755 --- a/action/run.sh +++ b/action/run.sh @@ -275,6 +275,14 @@ config_path=$(trim_ws "${MCPPROBE_CONFIG:-}") if [[ -n "$config_path" && "$run_lint" == true ]]; then require_cli_flag config --config fi +bearer_env=$(trim_ws "${MCPPROBE_BEARER_ENV:-}") +if [[ -n "${MCPPROBE_HEADER_ENV:-}" ]]; then + require_cli_flag header-env --header-env +fi +if [[ -n "$bearer_env" ]]; then + require_cli_flag bearer-env --bearer-env +fi + lint_baseline=$(trim_ws "${MCPPROBE_LINT_BASELINE:-}") if [[ -n "$lint_baseline" && "$run_lint" == true ]]; then require_cli_flag lint-baseline --baseline @@ -297,6 +305,10 @@ fi while IFS= read -r line; do common_args+=(--header "$line") done < <(each_nonempty_line "${MCPPROBE_HEADER:-}") +while IFS= read -r line; do + common_args+=(--header-env "$line") +done < <(each_nonempty_line "${MCPPROBE_HEADER_ENV:-}") +[[ -n "$bearer_env" ]] && common_args+=(--bearer-env "$bearer_env") while IFS= read -r line; do common_args+=(--env "$line") done < <(each_nonempty_line "${MCPPROBE_ENV:-}") diff --git a/src/McpProbe.Cli/ConnectError.cs b/src/McpProbe.Cli/ConnectError.cs index 0b40b26..ba63b1e 100644 --- a/src/McpProbe.Cli/ConnectError.cs +++ b/src/McpProbe.Cli/ConnectError.cs @@ -24,8 +24,8 @@ public static string Describe(HttpRequestException ex, Uri endpoint, HttpTranspo { var challenge = string.IsNullOrWhiteSpace(wwwAuthenticate) ? "" : $" (WWW-Authenticate: {Printable.Text(wwwAuthenticate)})"; return sentAuthorization - ? $"401 Unauthorized from {url}. The credentials in --header were rejected{challenge}." - : $"401 Unauthorized from {url}. The server wants authentication{challenge}. Pass --header 'Authorization: Bearer '."; + ? $"401 Unauthorized from {url}. The credentials were rejected{challenge}." + : $"401 Unauthorized from {url}. The server wants authentication{challenge}. Pass --header 'Authorization: Bearer ', or --bearer-env to read the token from an environment variable."; } if (status is HttpStatusCode.BadRequest or HttpStatusCode.NotFound or HttpStatusCode.MethodNotAllowed) diff --git a/src/McpProbe.Cli/ServerOptions.cs b/src/McpProbe.Cli/ServerOptions.cs index 5327741..66e9a31 100644 --- a/src/McpProbe.Cli/ServerOptions.cs +++ b/src/McpProbe.Cli/ServerOptions.cs @@ -29,6 +29,17 @@ internal sealed class ServerOptions AllowMultipleArgumentsPerToken = false, }; + private readonly Option _headerEnv = new("--header-env") + { + Description = "HTTP header whose value is read from an environment variable, as 'Name: VAR'. Repeatable. Only with --http. The value is never printed.", + AllowMultipleArgumentsPerToken = false, + }; + + private readonly Option _bearerEnv = new("--bearer-env") + { + Description = "Name of an environment variable that holds a bearer token. Sends 'Authorization: Bearer '. Only with --http. The value is never printed.", + }; + private readonly Option _env = new("--env") { Description = "Environment variable for the stdio server as NAME=value. Repeatable. Only with --stdio.", @@ -65,6 +76,8 @@ public void AddTo(Command command) command.Options.Add(_http); command.Options.Add(_transport); command.Options.Add(_headers); + command.Options.Add(_headerEnv); + command.Options.Add(_bearerEnv); command.Options.Add(_env); command.Options.Add(_cwd); command.Options.Add(_timeout); @@ -102,6 +115,13 @@ public void AddTo(Command command) result.AddError("--transport must be auto, streamable-http, or sse."); } } + + var hasHeaderEnv = result.GetResult(_headerEnv) is { Implicit: false }; + var hasBearerEnv = result.GetResult(_bearerEnv) is { Implicit: false }; + if ((hasHeaderEnv || hasBearerEnv) && result.GetResult(_http) is null) + { + result.AddError("--header-env and --bearer-env can only be used with --http."); + } }); } @@ -127,7 +147,7 @@ public async Task CaptureAsync(ParseResult parse, TextWriter stderr var target = new ServerTarget( parse.GetValue(_stdio), parse.GetValue(_http) is { } url ? ParseHttpUrl(url) : null, - ParsePairs(parse.GetValue(_headers), ':', "--header", "Name: value"), + BuildHttpHeaders(parse), ParsePairs(parse.GetValue(_env), '=', "--env", "NAME=value").ToDictionary(p => p.Key, p => (string?)p.Value, StringComparer.Ordinal), parse.GetValue(_cwd), ParseTransportMode(parse.GetValue(_transport)) ?? HttpTransportMode.AutoDetect, @@ -188,6 +208,75 @@ public async Task CaptureAsync(ParseResult parse, TextWriter stderr _ => null, }; + /// + /// Builds the HTTP headers from --header, then --header-env, then --bearer-env. Later sources win + /// for the same header name (compared case-insensitively). Environment-backed values are read here and never printed. + /// + private Dictionary BuildHttpHeaders(ParseResult parse) + { + var headers = ParsePairs(parse.GetValue(_headers), ':', "--header", "Name: value"); + var headerEnv = parse.GetValue(_headerEnv) ?? []; + var bearerEnv = parse.GetValue(_bearerEnv); + + if ((headerEnv.Length > 0 || bearerEnv is not null) && parse.GetResult(_http) is null) + { + throw new ArgumentException("--header-env and --bearer-env can only be used with --http."); + } + + foreach (var pair in headerEnv) + { + var index = pair.IndexOf(':', StringComparison.Ordinal); + if (index <= 0) + { + throw new ArgumentException($"Invalid --header-env '{pair}'. Use 'Name: VAR', where VAR is the name of an environment variable."); + } + + var name = pair[..index].Trim(); + var variable = pair[(index + 1)..].Trim(); + if (name.Length == 0) + { + throw new ArgumentException($"Invalid --header-env '{pair}'. Use 'Name: VAR', where VAR is the name of an environment variable."); + } + + SetHeader(headers, name, ReadVariable(variable, "--header-env")); + } + + if (bearerEnv is not null) + { + var token = ReadVariable(bearerEnv.Trim(), "--bearer-env"); + var value = token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) ? token : "Bearer " + token; + SetHeader(headers, "Authorization", value); + } + + return headers; + } + + private static string ReadVariable(string variable, string option) + { + if (variable.Length == 0 || variable.Any(c => char.IsWhiteSpace(c) || c is '=' or ':')) + { + throw new ArgumentException($"Invalid environment variable name '{variable}' for {option}."); + } + + var value = Environment.GetEnvironmentVariable(variable); + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException($"Environment variable '{variable}' for {option} is not set or is empty."); + } + + return value.Trim(); + } + + private static void SetHeader(Dictionary headers, string name, string value) + { + foreach (var existing in headers.Keys.Where(k => string.Equals(k, name, StringComparison.OrdinalIgnoreCase)).ToList()) + { + headers.Remove(existing); + } + + headers[name] = value; + } + private static Dictionary ParsePairs(string[]? values, char separator, string option, string format) { var result = new Dictionary(StringComparer.Ordinal); diff --git a/templates/azure-pipelines/mcpprobe.yml b/templates/azure-pipelines/mcpprobe.yml index 5c75f90..a3cce9f 100644 --- a/templates/azure-pipelines/mcpprobe.yml +++ b/templates/azure-pipelines/mcpprobe.yml @@ -36,6 +36,12 @@ parameters: - name: header type: string default: '' +- name: bearerEnv + type: string + default: '' +- name: headerEnv + type: string + default: '' - name: env type: string default: '' @@ -124,6 +130,8 @@ steps: MCPPROBE_FROM_FILE: ${{ parameters.fromFile }} MCPPROBE_BASELINE: ${{ parameters.baseline }} MCPPROBE_HEADER: ${{ parameters.header }} + MCPPROBE_BEARER_ENV: ${{ parameters.bearerEnv }} + MCPPROBE_HEADER_ENV: ${{ parameters.headerEnv }} MCPPROBE_ENV: ${{ parameters.env }} MCPPROBE_CWD: ${{ parameters.cwd }} MCPPROBE_TIMEOUT: ${{ parameters.timeout }} diff --git a/tests/McpProbe.Tests/CliAuthEnvTests.cs b/tests/McpProbe.Tests/CliAuthEnvTests.cs new file mode 100644 index 0000000..1c19814 --- /dev/null +++ b/tests/McpProbe.Tests/CliAuthEnvTests.cs @@ -0,0 +1,310 @@ +using System.Collections.Concurrent; +using McpProbe.Cli; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using WeatherServer; + +namespace McpProbe.Tests; + +public sealed class CliAuthEnvTests : IDisposable +{ + private readonly List _variables = []; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + public void Dispose() + { + foreach (var name in _variables) + { + Environment.SetEnvironmentVariable(name, null); + } + } + + private string SetVariable(string value) + { + var name = "MCPPROBE_TEST_AUTH_" + Guid.NewGuid().ToString("N"); + Environment.SetEnvironmentVariable(name, value); + _variables.Add(name); + return name; + } + + private string UnusedVariable() + { + var name = "MCPPROBE_TEST_AUTH_" + Guid.NewGuid().ToString("N"); + _variables.Add(name); + return name; + } + + private static async Task<(int Exit, string Out, string Err)> RunAsync(params string[] args) + { + using var stdout = new StringWriter(); + using var stderr = new StringWriter(); + var exit = await CliApp.RunAsync(args, stdout, stderr, Ct); + return (exit, stdout.ToString(), stderr.ToString()); + } + + [Fact] + public async Task BearerEnv_SendsTheTokenFromTheEnvironment() + { + await using var server = await AuthServer.StartAsync(); + var variable = SetVariable("SECRETTOKEN_BEARER_1"); + + var (exit, output, error) = await RunAsync("lint", "--http", server.Url, "--bearer-env", variable, "--timeout", "20"); + + Assert.True(exit == 0, error); + Assert.Contains("No lint findings.", output, StringComparison.Ordinal); + Assert.Contains("Bearer SECRETTOKEN_BEARER_1", server.SeenAuthorization); + Assert.DoesNotContain("SECRETTOKEN_BEARER_1", output, StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_BEARER_1", error, StringComparison.Ordinal); + } + + [Fact] + public async Task BearerEnv_DoesNotDoubleTheBearerPrefix() + { + await using var server = await AuthServer.StartAsync(); + var variable = SetVariable("bearer SECRETTOKEN_BEARER_2"); + + var (exit, _, error) = await RunAsync("lint", "--http", server.Url, "--bearer-env", variable, "--timeout", "20"); + + Assert.True(exit == 0, error); + Assert.Contains("bearer SECRETTOKEN_BEARER_2", server.SeenAuthorization); + Assert.DoesNotContain("Bearer bearer", string.Join("|", server.SeenAuthorization), StringComparison.Ordinal); + } + + [Fact] + public async Task HeaderEnv_SendsANamedHeaderFromTheEnvironment() + { + await using var server = await AuthServer.StartAsync(); + var variable = SetVariable("SECRETTOKEN_KEY_3"); + + var (exit, output, error) = await RunAsync("lint", "--http", server.Url, "--header-env", $"X-Api-Key: {variable}", "--timeout", "20"); + + Assert.True(exit == 0, error); + Assert.Contains("SECRETTOKEN_KEY_3", server.SeenApiKeys); + Assert.DoesNotContain("SECRETTOKEN_KEY_3", output, StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_KEY_3", error, StringComparison.Ordinal); + } + + [Fact] + public async Task BearerEnv_MissingVariable_IsAUsageErrorThatNamesTheVariable() + { + var variable = UnusedVariable(); + SetVariable("SECRETTOKEN_OTHER_VAR_6"); + + var (exit, output, error) = await RunAsync("lint", "--http", "http://127.0.0.1:1/mcp", "--bearer-env", variable); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Contains($"Environment variable '{variable}' for --bearer-env is not set or is empty.", error, StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_OTHER_VAR_6", error, StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_OTHER_VAR_6", output, StringComparison.Ordinal); + Assert.Equal("", output); + } + + [Fact] + public async Task HeaderEnv_EmptyVariable_IsAUsageError() + { + var variable = SetVariable(" "); + + var (exit, output, error) = await RunAsync("lint", "--http", "http://127.0.0.1:1/mcp", "--header-env", $"X-Api-Key: {variable}"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Contains($"Environment variable '{variable}' for --header-env is not set or is empty.", error, StringComparison.Ordinal); + Assert.Equal("", output); + } + + [Theory] + [InlineData("lint", "--stdio", "x")] + [InlineData("lint", "--from-file", "x.json")] + public async Task EnvAuthFlags_WithoutHttp_AreAUsageError(string command, string source, string value) + { + var variable = SetVariable("SECRETTOKEN_NOHTTP"); + + var (exit, _, error) = await RunAsync(command, source, value, "--bearer-env", variable); + Assert.Equal(ExitCodes.Error, exit); + Assert.Contains("--header-env and --bearer-env can only be used with --http.", error, StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_NOHTTP", error, StringComparison.Ordinal); + + (exit, _, error) = await RunAsync(command, source, value, "--header-env", $"X-Api-Key: {variable}"); + Assert.Equal(ExitCodes.Error, exit); + Assert.Contains("--header-env and --bearer-env can only be used with --http.", error, StringComparison.Ordinal); + } + + [Theory] + [InlineData("XApiKey")] + [InlineData(": VAR")] + [InlineData("X-Api-Key:")] + public async Task HeaderEnv_InvalidFormat_IsAUsageError(string value) + { + var (exit, _, error) = await RunAsync("lint", "--http", "http://127.0.0.1:1/mcp", "--header-env", value); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Contains("--header-env", error, StringComparison.Ordinal); + } + + [Fact] + public async Task BearerEnv_InvalidVariableName_IsAUsageError() + { + var (exit, _, error) = await RunAsync("lint", "--http", "http://127.0.0.1:1/mcp", "--bearer-env", "BAD=NAME"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Contains("Invalid environment variable name 'BAD=NAME' for --bearer-env.", error, StringComparison.Ordinal); + } + + [Fact] + public async Task EnvBackedHeaders_OverrideATypedHeaderWithTheSameName() + { + await using var server = await AuthServer.StartAsync(); + var variable = SetVariable("SECRETTOKEN_WINS_4"); + + var (exit, _, error) = await RunAsync( + "lint", "--http", server.Url, "--header", "Authorization: Bearer typed-loses", "--bearer-env", variable, "--timeout", "20"); + + Assert.True(exit == 0, error); + Assert.Contains("Bearer SECRETTOKEN_WINS_4", server.SeenAuthorization); + Assert.DoesNotContain("typed-loses", string.Join("|", server.SeenAuthorization), StringComparison.Ordinal); + } + + [Fact] + public async Task HeaderEnv_OverridesATypedHeaderWithTheSameName() + { + await using var server = await AuthServer.StartAsync(); + var variable = SetVariable("SECRETTOKEN_HEADERENV_WINS_9"); + + var (exit, output, error) = await RunAsync( + "lint", "--http", server.Url, "--header", "X-Api-Key: typed-loses", "--header-env", $"X-Api-Key: {variable}", "--timeout", "20"); + + Assert.True(exit == 0, error); + Assert.Contains("SECRETTOKEN_HEADERENV_WINS_9", server.SeenApiKeys); + Assert.DoesNotContain("typed-loses", string.Join("|", server.SeenApiKeys), StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_HEADERENV_WINS_9", output, StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_HEADERENV_WINS_9", error, StringComparison.Ordinal); + } + + [Fact] + public async Task BearerEnv_WinsOverHeaderEnvForAuthorization() + { + await using var server = await AuthServer.StartAsync(); + var headerVariable = SetVariable("Bearer SECRETTOKEN_HEADERENV_LOSES"); + var bearerVariable = SetVariable("SECRETTOKEN_BEARER_WINS_5"); + + var (exit, _, error) = await RunAsync( + "lint", "--http", server.Url, "--header-env", $"Authorization: {headerVariable}", "--bearer-env", bearerVariable, "--timeout", "20"); + + Assert.True(exit == 0, error); + Assert.Contains("Bearer SECRETTOKEN_BEARER_WINS_5", server.SeenAuthorization); + Assert.DoesNotContain("SECRETTOKEN_HEADERENV_LOSES", string.Join("|", server.SeenAuthorization), StringComparison.Ordinal); + } + + [Fact] + public async Task Unauthorized_WithBearerEnv_SaysTheCredentialsWereRejectedAndDoesNotPrintTheToken() + { + await using var stub = await StartRejectingStubAsync(); + var variable = SetVariable("SECRETTOKEN_WRONG_7"); + + var (exit, output, error) = await RunAsync("lint", "--http", stub.Url, "--bearer-env", variable, "--timeout", "20"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Contains("401 Unauthorized", error, StringComparison.Ordinal); + Assert.Contains("The credentials were rejected.", error, StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_WRONG_7", error, StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_WRONG_7", output, StringComparison.Ordinal); + } + + [Fact] + public async Task Unauthorized_WithHeaderEnv_SaysTheCredentialsWereRejectedAndDoesNotPrintTheToken() + { + await using var stub = await StartRejectingStubAsync(); + var variable = SetVariable("SECRETTOKEN_WRONG_8"); + + var (exit, output, error) = await RunAsync("lint", "--http", stub.Url, "--header-env", $"Authorization: {variable}", "--timeout", "20"); + + Assert.Equal(ExitCodes.Error, exit); + Assert.Contains("The credentials were rejected.", error, StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_WRONG_8", error, StringComparison.Ordinal); + Assert.DoesNotContain("SECRETTOKEN_WRONG_8", output, StringComparison.Ordinal); + } + + private static async Task StartRejectingStubAsync() + { + var builder = WebApplication.CreateSlimBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + var app = builder.Build(); + app.MapFallback(new RequestDelegate(context => + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + return Task.CompletedTask; + })); + await app.StartAsync(Ct); + return new Stub(app, app.Services.GetRequiredService().Features.Get()!.Addresses.Single() + "/mcp"); + } + + private sealed class Stub(WebApplication app, string url) : IAsyncDisposable + { + public string Url { get; } = url; + + public ValueTask DisposeAsync() => app.DisposeAsync(); + } + + private sealed class AuthServer : IAsyncDisposable + { + private readonly WebApplication _app; + + private AuthServer(WebApplication app, string url) + { + _app = app; + Url = url; + } + + public string Url { get; } + + public ConcurrentBag SeenAuthorization { get; } = []; + + public ConcurrentBag SeenApiKeys { get; } = []; + + public static async Task StartAsync() + { + var builder = WebApplication.CreateSlimBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + builder.Services.AddMcpServer().WithHttpTransport().WithWeatherFeatures(); + var app = builder.Build(); + AuthServer? server = null; + app.Use(async (context, next) => + { + var authorization = context.Request.Headers.Authorization.ToString(); + var apiKey = context.Request.Headers["X-Api-Key"].ToString(); + if (authorization.Length > 0) + { + server!.SeenAuthorization.Add(authorization); + } + + if (apiKey.Length > 0) + { + server!.SeenApiKeys.Add(apiKey); + } + + var authorized = authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) || apiKey.Length > 0; + if (!authorized) + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + return; + } + + await next(context); + }); + app.MapMcp("/mcp"); + await app.StartAsync(Ct); + var address = app.Services.GetRequiredService().Features.Get()!.Addresses.Single(); + server = new AuthServer(app, address + "/mcp"); + return server; + } + + public ValueTask DisposeAsync() => _app.DisposeAsync(); + } +} diff --git a/tests/McpProbe.Tests/CliTests.cs b/tests/McpProbe.Tests/CliTests.cs index 43ef131..eb98422 100644 --- a/tests/McpProbe.Tests/CliTests.cs +++ b/tests/McpProbe.Tests/CliTests.cs @@ -657,7 +657,7 @@ public async Task Http_Unauthorized_SaysWhatTheServerWantsAndWhatToPass() Assert.Equal(ExitCodes.Error, exit); Assert.Equal( - $"error: 401 Unauthorized from {stub.Url}. The server wants authentication (WWW-Authenticate: Bearer resource_metadata=\"http://example.test/.well-known/x\"). Pass --header 'Authorization: Bearer '.", + $"error: 401 Unauthorized from {stub.Url}. The server wants authentication (WWW-Authenticate: Bearer resource_metadata=\"http://example.test/.well-known/x\"). Pass --header 'Authorization: Bearer ', or --bearer-env to read the token from an environment variable.", error.TrimEnd()); } @@ -669,7 +669,7 @@ public async Task Http_UnauthorizedWithAuthorizationHeader_SaysTheCredentialsWer var (exit, _, error) = await RunAsync("lint", "--http", stub.Url, "--header", "authorization: Bearer nope", "--timeout", "10"); Assert.Equal(ExitCodes.Error, exit); - Assert.Equal($"error: 401 Unauthorized from {stub.Url}. The credentials in --header were rejected.", error.TrimEnd()); + Assert.Equal($"error: 401 Unauthorized from {stub.Url}. The credentials were rejected.", error.TrimEnd()); Assert.DoesNotContain("nope", error, StringComparison.Ordinal); } diff --git a/tests/McpProbe.Tests/ConnectErrorTests.cs b/tests/McpProbe.Tests/ConnectErrorTests.cs index 51be9ba..5cee3d9 100644 --- a/tests/McpProbe.Tests/ConnectErrorTests.cs +++ b/tests/McpProbe.Tests/ConnectErrorTests.cs @@ -80,6 +80,6 @@ public void Describe_Unauthorized_EscapesTheServersChallenge() [Fact] public void Describe_Unauthorized_WithoutAChallengeLeavesThatPartOut() => Assert.Equal( - "401 Unauthorized from https://example.test/mcp. The server wants authentication. Pass --header 'Authorization: Bearer '.", + "401 Unauthorized from https://example.test/mcp. The server wants authentication. Pass --header 'Authorization: Bearer ', or --bearer-env to read the token from an environment variable.", ConnectError.Describe(Failure(HttpStatusCode.Unauthorized), s_endpoint, HttpTransportMode.AutoDetect, false, " ")); }