-
Notifications
You must be signed in to change notification settings - Fork 4
/
SftpWatcherEntity.cs
191 lines (163 loc) · 6.43 KB
/
SftpWatcherEntity.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
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
using System;
using System.Collections.Generic;
using Renci.SshNet;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using System.Net;
using Newtonsoft.Json;
using Azure.Identity;
using Azure.Core;
namespace SftpWatcher
{
// Checks the list of files in an SFTP folder and emits events for newly added, removed and modified files.
public abstract class SftpWatcherEntity : ISftpWatcherEntity
{
public IDictionary<string, DateTime> files { get; set; }
public string error { get; set; }
// Does the actual job
public void Watch(string folderFullPath)
{
bool isFirstRun = this.files == null;
if (isFirstRun)
{
this.files = new Dictionary<string, DateTime>();
}
this.error = string.Empty;
try
{
// Intentionally NOT passing any creds via parameters or entity state. Don't want them to be stored anywhere.
this.GetParams(folderFullPath, out var serverName, out var folderName, out var fileMask, out var userName, out var password);
string timeoutString = Environment.GetEnvironmentVariable("SFTP_TIMEOUT_IN_SECONDS");
var timeout = TimeSpan.FromSeconds(string.IsNullOrEmpty(timeoutString) ? 5 : int.Parse(timeoutString));
using (var client = new SftpClient(serverName, userName, password))
{
// Not sure which one to set, so setting both
client.ConnectionInfo.Timeout = timeout;
client.OperationTimeout = timeout;
client.Connect();
var maskRegex = new Regex(Regex.Escape(fileMask).Replace("\\*", ".+"));
var newFiles = ListFilesInFolder(client, folderName, maskRegex);
// Emitting events
if (!isFirstRun || string.IsNullOrEmpty(Environment.GetEnvironmentVariable("STAY_SILENT_AT_FIRST_RUN")))
{
this.EmitEvents(serverName, this.files, newFiles);
}
// Updating our state
this.files = newFiles;
}
}
catch (Exception ex)
{
this.error = ex.Message;
}
}
protected abstract void EmitEvent(WhatHappenedEnum eventType, string filePath);
private void EmitEvents(string serverName, IDictionary<string, DateTime> existingFiles, IDictionary<string, DateTime> newFiles)
{
foreach (var kv in existingFiles)
{
if (!newFiles.ContainsKey(kv.Key))
{
this.EmitEvent(WhatHappenedEnum.FileRemoved, serverName + kv.Key);
}
}
foreach (var kv in newFiles)
{
if (!existingFiles.ContainsKey(kv.Key))
{
this.EmitEvent(WhatHappenedEnum.FileAdded, serverName + kv.Key);
}
else if (existingFiles[kv.Key] != kv.Value)
{
this.EmitEvent(WhatHappenedEnum.FileModified, serverName + kv.Key);
}
}
}
private void GetParams(string folderFullPath,
out string serverName,
out string folderName,
out string fileMask,
out string userName,
out string password)
{
int slashPos = folderFullPath.LastIndexOf('/');
if (slashPos < 0)
{
serverName = folderFullPath;
fileMask = "*.*";
}
else
{
serverName = folderFullPath.Substring(0, slashPos);
fileMask = folderFullPath.Substring(slashPos + 1);
}
slashPos = serverName.IndexOf('/');
if (slashPos < 0)
{
folderName = string.Empty;
}
else
{
folderName = serverName.Substring(slashPos + 1);
serverName = serverName.Substring(0, slashPos);
}
dynamic folderParams = JObject.Parse(Environment.GetEnvironmentVariable("FOLDERS_TO_WATCH"))[folderFullPath];
userName = ((JToken)folderParams).First.ToObject<JProperty>().Name;
password = folderParams[userName];
password = GetFromKeyVaultIfNeeded(password);
}
private static IDictionary<string, DateTime> ListFilesInFolder(SftpClient client, string folderName, Regex maskRegex)
{
var result = new Dictionary<string, DateTime>();
foreach (var item in client.ListDirectory(folderName))
{
if (item.IsDirectory)
{
if (item.Name == "." || item.Name == "..")
{
continue;
}
foreach (var kv in ListFilesInFolder(client, folderName + "/" + item.Name, maskRegex))
{
result[kv.Key] = kv.Value;
}
}
if (maskRegex.IsMatch(item.Name))
{
result[item.FullName] = item.LastWriteTime;
}
}
return result;
}
private const string KeyVaultUrlPart = ".vault.azure.net/secrets/";
private static string GetFromKeyVaultIfNeeded(string secret)
{
if (!secret.Contains(KeyVaultUrlPart))
{
return secret;
}
string accessToken = new DefaultAzureCredential()
.GetTokenAsync(new TokenRequestContext(new [] { "https://vault.azure.net" } ))
.Result
.Token;
// Taking the secret out of KeyVault
using (var client = new WebClient())
{
client.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {accessToken}");
string response = client.DownloadString($"{secret}?api-version=2016-10-01");
return ((dynamic)JsonConvert.DeserializeObject(response)).value;
}
}
}
// Watcher entity's interface
public interface ISftpWatcherEntity
{
void Watch(string folderFullPath);
}
public enum WhatHappenedEnum
{
FileAdded,
FileRemoved,
FileModified
}
}