-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
StackSettingsConfigValueJsonConverter.cs
63 lines (56 loc) · 2.49 KB
/
StackSettingsConfigValueJsonConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2016-2021, Pulumi Corporation
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Pulumi.Automation.Serialization.Json
{
internal class StackSettingsConfigValueJsonConverter : JsonConverter<StackSettingsConfigValue>
{
public override StackSettingsConfigValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var element = JsonSerializer.Deserialize<JsonElement>(ref reader, options);
// check if plain string
if (element.ValueKind == JsonValueKind.String)
{
var value = element.GetString();
return new StackSettingsConfigValue(value, false);
}
// check if the element is an object,
// if it has a single property called "secure" then it is a secret value
// otherwise, serialize the whole object as JSON into the stack settings value
if (element.ValueKind == JsonValueKind.Object)
{
foreach(var property in element.EnumerateObject())
{
if (string.Equals("Secure", property.Name, StringComparison.OrdinalIgnoreCase))
{
var secureValue = property.Value;
if (secureValue.ValueKind != JsonValueKind.String)
{
throw new JsonException($"Unable to deserialize [{typeToConvert.FullName}] as a secure string. Expecting a string secret.");
}
return new StackSettingsConfigValue(secureValue.GetString(), true);
}
}
}
var serializedElement = JsonSerializer.Serialize(element);
return new StackSettingsConfigValue(serializedElement, false);
}
public override void Write(Utf8JsonWriter writer, StackSettingsConfigValue value, JsonSerializerOptions options)
{
// secure string
if (value.IsSecure)
{
var securePropertyName = options.PropertyNamingPolicy?.ConvertName("Secure") ?? "Secure";
writer.WriteStartObject();
writer.WriteString(securePropertyName, value.Value);
writer.WriteEndObject();
}
// plain string
else
{
writer.WriteStringValue(value.Value);
}
}
}
}