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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
//! The `access` subcommand: configure a site's visitor access control —
//! HTTP Basic auth, IP allow/deny, rate limiting, and trusted proxies. Edits
//! the site's `SiteConfig.access` via the control-plane API.
use std::io::Read;
use boatramp_core::access::{BasicAuth, RateLimit};
use clap::Subcommand;
use crate::client;
use crate::config::ProjectConfig;
/// A failure in the `access` subcommand.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// A Basic-auth password was empty.
#[error("empty password")]
EmptyPassword,
/// The rate-limit value was not greater than zero.
#[error("rps must be > 0")]
RpsZero,
/// Resolving the target or talking to the control plane failed.
#[error(transparent)]
Client(#[from] crate::client::ClientError),
/// Reading the password from stdin failed.
#[error(transparent)]
Io(#[from] std::io::Error),
}
/// `access` module result; `Err` is [`Error`].
type Result<T> = std::result::Result<T, Error>;
/// Arguments for `boatramp access`.
#[derive(Debug, clap::Args)]
pub struct AccessArgs {
/// boatramp server base URL (overrides [deploy].server).
#[arg(long, env = "BOATRAMP_SERVER", global = true)]
server: Option<String>,
/// Site to edit (overrides [deploy].site).
#[arg(long, env = "BOATRAMP_SITE", global = true)]
site: Option<String>,
#[command(subcommand)]
command: AccessCommand,
}
#[derive(Debug, Subcommand)]
enum AccessCommand {
/// Show the site's current access-control policy.
Show,
/// Manage HTTP Basic auth credentials.
BasicAuth {
#[command(subcommand)]
command: BasicAuthCommand,
},
/// Manage IP allow/deny rules (CIDR or bare address).
Ip {
#[command(subcommand)]
command: IpCommand,
},
/// Configure per-client rate limiting.
RateLimit {
#[command(subcommand)]
command: RateLimitCommand,
},
/// Manage trusted reverse-proxy CIDRs (for `X-Forwarded-For` trust).
TrustedProxy {
#[command(subcommand)]
command: TrustedProxyCommand,
},
/// Configure the built-in WAF (user-agent rules + anomaly scoring).
Waf {
#[command(subcommand)]
command: WafCommand,
},
}
#[derive(Debug, Subcommand)]
enum WafCommand {
/// Enable user-agent filtering, optionally setting the deny/allow lists
/// (`--deny`/`--allow` **replace** the respective list when given).
UserAgent {
/// A user-agent substring/pattern to deny; repeatable.
#[arg(long = "deny", value_name = "PATTERN")]
deny: Vec<String>,
/// A user-agent substring/pattern to always allow; repeatable.
#[arg(long = "allow", value_name = "PATTERN")]
allow: Vec<String>,
},
/// Disable user-agent filtering.
UserAgentOff,
/// Enable heuristic anomaly scoring, optionally setting the block threshold.
Anomaly {
/// Score at or above which a request is blocked.
#[arg(long)]
threshold: Option<u32>,
},
/// Disable anomaly scoring.
AnomalyOff,
}
#[derive(Debug, Subcommand)]
enum BasicAuthCommand {
/// Add or update a user. Password from `--password`, else read from stdin.
Add {
/// Username.
user: String,
/// Password (omit to read one line from stdin, e.g. via a pipe).
#[arg(long)]
password: Option<String>,
/// Realm shown in the browser prompt.
#[arg(long)]
realm: Option<String>,
},
/// Remove a user.
Rm {
/// Username to remove.
user: String,
},
/// Disable Basic auth entirely (remove all credentials).
Clear,
}
#[derive(Debug, Subcommand)]
enum IpCommand {
/// Add an allow rule (only listed clients may connect).
Allow {
/// CIDR or bare IP.
cidr: String,
},
/// Add a deny rule (deny wins over allow).
Deny {
/// CIDR or bare IP.
cidr: String,
},
/// Remove all IP rules.
Clear,
}
#[derive(Debug, Subcommand)]
enum RateLimitCommand {
/// Set the per-client limit (requests/second + optional burst).
Set {
/// Sustained requests per second.
rps: u32,
/// Burst capacity (defaults to `rps`).
#[arg(long)]
burst: Option<u32>,
},
/// Disable rate limiting.
Off,
}
#[derive(Debug, Subcommand)]
enum TrustedProxyCommand {
/// Trust a reverse proxy by CIDR (so its `X-Forwarded-For` is believed).
Add {
/// CIDR or bare IP.
cidr: String,
},
/// Remove all trusted proxies.
Clear,
}
/// Entry point for `boatramp access`.
pub async fn run(args: AccessArgs, config: &ProjectConfig) -> Result<()> {
let (server, site) = client::resolve_target(args.server, args.site, config)?;
let cp = client::ControlPlane::new(
server,
client::http_client(client::token(config).as_deref()),
client::resolve_project(config),
);
let mut site_config = cp.fetch_site_config(&site).await?;
let access = &mut site_config.access;
match args.command {
AccessCommand::Show => {
print_access(&site_config.access);
return Ok(());
}
AccessCommand::BasicAuth { command } => match command {
BasicAuthCommand::Add {
user,
password,
realm,
} => {
let password = match password {
Some(p) => p,
None => read_stdin_line()?,
};
if password.is_empty() {
return Err(Error::EmptyPassword);
}
let hash = boatramp_core::access::hash_password(&password);
let basic = access.basic_auth.get_or_insert_with(|| BasicAuth {
realm: "Restricted".to_string(),
users: Default::default(),
});
if let Some(realm) = realm {
basic.realm = realm;
}
basic.users.insert(user.clone(), hash);
println!("added basic-auth user {user} to {site}");
}
BasicAuthCommand::Rm { user } => {
if let Some(basic) = &mut access.basic_auth {
basic.users.remove(&user);
if basic.users.is_empty() {
access.basic_auth = None;
}
}
println!("removed basic-auth user {user} from {site}");
}
BasicAuthCommand::Clear => {
access.basic_auth = None;
println!("disabled basic auth for {site}");
}
},
AccessCommand::Ip { command } => match command {
IpCommand::Allow { cidr } => {
push_unique(&mut access.ip.allow, &cidr);
println!("allow {cidr} on {site}");
}
IpCommand::Deny { cidr } => {
push_unique(&mut access.ip.deny, &cidr);
println!("deny {cidr} on {site}");
}
IpCommand::Clear => {
access.ip.allow.clear();
access.ip.deny.clear();
println!("cleared IP rules for {site}");
}
},
AccessCommand::RateLimit { command } => match command {
RateLimitCommand::Set { rps, burst } => {
if rps == 0 {
return Err(Error::RpsZero);
}
access.rate_limit = Some(RateLimit {
rps,
burst: burst.unwrap_or(0),
});
println!(
"rate limit {rps} req/s (burst {}) on {site}",
burst.unwrap_or(rps)
);
}
RateLimitCommand::Off => {
access.rate_limit = None;
println!("disabled rate limiting for {site}");
}
},
AccessCommand::TrustedProxy { command } => match command {
TrustedProxyCommand::Add { cidr } => {
push_unique(&mut access.trusted_proxies, &cidr);
println!("trust proxy {cidr} on {site}");
}
TrustedProxyCommand::Clear => {
access.trusted_proxies.clear();
println!("cleared trusted proxies for {site}");
}
},
AccessCommand::Waf { command } => match command {
WafCommand::UserAgent { deny, allow } => {
access.waf.user_agent.enabled = true;
if !deny.is_empty() {
access.waf.user_agent.deny = deny;
}
if !allow.is_empty() {
access.waf.user_agent.allow = allow;
}
println!("waf: user-agent filtering enabled for {site}");
}
WafCommand::UserAgentOff => {
access.waf.user_agent.enabled = false;
println!("waf: user-agent filtering disabled for {site}");
}
WafCommand::Anomaly { threshold } => {
access.waf.anomaly.enabled = true;
if let Some(t) = threshold {
access.waf.anomaly.threshold = t;
}
println!(
"waf: anomaly scoring enabled for {site} (threshold {})",
access.waf.anomaly.threshold
);
}
WafCommand::AnomalyOff => {
access.waf.anomaly.enabled = false;
println!("waf: anomaly scoring disabled for {site}");
}
},
}
cp.put_site_config(&site, &site_config).await?;
Ok(())
}
/// Append `value` if not already present.
fn push_unique(list: &mut Vec<String>, value: &str) {
if !list.iter().any(|existing| existing == value) {
list.push(value.to_string());
}
}
/// Read a single trimmed line (or piped content) from stdin.
fn read_stdin_line() -> Result<String> {
let mut buf = String::new();
std::io::stdin().read_to_string(&mut buf)?;
Ok(buf.trim().to_string())
}
/// Print a human-readable summary of an access policy.
fn print_access(access: &boatramp_core::access::AccessConfig) {
if !access.is_enforced() && access.trusted_proxies.is_empty() {
println!("no access control configured");
return;
}
if let Some(basic) = &access.basic_auth {
let users: Vec<&str> = basic.users.keys().map(String::as_str).collect();
println!(
"basic-auth realm \"{}\", users: {}",
basic.realm,
users.join(", ")
);
}
if !access.ip.allow.is_empty() {
println!("ip allow {}", access.ip.allow.join(", "));
}
if !access.ip.deny.is_empty() {
println!("ip deny {}", access.ip.deny.join(", "));
}
if let Some(rl) = &access.rate_limit {
println!(
"rate limit {} req/s, burst {}",
rl.rps,
rl.burst_capacity()
);
}
if !access.trusted_proxies.is_empty() {
println!("trusted px {}", access.trusted_proxies.join(", "));
}
}