-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathRequestLog.cs
More file actions
266 lines (243 loc) · 11.1 KB
/
Copy pathRequestLog.cs
File metadata and controls
266 lines (243 loc) · 11.1 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
using System.Diagnostics;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
namespace Epp.Otp;
// Only explicitly selected metadata enters logs; never serialize delivery/provider models.
public sealed class RequestLog
{
private static readonly string[] ContextFields =
{
"functionName", "functionRequestId", "functionInvocationId",
"x-ms-client-request-id", "x-ms-correlation-id", "msCorrelationIdSource", "omittedIdFields",
"channel", "evaluation", "providerName",
};
private static readonly string[] CredentialFields =
{
"providerAuthMode", "providerCredentialSource", "providerTenantId",
"functionOutboundClientId", "functionOutboundManagedIdentityClientId",
};
private static readonly Regex IdentifierPattern = new(@"\A[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\z", RegexOptions.CultureInvariant);
private readonly ILogger _logger;
private readonly Stopwatch _started = Stopwatch.StartNew();
private readonly Dictionary<string, object?> _data;
private readonly List<string> _omittedIdFields = new();
private Stopwatch? _providerStarted;
private Stopwatch? _credentialStarted;
public bool HasFailure => _data["failureStage"] is not null;
public RequestLog(ILogger logger, string requestId, string? invocationId, string? msRequestId, string? msCorrelationId)
{
_logger = logger;
_data = new()
{
["functionName"] = "SendOtp",
["functionRequestId"] = requestId,
["functionInvocationId"] = invocationId,
["x-ms-client-request-id"] = null,
["x-ms-correlation-id"] = null,
["msCorrelationIdSource"] = "none",
["omittedIdFields"] = Array.Empty<string>(),
["envelopeType"] = null,
["ttlSeconds"] = null,
["channel"] = null,
["evaluation"] = null,
["encryptionKeyIdMismatch"] = false,
["providerName"] = null,
["providerAuthMode"] = null,
["providerCredentialSource"] = null,
["providerCredentialElapsedMs"] = null,
["providerTenantId"] = null,
["functionOutboundClientId"] = null,
["functionOutboundManagedIdentityClientId"] = null,
["providerHttpMethod"] = null,
["providerEndpoint"] = null,
["providerAttempted"] = false,
["providerHttpStatus"] = null,
["providerStatus"] = null,
["providerOutcome"] = null,
["providerMessageId"] = null,
["providerElapsedMs"] = null,
["providerTimeoutMs"] = null,
["failureStage"] = null,
["failureReason"] = null,
["responseContainsNonce"] = null,
["responseContainsCorrelationId"] = null,
};
SetIdentifier("x-ms-client-request-id", msRequestId);
SetIdentifier("x-ms-correlation-id", msCorrelationId);
_data["msCorrelationIdSource"] = _data["x-ms-correlation-id"] is null ? "none" : "header";
}
private void SetIdentifier(string field, string? value)
{
var valid = value is { Length: <= 128 } && IdentifierPattern.IsMatch(value);
_data[field] = valid ? value : null;
_omittedIdFields.Remove(field);
if (!valid && !string.IsNullOrWhiteSpace(value)) _omittedIdFields.Add(field);
_data["omittedIdFields"] = _omittedIdFields.ToArray();
}
public void Service(string eventName, Dictionary<string, object?>? details = null, LogLevel level = LogLevel.Information)
{
var record = new Dictionary<string, object?> { ["logType"] = "service", ["eventName"] = eventName };
foreach (var field in ContextFields) record[field] = _data[field];
if (details is not null)
foreach (var (key, value) in details) record[key] = value;
record["elapsedMs"] = _started.ElapsedMilliseconds;
Write(level, eventName, record);
}
public void EnvelopeValidated(Envelope envelope, string? correlationId, string source)
{
_data["envelopeType"] = envelope.Type;
_data["ttlSeconds"] = envelope.TtlSeconds;
_data["channel"] = EnvelopeParser.ChannelName(envelope.Channel);
_data["evaluation"] = envelope.Mode == EnvelopeParser.ModeEvaluation;
SetIdentifier("x-ms-correlation-id", correlationId);
_data["msCorrelationIdSource"] = _data["x-ms-correlation-id"] is null ? "none" : source;
Service("envelope_validated", new()
{
["envelopeType"] = _data["envelopeType"],
["ttlSeconds"] = _data["ttlSeconds"],
["encryptedDeliveryContextPresent"] = true,
});
}
public void KeyIdMismatch()
{
_data["encryptionKeyIdMismatch"] = true;
Service("encryption_key_id_mismatch", level: LogLevel.Warning);
}
public void ProviderSelected(ProviderManifest manifest)
{
_data["providerName"] = manifest.Id;
_data["providerAuthMode"] = manifest.Auth.Mode is "apiKey" or "oauth" ? manifest.Auth.Mode : "unsupported";
Service("provider_selected", new() { ["providerAuthMode"] = _data["providerAuthMode"] });
}
public void CredentialResolutionStarted(AppConfig config)
{
_credentialStarted = Stopwatch.StartNew();
_data["providerCredentialSource"] = _data["providerAuthMode"] switch
{
"oauth" => "managed_identity_client_assertion",
"apiKey" => "key_vault",
_ => "unsupported",
};
if (Equals(_data["providerAuthMode"], "oauth"))
{
SetIdentifier("providerTenantId", config.ProviderTenantId);
SetIdentifier("functionOutboundClientId", config.OutboundClientId);
SetIdentifier("functionOutboundManagedIdentityClientId", config.OutboundManagedIdentityClientId);
}
Service("provider_credential_resolution_started", CredentialDetails());
}
private Dictionary<string, object?> CredentialDetails() =>
CredentialFields.ToDictionary(key => key, key => _data[key]);
private void CredentialResolutionFinished()
{
if (_credentialStarted is null) return;
_data["providerCredentialElapsedMs"] = _credentialStarted.ElapsedMilliseconds;
_credentialStarted = null;
}
public void CredentialResolved()
{
CredentialResolutionFinished();
var details = CredentialDetails();
details["providerCredentialElapsedMs"] = _data["providerCredentialElapsedMs"];
Service("provider_credential_resolved", details);
}
public void ProviderRequestBuilt(string? method, string endpoint)
{
var normalized = method?.ToUpperInvariant();
_data["providerHttpMethod"] = normalized is "GET" or "HEAD" or "POST" or "PUT" or "DELETE"
or "CONNECT" or "OPTIONS" or "TRACE" or "PATCH" ? normalized : "other";
var uri = new Uri(endpoint, UriKind.Absolute);
_data["providerEndpoint"] = uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped) + uri.AbsolutePath;
Service("provider_request_built", new()
{
["providerHttpMethod"] = _data["providerHttpMethod"],
["providerEndpoint"] = _data["providerEndpoint"],
["providerScheme"] = "https",
["redirectsAllowed"] = false,
});
}
public void ProviderRequestStarted(int timeoutMs)
{
_providerStarted = Stopwatch.StartNew();
_data["providerAttempted"] = true;
_data["providerTimeoutMs"] = timeoutMs;
Service("provider_request_started", new()
{
["providerTimeoutMs"] = timeoutMs,
["providerHttpMethod"] = _data["providerHttpMethod"],
["providerEndpoint"] = _data["providerEndpoint"],
});
}
public void ProviderResponseReceived(int status)
{
_data["providerHttpStatus"] = status;
Service("provider_response_received", new() { ["providerHttpStatus"] = status });
}
public void ProviderRequestFinished()
{
if (_providerStarted is null) return;
_data["providerElapsedMs"] = _providerStarted.ElapsedMilliseconds;
_providerStarted = null;
}
public void ProviderResponseProcessed(ProviderManifest manifest, ParsedResponse parsed, Outcome outcome, int httpStatus, bool validJson)
{
var status = parsed.ProviderStatusName ?? parsed.ProviderStatusCode;
var known = status is not null && status != "default" && manifest.ResponseMapping.ContainsKey(status);
_data["providerStatus"] = known ? status : "unmapped";
_data["providerOutcome"] = outcome.ToString();
SetIdentifier("providerMessageId", parsed.ProviderMessageId);
if (outcome != Outcome.Continue)
{
_data["failureStage"] = "provider_response";
_data["failureReason"] = validJson ? "provider_rejected" : "invalid_provider_json";
}
Service("provider_response_processed", new()
{
["providerHttpStatus"] = _data["providerHttpStatus"],
["providerStatus"] = _data["providerStatus"],
["providerOutcome"] = _data["providerOutcome"],
["providerMessageId"] = _data["providerMessageId"],
["providerElapsedMs"] = _data["providerElapsedMs"],
["httpStatus"] = httpStatus,
["failureReason"] = _data["failureReason"],
}, httpStatus >= 500 ? LogLevel.Error : httpStatus == 200 ? LogLevel.Information : LogLevel.Warning);
}
public void Failure(string stage, string reason, int httpStatus)
{
CredentialResolutionFinished();
ProviderRequestFinished();
_data["failureStage"] = stage;
_data["failureReason"] = reason;
Service(stage + "_failed", new() { ["failureReason"] = reason, ["httpStatus"] = httpStatus },
httpStatus >= 500 ? LogLevel.Error : LogLevel.Warning);
}
public void ResponsePrepared(int httpStatus, bool containsNonce, bool containsCorrelationId)
{
_data["responseContainsNonce"] = containsNonce;
_data["responseContainsCorrelationId"] = containsCorrelationId;
Service("response_prepared", new()
{
["httpStatus"] = httpStatus,
["responseContainsNonce"] = containsNonce,
["responseContainsCorrelationId"] = containsCorrelationId,
});
}
public void Complete(int httpStatus)
{
CredentialResolutionFinished();
ProviderRequestFinished();
var record = new Dictionary<string, object?>(_data)
{
["logType"] = "request",
["eventName"] = "request_completed",
["httpStatus"] = httpStatus,
["result"] = httpStatus == 200 ? (Equals(_data["evaluation"], true) ? "evaluated" : "accepted") : "failed",
["elapsedMs"] = _started.ElapsedMilliseconds,
};
Write(LogLevel.Information, "request_completed", record);
}
private void Write(LogLevel level, string eventName, Dictionary<string, object?> record) =>
_logger.Log(level, new EventId(0, eventName), record, null,
static (state, _) => JsonSerializer.Serialize(state));
}