Skip to content

Commit 649c38e

Browse files
authored
SWT token cleanup (#11148)
1 parent 0e0cadb commit 649c38e

18 files changed

+111
-320
lines changed

src/WebJobs.Script.WebHost/Management/FunctionsSyncManager.cs

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -729,7 +729,7 @@ internal HttpRequestMessage BuildSetTriggersRequest()
729729
}
730730

731731
// This function will call POST https://{app}.azurewebsites.net/operation/settriggers with the content
732-
// of triggers. It'll verify app ownership using a SWT token valid for 5 minutes. It should be plenty.
732+
// of triggers. It'll verify app ownership using a site token valid for 5 minutes. It should be plenty.
733733
private async Task<(bool Success, string ErrorMessage)> SetTriggersAsync(string content)
734734
{
735735
// sanitize the content before logging
@@ -747,12 +747,6 @@ internal HttpRequestMessage BuildSetTriggersRequest()
747747
request.Headers.Add("User-Agent", ScriptConstants.FunctionsUserAgent);
748748
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
749749

750-
if (_hostingConfigOptions.Value.SwtIssuerEnabled)
751-
{
752-
string swtToken = SimpleWebTokenHelper.CreateToken(DateTime.UtcNow.AddMinutes(5));
753-
request.Headers.Add(ScriptConstants.SiteRestrictedTokenHeaderName, swtToken);
754-
}
755-
756750
string jwtToken = JwtTokenHelper.CreateToken(DateTime.UtcNow.AddMinutes(5));
757751
request.Headers.Add(ScriptConstants.SiteTokenHeaderName, jwtToken);
758752

src/WebJobs.Script.WebHost/Metrics/LinuxContainerMetricsPublisher.cs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -292,12 +292,6 @@ private HttpRequestMessage BuildRequest<TContent>(HttpMethod method, string path
292292
request.Headers.Add(HostNameHeader, _hostNameProvider.Value);
293293
request.Headers.Add(StampNameHeader, _stampName);
294294

295-
if (_hostingConfigOptions.CurrentValue.SwtIssuerEnabled)
296-
{
297-
string swtToken = SimpleWebTokenHelper.CreateToken(DateTime.UtcNow.AddMinutes(5));
298-
request.Headers.Add(ScriptConstants.SiteRestrictedTokenHeaderName, swtToken);
299-
}
300-
301295
string jwtToken = JwtTokenHelper.CreateToken(DateTime.UtcNow.AddMinutes(5));
302296
request.Headers.Add(ScriptConstants.SiteTokenHeaderName, jwtToken);
303297

src/WebJobs.Script.WebHost/Security/SimpleWebTokenHelper.cs renamed to src/WebJobs.Script.WebHost/Security/EncryptionHelper.cs

Lines changed: 2 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,11 @@
66
using System.Linq;
77
using System.Security.Cryptography;
88
using System.Text;
9-
using Microsoft.AspNetCore.Authentication;
109

1110
namespace Microsoft.Azure.WebJobs.Script.WebHost.Security
1211
{
13-
public static class SimpleWebTokenHelper
12+
public static class EncryptionHelper
1413
{
15-
/// <summary>
16-
/// A SWT or a Simple Web Token is a token that's made of key=value pairs separated
17-
/// by &. We only specify expiration in ticks from now (exp={ticks})
18-
/// The SWT is then returned as an encrypted string.
19-
/// </summary>
20-
/// <param name="validUntil">Datetime for when the token should expire.</param>
21-
/// <param name="key">Optional key to encrypt the token with.</param>
22-
/// <returns>a SWT signed by this app.</returns>
23-
public static string CreateToken(DateTime validUntil, byte[] key = null) => Encrypt($"exp={validUntil.Ticks}", key);
24-
2514
internal static string Encrypt(string value, byte[] key = null, IEnvironment environment = null, bool includesSignature = false)
2615
{
2716
key = key ?? SecretsUtility.GetEncryptionKey(environment);
@@ -51,7 +40,7 @@ internal static string Encrypt(string value, byte[] key = null, IEnvironment env
5140
}
5241
else
5342
{
54-
// return {iv}.{swt}.{sha236(key)}
43+
// return {iv}.{content}.{sha236(key)}
5544
return string.Format("{0}.{1}.{2}", iv, Convert.ToBase64String(cipherStream.ToArray()), GetSHA256Base64String(aes.Key));
5645
}
5746
}
@@ -105,33 +94,6 @@ public static string Decrypt(string value, IEnvironment environment = null)
10594
return Decrypt(key, value);
10695
}
10796

108-
public static bool TryValidateToken(string token, ISystemClock systemClock)
109-
{
110-
try
111-
{
112-
return ValidateToken(token, systemClock);
113-
}
114-
catch
115-
{
116-
return false;
117-
}
118-
}
119-
120-
public static bool ValidateToken(string token, ISystemClock systemClock, IEnvironment environment = null)
121-
{
122-
var data = Decrypt(token, environment);
123-
124-
var parsedToken = data
125-
// token = key1=value1;key2=value2
126-
.Split(';', StringSplitOptions.RemoveEmptyEntries)
127-
// ["key1=value1", "key2=value2"]
128-
.Select(v => v.Split('=', StringSplitOptions.RemoveEmptyEntries))
129-
// [["key1", "value1"], ["key2", "value2"]]
130-
.ToDictionary(k => k[0], v => v[1]);
131-
132-
return parsedToken.ContainsKey("exp") && systemClock.UtcNow.UtcDateTime < new DateTime(long.Parse(parsedToken["exp"]));
133-
}
134-
13597
private static string GetSHA256Base64String(byte[] key)
13698
{
13799
using (var sha256 = SHA256.Create())

src/WebJobs.Script.WebHost/StartupContextProvider.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ private StartupContext GetStartupContextOrNull()
113113
// Dont' want to block on this file operation, so we kick it off in the background.
114114
Task.Run(() => File.Delete(contextPath));
115115

116-
string decryptedContent = SimpleWebTokenHelper.Decrypt(content, environment: _environment);
116+
string decryptedContent = EncryptionHelper.Decrypt(content, environment: _environment);
117117
var context = JsonConvert.DeserializeObject<StartupContext>(decryptedContent);
118118

119119
return context;
@@ -139,7 +139,7 @@ private StartupContext GetStartupContextOrNull()
139139
/// <returns>The decrypted assignment context</returns>
140140
public virtual HostAssignmentContext SetContext(EncryptedHostAssignmentContext encryptedContext)
141141
{
142-
string decryptedContext = SimpleWebTokenHelper.Decrypt(encryptedContext.EncryptedContext, environment: _environment);
142+
string decryptedContext = EncryptionHelper.Decrypt(encryptedContext.EncryptedContext, environment: _environment);
143143
var hostAssignmentContext = JsonConvert.DeserializeObject<HostAssignmentContext>(decryptedContext);
144144

145145
// Don't update StartupContext for warmup requests

src/WebJobs.Script/Config/FunctionsHostingConfigOptions.cs

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -62,22 +62,6 @@ internal bool ShutdownWebhostWorkerChannelsOnHostShutdown
6262
}
6363
}
6464

65-
/// <summary>
66-
/// Gets or sets a value indicating whether SWT tokens should be sent on outgoing requests.
67-
/// </summary>
68-
internal bool SwtIssuerEnabled
69-
{
70-
get
71-
{
72-
return GetFeatureAsBooleanOrDefault(ScriptConstants.HostingConfigSwtIssuerEnabled, true);
73-
}
74-
75-
set
76-
{
77-
_features[ScriptConstants.HostingConfigSwtIssuerEnabled] = value ? "1" : "0";
78-
}
79-
}
80-
8165
/// <summary>
8266
/// Gets or sets a string delimited by '|' that contains a list of admin APIs that are allowed to
8367
/// be invoked internally by platform components.

src/WebJobs.Script/ScriptConstants.cs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,6 @@ public static class ScriptConstants
108108
public const string AntaresLogIdHeaderName = "X-ARR-LOG-ID";
109109
public const string AntaresScaleOutHeaderName = "X-FUNCTION-SCALEOUT";
110110
public const string AntaresColdStartHeaderName = "X-MS-COLDSTART";
111-
public const string SiteRestrictedTokenHeaderName = "x-ms-site-restricted-token";
112111
public const string SiteTokenHeaderName = "x-ms-site-token";
113112
public const string EasyAuthIdentityHeader = "x-ms-client-principal";
114113
public const string AntaresPlatformInternal = "x-ms-platform-internal";
@@ -145,7 +144,6 @@ public static class ScriptConstants
145144
public const string HostingConfigDisableLinuxAppServiceDetailedExecutionEvents = "DisableLinuxExecutionDetails";
146145
public const string HostingConfigDisableLinuxAppServiceExecutionEventLogBackoff = "DisableLinuxLogBackoff";
147146
public const string FeatureFlagEnableLegacyDurableVersionCheck = "EnableLegacyDurableVersionCheck";
148-
public const string HostingConfigSwtIssuerEnabled = "SwtIssuerEnabled";
149147
public const string HostingConfigInternalAuthApisAllowList = "InternalAuthApisAllowList";
150148
public const string HostingConfigDotNetInProcDisabled = "DotNetInProcDisabled";
151149

test/WebJobs.Script.Tests.Integration/ContainerManagement/AtlasContainerInitializationHostedServiceTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ private static string GetEncryptedHostAssignmentContext(HostAssignmentContext ho
194194
using (var env = new TestScopedEnvironmentVariable(WebSiteAuthEncryptionKey, containerEncryptionKey))
195195
{
196196
var serializeObject = JsonConvert.SerializeObject(hostAssignmentContext);
197-
return SimpleWebTokenHelper.Encrypt(serializeObject);
197+
return EncryptionHelper.Encrypt(serializeObject);
198198
}
199199
}
200200

test/WebJobs.Script.Tests.Integration/ContainerManagement/LegionContainerInitializationHostedServiceTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ private static string GetEncryptedHostAssignmentContext(HostAssignmentContext ho
170170
using (var env = new TestScopedEnvironmentVariable(WebSiteAuthEncryptionKey, containerEncryptionKey))
171171
{
172172
var serializeObject = JsonConvert.SerializeObject(hostAssignmentContext);
173-
return SimpleWebTokenHelper.Encrypt(serializeObject);
173+
return EncryptionHelper.Encrypt(serializeObject);
174174
}
175175
}
176176

test/WebJobs.Script.Tests.Integration/Host/StandbyManager/StandbyManagerE2ETests_Linux.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ private static EncryptedHostAssignmentContext CreateEncryptedContext(HostAssignm
283283
{
284284
string json = JsonConvert.SerializeObject(context);
285285
var encryptionKey = Convert.FromBase64String(key);
286-
string encrypted = SimpleWebTokenHelper.Encrypt(json, encryptionKey);
286+
string encrypted = EncryptionHelper.Encrypt(json, encryptionKey);
287287

288288
return new EncryptedHostAssignmentContext { EncryptedContext = encrypted };
289289
}

test/WebJobs.Script.Tests.Integration/Management/FunctionsSyncManagerTests.cs

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -391,13 +391,11 @@ public void ArmCacheEnabled_VerifyDefault()
391391
}
392392

393393
[Theory]
394-
[InlineData(true, true)]
395-
[InlineData(false, true)]
396-
[InlineData(true, false)]
397-
public async Task TrySyncTriggers_PostsExpectedContent(bool cacheEnabled, bool swtIssuerEnabled)
394+
[InlineData(true)]
395+
[InlineData(false)]
396+
public async Task TrySyncTriggers_PostsExpectedContent(bool cacheEnabled)
398397
{
399398
_mockEnvironment.Setup(p => p.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteArmCacheEnabled)).Returns(cacheEnabled ? "1" : "0");
400-
_hostingConfigOptions.SwtIssuerEnabled = swtIssuerEnabled;
401399

402400
using (var env = new TestScopedEnvironmentVariable(_vars))
403401
{
@@ -413,16 +411,6 @@ public async Task TrySyncTriggers_PostsExpectedContent(bool cacheEnabled, bool s
413411
// verify expected headers
414412
Assert.Equal(ScriptConstants.FunctionsUserAgent, _mockHttpHandler.LastRequest.Headers.UserAgent.ToString());
415413
Assert.True(_mockHttpHandler.LastRequest.Headers.Contains(ScriptConstants.AntaresLogIdHeaderName));
416-
417-
if (swtIssuerEnabled)
418-
{
419-
Assert.NotEmpty(_mockHttpHandler.LastRequest.Headers.GetValues(ScriptConstants.SiteRestrictedTokenHeaderName));
420-
}
421-
else
422-
{
423-
Assert.False(_mockHttpHandler.LastRequest.Headers.Contains(ScriptConstants.SiteRestrictedTokenHeaderName));
424-
}
425-
426414
Assert.NotEmpty(_mockHttpHandler.LastRequest.Headers.GetValues(ScriptConstants.SiteTokenHeaderName));
427415

428416
if (cacheEnabled)

0 commit comments

Comments
 (0)