Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0798124811 | ||
|
|
a10510ed6e | ||
|
|
2371486f39 | ||
|
|
a1e5daba59 | ||
|
|
2bd81a66a4 | ||
|
|
d67871f491 | ||
|
|
1a7f502fce | ||
|
|
b2c27d26e8 | ||
|
|
8fa3a15807 | ||
|
|
862c68c846 | ||
|
|
ac62171467 | ||
|
|
2080fb897b | ||
|
|
bf62054c2b | ||
|
|
cd4c613758 | ||
|
|
efbf6c687c | ||
|
|
ee495478ff | ||
|
|
4c18de8b7a | ||
|
|
0cfa9fc07a | ||
|
|
9e9bc2b0ae | ||
|
|
07bf98e522 | ||
|
|
e0e758554c | ||
|
|
479a0a96eb | ||
|
|
c6e22fc91b | ||
|
|
9bc9cb56c1 | ||
|
|
8bcdc5420a | ||
|
|
0a355c299b | ||
|
|
192d9058c3 | ||
|
|
b88b32d0f1 | ||
|
|
12c97c4a7d | ||
|
|
97528d65d6 | ||
|
|
295698e62f | ||
|
|
3b61aa924a | ||
|
|
02ba19d709 | ||
|
|
55801384eb | ||
|
|
27c2f467c4 | ||
|
|
cab5ec40cc | ||
|
|
5cf848f7fe | ||
|
|
a32e36be7e | ||
|
|
10231df860 | ||
|
|
ae93a57aab | ||
|
|
9fd355b68e | ||
|
|
00089d7efb | ||
|
|
0124f77f7b | ||
|
|
6711ce2c43 | ||
|
|
a3a11897c2 | ||
|
|
5e6542d08e | ||
|
|
f311fde74e | ||
|
|
acc5c71bfa | ||
|
|
504c0b4156 | ||
|
|
bf0a2ca72d | ||
|
|
bb980c5eef | ||
|
|
ce7d75f15a | ||
|
|
37b44ddb2e | ||
|
|
8c668e51a6 | ||
|
|
9928996fab | ||
|
|
d0a2532c27 | ||
|
|
0491cb5790 | ||
|
|
816bd7db00 | ||
|
|
b165965289 | ||
|
|
86896d68c2 | ||
|
|
64a2927b94 | ||
|
|
87617a0726 | ||
|
|
141334f7e2 | ||
|
|
69f6a39396 | ||
|
|
70e23c7e20 | ||
|
|
1df849442e | ||
|
|
7fdb336c79 | ||
|
|
46b8d810c5 | ||
|
|
dd40eb379e | ||
|
|
13545ac725 | ||
|
|
040a01536a | ||
|
|
4e2a90b15b | ||
|
|
e0d919ed4a | ||
|
|
3f4efc5f8f | ||
|
|
4881b90b0b | ||
|
|
1b749a857c | ||
|
|
2079f99d04 | ||
|
|
5e0ffc1155 | ||
|
|
d4fa8966b2 | ||
|
|
a293d8f92c | ||
|
|
367a140e2a | ||
|
|
4b06dce7f4 | ||
|
|
47a3e1cfef | ||
|
|
1047818fdc | ||
|
|
3d093a3a45 | ||
|
|
992d2a4d06 | ||
|
|
12f0f187a6 | ||
|
|
997e8b419f | ||
|
|
1d9132de3b | ||
|
|
e1c2618dc8 | ||
|
|
a7df7adc8e | ||
|
|
03d164c9d3 | ||
|
|
f522674a1c | ||
|
|
51fcccafa2 | ||
|
|
e3913ab4c9 | ||
|
|
c16f21bba3 | ||
|
|
61d9acc7c6 | ||
|
|
8d7b01629d | ||
|
|
5685948608 | ||
|
|
c98a065587 | ||
|
|
e46c3d2b4d | ||
|
|
fa228acc3a | ||
|
|
e7e0f9d33e | ||
|
|
a51b20add7 | ||
|
|
890f715388 | ||
|
|
89bc74e644 | ||
|
|
60c24e3ee4 | ||
|
|
486001b584 | ||
|
|
52c949e396 | ||
|
|
d7c5c2f37b | ||
|
|
ae5b8f31db | ||
|
|
c260e37e78 | ||
|
|
7501253970 | ||
|
|
5b9c711008 | ||
|
|
ddd1005067 | ||
|
|
e866a4a643 | ||
|
|
94400ba7d5 | ||
|
|
616600687d | ||
|
|
e8b8dc2976 | ||
|
|
ddf865d0b4 | ||
|
|
96bbc2dbc2 | ||
|
|
161148d1f6 | ||
|
|
760987f09b | ||
|
|
a75f34865e | ||
|
|
886fcd9bb8 | ||
|
|
55775b6b05 | ||
|
|
871dedf0a3 | ||
|
|
913148a75a | ||
|
|
e746963052 | ||
|
|
b761d3b493 | ||
|
|
c5dcc2e50a | ||
|
|
70d71ce14e | ||
|
|
33a5600a30 | ||
|
|
741169d807 | ||
|
|
ebc00a5df6 | ||
|
|
c2cc007a81 | ||
|
|
4aab08e6f0 | ||
|
|
12d9d733a5 | ||
|
|
35271049dd | ||
|
|
6f9cd6b471 | ||
|
|
865b7fd5c4 | ||
|
|
f35352eedd | ||
|
|
53580d7919 | ||
|
|
049b81610d | ||
|
|
fd60899f16 | ||
|
|
e0c4c849dc | ||
|
|
cb26201506 | ||
|
|
992e3c8db2 | ||
|
|
4956b64371 | ||
|
|
df6b362a31 | ||
|
|
2943634248 | ||
|
|
06f5a1af42 | ||
|
|
61d674199f | ||
|
|
398916fe10 | ||
|
|
bf4c46238e | ||
|
|
5ffa55c03c | ||
|
|
50f0985f4f | ||
|
|
69475604c0 | ||
|
|
856b6f1e1b | ||
|
|
414379b74e | ||
|
|
80b92ebe69 | ||
|
|
983d0e8639 | ||
|
|
d77437cda8 | ||
|
|
3d5cbedae1 |
No files matched your search
@@ -0,0 +1,3 @@
|
||||
[env]
|
||||
# in development (i.e. when running through Cargo), store state in project directory
|
||||
CREDDY_DATA_DIR = { value = "data", relative = true }
|
||||
@@ -1,7 +1,17 @@
|
||||
dist
|
||||
**/node_modules
|
||||
src-tauri/target/
|
||||
**/creddy.db
|
||||
# state directory for development work
|
||||
data/
|
||||
.vscode
|
||||
|
||||
# just in case
|
||||
credentials*
|
||||
pacman/pkg
|
||||
pacman/src
|
||||
pacman/*.deb
|
||||
pacman/*.tar.zst
|
||||
|
||||
# temporary worktree for master while we work on rewrite
|
||||
master
|
||||
|
||||
|
||||
# Added by cargo
|
||||
|
||||
/target
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "creddy"
|
||||
version = "0.7.0"
|
||||
description = "A friendly AWS credentials manager"
|
||||
authors = ["Joseph Montanaro"]
|
||||
license = ""
|
||||
repository = ""
|
||||
default-run = "creddy"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
argon2 = { version = "0.6.0", features = ["parallel", "zeroize"] }
|
||||
base64ct = "1.8.3"
|
||||
dirs = "7.0.0"
|
||||
duckdb = { version = "1.20000.1", features = ["bundled"] }
|
||||
getrandom = { version = "0.4.3", features = ["sys_rng"] }
|
||||
gpui-kit = "0.7.0"
|
||||
gpui-omarchy = "0.2.1"
|
||||
include_dir = "0.7.4"
|
||||
serde = "1.0.229"
|
||||
serde_json = "1.0.154"
|
||||
testresult = "0.4.2"
|
||||
thiserror = "2.0.21"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.27.0"
|
||||
@@ -1,24 +0,0 @@
|
||||
## Creddy: Low-friction AWS credential helper
|
||||
|
||||
_Security at the expense of usability comes at the expense of security._ - Avi Douglen
|
||||
|
||||
**Creddy** is an AWS credential helper that focuses on improving security without interrupting your workflow (much). It works by mimicking the AWS Instance Metadata Service and requesting your approval before granting any application access to your AWS credentials. Additionally, the credentials it hands out are short-lived session credentials rather than long-lived credentials, meaning that even if they are compromised, the damage that the attacker can do is limited.
|
||||
|
||||
### What was wrong with all the existing AWS credential managers?
|
||||
|
||||
Most other AWS credential managers that I have seen differ in two ways.
|
||||
|
||||
**First**, they require the user to be _proactive_ instead of _reactive_, i.e. you must remember "this command will require AWS credentials" and invoke it in some special way. By contrast, Creddy waits patiently in the background until an application requests credentials, then asks for your approval before proceeding. In most cases, this requires only a couple of keystrokes, after which your original operation continues as invoked. This completely prevents the frustrating workflow of:
|
||||
|
||||
```
|
||||
$ aws do-something-interesting
|
||||
...
|
||||
...
|
||||
Unable to locate credentials. You can configure credentials by running "aws configure".
|
||||
# a deep sigh of the most profound resignation
|
||||
$ with-aws-credentials aws do-something-interesting
|
||||
```
|
||||
|
||||
**Second**, other credential managers are mostly backed by the system credential store. While this may sound like a good idea, it has a critical weakness: By default, on most systems, a user's credentials are accessible to _any process running as that user_. In other words, if your quick nodejs script happens to depend on a compromised module, congratulations: you have just given that module access to your AWS account.
|
||||
|
||||
By contrast, Creddy encrypts your main long-lived AWS credentials with a passphrase (using libsodium's `SecretBox`) and, importantly, _does not store that passphrase_. Although this means that you, the user, must re-enter the passphrase every time Creddy needs to generate a new session, this is normally only necessary about once per day. In my own opinion, this is a worthwhile tradeoff.
|
||||
@@ -0,0 +1,4 @@
|
||||
fn main() {
|
||||
// include_dir! only tracks files that already exist, so rebuild when one is added
|
||||
println!("cargo:rerun-if-changed=migrations");
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
My original plan was to use [libsodium](https://doc.libsodium.org/) to handle encryption. However, the Rust bindings for libsodium are no longer actively maintained, which left me uncomfortable with using it. Instead, I switched to the [RustCrypto](https://github.com/RustCrypto) implementations of the same (or nearly the same) cryptographic primitives provided by libsodium.
|
||||
|
||||
Creddy makes use of two cryptographic primitives: A key-derivation function, which is currently `argon2id`, and a symmetric encryption algorithm, currently `XChaCha20Poly1305`.
|
||||
* I chose `argon2id` because it's what libsodium uses, and because its difficulty parameters admit of very granular tuning.
|
||||
* I chose `XChaCha20Poly1305` because it's _almost_ what libsodium uses - libsodium uses `XSalsa20Poly1305`, and it's my undersatnding that `XChaCha20Poly1305` is an evolution of the former. In both cases I use the eXtended variants, which make use of longer (24-byte) nonces than the non-X variants. This appealed to me because I wanted to be able to randomly generate a nonce every time I needed one, and I have seen [recommendations](https://latacora.micro.blog/2018/04/03/cryptographic-right-answers.html) that the 12-byte nonces used by the non-X variants are _juuust_ a touch small for that to be truly worry-free. The RustCrypto implementation of `XChaCha20Poly1305` has also been subject to a security audit, which is nice.
|
||||
|
||||
I tuned the `argon2id` parameters so that key-derivation would take ~800ms on my Ryzen 1600X. This is probably overkill, but I don't intend for key-derivation to be a frequent occurrence - no more than once a day, under normal circumstances. Taking in the neighborhood of 1 second seemed about the longest I could reasonably go.
|
||||
|
||||
**DISCLAIMER**: I am not a professional cryptographer, merely an interested amateur. While I've tried to be as careful as possible with selecting and making use of the cryptographic building blocks I've chosen here, there is always the possibility that I've screwed something up. If anyone would like to sponsor an _actual_ security review of Creddy by people who _actually_ know what they're doing instead of just what they've read on the internet, please let me know.
|
||||
@@ -9,7 +9,7 @@ The following is a list of security features that I hope to add eventually, in a
|
||||
* To defend against the possibility that an attacker could replace, say, the `aws` executable with a malicious one that snarfs your credentials and then passes the command on to the real one, maybe track the path (and maybe even the hash) of the executable, and raise a warning if this is the first time we've seen that one? Using the hash would be safer, but would also introduce a lot of false positives, since every time the application gets updated it would trigger. On the other hand, users should presumably know when they've updated things, so maybe it would be ok. On the _other_ other hand, if somebody doesn't use `aws` very often then it might be weeks or months in between updating it and actually using the updated executable, in which case they probably won't remember that this is the first time they've used it since updating.
|
||||
Another possible approach is to _watch_ the files in question, and alert the user whenever any of them changes. Presumably the user will know whether this change is expected or not.
|
||||
* Downgrade privileges after launching. In particular, if possible, disallow any kind of outgoing network access (obviously we have to bind the listening socket, but maybe we can filter that down to _just_ the ability to bind that particular address/port) and filesystem access outside of state db. I think this is doable on Linux, although it may involve high levels of `seccomp` grossness. No idea whether it's possible on Windows. Probably possible on MacOS although it may require lengths to which I am currently unwilling to go (e.g. pay for a certificate from Apple or something.)
|
||||
* "Panic button" - if a potential attack is detected (e.g. the user denies a request but Creddy discovers the request has already succeeded somehow), offer a one-click option to lock out the current IAM user. (Sadly, you can't revoke session tokens, so this is the only way to limit a potential compromise). Not sure how feasible this is, session credentials may be limited with regard to what kind of IAM operations they can carry out.)
|
||||
* "Panic button" - if a potential attack is detected (e.g. the user denies a request but Creddy discovers the request has already succeeded somehow), offer a one-click option to lock out the current IAM user. Sadly, you can't revoke session tokens, so this is the only way to limit a potential compromise. Obviously this would require the current user having the ability to revoke their own IAM permissions.)
|
||||
* Some kind of Yubikey or other HST integration. (Optional, since not everyone will have a HST.) This comes in two flavors:
|
||||
1. (Probably doable) Store the encryption key for the passphrase on the HST, and ask the HST to decrypt the passphrase instead of asking the user to enter it. This has the advantage of being a) lower-friction, since the user doesn't have to type in the passphrase, and b) more secure, since the application code never sees the encryption key.
|
||||
2. (Less doable) Store the actual AWS secret key on the HST, and then ask the HST to just sign the whole `GetSessionToken` request. This requires that the HST support the exact signing algorithm required by AWS, which a) it probably doesn't, and b) is subject to change anyway. So this is probably not doable, but it's worth at least double-checking, since it would provide the maximum theoretical level of security. (That is, after initial setup, the application would never again see the long-lived AWS secret key.)
|
||||
@@ -19,9 +19,9 @@ Another possible approach is to _watch_ the files in question, and alert the use
|
||||
|
||||
Who exactly are we defending against and why?
|
||||
|
||||
The basic idea behind Creddy is that it provides "gap coverage" between two wildly different security boundaries: 1) the older, user-based model, where all code executing as a given user is assumed to have the same level of trust, and 2) the newer, application-based model (most clearly seen on mobile devices) where that bondary instead exists around each _application_.
|
||||
The basic idea behind Creddy is that it provides "gap coverage" between two wildly different security models: 1) the older, user-based model, where all code executing as a given user is assumed to have the same level of trust, and 2) the newer, application-based model (most clearly seen on mobile devices) where that bondary instead exists around each _application_.
|
||||
|
||||
The unfortunate reality is that desktop environments are unlikely to adopt the latter model any time soon, if ever. This is primarily due to friction: Per-application security is a nightmare to manage. The only reason it works at all on mobile devices is because most mobile apps eschew the local device in favor of cloud-backed services where they can, e.g. for file storage. Arguably, the higher-friction trust model of mobile environments is in part _why_ mobile apps tend to be cloud-first.
|
||||
The unfortunate reality is that desktop environments are unlikely to adopt the latter model any time soon, if ever. This is primarily due to friction: Per-application security is a nightmare to manage. The only reason it works at all on mobile devices is because most mobile apps eschew the local device in favor of cloud-backed services where they can, e.g. for file storage. Arguably, the higher-friction trust model of mobile environments (along with the frequently-replaced nature of mobile devices) is in part _why_ mobile apps tend to be cloud-first.
|
||||
|
||||
Regardless, we live in a world where it's difficult to run untrusted code without giving it an inordinate level of access to the machine on which it runs. Creddy attempts to prevent that access from including your AWS credentials. The threat model is thus "untrusted code running under your user". This is especially likely to occur in the form of a supply-chain attack, where the compromised code is not your own but rather a dependency, or a dependency of a dependency, etc.
|
||||
|
||||
@@ -31,13 +31,13 @@ There are lots of ways that I can imagine someone might try to circumvent Creddy
|
||||
|
||||
### Tricking Creddy into allowing a request that it shouldn't
|
||||
|
||||
If an attacker is able to compromise Creddy's frontend, e.g. via a JS library that Creddy relies on, they could forge "request accepted" responses and cause the backend to hand out credentials to an unauthorized client. Most likely, the user would immediately be alerted to the fact that Something Is Up because as soon as the request came in, Creddy would pop up requesting permission. When the user (presumably) denied the request, Creddy would discover that the request had already been approved - we could make this a high-alert situation because it would be unlikely to happen unless something fishy were going on. Additionally, the request and (hopefully) what executable made it would be logged.
|
||||
If an attacker is able to compromise Creddy's frontend, e.g. via a JS library that Creddy relies on, they could forge "request accepted" responses and cause the backend to hand out credentials to an unauthorized client. Most likely, the user would immediately be alerted to the fact that Something Is Up because Creddy would pop up requesting then permission, and then immediately disappear again because the request had been approved. Additionally, the request and (hopefully) what executable made it would be logged.
|
||||
|
||||
### Tricking the user into allowing a request they didn't intend to
|
||||
|
||||
If an attacker can edit the user's .bashrc or similar, they could theoretically insert a function or pre-command hook that wraps, say, the `aws` command, and dump the credentials before continuing on with the user's command. This would most likely alert the user because either a) the attacker is hijacking the original `aws` command and thus it doesn't do what the user told it to, or b) the user's original `aws` command proceeds as normal after the malicious one, and the user is alerted by the second request where there should only have been one.
|
||||
If an attacker can edit the user's .bashrc or similar, they could theoretically insert a function or pre-command hook that wraps, say, the `aws` command, and dump the credentials before continuing on with the user's command. The attacker could inject the credentials into the environment before running the original command, so as to avoid alerting the user by issuing a second credentials request.
|
||||
|
||||
A similar but more-difficult-to-detect attack would be replacing the `aws` executable, or any other executable that is always expected to ask for AWS credentials, with a malicious wrapper that snarfs the credentials before passing them through to the original command. Creddy could defend against this to a certain extent by storing the hash of the executable, as discussed above.
|
||||
Another attack along the same lines would be replacing the `aws` executable, or any other executable that is always expected to ask for AWS credentials, with a malicious wrapper that snarfs the credentials before passing them through to the original command. Creddy could defend against this to a certain extent by storing the hash of the executable, as discussed above.
|
||||
|
||||
### Pretending to be the user
|
||||
|
||||
@@ -46,3 +46,5 @@ Most desktop environments don't prevent applications from simulating user-input
|
||||
### Twiddling with Creddy's persistent state
|
||||
|
||||
The solutions to or mitigations for a lot of these attacks rely on Creddy being able to assume that its local database hasn't been tampered with. Unfortunately, given that our threat model is "other code running as the same user", this isn't a safe assumption.
|
||||
|
||||
The solution to this problem is probably just to encrypt the entire database. This introduces a bit of complexity since certain settings, like `start_on_login` and `start_minimized`, will need to be accessible before the app is unlocked,but these settings can probably just be stashed alongside the database and kept in sync on every config save.
|
||||
@@ -0,0 +1,26 @@
|
||||
## Definitely
|
||||
|
||||
* ~~Switch to "process" provider for AWS credentials (much less hacky)~~
|
||||
* ~~Frontend needs to react when request is cancelled from backend~~
|
||||
* ~~Session timeout~~
|
||||
* ~~Fix rehide behavior when new request comes in while old one is still being resolved~~
|
||||
* ~~Switch tray menu item to Hide when window is visible~~
|
||||
* Clear password input after unlock fails
|
||||
* Indicate on approval screen when additional requests are pending
|
||||
* Additional hotkey configuration (approve/deny at the very least)
|
||||
* Logging
|
||||
* Icon
|
||||
* Auto-updates
|
||||
* ~~SSH key handling~~
|
||||
* ~~Docker credential helper~~
|
||||
* Encrypted sync server
|
||||
|
||||
## Maybe
|
||||
|
||||
* Flatten error type hierarchy
|
||||
* Rehide after terminal launch from locked
|
||||
* Generalize Request across both credentials and terminal launch?
|
||||
* Make hotkey configuration a little more tolerant of slight mistiming
|
||||
* Distinguish between request that was denied and request that was canceled (e.g. due to error)
|
||||
* Use atomic types for primitive state values instead of RwLock'd types
|
||||
* Rework approval flow to be a fullscreen overlay instead of mixing with normal navigation (as more views are added the pain of the current situation will only increase)
|
||||
@@ -1,25 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vite + Svelte</title>
|
||||
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
display: grid;
|
||||
align-items: center;
|
||||
justify-items: center;
|
||||
min-width: 100vw;
|
||||
min-height: 100vh;
|
||||
}
|
||||
</style>
|
||||
|
||||
</head>
|
||||
<body class="bg-zinc-800">
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,4 @@
|
||||
-- config will only ever hold a single row with a single value
|
||||
CREATE TABLE config (value JSON);
|
||||
-- seed it with an empty object, which will be populated with default values on deserialization
|
||||
INSERT INTO config VALUES ('{}');
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"name": "creddy",
|
||||
"version": "0.1.0",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/vite-plugin-svelte": "^1.0.1",
|
||||
"@tauri-apps/cli": "^1.0.5",
|
||||
"autoprefixer": "^10.4.8",
|
||||
"postcss": "^8.4.16",
|
||||
"svelte": "^3.49.0",
|
||||
"tailwindcss": "^3.1.8",
|
||||
"vite": "^3.0.7"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^1.0.2"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
[package]
|
||||
name = "app"
|
||||
version = "0.1.0"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
license = ""
|
||||
repository = ""
|
||||
default-run = "app"
|
||||
edition = "2021"
|
||||
rust-version = "1.57"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "1.0.4", features = [] }
|
||||
|
||||
[dependencies]
|
||||
serde_json = "1.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tauri = { version = "1.0.5", features = ["api-all"] }
|
||||
sodiumoxide = "0.2.7"
|
||||
tokio = { version = ">=1.19", features = ["full"] }
|
||||
sqlx = { version = "0.6.2", features = ["sqlite", "runtime-tokio-rustls"] }
|
||||
netstat2 = "0.9.1"
|
||||
sysinfo = "0.26.8"
|
||||
|
||||
[features]
|
||||
# by default Tauri runs in production mode
|
||||
# when `tauri dev` runs it is executed with `cargo run --no-default-features` if `devPath` is an URL
|
||||
default = [ "custom-protocol" ]
|
||||
# this feature is used used for production builds where `devPath` points to the filesystem
|
||||
# DO NOT remove this
|
||||
custom-protocol = [ "tauri/custom-protocol" ]
|
||||
@@ -1,3 +0,0 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
|
Before Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 974 B |
|
Before Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 7.6 KiB |
|
Before Width: | Height: | Size: 903 B |
|
Before Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 85 KiB |
|
Before Width: | Height: | Size: 14 KiB |
@@ -1,17 +0,0 @@
|
||||
-- Add migration script here
|
||||
CREATE TABLE credentials (
|
||||
access_key_id TEXT NOT NULL,
|
||||
secret_key_enc BLOB NOT NULL,
|
||||
salt BLOB NOT NULL,
|
||||
nonce BLOB NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE config (
|
||||
name TEXT,
|
||||
data TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE clients (
|
||||
name TEXT,
|
||||
path TEXT
|
||||
);
|
||||
@@ -1,51 +0,0 @@
|
||||
use netstat2::{AddressFamilyFlags, ProtocolFlags, ProtocolSocketInfo};
|
||||
use sysinfo::{System, SystemExt, Pid, ProcessExt};
|
||||
|
||||
use crate::errors::*;
|
||||
use crate::ipc::Client;
|
||||
|
||||
|
||||
fn get_associated_pids(local_port: u16) -> Result<Vec<u32>, netstat2::error::Error> {
|
||||
let mut it = netstat2::iterate_sockets_info(
|
||||
AddressFamilyFlags::IPV4,
|
||||
ProtocolFlags::TCP
|
||||
)?;
|
||||
|
||||
for (i, item) in it.enumerate() {
|
||||
let sock_info = item?;
|
||||
let proto_info = match sock_info.protocol_socket_info {
|
||||
ProtocolSocketInfo::Tcp(tcp_info) => tcp_info,
|
||||
ProtocolSocketInfo::Udp(_) => {continue;}
|
||||
};
|
||||
|
||||
if proto_info.local_port == local_port
|
||||
&& proto_info.remote_port == 12345
|
||||
&& proto_info.local_addr == std::net::Ipv4Addr::LOCALHOST
|
||||
&& proto_info.remote_addr == std::net::Ipv4Addr::LOCALHOST
|
||||
{
|
||||
return Ok(sock_info.associated_pids)
|
||||
}
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
|
||||
// Theoretically, on some systems, multiple processes can share a socket. We have to
|
||||
// account for this even though 99% of the time there will be only one.
|
||||
pub fn get_clients(local_port: u16) -> Result<Vec<Client>, ClientInfoError> {
|
||||
let mut clients = Vec::new();
|
||||
let mut sys = System::new();
|
||||
for p in get_associated_pids(local_port)? {
|
||||
let pid = Pid::from(p as usize);
|
||||
sys.refresh_process(pid);
|
||||
let proc = sys.process(pid)
|
||||
.ok_or(ClientInfoError::PidNotFound)?;
|
||||
|
||||
let client = Client {
|
||||
pid: p,
|
||||
exe: proc.exe().to_string_lossy().into_owned(),
|
||||
};
|
||||
clients.push(client);
|
||||
}
|
||||
Ok(clients)
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::convert::From;
|
||||
use std::str::Utf8Error;
|
||||
|
||||
use sqlx::{
|
||||
error::Error as SqlxError,
|
||||
migrate::MigrateError,
|
||||
};
|
||||
|
||||
|
||||
// error during initial setup (primarily loading state from db)
|
||||
pub enum SetupError {
|
||||
InvalidRecord, // e.g. wrong size blob for nonce or salt
|
||||
DbError(SqlxError),
|
||||
}
|
||||
impl From<SqlxError> for SetupError {
|
||||
fn from(e: SqlxError) -> SetupError {
|
||||
SetupError::DbError(e)
|
||||
}
|
||||
}
|
||||
impl From<MigrateError> for SetupError {
|
||||
fn from (e: MigrateError) -> SetupError {
|
||||
SetupError::DbError(SqlxError::from(e))
|
||||
}
|
||||
}
|
||||
impl Display for SetupError {
|
||||
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
|
||||
match self {
|
||||
SetupError::InvalidRecord => write!(f, "Malformed database record"),
|
||||
SetupError::DbError(e) => write!(f, "Error from database: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// error when attempting to tell a request handler whether to release or deny crednetials
|
||||
pub enum SendResponseError {
|
||||
NotFound, // no request with the given id
|
||||
Abandoned, // request has already been closed by client
|
||||
}
|
||||
|
||||
impl Display for SendResponseError {
|
||||
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
|
||||
use SendResponseError::*;
|
||||
match self {
|
||||
NotFound => write!(f, "The specified command was not found."),
|
||||
Abandoned => write!(f, "The specified request was closed by the client."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// errors encountered while handling an HTTP request
|
||||
pub enum RequestError {
|
||||
StreamIOError(std::io::Error),
|
||||
InvalidUtf8,
|
||||
MalformedHttpRequest,
|
||||
RequestTooLarge,
|
||||
NoCredentials(GetCredentialsError),
|
||||
ClientInfo(ClientInfoError),
|
||||
}
|
||||
impl From<tokio::io::Error> for RequestError {
|
||||
fn from(e: std::io::Error) -> RequestError {
|
||||
RequestError::StreamIOError(e)
|
||||
}
|
||||
}
|
||||
impl From<Utf8Error> for RequestError {
|
||||
fn from(_e: Utf8Error) -> RequestError {
|
||||
RequestError::InvalidUtf8
|
||||
}
|
||||
}
|
||||
impl From<GetCredentialsError> for RequestError {
|
||||
fn from (e: GetCredentialsError) -> RequestError {
|
||||
RequestError::NoCredentials(e)
|
||||
}
|
||||
}
|
||||
impl From<ClientInfoError> for RequestError {
|
||||
fn from(e: ClientInfoError) -> RequestError {
|
||||
RequestError::ClientInfo(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for RequestError {
|
||||
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
|
||||
use RequestError::*;
|
||||
match self {
|
||||
StreamIOError(e) => write!(f, "Stream IO error: {e}"),
|
||||
InvalidUtf8 => write!(f, "Could not decode UTF-8 from bytestream"),
|
||||
MalformedHttpRequest => write!(f, "Maformed HTTP request"),
|
||||
RequestTooLarge => write!(f, "HTTP request too large"),
|
||||
NoCredentials(GetCredentialsError::Locked) => write!(f, "Recieved go-ahead but app is locked"),
|
||||
NoCredentials(GetCredentialsError::Empty) => write!(f, "Received go-ahead but no credentials are known"),
|
||||
ClientInfo(ClientInfoError::PidNotFound) => write!(f, "Could not resolve PID of client process."),
|
||||
ClientInfo(ClientInfoError::NetstatError(e)) => write!(f, "Error getting client socket details: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub enum GetCredentialsError {
|
||||
Locked,
|
||||
Empty,
|
||||
}
|
||||
|
||||
|
||||
pub enum UnlockError {
|
||||
NotLocked,
|
||||
NoCredentials,
|
||||
BadPassphrase,
|
||||
InvalidUtf8, // Somehow we got invalid utf-8 even though decryption succeeded
|
||||
DbError(SqlxError),
|
||||
}
|
||||
impl From<SqlxError> for UnlockError {
|
||||
fn from (e: SqlxError) -> UnlockError {
|
||||
match e {
|
||||
SqlxError::RowNotFound => UnlockError::NoCredentials,
|
||||
_ => UnlockError::DbError(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Display for UnlockError {
|
||||
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
|
||||
use UnlockError::*;
|
||||
match self {
|
||||
NotLocked => write!(f, "App is not locked"),
|
||||
NoCredentials => write!(f, "No saved credentials were found"),
|
||||
BadPassphrase => write!(f, "Invalid passphrase"),
|
||||
InvalidUtf8 => write!(f, "Decrypted data was corrupted"),
|
||||
DbError(e) => write!(f, "Database error: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Errors encountered while trying to figure out who's on the other end of a request
|
||||
pub enum ClientInfoError {
|
||||
PidNotFound,
|
||||
NetstatError(netstat2::error::Error),
|
||||
}
|
||||
impl From<netstat2::error::Error> for ClientInfoError {
|
||||
fn from(e: netstat2::error::Error) -> ClientInfoError {
|
||||
ClientInfoError::NetstatError(e)
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
use serde::{Serialize, Deserialize};
|
||||
use tauri::State;
|
||||
|
||||
use crate::state::{AppState, Session, Credentials};
|
||||
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct Client {
|
||||
pub pid: u32,
|
||||
pub exe: String,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct Request {
|
||||
pub id: u64,
|
||||
pub clients: Vec<Client>,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct RequestResponse {
|
||||
pub id: u64,
|
||||
pub approval: Approval,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub enum Approval {
|
||||
Approved,
|
||||
Denied,
|
||||
}
|
||||
|
||||
|
||||
#[tauri::command]
|
||||
pub fn respond(response: RequestResponse, app_state: State<'_, AppState>) -> Result<(), String> {
|
||||
app_state.send_response(response)
|
||||
.map_err(|e| format!("Error responding to request: {e}"))
|
||||
}
|
||||
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn unlock(passphrase: String, app_state: State<'_, AppState>) -> Result<(), String> {
|
||||
app_state.decrypt(&passphrase)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_session_status(app_state: State<'_, AppState>) -> String {
|
||||
let session = app_state.session.read().unwrap();
|
||||
match *session {
|
||||
Session::Locked(_) => "locked".into(),
|
||||
Session::Unlocked(_) => "unlocked".into(),
|
||||
Session::Empty => "empty".into()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn save_credentials(
|
||||
credentials: Credentials,
|
||||
passphrase: String,
|
||||
app_state: State<'_, AppState>
|
||||
) -> Result<(), String> {
|
||||
app_state.save_creds(credentials, &passphrase)
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
#![cfg_attr(
|
||||
all(not(debug_assertions), target_os = "windows"),
|
||||
windows_subsystem = "windows"
|
||||
)]
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
mod errors;
|
||||
mod clientinfo;
|
||||
mod ipc;
|
||||
mod state;
|
||||
mod server;
|
||||
mod storage;
|
||||
|
||||
|
||||
fn main() {
|
||||
let initial_state = match state::AppState::new() {
|
||||
Ok(state) => state,
|
||||
Err(e) => {eprintln!("{}", e); return;}
|
||||
};
|
||||
|
||||
tauri::Builder::default()
|
||||
.manage(initial_state)
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
ipc::unlock,
|
||||
ipc::respond,
|
||||
ipc::get_session_status,
|
||||
ipc::save_credentials,
|
||||
])
|
||||
.setup(|app| {
|
||||
let addr = std::net::SocketAddrV4::from_str("127.0.0.1:12345").unwrap();
|
||||
tauri::async_runtime::spawn(server::serve(addr, app.handle()));
|
||||
Ok(())
|
||||
})
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
use std::io;
|
||||
use std::net::SocketAddrV4;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
use crate::clientinfo;
|
||||
use crate::errors::RequestError;
|
||||
use crate::ipc::{Request, Approval};
|
||||
|
||||
|
||||
pub async fn serve(addr: SocketAddrV4, app_handle: AppHandle) -> io::Result<()> {
|
||||
let listener = TcpListener::bind(&addr).await?;
|
||||
println!("Listening on {addr}");
|
||||
loop {
|
||||
let new_handle = app_handle.app_handle();
|
||||
match listener.accept().await {
|
||||
Ok((stream, _)) => {
|
||||
tokio::spawn(async {
|
||||
if let Err(e) = handle(stream, new_handle).await {
|
||||
eprintln!("{e}");
|
||||
}
|
||||
});
|
||||
},
|
||||
Err(e) => {
|
||||
eprintln!("Error accepting connection: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// it doesn't really return Approval, we just need to placate the compiler
|
||||
async fn stall(stream: &mut TcpStream) -> Result<Approval, tokio::io::Error> {
|
||||
let delay = std::time::Duration::from_secs(1);
|
||||
loop {
|
||||
tokio::time::sleep(delay).await;
|
||||
stream.write(b"x").await?;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async fn handle(mut stream: TcpStream, app_handle: AppHandle) -> Result<(), RequestError> {
|
||||
let (chan_send, chan_recv) = oneshot::channel();
|
||||
let app_state = app_handle.state::<crate::state::AppState>();
|
||||
let request_id = app_state.register_request(chan_send);
|
||||
|
||||
let peer_addr = match stream.peer_addr()? {
|
||||
std::net::SocketAddr::V4(addr) => addr,
|
||||
_ => unreachable!(), // we only listen on IPv4
|
||||
};
|
||||
let clients = clientinfo::get_clients(peer_addr.port())?;
|
||||
|
||||
// Do we want to panic if this fails? Does that mean the frontend is dead?
|
||||
let req = Request {id: request_id, clients};
|
||||
app_handle.emit_all("credentials-request", req).unwrap();
|
||||
|
||||
let mut buf = [0; 8192]; // it's what tokio's BufReader uses
|
||||
let mut n = 0;
|
||||
loop {
|
||||
n += stream.read(&mut buf[n..]).await?;
|
||||
if &buf[(n - 4)..n] == b"\r\n\r\n" {break;}
|
||||
if n == buf.len() {return Err(RequestError::RequestTooLarge);}
|
||||
}
|
||||
|
||||
println!("{}", std::str::from_utf8(&buf).unwrap());
|
||||
|
||||
stream.write(b"HTTP/1.0 200 OK\r\n").await?;
|
||||
stream.write(b"Content-Type: application/json\r\n").await?;
|
||||
stream.write(b"X-Creddy-delaying-tactic: ").await?;
|
||||
|
||||
let approval = tokio::select!{
|
||||
e = stall(&mut stream) => e?, // this will never return Ok, just Err if it can't write to the stream
|
||||
r = chan_recv => r.unwrap(), // only panics if the sender is dropped without sending, which shouldn't happen
|
||||
};
|
||||
|
||||
if matches!(approval, Approval::Denied) {
|
||||
// because we own the stream, it gets closed when we return.
|
||||
// Unfortunately we've already signaled 200 OK, there's no way around this -
|
||||
// we have to write the status code first thing, and we have to assume that the user
|
||||
// might need more time than that gives us (especially if entering the passphrase).
|
||||
// Fortunately most AWS libs automatically retry if the request dies uncompleted, allowing
|
||||
// us to respond with a proper error status.
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let creds = app_state.get_creds_serialized()?;
|
||||
|
||||
stream.write(b"\r\nContent-Length: ").await?;
|
||||
stream.write(creds.as_bytes().len().to_string().as_bytes()).await?;
|
||||
stream.write(b"\r\n\r\n").await?;
|
||||
stream.write(creds.as_bytes()).await?;
|
||||
stream.write(b"\r\n\r\n").await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use serde::{Serialize, Deserialize};
|
||||
use tokio::sync::oneshot::Sender;
|
||||
use sqlx::{SqlitePool, sqlite::SqlitePoolOptions, sqlite::SqliteConnectOptions};
|
||||
use sodiumoxide::crypto::{
|
||||
pwhash,
|
||||
pwhash::Salt,
|
||||
secretbox,
|
||||
secretbox::{Nonce, Key}
|
||||
};
|
||||
use tauri::async_runtime as runtime;
|
||||
|
||||
use crate::ipc;
|
||||
use crate::errors::*;
|
||||
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum Credentials {
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
LongLived {
|
||||
access_key_id: String,
|
||||
secret_access_key: String,
|
||||
},
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
ShortLived {
|
||||
access_key_id: String,
|
||||
secret_access_key: String,
|
||||
token: String,
|
||||
expiration: String,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
pub struct LockedCredentials {
|
||||
access_key_id: String,
|
||||
secret_key_enc: Vec<u8>,
|
||||
salt: Salt,
|
||||
nonce: Nonce,
|
||||
}
|
||||
|
||||
|
||||
pub enum Session {
|
||||
Unlocked(Credentials),
|
||||
Locked(LockedCredentials),
|
||||
Empty,
|
||||
}
|
||||
|
||||
|
||||
// #[derive(Serialize, Deserialize)]
|
||||
// pub enum SessionStatus {
|
||||
// Unlocked,
|
||||
// Locked,
|
||||
// Empty,
|
||||
// }
|
||||
|
||||
|
||||
pub struct AppState {
|
||||
pub session: RwLock<Session>,
|
||||
pub request_count: RwLock<u64>,
|
||||
pub open_requests: RwLock<HashMap<u64, Sender<ipc::Approval>>>,
|
||||
pool: SqlitePool,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new() -> Result<Self, SetupError> {
|
||||
let conn_opts = SqliteConnectOptions::new()
|
||||
.filename("creddy.db")
|
||||
.create_if_missing(true);
|
||||
let pool_opts = SqlitePoolOptions::new();
|
||||
|
||||
let pool: SqlitePool = runtime::block_on(pool_opts.connect_with(conn_opts))?;
|
||||
runtime::block_on(sqlx::migrate!().run(&pool))?;
|
||||
let creds = runtime::block_on(Self::load_creds(&pool))?;
|
||||
|
||||
let state = AppState {
|
||||
session: RwLock::new(creds),
|
||||
request_count: RwLock::new(0),
|
||||
open_requests: RwLock::new(HashMap::new()),
|
||||
pool,
|
||||
};
|
||||
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
async fn load_creds(pool: &SqlitePool) -> Result<Session, SetupError> {
|
||||
let res = sqlx::query!("SELECT * FROM credentials")
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
let row = match res {
|
||||
Some(r) => r,
|
||||
None => {return Ok(Session::Empty);}
|
||||
};
|
||||
|
||||
let salt_buf: [u8; 32] = row.salt
|
||||
.try_into()
|
||||
.map_err(|_e| SetupError::InvalidRecord)?;
|
||||
let nonce_buf: [u8; 24] = row.nonce
|
||||
.try_into()
|
||||
.map_err(|_e| SetupError::InvalidRecord)?;
|
||||
|
||||
let creds = LockedCredentials {
|
||||
access_key_id: row.access_key_id,
|
||||
secret_key_enc: row.secret_key_enc,
|
||||
salt: Salt(salt_buf),
|
||||
nonce: Nonce(nonce_buf),
|
||||
};
|
||||
Ok(Session::Locked(creds))
|
||||
}
|
||||
|
||||
pub async fn save_creds(&self, creds: Credentials, passphrase: &str) -> Result<(), sqlx::error::Error> {
|
||||
let (key_id, secret_key) = match creds {
|
||||
Credentials::LongLived {access_key_id, secret_access_key} => {
|
||||
(access_key_id, secret_access_key)
|
||||
},
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let salt = pwhash::gen_salt();
|
||||
let mut key_buf = [0; secretbox::KEYBYTES];
|
||||
pwhash::derive_key_interactive(&mut key_buf, passphrase.as_bytes(), &salt).unwrap();
|
||||
let key = Key(key_buf);
|
||||
// not sure we need both salt AND nonce given that we generate a
|
||||
// fresh salt every time we encrypt, but better safe than sorry
|
||||
let nonce = secretbox::gen_nonce();
|
||||
let key_enc = secretbox::seal(secret_key.as_bytes(), &nonce, &key);
|
||||
|
||||
// insert into database
|
||||
|
||||
// eventually replace this with a temporary session
|
||||
let mut session = self.session.write().unwrap();
|
||||
*session = Session::Unlocked(Credentials::LongLived {
|
||||
access_key_id: key_id,
|
||||
secret_access_key: secret_key,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn register_request(&self, chan: Sender<ipc::Approval>) -> u64 {
|
||||
let count = {
|
||||
let mut c = self.request_count.write().unwrap();
|
||||
*c += 1;
|
||||
c
|
||||
};
|
||||
|
||||
let mut open_requests = self.open_requests.write().unwrap();
|
||||
open_requests.insert(*count, chan); // `count` is the request id
|
||||
*count
|
||||
}
|
||||
|
||||
pub fn send_response(&self, response: ipc::RequestResponse) -> Result<(), SendResponseError> {
|
||||
let mut open_requests = self.open_requests.write().unwrap();
|
||||
let chan = open_requests
|
||||
.remove(&response.id)
|
||||
.ok_or(SendResponseError::NotFound)
|
||||
?;
|
||||
|
||||
chan.send(response.approval)
|
||||
.map_err(|_e| SendResponseError::Abandoned)
|
||||
}
|
||||
|
||||
pub async fn decrypt(&self, passphrase: &str) -> Result<(), UnlockError> {
|
||||
let session = self.session.read().unwrap();
|
||||
let locked = match *session {
|
||||
Session::Empty => {return Err(UnlockError::NoCredentials);},
|
||||
Session::Unlocked(_) => {return Err(UnlockError::NotLocked);},
|
||||
Session::Locked(ref c) => c,
|
||||
};
|
||||
|
||||
let mut key_buf = [0; secretbox::KEYBYTES];
|
||||
// pretty sure this only fails if we're out of memory
|
||||
pwhash::derive_key_interactive(&mut key_buf, passphrase.as_bytes(), &locked.salt).unwrap();
|
||||
let decrypted = secretbox::open(&locked.secret_key_enc, &locked.nonce, &Key(key_buf))
|
||||
.map_err(|_e| UnlockError::BadPassphrase)?;
|
||||
|
||||
let secret_str = String::from_utf8(decrypted).map_err(|_e| UnlockError::InvalidUtf8)?;
|
||||
let mut session = self.session.write().unwrap();
|
||||
let creds = Credentials::LongLived {
|
||||
access_key_id: locked.access_key_id.clone(),
|
||||
secret_access_key: secret_str,
|
||||
};
|
||||
*session = Session::Unlocked(creds);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_creds_serialized(&self) -> Result<String, GetCredentialsError> {
|
||||
let session = self.session.read().unwrap();
|
||||
match *session {
|
||||
Session::Unlocked(ref creds) => Ok(serde_json::to_string(creds).unwrap()),
|
||||
Session::Locked(_) => Err(GetCredentialsError::Locked),
|
||||
Session::Empty => Err(GetCredentialsError::Empty),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
use sodiumoxide::crypto::{pwhash, secretbox};
|
||||
|
||||
use crate::state;
|
||||
|
||||
|
||||
pub fn save(data: &str, passphrase: &str) {
|
||||
let salt = pwhash::Salt([0; 32]); // yes yes, just for now
|
||||
let mut kbuf = [0; secretbox::KEYBYTES];
|
||||
pwhash::derive_key_interactive(&mut kbuf, passphrase.as_bytes(), &salt)
|
||||
.expect("Couldn't compute password hash. Are you out of memory?");
|
||||
let key = secretbox::Key(kbuf);
|
||||
let nonce = secretbox::Nonce([0; 24]); // we don't care about e.g. replay attacks so this might be safe?
|
||||
let encrypted = secretbox::seal(data.as_bytes(), &nonce, &key);
|
||||
|
||||
//todo: store in a database, along with salt, nonce, and hash parameters
|
||||
std::fs::write("credentials.enc", &encrypted).expect("Failed to write file.");
|
||||
|
||||
//todo: key is automatically zeroed, but we should use 'zeroize' or something to zero out passphrase and data
|
||||
}
|
||||
|
||||
|
||||
// pub fn load(passphrase: &str) -> String {
|
||||
// let salt = pwhash::Salt([0; 32]);
|
||||
// let mut kbuf = [0; secretbox::KEYBYTES];
|
||||
// pwhash::derive_key_interactive(&mut kbuf, passphrase.as_bytes(), &salt)
|
||||
// .expect("Couldn't compute password hash. Are you out of memory?");
|
||||
// let key = secretbox::Key(kbuf);
|
||||
// let nonce = secretbox::Nonce([0; 24]);
|
||||
|
||||
// let encrypted = std::fs::read("credentials.enc").expect("Failed to read file.");
|
||||
// let decrypted = secretbox::open(&encrypted, &nonce, &key).expect("Failed to decrypt.");
|
||||
// String::from_utf8(decrypted).expect("Invalid utf-8")
|
||||
// }
|
||||
|
||||
pub fn load(passphrase: &str) -> state::Credentials {
|
||||
state::Credentials::ShortLived {
|
||||
access_key_id: "ASIAZ7WSVLORKQI27QGB".to_string(),
|
||||
secret_access_key: "blah".to_string(),
|
||||
token: "gah".to_string(),
|
||||
expiration: "2022-11-29T10:45:12Z".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
{
|
||||
"$schema": "../node_modules/@tauri-apps/cli/schema.json",
|
||||
"build": {
|
||||
"beforeBuildCommand": "npm run build",
|
||||
"beforeDevCommand": "npm run dev",
|
||||
"devPath": "http://localhost:5173",
|
||||
"distDir": "../dist"
|
||||
},
|
||||
"package": {
|
||||
"productName": "creddy",
|
||||
"version": "0.1.0"
|
||||
},
|
||||
"tauri": {
|
||||
"allowlist": {
|
||||
"all": true
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"category": "DeveloperTool",
|
||||
"copyright": "",
|
||||
"deb": {
|
||||
"depends": []
|
||||
},
|
||||
"externalBin": [],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"identifier": "com.tauri.dev",
|
||||
"longDescription": "",
|
||||
"macOS": {
|
||||
"entitlements": null,
|
||||
"exceptionDomain": "",
|
||||
"frameworks": [],
|
||||
"providerShortName": null,
|
||||
"signingIdentity": null
|
||||
},
|
||||
"resources": [],
|
||||
"shortDescription": "",
|
||||
"targets": "all",
|
||||
"windows": {
|
||||
"certificateThumbprint": null,
|
||||
"digestAlgorithm": "sha256",
|
||||
"timestampUrl": ""
|
||||
}
|
||||
},
|
||||
"security": {
|
||||
"csp": null
|
||||
},
|
||||
"updater": {
|
||||
"active": false
|
||||
},
|
||||
"windows": [
|
||||
{
|
||||
"fullscreen": false,
|
||||
"height": 600,
|
||||
"resizable": true,
|
||||
"title": "Creddy",
|
||||
"width": 800
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
<script>
|
||||
import { emit, listen } from '@tauri-apps/api/event';
|
||||
import queue from './lib/queue.js';
|
||||
|
||||
const VIEWS = import.meta.glob('./views/*.svelte', {eager: true});
|
||||
|
||||
window.emit = emit;
|
||||
window.queue = queue;
|
||||
|
||||
var appState = {
|
||||
currentRequest: null,
|
||||
pendingRequests: queue(),
|
||||
credentialStatus: 'locked',
|
||||
}
|
||||
window.appState = appState;
|
||||
|
||||
|
||||
import { invoke } from '@tauri-apps/api/tauri';
|
||||
window.invoke = invoke;
|
||||
|
||||
|
||||
var currentView = VIEWS['./views/Home.svelte'].default;
|
||||
window.currentView = currentView;
|
||||
window.VIEWS = VIEWS;
|
||||
function navigate(svelteEvent) {
|
||||
const moduleName = `./views/${svelteEvent.detail.target}.svelte`;
|
||||
currentView = VIEWS[moduleName].default;
|
||||
}
|
||||
window.navigate = navigate;
|
||||
|
||||
listen('credentials-request', (tauriEvent) => {
|
||||
appState.pendingRequests.put(tauriEvent.payload);
|
||||
console.log('Received request.');
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:component this={currentView} on:navigate={navigate} bind:appState={appState} />
|
||||
@@ -0,0 +1,3 @@
|
||||
mod passphrase_input;
|
||||
|
||||
pub use passphrase_input::{PassphraseInput, PassphraseInputEvent};
|
||||
@@ -0,0 +1,97 @@
|
||||
use gpui_kit::assets::IconName;
|
||||
use gpui_kit::base::input::{InputEvent, InputState};
|
||||
use gpui_kit::{
|
||||
App, AppContext, Context, Entity, EventEmitter, IntoElement, Render, SharedString, Styled,
|
||||
Subscription, Window,
|
||||
};
|
||||
use gpui_omarchy::{ButtonVariant, icon_button, input};
|
||||
|
||||
|
||||
/// A masked passphrase field with a show/hide toggle.
|
||||
///
|
||||
/// The `show` flag is passed in from outside so that it can be shared
|
||||
/// (e.g. passphrase and confirm-passphrase inputs should share it).
|
||||
pub struct PassphraseInput {
|
||||
state: Entity<InputState>,
|
||||
show: Entity<bool>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
pub enum PassphraseInputEvent {
|
||||
/// The user pressed Enter in the field.
|
||||
Submit,
|
||||
/// The field's text changed.
|
||||
Change,
|
||||
/// The field lost focus.
|
||||
Blur,
|
||||
}
|
||||
|
||||
impl EventEmitter<PassphraseInputEvent> for PassphraseInput {}
|
||||
|
||||
impl PassphraseInput {
|
||||
pub fn new(show: Entity<bool>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let masked = !*show.read(cx);
|
||||
let state = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.masked(masked)
|
||||
.placeholder("correct horse battery staple")
|
||||
});
|
||||
|
||||
// keep this field's masking in sync with the shared flag
|
||||
let sync_mask = cx.observe_in(&show, window, |this, show, window, cx| {
|
||||
let masked = !*show.read(cx);
|
||||
this.state.update(cx, |state, cx| state.set_masked(masked, window, cx));
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// re-emit the subset of input events that consumers care about
|
||||
let forward = cx.subscribe(&state, |_, _, event: &InputEvent, cx| {
|
||||
let event = match event {
|
||||
InputEvent::PressEnter { .. } => PassphraseInputEvent::Submit,
|
||||
InputEvent::Change => PassphraseInputEvent::Change,
|
||||
InputEvent::Blur => PassphraseInputEvent::Blur,
|
||||
InputEvent::Focus => return,
|
||||
};
|
||||
cx.emit(event);
|
||||
});
|
||||
|
||||
Self {
|
||||
state,
|
||||
show,
|
||||
_subscriptions: vec![sync_mask, forward],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value(&self, cx: &App) -> SharedString {
|
||||
self.state.read(cx).value()
|
||||
}
|
||||
|
||||
pub fn focus(&self, window: &mut Window, cx: &mut App) {
|
||||
self.state.update(cx, |state, cx| state.focus(window, cx));
|
||||
}
|
||||
|
||||
fn toggle_show(&mut self, cx: &mut Context<Self>) {
|
||||
self.show.update(cx, |show, cx| {
|
||||
*show = !*show;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for PassphraseInput {
|
||||
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let (icon, label) = if *self.show.read(cx) {
|
||||
(IconName::EyeOff, "Hide passphrase")
|
||||
}
|
||||
else {
|
||||
(IconName::Eye, "Show passphrase")
|
||||
};
|
||||
|
||||
input("passphrase", &self.state, window, cx)
|
||||
.w_full()
|
||||
.suffix(
|
||||
icon_button("toggle-show", icon, label, ButtonVariant::Secondary, cx)
|
||||
.on_click(cx.listener(|this, _, _, cx| this.toggle_show(cx))),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
use std::env;
|
||||
use std::ffi::OsString;
|
||||
use std::fs::File;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use gpui_kit::Global;
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
use crate::error::CreddyError;
|
||||
|
||||
|
||||
/// Config that doesn't need to or can't be stored in the encrypted db
|
||||
/// (such as settings that must be known at startup, before unlock).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PublicConfig {
|
||||
db_salt: [u8; 32],
|
||||
}
|
||||
|
||||
impl PublicConfig {
|
||||
/// Construct a PublicConfig with default values, in case there is nothing saved on disk
|
||||
pub fn default() -> PublicConfig {
|
||||
let mut db_salt = [0u8; 32];
|
||||
let _ = getrandom::fill(&mut db_salt);
|
||||
PublicConfig { db_salt }
|
||||
}
|
||||
|
||||
/// Load non-sensitive config from disk.
|
||||
pub fn load(path: &Path) -> Result<PublicConfig, CreddyError> {
|
||||
if path.exists() {
|
||||
let f = File::open(path)?;
|
||||
serde_json::from_reader(f).map_err(|e| CreddyError::InvalidJSON(e))
|
||||
}
|
||||
else {
|
||||
Ok(PublicConfig::default())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&self, path: &Path) -> Result<(), CreddyError> {
|
||||
let file = File::create(path)?;
|
||||
serde_json::to_writer(file, self)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Config that can be stored in the encrypted db
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct PrivateConfig {
|
||||
rehide_ms: u64,
|
||||
}
|
||||
|
||||
impl Default for PrivateConfig {
|
||||
fn default() -> PrivateConfig {
|
||||
PrivateConfig {
|
||||
rehide_ms: 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AppConfig {
|
||||
pub data_dir: PathBuf,
|
||||
pub db_salt: [u8; 32],
|
||||
pub rehide_ms: u64,
|
||||
}
|
||||
|
||||
impl AppConfig {
|
||||
/// Load config from disk, using defaults for non-public values.
|
||||
pub fn load() -> Result<AppConfig, CreddyError> {
|
||||
let data_dir = AppConfig::resolve_data_dir(
|
||||
env::var_os("CREDDY_DATA_DIR"),
|
||||
dirs::data_dir(),
|
||||
)?;
|
||||
|
||||
AppConfig::load_from(data_dir)
|
||||
}
|
||||
|
||||
pub fn load_from(data_dir: PathBuf) -> Result<AppConfig, CreddyError> {
|
||||
let public_config = PublicConfig::load(&data_dir.join("public_config.json"))?;
|
||||
let private_config = PrivateConfig::default();
|
||||
Ok(AppConfig::from_parts(data_dir, public_config, private_config))
|
||||
}
|
||||
|
||||
fn resolve_data_dir(creddy_data_dir: Option<OsString>, platform_data_dir: Option<PathBuf>) -> Result<PathBuf, CreddyError> {
|
||||
creddy_data_dir
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| platform_data_dir.map(|d| d.join("creddy")))
|
||||
.ok_or(CreddyError::DataDirNotFound)
|
||||
}
|
||||
|
||||
/// Pull the appropriate fields from instances of PublicConfig and PrivateConfig (plus data_dir since that comes from neither)
|
||||
fn from_parts(data_dir: PathBuf, public: PublicConfig, private: PrivateConfig) -> AppConfig {
|
||||
AppConfig {
|
||||
data_dir,
|
||||
db_salt: public.db_salt,
|
||||
rehide_ms: private.rehide_ms,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn merge_private(&mut self, private: PrivateConfig) {
|
||||
self.rehide_ms = private.rehide_ms;
|
||||
}
|
||||
|
||||
pub fn public_config_path(&self) -> PathBuf {
|
||||
self.data_dir.join("public_config.json")
|
||||
}
|
||||
|
||||
pub fn db_path(&self) -> PathBuf {
|
||||
self.data_dir.join("creddy.duckdb")
|
||||
}
|
||||
|
||||
pub fn public_config(&self) -> PublicConfig {
|
||||
PublicConfig {
|
||||
db_salt: self.db_salt,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn private_config(&self) -> PrivateConfig {
|
||||
PrivateConfig {
|
||||
rehide_ms: self.rehide_ms,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AppConfig {
|
||||
fn default() -> AppConfig {
|
||||
// AppConfig::default will only be called for testing or to fill in
|
||||
// remaining defaults when constructing otherwise, and data_dir is
|
||||
// always specified otherwise
|
||||
AppConfig::from_parts(
|
||||
PathBuf::from(""),
|
||||
PublicConfig::default(),
|
||||
PrivateConfig::default(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Global for AppConfig {}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::NamedTempFile;
|
||||
use testresult::TestResult;
|
||||
|
||||
#[test]
|
||||
fn test_public_default() {
|
||||
let conf = PublicConfig::default();
|
||||
assert!(conf.db_salt.len() == 32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_public_config_load_not_present() -> TestResult {
|
||||
let p = tempfile::tempdir()?.path().join("public_config.json");
|
||||
let conf = PublicConfig::load(&p)?;
|
||||
assert!(conf.db_salt.len() == 32);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_public_config_load_present() -> TestResult {
|
||||
let data_dir = tempfile::tempdir()?;
|
||||
let p = data_dir.path().join("public_config.json");
|
||||
let expected = PublicConfig::default(); // uses a random db salt
|
||||
let f = File::create(&p)?;
|
||||
serde_json::to_writer(f, &expected)?;
|
||||
|
||||
let loaded = PublicConfig::load(&p)?;
|
||||
assert!(loaded.db_salt == expected.db_salt);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_config_load_not_present() -> TestResult {
|
||||
let data_dir = tempfile::tempdir()?;
|
||||
let config = AppConfig::load_from(data_dir.path().to_path_buf())?;
|
||||
assert!(config.data_dir == data_dir.path());
|
||||
assert!(config.db_salt.len() == 32);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_config_load_present() -> TestResult {
|
||||
let data_dir = tempfile::tempdir()?;
|
||||
let p = data_dir.path().join("public_config.json");
|
||||
let public = PublicConfig::default(); // uses a random db salt
|
||||
let f = File::create(&p)?;
|
||||
serde_json::to_writer(f, &public)?;
|
||||
|
||||
let config = AppConfig::load_from(data_dir.path().to_path_buf())?;
|
||||
assert!(config.data_dir == data_dir.path());
|
||||
assert!(config.db_salt == public.db_salt);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_data_dir_override() -> TestResult {
|
||||
let data_dir = AppConfig::resolve_data_dir(
|
||||
Some(OsString::from("/tmp/creddy")),
|
||||
None,
|
||||
)?;
|
||||
assert!(data_dir == PathBuf::from("/tmp/creddy"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_data_dir_default() -> TestResult {
|
||||
let data_dir = AppConfig::resolve_data_dir(
|
||||
None,
|
||||
Some(PathBuf::from("/tmp")),
|
||||
)?;
|
||||
|
||||
assert!(data_dir == PathBuf::from("/tmp/creddy"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_config_paths() {
|
||||
let mut config = AppConfig::default();
|
||||
config.data_dir = PathBuf::from("/tmp/creddy");
|
||||
|
||||
assert!(config.db_path() == PathBuf::from("/tmp/creddy/creddy.duckdb"));
|
||||
assert!(config.public_config_path() == PathBuf::from("/tmp/creddy/public_config.json"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_public_config_from_app_config() {
|
||||
let mut config = AppConfig::default();
|
||||
config.data_dir = PathBuf::from("/tmp/creddy");
|
||||
|
||||
let public = config.public_config();
|
||||
assert!(public.db_salt == config.db_salt);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_public_config_save_load() -> TestResult {
|
||||
let file = NamedTempFile::new()?;
|
||||
let expected = PublicConfig::default();
|
||||
expected.save(file.path())?;
|
||||
|
||||
let loaded = PublicConfig::load(file.path())?;
|
||||
assert!(loaded.db_salt == expected.db_salt);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use crate::config::PrivateConfig;
|
||||
use crate::error::CreddyError;
|
||||
use super::Db;
|
||||
|
||||
impl Db {
|
||||
pub fn load_private_config(&self) -> Result<PrivateConfig, CreddyError> {
|
||||
let conn = self.connection.lock().unwrap();
|
||||
let json: String = conn.query_row("SELECT value FROM config", [], |row| row.get(0))?;
|
||||
let config: PrivateConfig = serde_json::from_str(&json)?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub fn save_private_config(&self, config: &PrivateConfig) -> Result<(), CreddyError> {
|
||||
let json = serde_json::to_string(&config)?;
|
||||
let conn = self.connection.lock().unwrap();
|
||||
conn.execute("INSERT INTO config VALUES (?);", [&json])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use testresult::TestResult;
|
||||
use tempfile::TempDir;
|
||||
use crate::config::AppConfig;
|
||||
use super::*;
|
||||
|
||||
|
||||
fn test_db() -> Result<(Db, TempDir), CreddyError> {
|
||||
let data_dir = tempfile::tempdir()?;
|
||||
let mut config = AppConfig::default();
|
||||
config.data_dir = data_dir.path().to_path_buf();
|
||||
let db = Db::connect(&config, "correct horse battery staple")?;
|
||||
Ok((db, data_dir))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_save_private_config() -> TestResult {
|
||||
let (db, _data_dir) = test_db()?;
|
||||
let private_config = PrivateConfig::default();
|
||||
db.save_private_config(&private_config)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_priate_config() -> TestResult {
|
||||
let (db, _data_dir) = test_db()?;
|
||||
let private_config = PrivateConfig::default();
|
||||
db.save_private_config(&private_config)?;
|
||||
let loaded = db.load_private_config()?;
|
||||
assert_eq!(loaded, private_config);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
use duckdb::Connection;
|
||||
use include_dir::{Dir, include_dir};
|
||||
|
||||
use crate::error::CreddyError;
|
||||
|
||||
|
||||
static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
|
||||
|
||||
|
||||
struct Migration {
|
||||
id: &'static str,
|
||||
sql: &'static str,
|
||||
}
|
||||
|
||||
|
||||
/// Run all unapplied database migrations.
|
||||
pub fn migrate(conn: &mut Connection) -> Result<(), CreddyError> {
|
||||
apply_migrations(conn, &embedded_migrations())
|
||||
}
|
||||
|
||||
/// Sorted list of migration files, checked for utf-8-ness at compile time.
|
||||
fn embedded_migrations() -> Vec<Migration> {
|
||||
let mut migrations: Vec<Migration> = MIGRATIONS_DIR
|
||||
.files()
|
||||
.filter(|f| f.path().extension().is_some_and(|ext| ext == "sql"))
|
||||
.map(|f| Migration {
|
||||
// these are baked in at compile time, so a bad file is a build problem, not a runtime one
|
||||
id: f.path().file_name().and_then(|n| n.to_str()).expect("migration filename is not UTF-8"),
|
||||
sql: f.contents_utf8().expect("migration file is not UTF-8"),
|
||||
})
|
||||
.collect();
|
||||
migrations.sort_by_key(|m| m.id);
|
||||
migrations
|
||||
}
|
||||
|
||||
/// Run a specific list of migrations. (Makes testing easier than always hard-coding)
|
||||
fn apply_migrations(conn: &mut Connection, known: &[Migration]) -> Result<(), CreddyError> {
|
||||
create_migrations_table(conn)?;
|
||||
let applied = list_applied_migrations(conn)?;
|
||||
|
||||
// the applied migrations must be exactly the first N known ones
|
||||
for (i, id) in applied.iter().enumerate() {
|
||||
if known.get(i).is_some_and(|m| m.id == id) {
|
||||
continue;
|
||||
}
|
||||
// at this point, either known[i] doesn't exist or doesn't match `id`
|
||||
if known.iter().any(|m| m.id == id) {
|
||||
return Err(CreddyError::MigrationOutOfOrder(id.clone()));
|
||||
}
|
||||
//
|
||||
return Err(CreddyError::DbTooNew(id.clone()));
|
||||
}
|
||||
|
||||
for migration in &known[applied.len()..] {
|
||||
let tx = conn.transaction()?;
|
||||
tx.execute_batch(migration.sql)?;
|
||||
tx.execute("INSERT INTO _migrations (id) VALUES (?);", [migration.id])?;
|
||||
tx.commit()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create the migrations table if it doesn't exist already.
|
||||
fn create_migrations_table(conn: &Connection) -> Result<(), CreddyError> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS _migrations (
|
||||
id VARCHAR PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT current_timestamp
|
||||
);",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List migrations that have been applied to this database, in the order they were applied.
|
||||
fn list_applied_migrations(conn: &Connection) -> Result<Vec<String>, CreddyError> {
|
||||
let mut stmt = conn.prepare("SELECT id FROM _migrations ORDER BY id;")?;
|
||||
let ids = stmt
|
||||
.query_map([], |row| row.get(0))?
|
||||
.collect::<Result<Vec<String>, _>>()?;
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use testresult::TestResult;
|
||||
use super::*;
|
||||
|
||||
const FIRST: Migration = Migration {
|
||||
id: "0001_first.sql",
|
||||
sql: "CREATE TABLE a (x INTEGER);",
|
||||
};
|
||||
const SECOND: Migration = Migration {
|
||||
id: "0002_second.sql",
|
||||
sql: "CREATE TABLE b (x INTEGER); INSERT INTO b VALUES (1);",
|
||||
};
|
||||
|
||||
fn table_exists(conn: &Connection, name: &str) -> duckdb::Result<bool> {
|
||||
conn.query_row(
|
||||
"SELECT count(*) > 0 FROM duckdb_tables() WHERE table_name = ?;",
|
||||
[name],
|
||||
|row| row.get(0),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_embedded_migrations_apply() -> TestResult {
|
||||
let mut conn = Connection::open_in_memory()?;
|
||||
migrate(&mut conn)?;
|
||||
|
||||
let applied = list_applied_migrations(&conn)?;
|
||||
let expected: Vec<_> = embedded_migrations().iter().map(|m| m.id.to_string()).collect();
|
||||
assert_eq!(applied, expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_apply_incrementally() -> TestResult {
|
||||
let mut conn = Connection::open_in_memory()?;
|
||||
apply_migrations(&mut conn, &[FIRST])?;
|
||||
assert_eq!(list_applied_migrations(&conn)?, ["0001_first.sql"]);
|
||||
|
||||
// already-applied migrations are skipped, so re-running FIRST would fail if it weren't
|
||||
apply_migrations(&mut conn, &[FIRST, SECOND])?;
|
||||
assert_eq!(list_applied_migrations(&conn)?, ["0001_first.sql", "0002_second.sql"]);
|
||||
assert!(table_exists(&conn, "b")?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_failed_migration_rolls_back() -> TestResult {
|
||||
let mut conn = Connection::open_in_memory()?;
|
||||
let broken = Migration {
|
||||
id: "0002_broken.sql",
|
||||
sql: "CREATE TABLE b (x INTEGER); this is not sql;",
|
||||
};
|
||||
|
||||
let res = apply_migrations(&mut conn, &[FIRST, broken]);
|
||||
assert!(matches!(res, Err(CreddyError::Db(_))));
|
||||
|
||||
// FIRST stays applied, but nothing from the broken migration survives
|
||||
assert_eq!(list_applied_migrations(&conn)?, ["0001_first.sql"]);
|
||||
assert!(table_exists(&conn, "a")?);
|
||||
assert!(!table_exists(&conn, "b")?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_db_too_new() -> TestResult {
|
||||
let mut conn = Connection::open_in_memory()?;
|
||||
apply_migrations(&mut conn, &[FIRST, SECOND])?;
|
||||
|
||||
// simulates running an older version of the app, which doesn't know about SECOND
|
||||
match apply_migrations(&mut conn, &[FIRST]) {
|
||||
Err(CreddyError::DbTooNew(id)) => assert_eq!(id, "0002_second.sql"),
|
||||
res => panic!("Expected DbTooNew, got {res:?}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_migration_out_of_order() -> TestResult {
|
||||
let mut conn = Connection::open_in_memory()?;
|
||||
apply_migrations(&mut conn, &[SECOND])?;
|
||||
|
||||
// FIRST sorts before an already-applied migration, so it was added after the fact
|
||||
match apply_migrations(&mut conn, &[FIRST, SECOND]) {
|
||||
Err(CreddyError::MigrationOutOfOrder(id)) => assert_eq!(id, "0002_second.sql"),
|
||||
res => panic!("Expected MigrationOutOfOrder, got {res:?}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
use std::fs;
|
||||
use std::sync::Mutex;
|
||||
use argon2::{Algorithm, Argon2, Version, Error as Argon2Error, ParamsBuilder};
|
||||
use base64ct::{Base64, Encoding};
|
||||
use duckdb::{
|
||||
Connection,
|
||||
params,
|
||||
};
|
||||
|
||||
use crate::error::CreddyError;
|
||||
use crate::config::AppConfig;
|
||||
|
||||
mod config;
|
||||
mod migrations;
|
||||
|
||||
// tests take forever with production parameters, so we turn them down in dev
|
||||
#[cfg(not(debug_assertions))]
|
||||
const MEM_COST: u32 = 128 * 1024;
|
||||
#[cfg(not(debug_assertions))]
|
||||
const TIME_COST: u32 = 8;
|
||||
#[cfg(not(debug_assertions))]
|
||||
const PARALLELISM_COST: u32 = 4;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
const MEM_COST: u32 = 1024;
|
||||
#[cfg(debug_assertions)]
|
||||
const TIME_COST: u32 = 1;
|
||||
#[cfg(debug_assertions)]
|
||||
const PARALLELISM_COST: u32 = 1;
|
||||
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Db {
|
||||
connection: Mutex<Connection>,
|
||||
}
|
||||
|
||||
impl Db {
|
||||
/// Connect to the database, creating it if necessary.
|
||||
pub fn connect(config: &AppConfig, passphrase: &str) -> Result<Self, CreddyError> {
|
||||
fs::create_dir_all(&config.data_dir)?;
|
||||
// since we are about to make use of the salt stored in `config`, we need to save it now
|
||||
config.public_config().save(&config.public_config_path())?;
|
||||
|
||||
let path = config.db_path()
|
||||
.into_os_string()
|
||||
.into_string()
|
||||
.map_err(|s| CreddyError::InvalidPath(s))?;
|
||||
let key = Db::derive_key(passphrase, &config.db_salt)?;
|
||||
dbg!(&key);
|
||||
|
||||
let mut conn = Connection::open_in_memory()?;
|
||||
conn.execute(
|
||||
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
|
||||
params![path, key],
|
||||
)?;
|
||||
// must come before migrating, or the tables end up in the in-memory db
|
||||
conn.execute("USE creddy;", [])?;
|
||||
migrations::migrate(&mut conn)?;
|
||||
Ok(Self{ connection: Mutex::new(conn) })
|
||||
}
|
||||
|
||||
/// Hash the given passphrase/salt with argon2, then encode to base64 for DuckDB
|
||||
fn derive_key(passphrase: &str, salt: &[u8; 32]) -> Result<String, Argon2Error> {
|
||||
let params = ParamsBuilder::new()
|
||||
.m_cost(MEM_COST)
|
||||
.t_cost(TIME_COST)
|
||||
.p_cost(PARALLELISM_COST)
|
||||
.build()
|
||||
.unwrap(); // only errors if the given params are invalid
|
||||
|
||||
let hasher = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
||||
|
||||
let mut key = [0; 32]; // todo: replace this with a `zeroize` or `secrecy` type
|
||||
hasher.hash_password_into(passphrase.as_bytes(), salt, &mut key)?;
|
||||
|
||||
Ok(Base64::encode_string(&key))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use testresult::TestResult;
|
||||
use duckdb::Error;
|
||||
use super::*;
|
||||
|
||||
const TEST_PASSPHRASE: &'static str = "correct horse battery staple";
|
||||
const TEST_SALT: [u8; 32] = [0; 32];
|
||||
// the result of hashing TEST_PASSPHRASE with TEST_SALT and encoding to Base64
|
||||
const TEST_KEY: &'static str = "YvOfk7EXGX+SnvdGySbTtf8OXAXg3AGikvKxJOLkLOo=";
|
||||
|
||||
#[test]
|
||||
fn test_connect_new() -> TestResult {
|
||||
let data_dir = tempfile::tempdir()?;
|
||||
let mut config = AppConfig::default();
|
||||
config.data_dir = data_dir.path().to_path_buf();
|
||||
|
||||
let res = Db::connect(&config, TEST_PASSPHRASE);
|
||||
assert!(res.is_ok());
|
||||
|
||||
// confirm that db is in fact encrypted
|
||||
match Connection::open(&config.db_path()) {
|
||||
Err(Error::DuckDBFailure(error, _desc)) => {
|
||||
assert!(error.code == duckdb::ErrorCode::Unknown);
|
||||
assert!(error.extended_code == 1);
|
||||
},
|
||||
Err(e) => panic!("Unexpected error type: {e:?}"),
|
||||
Ok(_) => panic!("Should not be able to open newly-created database without encryption key"),
|
||||
};
|
||||
|
||||
// confirm that using a different passphrase won't work
|
||||
let res = Db::connect(&config, "not the correct passphrase");
|
||||
match res {
|
||||
Err(CreddyError::Db(Error::DuckDBFailure(error, Some(desc)))) => {
|
||||
assert!(error.code == duckdb::ErrorCode::Unknown);
|
||||
assert!(error.extended_code == 1);
|
||||
assert!(desc.contains("Wrong encryption key"));
|
||||
},
|
||||
Err(e) => panic!("Unexpected error type: {e:?}"),
|
||||
Ok(_) => panic!("Should not be able to open database with a different passphrase"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connect_existing() -> TestResult {
|
||||
let data_dir = tempfile::tempdir()?;
|
||||
let mut config = AppConfig::default();
|
||||
config.data_dir = data_dir.path().to_path_buf();
|
||||
config.db_salt = TEST_SALT;
|
||||
|
||||
dbg!(TEST_KEY);
|
||||
let conn = Connection::open_in_memory()?;
|
||||
conn.execute(
|
||||
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
|
||||
params![&config.db_path().to_string_lossy(), TEST_KEY],
|
||||
)?;
|
||||
|
||||
Db::connect(&config, TEST_PASSPHRASE)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connect_create_dir() -> TestResult {
|
||||
let tmp_dir = tempfile::tempdir()?;
|
||||
|
||||
let mut config = AppConfig::default();
|
||||
config.data_dir = tmp_dir.path().join("creddy");
|
||||
// data_dir does not exist at this point
|
||||
|
||||
Db::connect(&config, TEST_PASSPHRASE)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connect_migrates_attached_db() -> TestResult {
|
||||
let data_dir = tempfile::tempdir()?;
|
||||
let mut config = AppConfig::default();
|
||||
config.data_dir = data_dir.path().to_path_buf();
|
||||
|
||||
let db = Db::connect(&config, TEST_PASSPHRASE)?;
|
||||
|
||||
// the migrations table should live in the encrypted db, not the in-memory one
|
||||
let database: String = db.connection.lock().unwrap().query_row(
|
||||
"SELECT database_name FROM duckdb_tables() WHERE table_name = '_migrations';",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
assert_eq!(database, "creddy");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_derive_key() -> TestResult {
|
||||
let key = Db::derive_key(TEST_PASSPHRASE, &TEST_SALT)?;
|
||||
dbg!(&key);
|
||||
dbg!(TEST_KEY);
|
||||
assert!(key == TEST_KEY);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use std::ffi::OsString;
|
||||
use thiserror::Error;
|
||||
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum CreddyError {
|
||||
#[error("Couldn't determine location for app state")]
|
||||
DataDirNotFound,
|
||||
|
||||
#[error("Invalid path: {0:?}")]
|
||||
InvalidPath(OsString),
|
||||
|
||||
#[error("Error from database: {0}")]
|
||||
Db(#[from] duckdb::Error),
|
||||
|
||||
#[error("I/O error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
#[error("Unable to hash password: {0}")]
|
||||
PasswordHash(#[from] argon2::Error),
|
||||
|
||||
#[error("Unable to get random data: {0}")]
|
||||
Entropy(#[from] getrandom::Error),
|
||||
|
||||
#[error("This database was created by a newer version of Creddy (unknown migration {0})")]
|
||||
DbTooNew(String),
|
||||
|
||||
#[error("Migration {0} was applied before an earlier migration that hasn't been")]
|
||||
MigrationOutOfOrder(String),
|
||||
|
||||
#[error("Invalid JSON: {0}")]
|
||||
InvalidJSON(#[from] serde_json::Error),
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
/* Simple asynchronous queue.
|
||||
To make `get` blocking, we create a new promise and store its `resolve` function in `resolvers`.
|
||||
The next time an item is added to the queue, it will be resolved.
|
||||
*/
|
||||
|
||||
export default function() {
|
||||
return {
|
||||
items: [],
|
||||
|
||||
resolvers: [],
|
||||
|
||||
put(item) {
|
||||
this.items.push(item);
|
||||
let resolver = this.resolvers.shift();
|
||||
if (resolver) {
|
||||
resolver();
|
||||
}
|
||||
},
|
||||
|
||||
async get() {
|
||||
if (this.items.length === 0) {
|
||||
await new Promise((resolve, reject) => {
|
||||
this.resolvers.push(resolve);
|
||||
})
|
||||
}
|
||||
|
||||
return this.items.shift();
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import './style.css';
|
||||
import App from './App.svelte';
|
||||
|
||||
const app = new App({
|
||||
target: document.getElementById('app')
|
||||
})
|
||||
|
||||
export default app;
|
||||
@@ -0,0 +1,70 @@
|
||||
use gpui_kit::{
|
||||
AppContext, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div,
|
||||
};
|
||||
use gpui_omarchy::ActiveTheme;
|
||||
|
||||
mod components;
|
||||
mod config;
|
||||
mod db;
|
||||
mod error;
|
||||
mod screens;
|
||||
mod session;
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_data;
|
||||
|
||||
use config::AppConfig;
|
||||
use session::AppSession;
|
||||
use screens::{HomeScreen, UnlockScreen, WelcomeScreen};
|
||||
|
||||
struct CreddyApp {}
|
||||
|
||||
impl Render for CreddyApp {
|
||||
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let session = cx.global::<AppSession>();
|
||||
let screen = match session {
|
||||
AppSession::Empty => window
|
||||
.use_keyed_state("welcome", cx, |window, cx| {
|
||||
WelcomeScreen::new(window, cx)
|
||||
})
|
||||
.into_any_element(),
|
||||
AppSession::Locked => window
|
||||
.use_keyed_state("unlock", cx, |window, cx| UnlockScreen::new(window, cx))
|
||||
.into_any_element(),
|
||||
AppSession::Unlocked { .. } => window
|
||||
.use_keyed_state("home", cx, |_, _| HomeScreen {})
|
||||
.into_any_element(),
|
||||
};
|
||||
|
||||
let theme = cx.omarchy();
|
||||
div()
|
||||
.size_full()
|
||||
.bg(theme.background)
|
||||
.text_color(theme.foreground)
|
||||
.font_family(theme.font.clone())
|
||||
.child(screen)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// todo: replace this with proper error handling
|
||||
let app_config = AppConfig::load().expect("failed to load config");
|
||||
let app_session = AppSession::load(&app_config);
|
||||
|
||||
// Icons are read through the asset source, so register the bundle.
|
||||
gpui_kit::application()
|
||||
.with_assets(gpui_kit::assets::Assets)
|
||||
.run(|app| {
|
||||
gpui_omarchy::init(app);
|
||||
app.set_global(app_config);
|
||||
app.set_global(app_session);
|
||||
// refresh_windows() forces everything to re-render, which is kind of a nuclear solution,
|
||||
// but these values aren't expected to change very frequently, so it shouldn't be a problem
|
||||
app.observe_global::<AppConfig>(|app| app.refresh_windows()).detach();
|
||||
app.observe_global::<AppSession>(|app| app.refresh_windows()).detach();
|
||||
|
||||
app.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {}))
|
||||
.expect("open window");
|
||||
app.activate(true);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use gpui_kit::{div, Render, Window, Context, IntoElement, Styled, ParentElement};
|
||||
|
||||
pub struct HomeScreen {}
|
||||
|
||||
impl Render for HomeScreen {
|
||||
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
||||
div()
|
||||
.flex()
|
||||
.justify_center()
|
||||
.items_center()
|
||||
.child("Creddy is unlocked")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
mod home;
|
||||
mod unlock;
|
||||
mod welcome;
|
||||
|
||||
pub use home::HomeScreen;
|
||||
pub use unlock::UnlockScreen;
|
||||
pub use welcome::WelcomeScreen;
|
||||
@@ -0,0 +1,137 @@
|
||||
use gpui_kit::{
|
||||
AppContext, BorrowAppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString,
|
||||
Styled, Subscription, Task, Window, div, rems,
|
||||
};
|
||||
use gpui_omarchy::{ButtonVariant, Status, alert, button, focus_scope};
|
||||
|
||||
use crate::components::{PassphraseInput, PassphraseInputEvent};
|
||||
use crate::config::AppConfig;
|
||||
use crate::db::Db;
|
||||
use crate::error::CreddyError;
|
||||
use crate::session::AppSession;
|
||||
|
||||
|
||||
/// Shown at startup when a database exists: enter the passphrase to open it.
|
||||
pub struct UnlockScreen {
|
||||
passphrase: Entity<PassphraseInput>,
|
||||
error: Option<SharedString>,
|
||||
/// Set while the KDF is running; dropping it cancels the task.
|
||||
pending: Option<Task<()>>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl UnlockScreen {
|
||||
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
// nothing else shares the show/hide flag, so it's private to this input
|
||||
let show = cx.new(|_| false);
|
||||
let passphrase = cx.new(|cx| PassphraseInput::new(show, window, cx));
|
||||
passphrase.update(cx, |input, cx| input.focus(window, cx));
|
||||
|
||||
let submit = cx.subscribe_in(&passphrase, window, |this, _, event, window, cx| {
|
||||
if let PassphraseInputEvent::Submit = event {
|
||||
this.submit(window, cx);
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
passphrase,
|
||||
error: None,
|
||||
pending: None,
|
||||
_subscriptions: vec![submit],
|
||||
}
|
||||
}
|
||||
|
||||
fn submit(&mut self, _: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.pending.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let passphrase = self.passphrase.read(cx).value(cx);
|
||||
if passphrase.is_empty() {
|
||||
self.error = Some("Passphrase is empty.".into());
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
|
||||
let config = cx.global::<AppConfig>().clone();
|
||||
self.error = None;
|
||||
self.pending = Some(cx.spawn(async move |this, cx| {
|
||||
// argon2 is deliberately slow, so keep it off the UI thread
|
||||
let result = cx
|
||||
.background_spawn(async move {
|
||||
let db = Db::connect(&config, passphrase.as_str())?;
|
||||
// Some of AppConfig comes from the db, but we couldn't see it until now
|
||||
let private_config = db.load_private_config()?;
|
||||
Ok((db, private_config))
|
||||
})
|
||||
.await;
|
||||
|
||||
// db connection has been established or not, so now we handle the result
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.pending = None;
|
||||
match result {
|
||||
Ok((db, private_config)) => {
|
||||
cx.update_global::<AppConfig, _>(|config, _cx| config.merge_private(private_config));
|
||||
cx.set_global(AppSession::Unlocked(db));
|
||||
},
|
||||
Err(e) => this.error = Some(error_message(&e)),
|
||||
}
|
||||
cx.notify();
|
||||
});
|
||||
}));
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn a failed unlock into something fit to show the user.
|
||||
fn error_message(e: &CreddyError) -> SharedString {
|
||||
// todo: have Db::connect return a dedicated error variant for this instead
|
||||
if let CreddyError::Db(duckdb::Error::DuckDBFailure(_, Some(desc))) = e
|
||||
&& desc.contains("Wrong encryption key")
|
||||
{
|
||||
return "Incorrect passphrase.".into();
|
||||
}
|
||||
format!("Failed to unlock: {e}").into()
|
||||
}
|
||||
|
||||
impl Render for UnlockScreen {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
focus_scope("unlock")
|
||||
.size_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.items_center()
|
||||
.p(rems(0.5))
|
||||
.child(
|
||||
div()
|
||||
.text_size(rems(1.875))
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.child("Creddy is locked"),
|
||||
)
|
||||
.child(
|
||||
// fill the rest of the window so the form sits in the middle of it
|
||||
div()
|
||||
.flex_1()
|
||||
.w_full()
|
||||
.max_w(rems(24.))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.justify_center()
|
||||
.gap(rems(1.))
|
||||
.child(
|
||||
div()
|
||||
.text_center()
|
||||
.text_size(rems(1.25))
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.child("Please enter your passphrase"),
|
||||
)
|
||||
.children(self.error.clone().map(|e| alert(e, Status::Error, cx)))
|
||||
.child(self.passphrase.clone())
|
||||
.child(
|
||||
button("submit", "Submit", ButtonVariant::Primary, cx)
|
||||
.disabled(self.pending.is_some())
|
||||
.on_click(cx.listener(|this, _, window, cx| this.submit(window, cx))),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
use gpui_kit::{
|
||||
AppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString,
|
||||
Styled, Subscription, Task,Window, div, rems,
|
||||
};
|
||||
use gpui_omarchy::{ActiveTheme, ButtonVariant, Status, alert, button, focus_scope};
|
||||
|
||||
use crate::components::{PassphraseInput, PassphraseInputEvent};
|
||||
use crate::config::AppConfig;
|
||||
use crate::db::Db;
|
||||
use crate::session::AppSession;
|
||||
|
||||
|
||||
const MISMATCH: &str = "Passphrases do not match.";
|
||||
|
||||
|
||||
/// First-run screen: choose a passphrase, derive the key, and unlock the session.
|
||||
pub struct WelcomeScreen {
|
||||
passphrase: Entity<PassphraseInput>,
|
||||
confirm: Entity<PassphraseInput>,
|
||||
error: Option<SharedString>,
|
||||
/// Set while the KDF is running; dropping it cancels the task.
|
||||
pending: Option<Task<()>>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl WelcomeScreen {
|
||||
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let show = cx.new(|_| false);
|
||||
let passphrase = cx.new(|cx| PassphraseInput::new(show.clone(), window, cx));
|
||||
let confirm = cx.new(|cx| PassphraseInput::new(show, window, cx));
|
||||
passphrase.update(cx, |input, cx| input.focus(window, cx));
|
||||
|
||||
let mut _subscriptions = Vec::new();
|
||||
for input in [&passphrase, &confirm] {
|
||||
_subscriptions.push(cx.subscribe_in(input, window, |this, _, event, window, cx| {
|
||||
match event {
|
||||
PassphraseInputEvent::Submit => this.submit(window, cx),
|
||||
// typing only dismisses the mismatch error, never raises it
|
||||
PassphraseInputEvent::Change if this.passphrases_match(cx) => {
|
||||
this.error = None;
|
||||
cx.notify();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}));
|
||||
}
|
||||
// leaving the confirm field is what raises the mismatch error
|
||||
_subscriptions.push(cx.subscribe_in(&confirm, window, |this, _, event, _, cx| {
|
||||
if let PassphraseInputEvent::Blur = event
|
||||
&& !this.passphrases_match(cx)
|
||||
{
|
||||
this.error = Some(MISMATCH.into());
|
||||
cx.notify();
|
||||
}
|
||||
}));
|
||||
|
||||
Self {
|
||||
passphrase,
|
||||
confirm,
|
||||
error: None,
|
||||
pending: None,
|
||||
_subscriptions,
|
||||
}
|
||||
}
|
||||
|
||||
fn passphrases_match(&self, cx: &Context<Self>) -> bool {
|
||||
self.passphrase.read(cx).value(cx) == self.confirm.read(cx).value(cx)
|
||||
}
|
||||
|
||||
fn submit(&mut self, _: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.pending.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let passphrase = self.passphrase.read(cx).value(cx);
|
||||
if !self.passphrases_match(cx) {
|
||||
self.error = Some(MISMATCH.into());
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
if passphrase.is_empty() {
|
||||
self.error = Some("Passphrase is empty.".into());
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
|
||||
let config = cx.global::<AppConfig>().clone();
|
||||
self.error = None;
|
||||
// todo: persist the salt (and KDF params) so the database can be unlocked again later
|
||||
self.pending = Some(cx.spawn(async move |this, cx| {
|
||||
// argon2 is deliberately slow, so keep it off the UI thread
|
||||
let result = cx
|
||||
.background_spawn(async move {
|
||||
Db::connect(&config, passphrase.as_str())
|
||||
})
|
||||
.await;
|
||||
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.pending = None;
|
||||
match result {
|
||||
Ok(db) => cx.set_global(AppSession::Unlocked(db)),
|
||||
Err(e) => this.error = Some(format!("Failed to derive key: {e}").into()),
|
||||
}
|
||||
cx.notify();
|
||||
});
|
||||
}));
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for WelcomeScreen {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let t = cx.omarchy();
|
||||
let field = |label: &'static str, input: &Entity<PassphraseInput>| {
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(rems(0.25))
|
||||
.child(div().text_size(rems(0.875)).child(label))
|
||||
.child(input.clone())
|
||||
};
|
||||
|
||||
focus_scope("welcome")
|
||||
.size_full()
|
||||
.flex()
|
||||
.justify_center()
|
||||
.items_center()
|
||||
.bg(t.background)
|
||||
.text_color(t.foreground)
|
||||
.font_family(t.font.clone())
|
||||
.child(
|
||||
div()
|
||||
.w_full()
|
||||
.max_w(rems(32.))
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(rems(2.))
|
||||
.child(
|
||||
div()
|
||||
.text_center()
|
||||
.text_size(rems(1.5))
|
||||
.font_weight(FontWeight::BOLD)
|
||||
.child("Welcome to Creddy!"),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(rems(1.))
|
||||
.child("Create a passphrase to get started.")
|
||||
.child(
|
||||
"Please note that if you forget your passphrase, there is no way \
|
||||
to recover your stored credentials. You will have to start over \
|
||||
with a new passphrase.",
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.w_full()
|
||||
.max_w(rems(24.))
|
||||
.mx_auto()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(rems(1.))
|
||||
.children(self.error.clone().map(|e| alert(e, Status::Error, cx)))
|
||||
.child(field("Passphrase", &self.passphrase))
|
||||
.child(field("Re-enter passphrase", &self.confirm))
|
||||
.child(
|
||||
button("submit", "Submit", ButtonVariant::Primary, cx)
|
||||
.disabled(self.pending.is_some())
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.submit(window, cx)
|
||||
})),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use gpui_kit::Global;
|
||||
use crate::config::AppConfig;
|
||||
use crate::error::CreddyError;
|
||||
use crate::db::Db;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AppSession {
|
||||
Empty,
|
||||
Locked,
|
||||
Unlocked(Db),
|
||||
}
|
||||
|
||||
impl AppSession {
|
||||
pub fn load(config: &AppConfig) -> AppSession {
|
||||
if config.db_path().exists() {
|
||||
AppSession::Locked
|
||||
} else {
|
||||
AppSession::Empty
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unlock(&mut self, passphrase: &str) -> Result<AppSession, CreddyError> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl Global for AppSession {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// #[test]
|
||||
// fn test_new() {
|
||||
// let passphrase = "correct horse battery staple";
|
||||
// let salt = AppSession::salt().expect("salt generation failed.");
|
||||
// let session = AppSession::new(passphrase, &salt).expect("password KDF failed.");
|
||||
// match session {
|
||||
// AppSession::Unlocked { .. } => (),
|
||||
// _ => panic!("AppSession::new() should return an unlocked session"),
|
||||
// }
|
||||
// }
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@@ -1,39 +0,0 @@
|
||||
<script>
|
||||
import { createEventDispatcher } from 'svelte';
|
||||
import { invoke } from '@tauri-apps/api/tauri';
|
||||
|
||||
export let appState;
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
|
||||
async function approve() {
|
||||
let status = await invoke('get_session_status');
|
||||
if (status === 'unlocked') {
|
||||
dispatch('navigate', {target: 'ShowApproved'});
|
||||
}
|
||||
else if (status === 'locked') {
|
||||
dispatch('navigate', {target: 'Unlock'})
|
||||
}
|
||||
else {
|
||||
dispatch('navigate', {target: 'EnterCredentials'});
|
||||
}
|
||||
}
|
||||
|
||||
function deny() {
|
||||
dispatch('navigate', {target: 'ShowDenied'});
|
||||
}
|
||||
</script>
|
||||
|
||||
<h2 class="text-3xl text-gray-200">An application would like to access your AWS credentials.</h2>
|
||||
|
||||
<button on:click={approve}>
|
||||
<svg class="w-32 stroke-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<button on:click={deny}>
|
||||
<svg class="w-32 stroke-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
@@ -1,41 +0,0 @@
|
||||
<script>
|
||||
import { onMount, createEventDispatcher } from 'svelte';
|
||||
import { invoke } from '@tauri-apps/api/tauri';
|
||||
|
||||
export let appState;
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
let AccessKeyId, SecretAccessKey, passphrase
|
||||
|
||||
async function save() {
|
||||
try {
|
||||
console.log('Saving credentials.');
|
||||
let credentials = {AccessKeyId, SecretAccessKey};
|
||||
console.log(credentials);
|
||||
await invoke('save_credentials', {credentials, passphrase});
|
||||
if (appState.currentRequest) {
|
||||
dispatch('navigate', {target: 'ShowApproved'})
|
||||
}
|
||||
else {
|
||||
dispatch('navigate', {target: 'Home'})
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.log("Error saving credentials:", e);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
<form action="#" on:submit|preventDefault="{save}">
|
||||
<div class="text-gray-200">AWS Access Key ID</div>
|
||||
<input class="text-gray-200 bg-zinc-800" type="text" bind:value="{AccessKeyId}" />
|
||||
|
||||
<div class="text-gray-200">AWS Secret Access Key</div>
|
||||
<input class="text-gray-200 bg-zinc-800" type="text" bind:value="{SecretAccessKey}" />
|
||||
|
||||
<div class="text-gray-200">Passphrase</div>
|
||||
<input class="text-gray-200 bg-zinc-800" type="text" bind:value="{passphrase}" />
|
||||
|
||||
<input class="text-gray-200" type="submit" />
|
||||
</form>
|
||||
@@ -1,18 +0,0 @@
|
||||
<script>
|
||||
import { onMount, createEventDispatcher } from 'svelte';
|
||||
|
||||
export let appState;
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
|
||||
onMount(async () => {
|
||||
// will block until a request comes in
|
||||
let req = await appState.pendingRequests.get();
|
||||
appState.currentRequest = req;
|
||||
console.log('Got credentials request from queue:');
|
||||
console.log(req);
|
||||
dispatch('navigate', {target: 'Approve'});
|
||||
});
|
||||
</script>
|
||||
|
||||
<h1 class="text-4xl text-gray-300">Creddy</h1>
|
||||
@@ -1,21 +0,0 @@
|
||||
<script>
|
||||
import { onMount, createEventDispatcher } from 'svelte';
|
||||
import { emit } from '@tauri-apps/api/event';
|
||||
import { invoke } from '@tauri-apps/api/tauri';
|
||||
|
||||
export let appState;
|
||||
|
||||
onMount(async () => {
|
||||
let response = {
|
||||
id: appState.currentRequest.id,
|
||||
approval: 'Approved',
|
||||
}
|
||||
await invoke('respond', {response});
|
||||
appState.currentRequest = null;
|
||||
});
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
window.setTimeout(() => dispatch('navigate', {target: 'Home'}), 3000);
|
||||
</script>
|
||||
|
||||
<h1 class="text-4xl text-gray-300">Approved!</h1>
|
||||
@@ -1,21 +0,0 @@
|
||||
<script>
|
||||
import { onMount, createEventDispatcher } from 'svelte';
|
||||
import { emit } from '@tauri-apps/api/event';
|
||||
import { invoke } from '@tauri-apps/api/tauri';
|
||||
|
||||
export let appState;
|
||||
|
||||
onMount(async () => {
|
||||
let response = {
|
||||
id: appState.currentRequest.id,
|
||||
approval: 'Denied',
|
||||
}
|
||||
await invoke('respond', {response});
|
||||
appState.currentRequest = null;
|
||||
});
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
window.setTimeout(() => dispatch('navigate', {target: 'Home'}), 3000);
|
||||
</script>
|
||||
|
||||
<h1 class="text-4xl text-gray-300">Denied!</h1>
|
||||
@@ -1,25 +0,0 @@
|
||||
<script>
|
||||
import { invoke } from '@tauri-apps/api/tauri';
|
||||
import { createEventDispatcher } from 'svelte';
|
||||
|
||||
export let appState;
|
||||
|
||||
const dispatch = createEventDispatcher();
|
||||
|
||||
let passphrase = '';
|
||||
async function unlock() {
|
||||
console.log('invoking unlock command.')
|
||||
|
||||
try {
|
||||
await invoke('unlock', {passphrase});
|
||||
}
|
||||
catch (e) {
|
||||
console.log('Unlock error:', e);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<form action="#" on:submit|preventDefault="{unlock}">
|
||||
<div class="text-gray-200">Enter your passphrase:</div>
|
||||
<input class="text-gray-200 bg-zinc-800" type="password" placeholder="correct horse battery staple" bind:value="{passphrase}" />
|
||||
</form>
|
||||
@@ -1,11 +0,0 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: [
|
||||
"./index.html",
|
||||
"./src/**/*.{svelte,html}",
|
||||
],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import { svelte } from '@sveltejs/vite-plugin-svelte'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [svelte()]
|
||||
})
|
||||