Skip to content

Commit 6888332

Browse files
authored
Add General properties to Application Name Telemetry (#3826)
**Suggested title:** Add general settings to application-name telemetry ## Why make this change? Closes #3792. The application-name telemetry format reserved a General section but was initially empty. We populate it with the agreed host and data-source characteristics to improve aggregate usage visibility without collecting identifiers or secrets. ## What is this change? Adds six positional fields using the existing shared encoder/decoder design: | Position | Field | Values | |---|---|---| | 1 | Operating system | Windows, Linux, macOS, Other, Unknown | | 2 | Running in container | No, Yes, Missing | | 3 | Hosting environment | Local, Azure, AWS, GCP, Other, Missing | | 4 | Azure hosting service | Container Apps, AKS, App Service, ACI, Other, Not Azure, Missing | | 5 | Multiple parsed data sources | No, Yes, Missing | | 6 | Managed identity | No, Yes, Missing | The format remains: `<marker><version>+<context>|<general>|<runtime>|<entity>+` - **Preserves compatibility:** fills the reserved section without shifting Runtime or Entity positions. Older empty-General tokens, truncated tokens, hosted markers, and the existing opt-out remain supported. - **Uses offline, conservative detection:** reads OS APIs and known runtime environment signals. `DAB_HOSTING_ENVIRONMENT` and `DAB_AZURE_HOSTING_SERVICE` provide explicit overrides. Detection performs no metadata requests or credential acquisition. - **Reports MI per data source:** inspects the effective connection string, including overrides. The CLI uses the default source. Ambiguous credential chains and mixed OBO/metadata authentication report `M`; `DefaultAzureCredential` availability is not treated as proof of MI use. - **Protects connection behavior:** bounds the SQL telemetry suffix to the available application-name budget while preserving the existing custom name and OBO isolation prefix. PostgreSQL normalization remains server-side. - **Keeps CLI inspection offline:** recursively loads configurations using existing property converters without resolving Key Vault secrets or starting runtime watchers. Adds cycle/depth protection. - Updates the existing design documentation and adds regression coverage for detection, compatibility, authentication, privacy, and provider-specific boundaries. ## How was this tested? - [x] Integration Tests - [x] Unit Tests ## Sample Request(s) Inspect the telemetry for a configuration: ```console dab appname --config dab-config.json ``` Decode an illustrative token: ```console dab appname --decode "dab_oss_1.2.3+XXSX|L1AC01|MMMM00MMM00MMMMMMMMM|MMM?MMMMMMMMM?+" ``` The General section, `L1AC01`, represents **Linux, running in a container, Azure Container Apps, one data source, and explicitly configured managed identity**.
1 parent a9babf9 commit 6888332

11 files changed

Lines changed: 1510 additions & 42 deletions

‎docs/design/application-name-telemetry.md‎

Lines changed: 108 additions & 10 deletions
Large diffs are not rendered by default.

‎src/Cli.Tests/EndToEndTests.cs‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,12 @@ public void TestAppNameEncodeAndDecode()
170170
string telemetry = _fileSystem.File.ReadAllText("appname-out.txt");
171171
Assert.IsTrue(telemetry.StartsWith("dab_oss_"), telemetry);
172172
Assert.IsTrue(telemetry.EndsWith("+"), telemetry);
173+
string[] sections = telemetry[(telemetry.IndexOf('+') + 1)..^1].Split('|');
174+
Assert.AreEqual(4, sections.Length, "General settings must not shift runtime/entity sections.");
175+
Assert.AreEqual("XXXX", sections[0], "The CLI still has no live connection context.");
176+
Assert.AreEqual(6, sections[1].Length, "The CLI should emit all six general flags.");
177+
Assert.AreEqual('0', sections[1][4], "One parsed data source is not multiple data sources.");
178+
Assert.AreEqual('0', sections[1][5], "The default data source uses explicit SQL credentials, not MI.");
173179

174180
// Act: decode the produced string back into a human-readable description.
175181
int decodeCode = Program.Execute(
@@ -180,6 +186,12 @@ public void TestAppNameEncodeAndDecode()
180186
Assert.AreEqual(0, decodeCode, "appname --decode should succeed");
181187
string decoded = _fileSystem.File.ReadAllText("appname-decoded.txt");
182188
Assert.IsTrue(decoded.Contains("Version: dab_oss_"), decoded);
189+
Assert.IsTrue(decoded.Contains("General > operating-system:"), decoded);
190+
Assert.IsTrue(decoded.Contains("General > running-in-container:"), decoded);
191+
Assert.IsTrue(decoded.Contains("General > hosting-environment:"), decoded);
192+
Assert.IsTrue(decoded.Contains("General > azure-hosting-service:"), decoded);
193+
Assert.IsTrue(decoded.Contains("General > multiple-data-sources: 0"), decoded);
194+
Assert.IsTrue(decoded.Contains("General > managed-identity: 0"), decoded);
183195
Assert.IsTrue(decoded.Contains("runtime.rest.enabled"), decoded);
184196
Assert.IsTrue(decoded.Contains("entities.any.table"), decoded);
185197
}
@@ -209,6 +221,126 @@ public void TestAppNameEncodeSupportsAbsolutePaths()
209221
Assert.IsTrue(_fileSystem.File.ReadAllText(outputPath).StartsWith("dab_oss_", StringComparison.Ordinal));
210222
}
211223

