Skip to content

Commit 4e605bb

Browse files
Allow overriding the API token with DEV_PROXY_API_TOKEN (#2010)
* Allow overriding the API token with DEV_PROXY_API_TOKEN Lets orchestrators such as the Aspire integration start Dev Proxy with a known API token instead of reading per-process token files. Values are trimmed, must be at least 32 characters, and must be valid Bearer token characters; invalid values stop startup with a clear error. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Validate DEV_PROXY_API_TOKEN at proxy start after env overrides - Restore CRLF line endings in Program.cs and DevProxyCommand.cs - Resolve and validate the token in the root command after config env and --env overrides are applied, logging a clean error and exiting with 1 - Limit the early check to the detached parent, honoring its --env value and skipping help, version, and subcommands - Don't check the token for stdio Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Gate detached token preflight on help/version only The detached path is only reached for the root command, so the hard-coded subcommand list isn't needed and would miss plugin commands. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Exclude = padding from API token minimum and drop detached preflight Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 7e82379 commit 4e605bb

4 files changed

Lines changed: 177 additions & 3 deletions

File tree

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using Xunit;
6+
7+
namespace DevProxy.Tests;
8+
9+
public class ApiSecurityTokenTests
10+
{
11+
[Theory]
12+
[InlineData(null)]
13+
[InlineData("")]
14+
[InlineData(" ")]
15+
public void TryResolveToken_NoOverride_GeneratesRandomToken(string? value)
16+
{
17+
Assert.True(ApiSecurity.TryResolveToken(value, out var first, out var error));
18+
Assert.Null(error);
19+
Assert.Equal(64, first.Length);
20+
Assert.True(first.All(Uri.IsHexDigit));
21+
22+
Assert.True(ApiSecurity.TryResolveToken(value, out var second, out _));
23+
Assert.NotEqual(first, second);
24+
}
25+
26+
[Fact]
27+
public void TryResolveToken_ValidOverride_UsesValue()
28+
{
29+
var value = Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32));
30+
31+
Assert.True(ApiSecurity.TryResolveToken(value, out var token, out var error));
32+
Assert.Null(error);
33+
Assert.Equal(value, token);
34+
}
35+
36+
[Fact]
37+
public void TryResolveToken_OverrideWithSurroundingWhitespace_IsTrimmed()
38+
{
39+
var value = new string('a', 32);
40+
41+
Assert.True(ApiSecurity.TryResolveToken($" {value}\n", out var token, out _));
42+
Assert.Equal(value, token);
43+
}
44+
45+
[Theory]
46+
[InlineData("abcdefghijklmnopqrstuvwxyz-._~+/0123==")]
47+
[InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ012345")]
48+
public void TryResolveToken_Base64TokenCharacters_Accepted(string value)
49+
{
50+
Assert.True(ApiSecurity.TryResolveToken(value, out var token, out _));
51+
Assert.Equal(value, token);
52+
}
53+
54+
[Theory]
55+
[InlineData("short")]
56+
[InlineData("0123456789abcdef0123456789abcde")]
57+
public void TryResolveToken_TooShort_Fails(string value)
58+
{
59+
Assert.False(ApiSecurity.TryResolveToken(value, out _, out var error));
60+
Assert.Contains(ApiSecurity.TokenEnvironmentVariable, error, StringComparison.Ordinal);
61+
Assert.Contains("32", error, StringComparison.Ordinal);
62+
}
63+
64+
[Theory]
65+
[InlineData("0123456789abcdef 0123456789abcdef")]
66+
[InlineData("0123456789abcdef0123456789abcdef\u00e9")]
67+
[InlineData("0123456789abcdef0123456789abcdef;")]
68+
[InlineData("0123456789abcdef=0123456789abcdef")]
69+
public void TryResolveToken_InvalidCharacters_Fails(string value)
70+
{
71+
Assert.False(ApiSecurity.TryResolveToken(value, out _, out var error));
72+
Assert.Contains(ApiSecurity.TokenEnvironmentVariable, error, StringComparison.Ordinal);
73+
}
74+
75+
[Theory]
76+
[InlineData("================================")]
77+
[InlineData("a===============================")]
78+
public void TryResolveToken_PaddingNotCountedTowardMinimum_Fails(string value)
79+
{
80+
Assert.False(ApiSecurity.TryResolveToken(value, out _, out var error));
81+
Assert.Contains("padding", error, StringComparison.Ordinal);
82+
}
83+
84+
[Fact]
85+
public void TryResolveToken_MinimumLengthWithPadding_Accepted()
86+
{
87+
var value = new string('a', 32) + "==";
88+
89+
Assert.True(ApiSecurity.TryResolveToken(value, out var token, out _));
90+
Assert.Equal(value, token);
91+
}
92+
}

‎DevProxy/ApiSecurity.cs‎

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,83 @@ namespace DevProxy;
77

