Skip to content

Commit ecf6140

Browse files
committed
[user-jwts] Read and generate secrets ID with SecretsManager (dotnet#42006)
* [user-jwts] Read secrets ID from SecretsManager and generate missing secrets * Address feedback from review * Add shared localizations strings for secrets * Update localization and address feedback
1 parent fb91b21 commit ecf6140

14 files changed

+303
-115
lines changed

src/Tools/dotnet-user-secrets/src/Internal/MsBuildProjectFinder.cs renamed to src/Tools/Shared/SecretsHelpers/MsBuildProjectFinder.cs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4-
using System;
5-
using System.IO;
64
using System.Linq;
5+
using Microsoft.AspNetCore.Tools;
76
using Microsoft.Extensions.Tools.Internal;
87

9-
namespace Microsoft.Extensions.SecretManager.Tools.Internal;
10-
118
internal sealed class MsBuildProjectFinder
129
{
1310
private readonly string _directory;
@@ -36,20 +33,20 @@ public string FindMsBuildProject(string project)
3633

3734
if (projects.Count > 1)
3835
{
39-
throw new FileNotFoundException(Resources.FormatError_MultipleProjectsFound(projectPath));
36+
throw new FileNotFoundException(SecretsHelpersResources.FormatError_MultipleProjectsFound(projectPath));
4037
}
4138

4239
if (projects.Count == 0)
4340
{
44-
throw new FileNotFoundException(Resources.FormatError_NoProjectsFound(projectPath));
41+
throw new FileNotFoundException(SecretsHelpersResources.FormatError_NoProjectsFound(projectPath));
4542
}
4643

4744
return projects[0];
4845
}
4946

5047
if (!File.Exists(projectPath))
5148
{
52-
throw new FileNotFoundException(Resources.FormatError_ProjectPath_NotFound(projectPath));
49+
throw new FileNotFoundException(SecretsHelpersResources.FormatError_ProjectPath_NotFound(projectPath));
5350
}
5451

5552
return projectPath;

src/Tools/dotnet-user-secrets/src/Internal/ProjectIdResolver.cs renamed to src/Tools/Shared/SecretsHelpers/ProjectIdResolver.cs

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,15 @@
66
using System.IO;
77
using System.Linq;
88
using System.Text;
9+
using Microsoft.AspNetCore.Tools;
910
using Microsoft.Extensions.CommandLineUtils;
1011
using Microsoft.Extensions.Tools.Internal;
1112

12-
namespace Microsoft.Extensions.SecretManager.Tools.Internal;
13-
1413
/// <summary>
1514
/// This API supports infrastructure and is not intended to be used
1615
/// directly from your code. This API may change or be removed in future releases.
1716
/// </summary>
18-
public class ProjectIdResolver
17+
internal sealed class ProjectIdResolver
1918
{
2019
private const string DefaultConfig = "Debug";
2120
private readonly IReporter _reporter;
@@ -32,9 +31,18 @@ public ProjectIdResolver(IReporter reporter, string workingDirectory)
3231
public string Resolve(string project, string configuration)
3332
{
3433
var finder = new MsBuildProjectFinder(_workingDirectory);
35-
var projectFile = finder.FindMsBuildProject(project);
34+
string projectFile;
35+
try
36+
{
37+
projectFile = finder.FindMsBuildProject(project);
38+
}
39+
catch (Exception ex)
40+
{
41+
_reporter.Error(ex.Message);
42+
return null;
43+
}
3644

37-
_reporter.Verbose(Resources.FormatMessage_Project_File_Path(projectFile));
45+
_reporter.Verbose(SecretsHelpersResources.FormatMessage_Project_File_Path(projectFile));
3846

3947
configuration = !string.IsNullOrEmpty(configuration)
4048
? configuration
@@ -98,18 +106,20 @@ public string Resolve(string project, string configuration)
98106
_reporter.Verbose(outputBuilder.ToString());
99107
_reporter.Verbose(errorBuilder.ToString());
100108
_reporter.Error($"Exit code: {process.ExitCode}");
101-
throw new InvalidOperationException(Resources.FormatError_ProjectFailedToLoad(projectFile));
109+
_reporter.Error(SecretsHelpersResources.FormatError_ProjectFailedToLoad(projectFile));
110+
return null;
102111
}
103112

104113
if (!File.Exists(outputFile))
105114
{
106-
throw new InvalidOperationException(Resources.FormatError_ProjectMissingId(projectFile));
115+
_reporter.Error(SecretsHelpersResources.FormatError_ProjectMissingId(projectFile));
116+
return null;
107117
}
108118

109119
var id = File.ReadAllText(outputFile)?.Trim();
110120
if (string.IsNullOrEmpty(id))
111121
{
112-
throw new InvalidOperationException(Resources.FormatError_ProjectMissingId(projectFile));
122+
_reporter.Error(SecretsHelpersResources.FormatError_ProjectMissingId(projectFile));
113123
}
114124
return id;
115125

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<root>
3+
<!--
4+
Microsoft ResX Schema
5+
6+
Version 2.0
7+
8+
The primary goals of this format is to allow a simple XML format
9+
that is mostly human readable. The generation and parsing of the
10+
various data types are done through the TypeConverter classes
11+
associated with the data types.
12+
13+
Example:
14+
15+
... ado.net/XML headers & schema ...
16+
<resheader name="resmimetype">text/microsoft-resx</resheader>
17+
<resheader name="version">2.0</resheader>
18+
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
19+
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
20+
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
21+
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
22+
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
23+
<value>[base64 mime encoded serialized .NET Framework object]</value>
24+
</data>
25+
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
26+
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
27+
<comment>This is a comment</comment>
28+
</data>
29+
30+
There are any number of "resheader" rows that contain simple
31+
name/value pairs.
32+
33+
Each data row contains a name, and value. The row also contains a
34+
type or mimetype. Type corresponds to a .NET class that support
35+
text/value conversion through the TypeConverter architecture.
36+
Classes that don't support this are serialized and stored with the
37+
mimetype set.
38+
39+
The mimetype is used for serialized objects, and tells the
40+
ResXResourceReader how to depersist the object. This is currently not
41+
extensible. For a given mimetype the value must be set accordingly:
42+
43+
Note - application/x-microsoft.net.object.binary.base64 is the format
44+
that the ResXResourceWriter will generate, however the reader can
45+
read any of the formats listed below.
46+
47+
mimetype: application/x-microsoft.net.object.binary.base64
48+
value : The object must be serialized with
49+
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
50+
: and then encoded with base64 encoding.
51+
52+
mimetype: application/x-microsoft.net.object.soap.base64
53+
value : The object must be serialized with
54+
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
55+
: and then encoded with base64 encoding.
56+
57+
mimetype: application/x-microsoft.net.object.bytearray.base64
58+
value : The object must be serialized into a byte array
59+
: using a System.ComponentModel.TypeConverter
60+
: and then encoded with base64 encoding.
61+
-->
62+
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
63+
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
64+
<xsd:element name="root" msdata:IsDataSet="true">
65+
<xsd:complexType>
66+
<xsd:choice maxOccurs="unbounded">
67+
<xsd:element name="metadata">
68+
<xsd:complexType>
69+
<xsd:sequence>
70+
<xsd:element name="value" type="xsd:string" minOccurs="0" />
71+
</xsd:sequence>
72+
<xsd:attribute name="name" use="required" type="xsd:string" />
73+
<xsd:attribute name="type" type="xsd:string" />
74+
<xsd:attribute name="mimetype" type="xsd:string" />
75+
<xsd:attribute ref="xml:space" />
76+
</xsd:complexType>
77+
</xsd:element>
78+
<xsd:element name="assembly">
79+
<xsd:complexType>
80+
<xsd:attribute name="alias" type="xsd:string" />
81+
<xsd:attribute name="name" type="xsd:string" />
82+
</xsd:complexType>
83+
</xsd:element>
84+
<xsd:element name="data">
85+
<xsd:complexType>
86+
<xsd:sequence>
87+
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
88+
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
89+
</xsd:sequence>
90+
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
91+
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
92+
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
93+
<xsd:attribute ref="xml:space" />
94+
</xsd:complexType>
95+
</xsd:element>
96+
<xsd:element name="resheader">
97+
<xsd:complexType>
98+
<xsd:sequence>
99+
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
100+
</xsd:sequence>
101+
<xsd:attribute name="name" type="xsd:string" use="required" />
102+
</xsd:complexType>
103+
</xsd:element>
104+
</xsd:choice>
105+
</xsd:complexType>
106+
</xsd:element>
107+
</xsd:schema>
108+
<resheader name="resmimetype">
109+
<value>text/microsoft-resx</value>
110+
</resheader>
111+
<resheader name="version">
112+
<value>2.0</value>
113+
</resheader>
114+
<resheader name="reader">
115+
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
116+
</resheader>
117+
<resheader name="writer">
118+
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
119+
</resheader>
120+
<data name="Error_InvalidSecretsId" xml:space="preserve">
121+
<value>The UserSecretsId '{userSecretsId}' cannot contain any characters that cannot be used in a file path.</value>
122+
</data>
123+
<data name="Error_MultipleProjectsFound" xml:space="preserve">
124+
<value>Multiple MSBuild project files found in '{projectPath}'. Specify which to use with the --project option.</value>
125+
</data>
126+
<data name="Error_NoProjectsFound" xml:space="preserve">
127+
<value>Could not find a MSBuild project file in '{projectPath}'. Specify which project to use with the --project option.</value>
128+
</data>
129+
<data name="Error_ProjectFailedToLoad" xml:space="preserve">
130+
<value>Could not load the MSBuild project '{project}'.</value>
131+
</data>
132+
<data name="Error_ProjectMissingId" xml:space="preserve">
133+
<value>Could not find the global property 'UserSecretsId' in MSBuild project '{project}'. Ensure this property is set in the project or use the '--id' command line option.</value>
134+
</data>
135+
<data name="Error_ProjectPath_NotFound" xml:space="preserve">
136+
<value>The project file '{0}' does not exist.</value>
137+
</data>
138+
<data name="Message_ProjectAlreadyInitialized" xml:space="preserve">
139+
<value>The MSBuild project '{project}' has already been initialized with a UserSecretsId.</value>
140+
</data>
141+
<data name="Message_Project_File_Path" xml:space="preserve">
142+
<value>Project file path {project}.</value>
143+
</data>
144+
<data name="Message_SetUserSecretsIdForProject" xml:space="preserve">
145+
<value>Set UserSecretsId to '{userSecretsId}' for MSBuild project '{project}'.</value>
146+
</data>
147+
</root>
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
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+
4+
using System.Linq;
5+
using System.Xml;
6+
using System.Xml.Linq;
7+
using System.Xml.XPath;
8+
using Microsoft.AspNetCore.Tools;
9+
using Microsoft.Extensions.Tools.Internal;
10+
11+
internal static class UserSecretsCreator
12+
{
13+
public static string CreateUserSecretsId(IReporter reporter, string project, string workingDirectory, string overrideId = null)
14+
{
15+
var projectPath = ResolveProjectPath(project, workingDirectory);
16+
17+
// Load the project file as XML
18+
var projectDocument = XDocument.Load(projectPath, LoadOptions.PreserveWhitespace);
19+
20+
// Accept the `--id` CLI option to the main app
21+
string newSecretsId = string.IsNullOrWhiteSpace(overrideId)
22+
? Guid.NewGuid().ToString()
23+
: overrideId;
24+
25+
// Confirm secret ID does not contain invalid characters
26+
if (Path.GetInvalidPathChars().Any(newSecretsId.Contains))
27+
{
28+
throw new ArgumentException(SecretsHelpersResources.FormatError_InvalidSecretsId(newSecretsId));
29+
}
30+
31+
var existingUserSecretsId = projectDocument.XPathSelectElements("//UserSecretsId").FirstOrDefault();
32+
33+
// Check if a UserSecretsId is already set
34+
if (existingUserSecretsId is not null)
35+
{
36+
// Only set the UserSecretsId if the user specified an explicit value
37+
if (string.IsNullOrWhiteSpace(overrideId))
38+
{
39+
reporter.Output(SecretsHelpersResources.FormatMessage_ProjectAlreadyInitialized(projectPath));
40+
return existingUserSecretsId.Value;
41+
}
42+
43+
existingUserSecretsId.SetValue(newSecretsId);
44+
}
45+
else
46+
{
47+
// Find the first non-conditional PropertyGroup
48+
var propertyGroup = projectDocument.Root.DescendantNodes()
49+
.FirstOrDefault(node => node is XElement el
50+
&& el.Name == "PropertyGroup"
51+
&& el.Attributes().All(attr =>
52+
attr.Name != "Condition")) as XElement;
53+
54+
// No valid property group, create a new one
55+
if (propertyGroup == null)
56+
{
57+
propertyGroup = new XElement("PropertyGroup");
58+
projectDocument.Root.AddFirst(propertyGroup);
59+
}
60+
61+
// Add UserSecretsId element
62+
propertyGroup.Add(" ");
63+
propertyGroup.Add(new XElement("UserSecretsId", newSecretsId));
64+
propertyGroup.Add($"{Environment.NewLine} ");
65+
}
66+
67+
var settings = new XmlWriterSettings
68+
{
69+
OmitXmlDeclaration = true,
70+
};
71+
72+
using var xw = XmlWriter.Create(projectPath, settings);
73+
projectDocument.Save(xw);
74+
75+
reporter.Output(SecretsHelpersResources.FormatMessage_SetUserSecretsIdForProject(newSecretsId, projectPath));
76+
return newSecretsId;
77+
}
78+
79+
private static string ResolveProjectPath(string name, string path)
80+
{
81+
var finder = new MsBuildProjectFinder(path);
82+
return finder.FindMsBuildProject(name);
83+
}
84+
}

src/Tools/dotnet-user-jwts/src/Helpers/DevJwtCliHelpers.cs

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44
using System.IdentityModel.Tokens.Jwt;
55
using System.Linq;
66
using System.Text.Json;
7-
using System.Xml.Linq;
8-
using System.Xml.XPath;
97
using Microsoft.Extensions.Configuration;
108
using Microsoft.Extensions.Configuration.UserSecrets;
119
using Microsoft.Extensions.Tools.Internal;
@@ -14,17 +12,15 @@ namespace Microsoft.AspNetCore.Authentication.JwtBearer.Tools;
1412

1513
internal static class DevJwtCliHelpers
1614
{
17-
public static string GetUserSecretsId(string projectFilePath)
15+
public static string GetOrSetUserSecretsId(IReporter reporter, string projectFilePath)
1816
{
19-
var projectDocument = XDocument.Load(projectFilePath, LoadOptions.PreserveWhitespace);
20-
var existingUserSecretsId = projectDocument.XPathSelectElements("//UserSecretsId").FirstOrDefault();
21-
22-
if (existingUserSecretsId == null)
17+
var resolver = new ProjectIdResolver(reporter, projectFilePath);
18+
var id = resolver.Resolve(projectFilePath, configuration: null);
19+
if (string.IsNullOrEmpty(id))
2320
{
24-
return null;
21+
return UserSecretsCreator.CreateUserSecretsId(reporter, projectFilePath, projectFilePath);
2522
}
26-
27-
return existingUserSecretsId.Value;
23+
return id;
2824
}
2925

3026
public static string GetProject(string projectPath = null)
@@ -54,7 +50,7 @@ public static bool GetProjectAndSecretsId(string projectPath, IReporter reporter
5450
return false;
5551
}
5652

57-
userSecretsId = GetUserSecretsId(project);
53+
userSecretsId = GetOrSetUserSecretsId(reporter, project);
5854
if (userSecretsId == null)
5955
{
6056
reporter.Error($"Project does not contain a user secrets ID.");
@@ -85,6 +81,7 @@ public static byte[] CreateSigningKeyMaterial(string userSecretsId, bool reset =
8581
// Create signing material and save to user secrets
8682
var newKeyMaterial = System.Security.Cryptography.RandomNumberGenerator.GetBytes(DevJwtsDefaults.SigningKeyLength);
8783
var secretsFilePath = PathHelper.GetSecretsPathFromSecretsId(userSecretsId);
84+
Directory.CreateDirectory(Path.GetDirectoryName(secretsFilePath));
8885

8986
IDictionary<string, string> secrets = null;
9087
if (File.Exists(secretsFilePath))

0 commit comments

Comments
 (0)