224+
/// <summary>Inspection must not require a resolvable connection string or create a Key Vault client.</summary>
225+
[DataTestMethod]
226+
[DataRow("@env('DAB_GENERAL_REVIEW_UNSET_CONNECTION')")]
227+
[DataRow("not a connection string")]
228+
[DataRow("@akv('database-connection')")]
229+
public void TestAppNameReview_InspectsUnresolvedCredentialsOffline(string connectionString)
230+
{
231+
// The invalid URI fails before any network access if the runtime AKV resolver is invoked.
232+
string configJson = $$"""
233+
{
234+
"data-source": { "database-type": "mssql", "connection-string": "{{connectionString}}" },
235+
"azure-key-vault": { "endpoint": "not-a-valid-vault-uri" },
236+
"entities": {}
237+
}
238+
""";
239+
_fileSystem!.File.WriteAllText("appname-review.json", configJson);
240+
241+
int code = Program.Execute(
242+
new[] { "appname", "--config", "appname-review.json", "--output", "appname-review.txt" },
243+
_cliLogger!, _fileSystem, _runtimeConfigLoader!);
244+
245+
Assert.AreEqual(CliReturnCode.SUCCESS, code);
246+
string telemetry = _fileSystem.File.ReadAllText("appname-review.txt");
247+
string[] sections = telemetry[(telemetry.IndexOf('+') + 1)..^1].Split('|');
248+
Assert.AreEqual('M', sections[1][5]);
249+
}
250+
251+
/// <summary>Inspection applies the offline policy recursively and preserves global/runtime semantics.</summary>
252+
[TestMethod]
253+
public void TestAppNameReview_NestedConfigurationsAreOffline()
254+
{
255+
const string root = """
256+
{
257+
"data-source-files": ["appname-child.json", "appname-missing.json"],
258+
"runtime": { "rest": { "enabled": false } },
259+
"entities": {}
260+
}
261+
""";
262+
const string child = """
263+
{
264+
"data-source": { "database-type": "mssql", "connection-string": "@akv('connection')" },
265+
"azure-key-vault": { "endpoint": "not-a-vault-uri" },
266+
"data-source-files": ["appname-grandchild.json"],
267+
"entities": { "Table": { "source": { "object": "table", "type": "table" }, "permissions": [] } }
268+
}
269+
""";
270+
const string grandchild = """
271+
{
272+
"data-source": { "database-type": "postgresql", "connection-string": "@akv('connection')" },
273+
"azure-key-vault": { "endpoint": "not-a-vault-uri" },
274+
"entities": { "View": { "source": { "object": "view", "type": "view" }, "permissions": [] } }
275+
}
276+
""";
277+
_fileSystem!.File.WriteAllText("appname-review.json", root);
278+
_fileSystem.File.WriteAllText("appname-child.json", child);
279+
_fileSystem.File.WriteAllText("appname-grandchild.json", grandchild);
280+
281+
int code = Program.Execute(
282+
new[] { "appname", "--config", "appname-review.json", "--output", "appname-review.txt" },
283+
_cliLogger!, _fileSystem, _runtimeConfigLoader!);
284+
285+
Assert.AreEqual(CliReturnCode.SUCCESS, code);
286+
string telemetry = _fileSystem.File.ReadAllText("appname-review.txt");
287+
string[] sections = telemetry[(telemetry.IndexOf('+') + 1)..^1].Split('|');
288+
Assert.AreEqual('1', sections[1][4], "Two loaded sources, not three file references.");
289+
Assert.AreEqual('M', sections[1][5], "The root has no default connection context.");
290+
Assert.AreEqual('0', sections[2][0], "Use the root runtime, not the child's defaults.");
291+
Assert.AreEqual("11", sections[3][..2], "Both descendants' entities must be counted.");
292+
Assert.IsNull(_runtimeConfigLoader!.RuntimeConfig, "Inspection must not configure or start the runtime loader.");
293+
Assert.AreEqual(root, _fileSystem.File.ReadAllText("appname-review.json"));
294+
Assert.AreEqual(child, _fileSystem.File.ReadAllText("appname-child.json"));
295+
}
296+
297+
/// <summary>Bad/cyclic child configs fail predictably without runaway recursive loading.</summary>
298+
[DataTestMethod]
299+
[DataRow("{ not json }")]
300+
[DataRow("{\"data-source-files\":[\"appname-review.json\"],\"entities\":{}}")]
301+
public void TestAppNameReview_InvalidOrCyclicChildFails(string child)
302+
{
303+
_fileSystem!.File.WriteAllText("appname-review.json", "{\"data-source-files\":[\"appname-child.json\"],\"entities\":{}}");
304+
_fileSystem.File.WriteAllText("appname-child.json", child);
305+
306+
int code = Program.Execute(
307+
new[] { "appname", "--config", "appname-review.json", "--output", "appname-review.txt" },
308+
_cliLogger!, _fileSystem, _runtimeConfigLoader!);
309+
310+
Assert.AreEqual(CliReturnCode.GENERAL_ERROR, code);
311+
Assert.IsFalse(_fileSystem.File.Exists("appname-review.txt"));
312+
}
313+
314+
/// <summary>Local environment substitution remains supported without resolving external secrets.</summary>
315+
[TestMethod]
316+
public void TestAppNameReview_UsesLocalEnvironmentAuthentication()
317+
{
318+
const string variable = "DAB_GENERAL_REVIEW_CONNECTION";
319+
string? original = Environment.GetEnvironmentVariable(variable);
320+
try
321+
{
322+
Environment.SetEnvironmentVariable(variable, "Server=unit-test.invalid;Authentication=Active Directory Managed Identity;");
323+
_fileSystem!.File.WriteAllText("appname-review.json", """
324+
{
325+
"data-source": { "database-type": "mssql", "connection-string": "@env('DAB_GENERAL_REVIEW_CONNECTION')" },
326+
"entities": {}
327+
}
328+
""");
329+
330+
int code = Program.Execute(
331+
new[] { "appname", "--config", "appname-review.json", "--output", "appname-review.txt" },
332+
_cliLogger!, _fileSystem, _runtimeConfigLoader!);
333+
334+
Assert.AreEqual(CliReturnCode.SUCCESS, code);
335+
string telemetry = _fileSystem.File.ReadAllText("appname-review.txt");
336+
Assert.AreEqual('1', telemetry[(telemetry.IndexOf('+') + 1)..^1].Split('|')[1][5]);
337+
}
338+
finally
339+
{
340+
Environment.SetEnvironmentVariable(variable, original);
341+
}
342+
}
343+
212344
/// <summary>
213345
/// The `appname` encode path returns GENERAL_ERROR (and writes no output file) when the config
214346
/// file cannot be found.