88
internal static class ApiSecurity
99
{
10-
private static readonly string Token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
11-
private static readonly byte[] TokenBytes = Encoding.UTF8.GetBytes(Token);
10+
internal const string TokenEnvironmentVariable = "DEV_PROXY_API_TOKEN";
11+
internal const int MinimumTokenLength = 32;
12+
13+
private static readonly Lock TokenLock = new();
14+
private static string? _token;
15+
private static byte[]? _tokenBytes;
16+
private static string Token => EnsureToken().Token;
17+
private static byte[] TokenBytes => EnsureToken().TokenBytes;
1218
private static bool _tokenDisplayed;
1319

20+
/// <summary>
21+
/// Resolves the API token from the value of <c>DEV_PROXY_API_TOKEN</c>.
22+
/// When the value is null or whitespace, a random token is generated.
23+
/// </summary>
24+
internal static bool TryResolveToken(string? environmentValue, out string token, out string? error)
25+
{
26+
error = null;
27+
if (string.IsNullOrWhiteSpace(environmentValue))
28+
{
29+
token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
30+
return true;
31+
}
32+
33+
token = environmentValue.Trim();
34+
if (token.TrimEnd('=').Length < MinimumTokenLength)
35+
{
36+
error = $"{TokenEnvironmentVariable} must be at least {MinimumTokenLength} characters long, not counting trailing = padding.";
37+
return false;
38+
}
39+
40+
// RFC 6750 b64token characters, so the value can be sent as a Bearer credential
41+
if (!token.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '.' or '_' or '~' or '+' or '/' or '=') ||
42+
token.TrimEnd('=').Contains('=', StringComparison.Ordinal))
43+
{
44+
error = $"{TokenEnvironmentVariable} may contain only ASCII letters, digits, and the characters - . _ ~ + / (optionally followed by trailing = padding).";
45+
return false;
46+
}
47+
48+
return true;
49+
}
50+
51+
/// <summary>
52+
/// Resolves the API token from the current (effective) value of <c>DEV_PROXY_API_TOKEN</c>.
53+
/// Call after environment overrides are applied. Once resolved, the token is kept for the
54+
/// lifetime of the process, so it survives configuration reloads.
55+
/// </summary>
56+
public static bool TryInitializeToken(out string? error)
57+
{
58+
lock (TokenLock)
59+
{
60+
error = null;
61+
if (_token is not null)
62+
{
63+
return true;
64+
}
65+
66+
if (!TryResolveToken(Environment.GetEnvironmentVariable(TokenEnvironmentVariable), out var token, out error))
67+
{
68+
return false;
69+
}
70+
71+
_tokenBytes = Encoding.UTF8.GetBytes(token);
72+
_token = token;
73+
return true;
74+
}
75+
}
76+
77+
private static (string Token, byte[] TokenBytes) EnsureToken()
78+
{
79+
if (!TryInitializeToken(out var error))
80+
{
81+
throw new InvalidOperationException(error);
82+
}
83+
84+
return (_token!, _tokenBytes!);
85+
}
86+
1487
public static bool ShouldDisplayToken => Environment.GetEnvironmentVariable("CI") is null;
1588
public static string? DisplayToken => ShouldDisplayToken ? Token : null;
1689

‎DevProxy/Commands/DevProxyCommand.cs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ public DevProxyCommand(
239239
IServiceProvider serviceProvider,
240240
UpdateNotification updateNotification,
241241
DevProxyConfigOptions options,
242-
ILogger<DevProxyCommand> logger) : base($"Start Dev Proxy\n\nAPI:\n Dev Proxy exposes an authenticated REST API for runtime management.\n Use --api-port (default: {proxyConfiguration.ApiPort}) and --api-ip-address (default: 127.0.0.1).\n The API bind address is independent of --ip-address.\n Run 'devproxy status' for the API URL and token, or 'devproxy api show' for endpoints.")
242+
ILogger<DevProxyCommand> logger) : base($"Start Dev Proxy\n\nAPI:\n Dev Proxy exposes an authenticated REST API for runtime management.\n Use --api-port (default: {proxyConfiguration.ApiPort}) and --api-ip-address (default: 127.0.0.1).\n The API bind address is independent of --ip-address.\n Run 'devproxy status' for the API URL and token, or 'devproxy api show' for endpoints.\n Set the DEV_PROXY_API_TOKEN environment variable (at least 32 characters) to use a fixed API token instead of a generated one.")
243243
{
244244
_serviceProvider = serviceProvider;
245245
_plugins = plugins;
@@ -284,6 +284,13 @@ private async Task<int> InvokeAsync(ParseResult parseResult, CancellationToken c
284284
{
285285
throw new InvalidOperationException("WebApplication instance is not set. Please provide it when invoking the command.");
286286
}
287+
// Environment overrides from config and --env are applied by now, so this
288+
// validates and pins the effective token before anything reads it.
289+
if (!ApiSecurity.TryInitializeToken(out var tokenError))
290+
{
291+
_logger.LogError("{TokenError}", tokenError);
292+
return 1;
293+
}
287294
if (!_plugins.Any())
288295
{
289296
_logger.LogError("You haven't configured any plugins. Please add plugins to your configuration file. Dev Proxy will exit.");

‎skills/dev-proxy/references/configuration.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,8 @@ Plugin-specific override:
144144

145145
Every API request requires `Authorization: Bearer <token>`. Startup and `devproxy status` show the per-process token in text and JSON, including redirected output and daemon logs. Tokens survive configuration reloads but change on process restart.
146146

147+
To use a known token, for example when an orchestrator starts Dev Proxy and calls its API, set the `DEV_PROXY_API_TOKEN` environment variable before starting the proxy, or pass it with `--env` or the config `env` section. The value must be at least 32 characters, not counting trailing `=` padding, and use only ASCII letters, digits, `-`, `.`, `_`, `~`, `+`, `/`, and trailing `=`; surrounding whitespace is trimmed. Invalid values stop startup with an error. The token is still saved for `devproxy status`, `devproxy api token`, and `devproxy stop`.
148+
147149
When the `CI` environment variable is set, automatic token output is suppressed. Explicit retrieval remains available:
148150

149151
```bash

0 commit comments

Comments
 (0)