-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patherror.rs
More file actions
542 lines (435 loc) · 18.6 KB
/
error.rs
File metadata and controls
542 lines (435 loc) · 18.6 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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use crate::{postgresql::Column, Identifier};
use bytes::BytesMut;
use cipherstash_client::{encryption, schema::ColumnType};
use eql_mapper::{EqlMapperError, EqlTermVariant};
use metrics_exporter_prometheus::BuildError;
use std::{io, time::Duration};
use thiserror::Error;
const ERROR_DOC_BASE_URL: &str = "https://github.com/cipherstash/proxy/blob/main/docs/errors.md";
const ERROR_DOC_CONFIG_URL: &str =
"https://github.com/cipherstash/proxy/blob/main/docs/how-to/index.md#configuring-proxy";
#[derive(Error, Debug)]
pub enum Error {
#[error("Connection closed after cancel request")]
CancelRequest,
#[error(transparent)]
Config(#[from] ConfigError),
#[error(transparent)]
Context(#[from] ContextError),
#[error("Connection closed by client")]
ConnectionClosed,
#[error("Connection timed out after {} ms", duration.as_millis())]
ConnectionTimeout { duration: Duration },
#[error("Error creating connection")]
DatabaseConnection,
#[error(transparent)]
Encrypt(#[from] EncryptError),
#[error(transparent)]
Io(io::Error),
#[error(transparent)]
Mapping(#[from] MappingError),
#[error(transparent)]
Prometheus(#[from] BuildError),
#[error(transparent)]
Protocol(#[from] ProtocolError),
#[error(transparent)]
Tls(#[from] rustls::Error),
#[error(transparent)]
ZeroKMS(#[from] ZeroKMSError),
#[error("Unknown error")]
Unknown,
#[error(transparent)]
SendError(#[from] tokio::sync::mpsc::error::SendError<BytesMut>),
}
#[derive(Error, Debug)]
pub enum ContextError {
#[error("Portal could not be found in context")]
UnknownPortal,
}
#[derive(Error, Debug)]
pub enum ZeroKMSError {
#[error("ZeroKMS authentication failed. Check the configured credentials. For help visit {}#zerokms-authentication-failed", ERROR_DOC_BASE_URL)]
AuthenticationFailed,
#[error(transparent)]
Builder(#[from] cipherstash_client::zerokms::ZeroKMSBuilderError),
#[error(transparent)]
System(#[from] cipherstash_client::zerokms::Error),
}
#[derive(Error, Debug)]
pub enum MappingError {
#[error("Invalid parameter for column '{}' of type '{}' in table '{}' (OID {}). For help visit {}#mapping-invalid-parameter",
_0.column_name(), _0.cast_type(), _0.table_name(), _0.oid(), ERROR_DOC_BASE_URL)]
InvalidParameter(Box<Column>),
#[error(
"{}. For help visit {}#mapping-invalid-sql-statement",
_0,
ERROR_DOC_BASE_URL
)]
InvalidSqlStatement(String),
#[error("Encryption of EQL column {column_type} using strategy {eql_term} is not supported. For help visit {}#mapping-unsupported-parameter-type", ERROR_DOC_BASE_URL)]
UnsupportedParameterType {
eql_term: EqlTermVariant,
column_type: ColumnType,
},
#[error("Statement could not be type checked: {}. For help visit {}#mapping-statement-could-not-be-type-checked", _0, ERROR_DOC_BASE_URL)]
StatementCouldNotBeTypeChecked(String),
#[error("Statement could not be transformed: {0}")]
StatementCouldNotBeTransformed(String),
#[error("Could not parse parameter")]
CouldNotParseParameter,
#[error("Statement encountered an internal error. This may be a bug in the statement mapping module of CipherStash Proxy. Please visit {}#mapping-internal-error for more information.", ERROR_DOC_BASE_URL)]
Internal(String),
#[error(transparent)]
EqlMapper(#[from] EqlMapperError),
}
#[derive(Error, Debug)]
pub enum ConfigError {
#[error(transparent)]
Certificate(#[from] rustls_pki_types::pem::Error),
#[error(transparent)]
Database(#[from] tokio_postgres::Error),
#[error(transparent)]
FileOrEnvironment(#[from] config::ConfigError),
#[error("Client key is not valid. For help visit {}", ERROR_DOC_CONFIG_URL)]
InvalidClientKey,
#[error(
"default_keyset_id is not a valid UUID. For help visit {}",
ERROR_DOC_CONFIG_URL
)]
InvalidDefaultKeysetId,
#[error("Server host {name} is not a valid server name")]
InvalidServerName { name: String },
#[error("Invalid {name}: {value}")]
InvalidParameter { name: String, value: String },
#[error(
"Invalid Workspace CRN: {crn}. CRN format is `crn:{{region}}.aws:{{workspace_id}}` For help visit {}",
ERROR_DOC_CONFIG_URL
)]
InvalidWorkspaceCrn { crn: String },
#[error("Missing an active Encrypt configuration")]
MissingActiveEncryptConfig,
#[error(
"Missing {field} from [{key}] configuration. For help visit {}",
ERROR_DOC_CONFIG_URL
)]
MissingFieldForKey { field: String, key: String },
#[error(
"Missing {field} from configuration. For help visit {}",
ERROR_DOC_CONFIG_URL
)]
MissingField { field: String },
#[error(
"Missing [auth] configuration. Check that workspace_id and client_access_key are defined. For help visit {}",
ERROR_DOC_CONFIG_URL
)]
MissingAuthKey,
#[error(
"Missing [encrypt] configuration. Check that client_id, client_key, and default_keyset_id are defined. For help visit {}",
ERROR_DOC_CONFIG_URL
)]
MissingEncryptKey,
#[error(
"Missing [database] configuration. Check that username, password, and name are defined. For help visit {}",
ERROR_DOC_CONFIG_URL
)]
MissingDatabaseKey,
#[error("Expected an Encrypt configuration table")]
MissingEncryptConfigTable,
#[error("Network configuration change requires restart For help visit {}#config-network-change-requires-restart", ERROR_DOC_BASE_URL)]
NetworkConfigurationChangeRequiresRestart,
#[error(transparent)]
Parse(#[from] serde_json::Error),
#[error("Database schema could not be loaded")]
SchemaCouldNotBeLoaded,
#[error("Client must connect with Transport Layer Security (TLS)")]
TlsRequired,
#[error(transparent)]
TlsConfigError(#[from] TlsConfigError),
}
#[derive(Error, Debug)]
pub enum TlsConfigError {
#[error(
"Invalid Transport Layer Security (TLS) certificate. For help visit {}#config-missing-or-invalid-tls",
ERROR_DOC_BASE_URL
)]
InvalidCertificate,
#[error(
"Invalid Transport Layer Security (TLS) private key. For help visit {}#config-missing-or-invalid-tls",
ERROR_DOC_BASE_URL
)]
InvalidPrivateKey,
#[error(
"Missing Transport Layer Security (TLS) certificate at path: {path}. For help visit {}#config-missing-or-invalid-tls",
ERROR_DOC_BASE_URL
)]
MissingCertificate { path: String },
#[error(
"Missing Transport Layer Security (TLS) private key at path: {path}. For help visit {}#config-missing-or-invalid-tls",
ERROR_DOC_BASE_URL
)]
MissingPrivateKey { path: String },
}
#[derive(Error, Debug)]
pub enum EncryptError {
#[error(transparent)]
CiphertextCouldNotBeSerialised(#[from] serde_json::Error),
#[error("Encrypted column could not be parsed")]
ColumnCouldNotBeParsed,
#[error("Encrypted column is null")]
ColumnIsNull,
#[error("Column '{column}' in table '{table}' could not be deserialised. For help visit {}#encrypt-column-could-not-be-deserialised", ERROR_DOC_BASE_URL)]
ColumnCouldNotBeDeserialised { table: String, column: String },
#[error("Column '{column}' in table '{table}' could not be encrypted. For help visit {}#encrypt-column-could-not-be-encrypted", ERROR_DOC_BASE_URL)]
ColumnCouldNotBeEncrypted { table: String, column: String },
#[error("Column configuration for column '{column}' in table '{table}' does not match the encrypted column. For help visit {}#encrypt-column-config-mismatch", ERROR_DOC_BASE_URL)]
ColumnConfigurationMismatch { table: String, column: String },
#[error(
"Could not decrypt data using keyset '{keyset_id}'. For help visit {}#encrypt-could-not-decrypt-data-for-keyset",
ERROR_DOC_BASE_URL
)]
CouldNotDecryptDataForKeyset { keyset_id: String },
#[error("InvalidIndexTerm")]
InvalidIndexTerm,
#[error(
"KeysetId `{id}` could not be parsed using `SET CIPHERSTASH.KEYSET_ID`. KeysetId should be a valid UUID. For help visit {}#encrypt-keyset-id-could-not-be-parsed",
ERROR_DOC_BASE_URL
)]
KeysetIdCouldNotBeParsed { id: String },
#[error(
"Keyset Id could not be set using `SET CIPHERSTASH.KEYSET_ID`. For help visit {}#encrypt-keyset-id-could-not-be-set",
ERROR_DOC_BASE_URL
)]
KeysetIdCouldNotBeSet,
#[error(
"Keyset Name could not be set using `SET CIPHERSTASH.KEYSET_NAME`. For help visit {}#encrypt-keyset-name-could-not-be-set",
ERROR_DOC_BASE_URL
)]
KeysetNameCouldNotBeSet,
/// This should in practice be unreachable
#[error("Missing encrypt configuration for column type `{plaintext_type}`. For help visit {}#encrypt-missing-encrypt-configuration", ERROR_DOC_BASE_URL)]
MissingEncryptConfiguration { plaintext_type: &'static str },
#[error("Decrypted column could not be encoded as the expected type. For help visit {}#encrypt-plaintext-could-not-be-encoded", ERROR_DOC_BASE_URL)]
PlaintextCouldNotBeEncoded,
#[error(transparent)]
Pipeline(#[from] encryption::EncryptionError),
#[error(transparent)]
PlaintextCouldNotBeDecoded(#[from] cipherstash_client::encryption::TypeParseError),
#[error("Missing keyset identifer.")]
MissingKeysetIdentifier,
#[error(
"Cannot SET CIPHERSTASH.KEYSET if a default keyset has been configured. For help visit {}#encrypt-unexpected-set-keyset",
ERROR_DOC_BASE_URL
)]
UnexpectedSetKeyset,
#[error(
"Column '{column}' in table '{table}' has no Encrypt configuration. For help visit {}#encrypt-unknown-column",
ERROR_DOC_BASE_URL
)]
UnknownColumn { table: String, column: String },
#[error(
"Unknown keyset name or id '{keyset}'. Check the configured credentials. For help visit {}#encrypt-unknown-keyset",
ERROR_DOC_BASE_URL
)]
UnknownKeysetIdentifier { keyset: String },
#[error(
"Table '{table}' has no Encrypt configuration. For help visit {}#encrypt-unknown-table",
ERROR_DOC_BASE_URL
)]
UnknownTable { table: String },
#[error("Unknown Index Term for column '{}' in table '{}'. For help visit {}#encrypt-unknown-index-term", _0.column(), _0.table(), ERROR_DOC_BASE_URL)]
UnknownIndexTerm(Identifier),
#[error("ZeroKMS error: `{}`", _0)]
ZeroKMS(String),
}
// This impl is very boilerplatey but we can't simply re-export the `cipherstash-client` version of the error
// because Proxy currently manages the documentation links.
impl From<cipherstash_client::eql::EqlError> for EncryptError {
fn from(value: cipherstash_client::eql::EqlError) -> Self {
match value {
cipherstash_client::eql::EqlError::CiphertextCouldNotBeSerialised(error) => {
Self::CiphertextCouldNotBeSerialised(error)
}
cipherstash_client::eql::EqlError::ColumnCouldNotBeParsed => {
Self::ColumnCouldNotBeParsed
}
cipherstash_client::eql::EqlError::ColumnIsNull => Self::ColumnIsNull,
cipherstash_client::eql::EqlError::ColumnCouldNotBeDeserialised { table, column } => {
Self::ColumnCouldNotBeDeserialised { table, column }
}
cipherstash_client::eql::EqlError::ColumnCouldNotBeEncrypted { table, column } => {
Self::ColumnCouldNotBeEncrypted { table, column }
}
cipherstash_client::eql::EqlError::ColumnConfigurationMismatch { table, column } => {
Self::ColumnConfigurationMismatch { table, column }
}
cipherstash_client::eql::EqlError::CouldNotDecryptDataForKeyset { keyset_id } => {
Self::CouldNotDecryptDataForKeyset { keyset_id }
}
cipherstash_client::eql::EqlError::InvalidIndexTerm => Self::InvalidIndexTerm,
cipherstash_client::eql::EqlError::MissingCiphertext(identifier) => {
Self::ColumnCouldNotBeDeserialised {
table: identifier.table,
column: identifier.column,
}
}
cipherstash_client::eql::EqlError::KeysetIdCouldNotBeParsed { id } => {
Self::KeysetIdCouldNotBeParsed { id }
}
cipherstash_client::eql::EqlError::KeysetIdCouldNotBeSet => Self::KeysetIdCouldNotBeSet,
cipherstash_client::eql::EqlError::KeysetNameCouldNotBeSet => {
Self::KeysetNameCouldNotBeSet
}
cipherstash_client::eql::EqlError::MissingEncryptConfiguration { plaintext_type } => {
Self::MissingEncryptConfiguration { plaintext_type }
}
cipherstash_client::eql::EqlError::PlaintextCouldNotBeEncoded => {
Self::PlaintextCouldNotBeEncoded
}
cipherstash_client::eql::EqlError::Pipeline(encryption_error) => {
Self::Pipeline(encryption_error)
}
cipherstash_client::eql::EqlError::PlaintextCouldNotBeDecoded(type_parse_error) => {
Self::PlaintextCouldNotBeDecoded(type_parse_error)
}
cipherstash_client::eql::EqlError::MissingKeysetIdentifier => {
Self::MissingKeysetIdentifier
}
cipherstash_client::eql::EqlError::UnexpectedSetKeyset => Self::UnexpectedSetKeyset,
cipherstash_client::eql::EqlError::UnknownColumn { table, column } => {
Self::UnknownColumn { table, column }
}
cipherstash_client::eql::EqlError::UnknownKeysetIdentifier { keyset } => {
Self::UnknownKeysetIdentifier { keyset }
}
cipherstash_client::eql::EqlError::UnknownTable { table } => {
Self::UnknownTable { table }
}
cipherstash_client::eql::EqlError::UnknownIndexTerm(identifier) => {
Self::UnknownIndexTerm(identifier)
}
cipherstash_client::eql::EqlError::ZeroKMS(err) => Self::ZeroKMS(err.to_string()),
cipherstash_client::eql::EqlError::RecordDecrypt(err) => Self::ZeroKMS(err.to_string()),
}
}
}
#[derive(Error, Debug)]
pub enum ProtocolError {
#[error("Database authentication failed. Check username and password. For help visit {}#authentication-failed-database", ERROR_DOC_BASE_URL)]
AuthenticationFailed,
#[error("Client authentication failed. Check username and password. For help visit {}#authentication-failed-client", ERROR_DOC_BASE_URL)]
ClientAuthenticationFailed,
#[error("Expected {expected} parameter format codes, received {received}")]
ParameterFormatCodesMismatch { expected: usize, received: usize },
#[error("Expected {expected} parameter format codes, received {received}")]
ParameterResultFormatCodesMismatch { expected: usize, received: usize },
#[error("Expected a {expected} message, received message code {received}")]
UnexpectedAuthenticationResponse { expected: String, received: i32 },
#[error("Expected {expected} message code, received {received}")]
UnexpectedMessageCode { expected: char, received: char },
#[error("Unexpected message length {len} for code {code}")]
UnexpectedMessageLength { code: u8, len: usize },
#[error("Unexpected null in string")]
UnexpectedNull,
#[error("Unexpected target {_0}")]
UnexpectedDescribeTarget(char),
#[error("Unexpected SASL authentication method {_0}")]
UnexpectedSaslAuthenticationMethod(String),
#[error("Unexpected SSLRequest")]
UnexpectedSSLRequest,
#[error("Expected a TLS connection")]
UnexpectedSSLResponse,
#[error("Unexpected StartupMessage")]
UnexpectedStartupMessage,
#[error("Unsupported authentication method {method_code}")]
UnsupportedAuthentication { method_code: i32 },
}
impl From<config::ConfigError> for Error {
fn from(e: config::ConfigError) -> Self {
Error::Config(e.into())
}
}
impl From<cipherstash_client::zerokms::ZeroKMSBuilderError> for Error {
fn from(e: cipherstash_client::zerokms::ZeroKMSBuilderError) -> Self {
Error::ZeroKMS(e.into())
}
}
impl From<cipherstash_client::encryption::TypeParseError> for Error {
fn from(e: cipherstash_client::encryption::TypeParseError) -> Self {
Error::Encrypt(e.into())
}
}
impl From<encryption::EncryptionError> for Error {
fn from(e: encryption::EncryptionError) -> Self {
Error::Encrypt(e.into())
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
match e.kind() {
io::ErrorKind::UnexpectedEof => Error::ConnectionClosed,
_ => Error::Io(e),
}
}
}
impl From<rustls_pki_types::pem::Error> for Error {
fn from(e: rustls_pki_types::pem::Error) -> Self {
Error::Config(e.into())
}
}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Self {
Error::Encrypt(e.into())
}
}
impl From<sqltk::parser::parser::ParserError> for Error {
fn from(e: sqltk::parser::parser::ParserError) -> Self {
Error::Mapping(MappingError::InvalidSqlStatement(e.to_string()))
}
}
impl From<std::ffi::NulError> for Error {
fn from(_: std::ffi::NulError) -> Self {
Error::Protocol(ProtocolError::UnexpectedNull)
}
}
impl From<tokio_postgres::Error> for Error {
fn from(e: tokio_postgres::Error) -> Self {
Error::Config(e.into())
}
}
impl From<std::num::ParseIntError> for Error {
fn from(_e: std::num::ParseIntError) -> Self {
MappingError::CouldNotParseParameter.into()
}
}
impl From<std::num::ParseFloatError> for Error {
fn from(_e: std::num::ParseFloatError) -> Self {
MappingError::CouldNotParseParameter.into()
}
}
impl From<rust_decimal::Error> for Error {
fn from(_e: rust_decimal::Error) -> Self {
MappingError::CouldNotParseParameter.into()
}
}
impl From<chrono::ParseError> for Error {
fn from(_e: chrono::ParseError) -> Self {
MappingError::CouldNotParseParameter.into()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_internal_error_message() {
let error = MappingError::Internal("unexpected bug encounterd".to_string());
let message = error.to_string();
assert_eq!(format!("Statement encountered an internal error. This may be a bug in the statement mapping module of CipherStash Proxy. Please visit {ERROR_DOC_BASE_URL}#mapping-internal-error for more information."), message);
}
#[test]
fn connection_timeout_message_shows_millis() {
let error = Error::ConnectionTimeout {
duration: Duration::from_millis(5000),
};
assert_eq!(error.to_string(), "Connection timed out after 5000 ms");
}
}