‎src/Cli/AppNameConfigLoader.cs‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
using System.Diagnostics.CodeAnalysis;
5+
using System.IO.Abstractions;
6+
using System.Text.Json;
7+
using System.Text.Json.Nodes;
8+
using Azure.DataApiBuilder.Config;
9+
using Azure.DataApiBuilder.Config.Converters;
10+
using Azure.DataApiBuilder.Config.ObjectModel;
11+
using Azure.DataApiBuilder.Service.Exceptions;
12+
13+
namespace Cli;
14+
15+
/// <summary>
16+
/// Reads a configuration for telemetry inspection without starting the runtime, creating watchers,
17+
/// injecting connection strings, or resolving Key Vault secrets. Uses the normal property converters
18+
/// but explicitly owns child-file traversal, because the runtime model's JSON constructor loads
19+
/// children with the runtime's secret-resolution policy.
20+
/// </summary>
21+
internal static class AppNameConfigLoader
22+
{
23+
internal static bool TryLoadConfig(string path, IFileSystem fileSystem, [NotNullWhen(true)] out RuntimeConfig? config)
24+
{
25+
DeserializationVariableReplacementSettings replacements = new(
26+
doReplaceEnvVar: true,
27+
doReplaceAkvVar: false,
28+
envFailureMode: EnvironmentVariableReplacementFailureMode.Ignore)
29+
{
30+
SkipApplicationNameInjection = true,
31+
};
32+
33+
try
34+
{
35+
JsonSerializerOptions options = RuntimeConfigLoader.GetSerializationOptions(replacements);
36+
HashSet<string> ancestors = new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
37+
config = ReadConfig(path, fileSystem, options, ancestors);
38+
return true;
39+
}
40+
catch (Exception ex) when (ex is JsonException or DataApiBuilderException or IOException
41+
or UnauthorizedAccessException or ArgumentException or InvalidOperationException)
42+
{
43+
// Exceptions from deserialization may include credential-bearing values. The command
44+
// reports a generic parse failure instead of exposing those details to the logger.
45+
config = null;
46+
return false;
47+
}
48+
}
49+
50+
private static RuntimeConfig ReadConfig(string path, IFileSystem fileSystem, JsonSerializerOptions options, HashSet<string> ancestors)
51+
{
52+
const int maxConfigDepth = 64;
53+
string fullPath = fileSystem.Path.GetFullPath(path);
54+
if (ancestors.Count >= maxConfigDepth || !ancestors.Add(fullPath))
55+
{
56+
throw new JsonException("Cyclic or excessively nested data-source-files.");
57+
}
58+
59+
try
60+
{
61+
JsonObject document = JsonNode.Parse(
62+
fileSystem.File.ReadAllText(fullPath),
63+
documentOptions: new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }) as JsonObject
64+
?? throw new JsonException("Configuration must be a JSON object.");
65+
66+
DataSourceFiles? files = document["data-source-files"]?.Deserialize<DataSourceFiles>(options);
67+
document.Remove("data-source-files");
68+
RuntimeConfig root = document.Deserialize<RuntimeConfig>(options)
69+
?? throw new JsonException("Configuration is empty.");
70+
71+
// Removing only the child-file property preserves the standard converters/defaults for
72+
// every other property while preventing constructor-driven runtime secret resolution.
73+
List<(string FileName, RuntimeConfig Config)> children = new();
74+
foreach (string childPath in files?.SourceFiles ?? Enumerable.Empty<string>())
75+
{
76+
// Match runtime semantics: file paths are relative to the process working directory,
77+
// and absent optional child files are not counted as configured data sources.
78+
if (fileSystem.File.Exists(childPath))
79+
{
80+
RuntimeConfig child = ReadConfig(childPath, fileSystem, options, ancestors);
81+
child.IsChildConfig = true;
82+
children.Add((childPath, child));
83+
}
84+
}
85+
86+
IEnumerable<RuntimeConfig> configs = new[] { root }.Concat(children.Select(child => child.Config));
87+
Dictionary<string, DataSource> sources = configs.SelectMany(config => config.GetDataSourceNamesToDataSourcesIterator())
88+
.ToDictionary(entry => entry.Key, entry => entry.Value);
89+
Dictionary<string, Entity> entities = configs.SelectMany(config => config.Entities)
90+
.ToDictionary(entry => entry.Key, entry => entry.Value);
91+
Dictionary<string, Autoentity> autoentities = configs.SelectMany(config => config.Autoentities)
92+
.ToDictionary(entry => entry.Key, entry => entry.Value);
93+
Dictionary<string, string> entitySources = configs.SelectMany(config => config.Entities
94+
.Where(_ => config.DataSource is not null || config.ChildConfigs.Count > 0)
95+
.Select(entity => new KeyValuePair<string, string>(entity.Key, config.GetDataSourceNameFromEntityName(entity.Key))))
96+
.ToDictionary(entry => entry.Key, entry => entry.Value);
97+
98+
// Use the existing explicit-data-source-map constructor: it performs no file loading.
99+
// This snapshot is for inspection only, never published to the runtime/provider.
100+
RuntimeConfig result = new(root.Schema, root.DataSource!, root.Runtime!, new(entities),
101+
root.DefaultDataSourceName, sources, entitySources, files, root.AzureKeyVault, new(autoentities));
102+
result.ChildConfigs.AddRange(children);
103+
return result;
104+
}
105+
finally
106+
{
107+
ancestors.Remove(fullPath);
108+
}
109+
}
110+
}

