-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathngrok.rs
More file actions
308 lines (253 loc) · 10.4 KB
/
ngrok.rs
File metadata and controls
308 lines (253 loc) · 10.4 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use std::time::Duration;
use anyhow::Context as _;
use async_trait::async_trait;
use devolutions_gateway_task::{ChildTask, ShutdownSignal, Task};
use futures::TryStreamExt as _;
use ngrok::config::{HttpTunnelBuilder, TcpTunnelBuilder, TunnelBuilder as _};
use ngrok::conn::ConnInfo as _;
use ngrok::tunnel::EndpointInfo as _;
use tracing::Instrument as _;
use crate::config::dto::{NgrokConf, NgrokTunnelConf};
use crate::generic_client::GenericClient;
use crate::DgwState;
#[derive(Clone)]
pub struct NgrokSession {
inner: ngrok::Session,
}
impl NgrokSession {
pub async fn connect(conf: &NgrokConf) -> anyhow::Result<Self> {
let mut builder = ngrok::Session::builder();
builder.authtoken(&conf.auth_token);
if let Some(heartbeat_interval) = conf.heartbeat_interval {
builder
.heartbeat_interval(Duration::from_secs(heartbeat_interval))
.context("set heartbeat interval")?;
}
if let Some(heartbeat_tolerance) = conf.heartbeat_tolerance {
builder
.heartbeat_tolerance(Duration::from_secs(heartbeat_tolerance))
.context("set heartbeat tolerence")?;
}
if let Some(metadata) = &conf.metadata {
builder.metadata(metadata);
}
if let Some(server_addr) = &conf.server_addr {
builder.server_addr(server_addr).context("set server address")?;
}
info!("Connecting to ngrok service");
// Connect the ngrok session
let session = builder.connect().await.context("connect to ngrok service")?;
debug!("Connected with success");
Ok(Self { inner: session })
}
// FIXME: Make this function non-async again when the ngrok UX issue is fixed.
pub async fn configure_endpoint(&self, name: &str, conf: &NgrokTunnelConf) -> NgrokTunnel {
use ngrok::config::Scheme;
match conf {
NgrokTunnelConf::Tcp(tcp_conf) => {
let mut builder = self.inner.tcp_endpoint();
builder.remote_addr(&tcp_conf.remote_addr);
if let Some(metadata) = &tcp_conf.metadata {
builder.metadata(metadata);
}
let before_cidrs = builder.clone();
tcp_conf.allow_cidrs.iter().for_each(|cidr| {
builder.allow_cidr(cidr);
});
tcp_conf.deny_cidrs.iter().for_each(|cidr| {
builder.deny_cidr(cidr);
});
// HACK: Find the subscription plan. This uses ngrok-rs internal API, so it’s not great.
// Ideally, we could use the `Session` to find out about the subscription plan without dirty tricks.
match builder
.clone()
.forwards_to("Devolutions Gateway Subscription probe")
.listen()
.await
{
// https://ngrok.com/docs/errors/err_ngrok_9017/
// "Your account is not authorized to use ip restrictions."
Err(ngrok::session::RpcError::Response(e))
if e.error_code.as_deref() == Some("ERR_NGROK_9017")
|| e.error_code.as_deref() == Some("9017") =>
{
info!(
address = tcp_conf.remote_addr,
"Detected a ngrok free plan subscription. IP restriction rules are disabled."
);
// Revert the builder to before applying the CIDR rules.
builder = before_cidrs;
}
_ => {}
}
NgrokTunnel {
name: name.to_owned(),
inner: NgrokTunnelInner::Tcp(builder),
}
}
NgrokTunnelConf::Http(http_conf) => {
let mut builder = self.inner.http_endpoint();
builder.domain(&http_conf.domain).scheme(Scheme::HTTPS);
if let Some(metadata) = &http_conf.metadata {
builder.metadata(metadata);
}
if let Some(circuit_breaker) = http_conf.circuit_breaker {
builder.circuit_breaker(circuit_breaker);
}
if matches!(http_conf.compression, Some(true)) {
builder.compression();
}
let before_cidrs = builder.clone();
http_conf.allow_cidrs.iter().for_each(|cidr| {
builder.allow_cidr(cidr);
});
http_conf.deny_cidrs.iter().for_each(|cidr| {
builder.deny_cidr(cidr);
});
// HACK: Find the subscription plan. This uses ngrok-rs internal API, so it’s not great.
// Ideally, we could use the `Session` to find out about the subscription plan without dirty tricks.
match builder
.clone()
.forwards_to("Devolutions Gateway Subscription probe")
.listen()
.await
{
// https://ngrok.com/docs/errors/err_ngrok_9017/
// "Your account is not authorized to use ip restrictions."
Err(ngrok::session::RpcError::Response(e))
if e.error_code.as_deref() == Some("ERR_NGROK_9017")
|| e.error_code.as_deref() == Some("9017") =>
{
info!(
domain = http_conf.domain,
"Detected a ngrok free plan subscription. IP restriction rules are disabled."
);
// Revert the builder to before applying the CIDR rules.
builder = before_cidrs;
}
_ => {}
}
NgrokTunnel {
name: name.to_owned(),
inner: NgrokTunnelInner::Http(builder),
}
}
}
}
}
// fn handle_http_tunnel(mut tunnel: impl UrlTunnel, ) ->
pub struct NgrokTunnel {
name: String,
inner: NgrokTunnelInner,
}
enum NgrokTunnelInner {
Tcp(TcpTunnelBuilder),
Http(HttpTunnelBuilder),
}
impl NgrokTunnel {
pub async fn open(self, state: DgwState) -> anyhow::Result<()> {
info!(name = self.name, "Open ngrok tunnel…");
let hostname = state.conf_handle.get_conf().hostname.clone();
match self.inner {
NgrokTunnelInner::Tcp(mut builder) => {
// Start tunnel with a TCP edge
let tunnel = builder
.forwards_to(hostname)
.listen()
.await
.context("TCP tunnel listen")?;
debug!(url = tunnel.url(), "Bound TCP ngrok tunnel");
run_tcp_tunnel(tunnel, state).await;
}
NgrokTunnelInner::Http(mut builder) => {
// Start tunnel with an HTTP edge
let tunnel = builder
.forwards_to(hostname)
.listen()
.await
.context("HTTP tunnel listen")?;
debug!(url = tunnel.url(), "Bound HTTP ngrok tunnel");
run_http_tunnel(tunnel, state).await;
}
}
Ok(())
}
}
async fn run_tcp_tunnel(mut tunnel: ngrok::tunnel::TcpTunnel, state: DgwState) {
info!(url = tunnel.url(), "TCP ngrok tunnel started");
loop {
match tunnel.try_next().await {
Ok(Some(conn)) => {
let state = state.clone();
let peer_addr = conn.remote_addr();
let fut = async move {
if let Err(e) = GenericClient::builder()
.conf(state.conf_handle.get_conf())
.client_addr(peer_addr)
.client_stream(conn)
.token_cache(state.token_cache)
.jrl(state.jrl)
.sessions(state.sessions)
.subscriber_tx(state.subscriber_tx)
.active_recordings(state.recordings.active_recordings)
.credential_store(state.credential_store)
.build()
.serve()
.await
{
error!(error = format!("{e:#}"), "handle_tcp_peer failed");
}
}
.instrument(info_span!("ngrok_tcp", client = %peer_addr));
ChildTask::spawn(fut).detach();
}
Ok(None) => {
info!(url = tunnel.url(), "Tunnel closed");
break;
}
Err(error) => {
error!(url = tunnel.url(), %error, "Failed to accept connection");
}
}
}
}
async fn run_http_tunnel(mut tunnel: ngrok::tunnel::HttpTunnel, state: DgwState) {
info!(url = tunnel.url(), "HTTP ngrok tunnel started");
loop {
match tunnel.try_next().await {
Ok(Some(conn)) => {
let state = state.clone();
let peer_addr = conn.remote_addr();
let fut = async move {
if let Err(e) = crate::listener::handle_http_peer(conn, state, peer_addr).await {
error!(error = format!("{e:#}"), "handle_http_peer failed");
}
}
.instrument(info_span!("ngrok_http", client = %peer_addr));
ChildTask::spawn(fut).detach();
}
Ok(None) => {
info!(url = tunnel.url(), "Tunnel closed");
break;
}
Err(error) => {
error!(url = tunnel.url(), %error, "Failed to accept connection");
}
}
}
}
pub struct NgrokTunnelTask {
pub tunnel: NgrokTunnel,
pub state: DgwState,
}
#[async_trait]
impl Task for NgrokTunnelTask {
type Output = anyhow::Result<()>;
const NAME: &'static str = "ngrok tunnel";
async fn run(self, mut shutdown_signal: ShutdownSignal) -> Self::Output {
tokio::select! {
result = self.tunnel.open(self.state) => result,
_ = shutdown_signal.wait() => Ok(()),
}
}
}