‎src/Cli/Commands/AppNameOptions.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
using Azure.DataApiBuilder.Config;
66
using Azure.DataApiBuilder.Config.ObjectModel;
77
using Azure.DataApiBuilder.Config.Telemetry;
8-
using Azure.DataApiBuilder.Core.Configurations;
98
using Cli.Constants;
109
using CommandLine;
1110
using Microsoft.Extensions.Logging;
@@ -58,14 +57,15 @@ public int Handler(ILogger logger, FileSystemRuntimeConfigLoader loader, IFileSy
5857
// We intentionally do NOT run full `validate` here — validation opens a database
5958
// connection, whereas encoding only needs the parsed runtime/entity settings.
6059
// Requiring a live database would defeat the purpose of this static inspection command.
61-
if (!ConfigGenerator.TryGetConfigForRuntimeEngine(Config, loader, fileSystem, out _))
60+
if (!ConfigGenerator.TryGetConfigForRuntimeEngine(Config, loader, fileSystem, out string configPath))
6261
{
6362
logger.LogError("Could not determine the config file to use.");
6463
return CliReturnCode.GENERAL_ERROR;
6564
}
6665

67-
RuntimeConfigProvider runtimeConfigProvider = new(loader);
68-
if (!runtimeConfigProvider.TryGetConfig(out RuntimeConfig? runtimeConfig) || runtimeConfig is null)
66+
// An inspection command must not use the runtime provider: that path resolves Key Vault
67+
// references and creates file watchers. Keep unresolved credentials as Missing instead.
68+
if (!AppNameConfigLoader.TryLoadConfig(configPath, fileSystem, out RuntimeConfig? runtimeConfig))
6969
{
7070
logger.LogError("Failed to parse the config file.");
7171
return CliReturnCode.GENERAL_ERROR;

‎src/Config/Azure.DataApiBuilder.Config.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
<PackageReference Include="Microsoft.Data.SqlClient" />
2626
<!-- Override the vulnerable Pkcs pulled in by Microsoft.Data.SqlClient (see Directory.Packages.props). -->
2727
<PackageReference Include="System.Security.Cryptography.Pkcs" />
28+
<PackageReference Include="MySqlConnector" />
2829
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" />
2930
<PackageReference Include="System.IdentityModel.Tokens.Jwt" />
3031
<PackageReference Include="Humanizer" />

‎src/Config/RuntimeConfigLoader.cs‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,10 @@ public static JsonSerializerOptions GetSerializationOptions(
429429
/// <returns>The connection string with the telemetry-bearing <c>Application Name</c> embedded.</returns>
430430
public static string GetConnectionStringWithApplicationName(string connectionString, RuntimeConfig config, DataSource dataSource)
431431
{
432+
// Hosted initialization and explicit overrides can supply a different connection string from
433+
// the one parsed into the config. Per-pool authentication telemetry must describe that string.
434+
dataSource = dataSource with { ConnectionString = connectionString };
435+
432436
return dataSource.DatabaseType switch
433437
{
434438
DatabaseType.MSSQL or DatabaseType.DWSQL => GetMsSqlConnectionStringWithApplicationName(connectionString, config, dataSource),
@@ -499,18 +503,43 @@ internal static string GetMsSqlConnectionStringWithApplicationName(string connec
499503
if (string.IsNullOrWhiteSpace(connectionStringBuilder.ApplicationName)
500504
|| connectionStringBuilder.ApplicationName.Equals(defaultApplicationName, StringComparison.OrdinalIgnoreCase))
501505
{
502-
connectionStringBuilder.ApplicationName = applicationName;
506+
connectionStringBuilder.ApplicationName = ComposeSqlApplicationName(string.Empty, applicationName);
503507
}
504508
else
505509
{
506510
// If the connection string contains the `Application Name` property with a value, update the value by adding the DataApiBuilder Application Name.
507-
connectionStringBuilder.ApplicationName += $",{applicationName}";
511+
connectionStringBuilder.ApplicationName = ComposeSqlApplicationName(connectionStringBuilder.ApplicationName, applicationName);
508512
}
509513

510514
// Return the updated connection string.
511515
return connectionStringBuilder.ConnectionString;
512516
}
513517

518+
/// <summary>
519+
/// SqlClient rejects names longer than 128 UTF-16 code units before opening a connection. Keep
520+
/// the existing name (including any isolation prefix) intact and fit only the DAB-owned suffix
521+
/// into the remaining budget. The decoder already accepts a truncated payload.
522+
/// </summary>
523+
private static string ComposeSqlApplicationName(string existingName, string telemetry)
524+
{
525+
const int maxLength = 128;
526+
string separator = existingName.Length == 0 ? string.Empty : ",";
527+
int available = maxLength - existingName.Length - separator.Length;
528+
if (available <= 0)
529+
{
530+
return existingName;
531+
}
532+
533+
int length = Math.Min(available, telemetry.Length);
534+
if (length < telemetry.Length && length > 0
535+
&& char.IsHighSurrogate(telemetry[length - 1]) && char.IsLowSurrogate(telemetry[length]))
536+
{
537+
length--;
538+
}
539+
540+
return length == 0 ? existingName : existingName + separator + telemetry[..length];
541+
}
542+
514543
/// <summary>
515544
/// It adds or replaces a property in the connection string with `Application Name` property.
516545
/// If the connection string already contains the property, it appends the property `Application Name` to the connection string,

0 commit comments

Comments
 (0)