Add ed-onde-account, an Onde account client
Signs a user in through the ondeinference.com API, finds or creates their app, activates it and returns the Onde Cloud key. ensure_key reuses an app by name, so calling it twice never makes a second one. The crate holds no Onde secrets: the API adds the smbCloud credentials on the server. Covered by tests against an in-process mock of the API. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Co-Authored-By: siGit Code v1.6.6 <noreply@sigit.si>
Seto Elkahfi committed
Oct 9, 2026 at 21:51 UTC
d8fc53e3487df2ae619610e3a7f0b349bed574b6
9 files changed
+929
Cargo.lock
+12
@@ -2062,6 +2062,18 @@ dependencies = [
2062
"tracing",
2063
]
2064
2065
+[[package]]
2066
+name = "ed-onde-account"
2067
+version = "1.2.1"
2068
+dependencies = [
2069
+ "axum",
2070
+ "reqwest 0.13.5",
2071
+ "serde",
2072
+ "serde_json",
2073
+ "thiserror 2.0.21",
2074
+ "tokio",
2075
+]
2076
+
2077
[[package]]
2078
name = "ed-uniffi-bindgen"
2079
version = "0.1.0"
Cargo.toml
+2
@@ -8,6 +8,7 @@ members = [
8
"crates/ed-acp",
9
"crates/ed-acp-tui",
10
"crates/ed-acp-testkit",
11
+ "crates/ed-onde-account",
12
"uniffi-bindgen",
13
]
14
@@ -62,6 +63,7 @@ ed-mcp = { version = "1.2.1", path = "crates/ed-mcp" }
63
ed-acp = { version = "1.2.1", path = "crates/ed-acp" }
64
ed-acp-tui = { version = "1.2.1", path = "crates/ed-acp-tui" }
65
ed-acp-testkit = { version = "1.2.1", path = "crates/ed-acp-testkit" }
66
+ed-onde-account = { version = "1.2.1", path = "crates/ed-onde-account" }
67
68
# gemm-common (via candle, via onde) depends on sysctl for every
69
# `target_vendor = "apple"`, but sysctl 0.6.0 only has a `sys` module behind
README.md
+1
@@ -84,6 +84,7 @@ The Onde Agent Platform crates, for agents that editors drive over the Agent Cli
84
| [`ed-acp`](crates/ed-acp) | An ACP v1 server: sessions, auth, the turn loop on Onde Cloud, tool approval, workspace tools and MCP. A product supplies a `Profile`. |
85
| [`ed-acp-tui`](crates/ed-acp-tui) | A terminal UI for any ACP agent. |
86
| [`ed-mcp`](crates/ed-mcp) | MCP client glue over `rmcp`, the official Rust SDK: stdio and streamable HTTP servers, bearer tokens, tool namespacing, timeouts, progress and cancellation. With the `agent` feature, `McpExecutor` serves a toolset to Ed as tools. |
87
+| [`ed-onde-account`](crates/ed-onde-account) | Onde Inference account client: sign in, activate an app and get its Onde Cloud API key through ondeinference.com, with no Onde secrets in the host app. |
88
| [`ed-acp-testkit`](crates/ed-acp-testkit) | Mock Onde Cloud endpoint, raw ACP client, the ACP registry probe and the ACP v1 conformance suite. |
89
90
Free the intelligence.
crates/ed-onde-account/Cargo.toml
new
+22
@@ -0,0 +1,22 @@
1
+[package]
2
+name = "ed-onde-account"
3
+description = "Onde Inference account client for Onde agents: sign in, list and activate apps, and mint an Onde Cloud API key through the ondeinference.com API. Holds no Onde secrets."
4
+keywords = ["onde", "agent", "auth", "api-key"]
5
+categories = ["api-bindings", "authentication"]
6
+version.workspace = true
7
+edition = "2024"
8
+rust-version.workspace = true
9
+license.workspace = true
10
+authors.workspace = true
11
+repository.workspace = true
12
+homepage.workspace = true
13
+
14
+[dependencies]
15
+reqwest.workspace = true
16
+serde.workspace = true
17
+serde_json.workspace = true
18
+thiserror.workspace = true
19
+
20
+[dev-dependencies]
21
+axum = "0.8"
22
+tokio = { workspace = true, features = ["macros", "net", "rt-multi-thread"] }
crates/ed-onde-account/LICENSE-APACHE
new
+202
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Splitfire AB (Onde Inference)
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
crates/ed-onde-account/LICENSE-MIT
new
+21
@@ -0,0 +1,21 @@
1
+MIT License
2
+
3
+Copyright (c) 2026 Splitfire AB (Onde Inference)
4
+
5
+Permission is hereby granted, free of charge, to any person obtaining a copy
6
+of this software and associated documentation files (the "Software"), to deal
7
+in the Software without restriction, including without limitation the rights
8
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+copies of the Software, and to permit persons to whom the Software is
10
+furnished to do so, subject to the following conditions:
11
+
12
+The above copyright notice and this permission notice shall be included in all
13
+copies or substantial portions of the Software.
14
+
15
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+SOFTWARE.
crates/ed-onde-account/README.md
new
+35
@@ -0,0 +1,35 @@
1
+# ed-onde-account
2
+
3
+An Onde Inference account client for [Ed](https://crates.io/crates/ed-agent) agents.
4
+
5
+It signs a user in to their Onde account, finds or creates their app, activates it, and returns
6
+the Onde Cloud API key (`app_id:app_secret`) an agent authenticates with. Every call goes through
7
+the ondeinference.com API, which keeps Onde's smbCloud credentials on the server, so nothing
8
+secret ships in the app that embeds this crate.
9
+
10
+```rust
11
+use ed_onde_account::{OndeAccount, SignIn};
12
+
13
+let account = OndeAccount::new(); // https://ondeinference.com, production
14
+match account.sign_in("me@example.com", "password").await? {
15
+ SignIn::Ready(token) => {
16
+ // Reuses the app named "My Agent", or creates and activates it.
17
+ let key = account.ensure_key(&token, "My Agent").await?;
18
+ println!("{}", key.as_str()); // app_id:app_secret
19
+ }
20
+ SignIn::NotFound => { /* no account yet */ }
21
+ SignIn::Incomplete { .. } => { /* e.g. the email isn't confirmed */ }
22
+}
23
+```
24
+
25
+- `sign_in`, `me`, `apps`, `create_app`, `activate` and `ensure_key`.
26
+- `ensure_key` is idempotent: it never creates a second app with the same name.
27
+- Errors are typed. `Error::Unauthorized` means the token expired and the user must sign in again;
28
+ `Error::Forbidden` means the account may not create apps.
29
+- `AccessToken` and `ApiKey` redact themselves in `Debug` output.
30
+
31
+Creating apps needs an Onde account that is allowed to, which every signed-up user is.
32
+
33
+## License
34
+
35
+MIT OR Apache-2.0
crates/ed-onde-account/src/lib.rs
new
+393
@@ -0,0 +1,393 @@
1
+//! A small client for the Onde Inference account API at ondeinference.com.
2
+//!
3
+//! It signs a user in, finds or creates their app, activates it and returns the Onde Cloud
4
+//! API key (`app_id:app_secret`) an agent authenticates with. Every call goes through
5
+//! onde-web's own API, which adds the smbCloud client credentials on the server, so no
6
+//! Onde secret ships in whatever embeds this crate.
7
+//!
8
+//! ```no_run
9
+//! # async fn run() -> Result<(), ed_onde_account::Error> {
10
+//! use ed_onde_account::{OndeAccount, SignIn};
11
+//!
12
+//! let account = OndeAccount::new();
13
+//! if let SignIn::Ready(token) = account.sign_in("me@example.com", "password").await? {
14
+//! let key = account.ensure_key(&token, "My Agent").await?;
15
+//! // key.as_str() is "app_id:app_secret"
16
+//! }
17
+//! # Ok(())
18
+//! # }
19
+//! ```
20
+
21
+use std::fmt;
22
+
23
+use reqwest::{Method, RequestBuilder, StatusCode, Url};
24
+use serde::{Deserialize, Deserializer};
25
+use serde_json::{Value, json};
26
+
27
+/// The production API host.
28
+pub const DEFAULT_BASE_URL: &str = "https://ondeinference.com";
29
+
30
+pub type Result<T, E = Error> = std::result::Result<T, E>;
31
+
32
+#[derive(Debug, thiserror::Error)]
33
+pub enum Error {
34
+ /// The access token is missing, expired or revoked. Sign in again.
35
+ #[error("not signed in, or the session expired")]
36
+ Unauthorized,
37
+ /// Sign-in was refused: the email and password don't match.
38
+ #[error("incorrect email or password")]
39
+ InvalidCredentials,
40
+ /// Signed in, but this account may not do that.
41
+ #[error("this Onde account is not allowed to do that")]
42
+ Forbidden,
43
+ /// The user's app with this name exists but is suspended, so it cannot get a key.
44
+ #[error("the app \"{0}\" is suspended")]
45
+ Suspended(String),
46
+ /// The API answered with another failure status.
47
+ #[error("Onde API error {status}: {message}")]
48
+ Http { status: u16, message: String },
49
+ /// The API answered, but not with the shape this client expects.
50
+ #[error("unexpected response from the Onde API: {0}")]
51
+ Unexpected(String),
52
+ /// The request never completed.
53
+ #[error("could not reach the Onde API: {0}")]
54
+ Transport(#[from] reqwest::Error),
55
+}
56
+
57
+/// Which Onde backend to talk to. Production unless a host is testing against the dev stack.
58
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
59
+pub enum OndeEnv {
60
+ #[default]
61
+ Production,
62
+ Development,
63
+}
64
+
65
+impl OndeEnv {
66
+ fn as_str(self) -> &'static str {
67
+ match self {
68
+ Self::Production => "production",
69
+ Self::Development => "development",
70
+ }
71
+ }
72
+}
73
+
74
+/// The smbCloud access token for a signed-in user. Debug output is redacted.
75
+#[derive(Clone, PartialEq, Eq)]
76
+pub struct AccessToken(String);
77
+
78
+impl AccessToken {
79
+ /// Wrap a token, stripping surrounding whitespace and any `Bearer ` prefixes.
80
+ pub fn new(token: impl AsRef<str>) -> Self {
81
+ let mut token = token.as_ref().trim();
82
+ while let Some(prefix) = token.get(..7) {
83
+ if !prefix.eq_ignore_ascii_case("bearer ") {
84
+ break;
85
+ }
86
+ token = token[7..].trim_start();
87
+ }
88
+ Self(token.to_owned())
89
+ }
90
+
91
+ pub fn as_str(&self) -> &str {
92
+ &self.0
93
+ }
94
+}
95
+
96
+impl fmt::Debug for AccessToken {
97
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98
+ f.write_str("AccessToken(<redacted>)")
99
+ }
100
+}
101
+
102
+/// An Onde Cloud API key, `app_id:app_secret`. Debug output is redacted.
103
+#[derive(Clone, PartialEq, Eq)]
104
+pub struct ApiKey(String);
105
+
106
+impl ApiKey {
107
+ pub fn new(app_id: &str, app_secret: &str) -> Self {
108
+ Self(format!("{app_id}:{app_secret}"))
109
+ }
110
+
111
+ pub fn as_str(&self) -> &str {
112
+ &self.0
113
+ }
114
+}
115
+
116
+impl fmt::Debug for ApiKey {
117
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118
+ f.write_str("ApiKey(<redacted>)")
119
+ }
120
+}
121
+
122
+/// How a sign-in attempt ended.
123
+#[derive(Debug, Clone, PartialEq, Eq)]
124
+pub enum SignIn {
125
+ Ready(AccessToken),
126
+ /// No account for this email.
127
+ NotFound,
128
+ /// The account exists but cannot sign in yet, for instance an unconfirmed email.
129
+ Incomplete {
130
+ error_code: Option<i64>,
131
+ },
132
+}
133
+
134
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
135
+#[serde(rename_all = "lowercase")]
136
+pub enum AppStatus {
137
+ Provisioning,
138
+ Active,
139
+ Suspended,
140
+ #[serde(other)]
141
+ Unknown,
142
+}
143
+
144
+/// An Onde app, the thing an API key belongs to.
145
+#[derive(Clone, Deserialize)]
146
+pub struct OndeApp {
147
+ #[serde(deserialize_with = "string_or_number")]
148
+ pub id: String,
149
+ pub name: String,
150
+ pub status: AppStatus,
151
+ #[serde(default, deserialize_with = "opt_string_or_number")]
152
+ pub app_id: Option<String>,
153
+ pub app_secret: Option<String>,
154
+}
155
+
156
+impl fmt::Debug for OndeApp {
157
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158
+ f.debug_struct("OndeApp")
159
+ .field("id", &self.id)
160
+ .field("name", &self.name)
161
+ .field("status", &self.status)
162
+ .field(
163
+ "app_secret",
164
+ &self.app_secret.as_ref().map(|_| "<redacted>"),
165
+ )
166
+ .finish()
167
+ }
168
+}
169
+
170
+impl OndeApp {
171
+ /// The key for this app, if the secret is present.
172
+ pub fn api_key(&self) -> Option<ApiKey> {
173
+ let secret = self.app_secret.as_deref().filter(|s| !s.is_empty())?;
174
+ Some(ApiKey::new(
175
+ self.app_id.as_deref().unwrap_or(&self.id),
176
+ secret,
177
+ ))
178
+ }
179
+}
180
+
181
+/// The signed-in user.
182
+#[derive(Debug, Clone, PartialEq, Eq)]
183
+pub struct Profile {
184
+ pub email: String,
185
+ pub name: Option<String>,
186
+ /// Whether the account may create apps (and so keys).
187
+ pub can_create: bool,
188
+}
189
+
190
+#[derive(Debug, Clone)]
191
+pub struct OndeAccount {
192
+ http: reqwest::Client,
193
+ base_url: Url,
194
+ env: OndeEnv,
195
+}
196
+
197
+impl Default for OndeAccount {
198
+ fn default() -> Self {
199
+ Self::new()
200
+ }
201
+}
202
+
203
+impl OndeAccount {
204
+ /// Production at ondeinference.com.
205
+ pub fn new() -> Self {
206
+ Self::with_base_url(DEFAULT_BASE_URL).expect("the default base URL is valid")
207
+ }
208
+
209
+ /// Point at another host, such as a local onde-web or a test server.
210
+ pub fn with_base_url(base_url: &str) -> Result<Self> {
211
+ let base_url = Url::parse(base_url)
212
+ .map_err(|e| Error::Unexpected(format!("invalid base URL: {e}")))?;
213
+ Ok(Self {
214
+ http: reqwest::Client::new(),
215
+ base_url,
216
+ env: OndeEnv::default(),
217
+ })
218
+ }
219
+
220
+ pub fn with_env(mut self, env: OndeEnv) -> Self {
221
+ self.env = env;
222
+ self
223
+ }
224
+
225
+ pub async fn sign_in(&self, email: &str, password: &str) -> Result<SignIn> {
226
+ let body = json!({ "email": email.trim(), "password": password });
227
+ let value = self
228
+ .send(self.request(Method::POST, "/api/auth/sign-in").json(&body))
229
+ .await
230
+ // There is no token to expire yet, so a 401 here is a wrong password.
231
+ .map_err(|e| match e {
232
+ Error::Unauthorized => Error::InvalidCredentials,
233
+ e => e,
234
+ })?;
235
+ match value.get("status").and_then(Value::as_str) {
236
+ Some("ready") => match value.get("accessToken").and_then(Value::as_str) {
237
+ Some(token) if !AccessToken::new(token).as_str().is_empty() => {
238
+ Ok(SignIn::Ready(AccessToken::new(token)))
239
+ }
240
+ _ => Err(Error::Unexpected(
241
+ "sign-in was ready without a token".into(),
242
+ )),
243
+ },
244
+ Some("notFound") => Ok(SignIn::NotFound),
245
+ Some("incomplete") => Ok(SignIn::Incomplete {
246
+ error_code: value.get("errorCode").and_then(Value::as_i64),
247
+ }),
248
+ _ => Err(Error::Unexpected("unknown sign-in status".into())),
249
+ }
250
+ }
251
+
252
+ pub async fn me(&self, token: &AccessToken) -> Result<Profile> {
253
+ let value = self
254
+ .send(
255
+ self.request(Method::GET, "/api/auth/me")
256
+ .bearer_auth(token.as_str()),
257
+ )
258
+ .await?;
259
+ let flag = |key: &str| value.get(key).and_then(Value::as_bool);
260
+ Ok(Profile {
261
+ email: value
262
+ .get("email")
263
+ .and_then(Value::as_str)
264
+ .unwrap_or_default()
265
+ .to_owned(),
266
+ name: value.get("name").and_then(Value::as_str).map(str::to_owned),
267
+ can_create: flag("can_create_gresiq_apps")
268
+ .or_else(|| flag("can_manage_all_gresiq_apps"))
269
+ .unwrap_or(false),
270
+ })
271
+ }
272
+
273
+ pub async fn apps(&self, token: &AccessToken) -> Result<Vec<OndeApp>> {
274
+ let value = self
275
+ .send(
276
+ self.request(Method::GET, "/api/gresiq/apps")
277
+ .bearer_auth(token.as_str()),
278
+ )
279
+ .await?;
280
+ decode(value)
281
+ }
282
+
283
+ pub async fn create_app(&self, token: &AccessToken, name: &str) -> Result<OndeApp> {
284
+ let value = self
285
+ .send(
286
+ self.request(Method::POST, "/api/gresiq/apps")
287
+ .bearer_auth(token.as_str())
288
+ .json(&json!({ "gresiq_app": { "name": name } })),
289
+ )
290
+ .await?;
291
+ decode(value)
292
+ }
293
+
294
+ /// Move a provisioning app to `active`. Onde Cloud refuses its key until then.
295
+ pub async fn activate(&self, token: &AccessToken, id: &str) -> Result<OndeApp> {
296
+ let value = self
297
+ .send(
298
+ self.request(Method::PATCH, &format!("/api/gresiq/apps/{id}"))
299
+ .bearer_auth(token.as_str())
300
+ .json(&json!({ "gresiq_app": { "status": "active" } })),
301
+ )
302
+ .await?;
303
+ decode(value)
304
+ }
305
+
306
+ /// Reuse the user's app named `name` (or create it), activate it if needed and return
307
+ /// its key. Safe to call again: it never creates a second app with the same name.
308
+ pub async fn ensure_key(&self, token: &AccessToken, name: &str) -> Result<ApiKey> {
309
+ let apps = self.apps(token).await?;
310
+ let named = || apps.iter().filter(|a| a.name == name);
311
+ let existing = named()
312
+ .find(|a| a.status == AppStatus::Active)
313
+ .or_else(|| named().find(|a| a.status != AppStatus::Suspended))
314
+ .cloned();
315
+
316
+ let mut app = match existing {
317
+ Some(app) => app,
318
+ // Whatever is left under this name is suspended.
319
+ None if named().next().is_some() => return Err(Error::Suspended(name.to_owned())),
320
+ None => self.create_app(token, name).await?,
321
+ };
322
+ if app.status != AppStatus::Active {
323
+ app = self.activate(token, &app.id).await?;
324
+ }
325
+ app.api_key()
326
+ .ok_or_else(|| Error::Unexpected("the app came back without a secret".into()))
327
+ }
328
+
329
+ fn request(&self, method: Method, path: &str) -> RequestBuilder {
330
+ let mut url = self.base_url.clone();
331
+ url.set_path(path);
332
+ url.query_pairs_mut().append_pair("env", self.env.as_str());
333
+ self.http.request(method, url)
334
+ }
335
+
336
+ async fn send(&self, request: RequestBuilder) -> Result<Value> {
337
+ let response = request.send().await?;
338
+ let status = response.status();
339
+ let text = response.text().await?;
340
+ let body: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
341
+ if status.is_success() {
342
+ return Ok(body);
343
+ }
344
+ Err(match status {
345
+ StatusCode::UNAUTHORIZED => Error::Unauthorized,
346
+ StatusCode::FORBIDDEN => Error::Forbidden,
347
+ _ => Error::Http {
348
+ status: status.as_u16(),
349
+ message: ["message", "error"]
350
+ .iter()
351
+ .find_map(|k| body.get(*k).and_then(Value::as_str))
352
+ .map(str::to_owned)
353
+ .or_else(|| {
354
+ body.get("errors")
355
+ .and_then(Value::as_array)
356
+ .map(|e| {
357
+ e.iter()
358
+ .filter_map(Value::as_str)
359
+ .collect::<Vec<_>>()
360
+ .join("; ")
361
+ })
362
+ .filter(|m| !m.is_empty())
363
+ })
364
+ .unwrap_or_else(|| "request failed".to_owned()),
365
+ },
366
+ })
367
+ }
368
+}
369
+
370
+fn decode<T: for<'de> Deserialize<'de>>(value: Value) -> Result<T> {
371
+ serde_json::from_value(value).map_err(|e| Error::Unexpected(e.to_string()))
372
+}
373
+
374
+fn string_or_number<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
375
+ match Value::deserialize(d)? {
376
+ Value::String(s) => Ok(s),
377
+ Value::Number(n) => Ok(n.to_string()),
378
+ other => Err(serde::de::Error::custom(format!(
379
+ "expected an id, got {other}"
380
+ ))),
381
+ }
382
+}
383
+
384
+fn opt_string_or_number<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
385
+ match Option::<Value>::deserialize(d)? {
386
+ None | Some(Value::Null) => Ok(None),
387
+ Some(Value::String(s)) => Ok(Some(s)),
388
+ Some(Value::Number(n)) => Ok(Some(n.to_string())),
389
+ Some(other) => Err(serde::de::Error::custom(format!(
390
+ "expected an id, got {other}"
391
+ ))),
392
+ }
393
+}
crates/ed-onde-account/tests/api.rs
new
+241
@@ -0,0 +1,241 @@
1
+//! The client against an in-process stand-in for onde-web's API.
2
+
3
+use std::sync::{Arc, Mutex};
4
+
5
+use axum::extract::{Path, Query, State};
6
+use axum::http::{HeaderMap, StatusCode};
7
+use axum::routing::{get, patch, post};
8
+use axum::{Json, Router};
9
+use ed_onde_account::{AccessToken, Error, OndeAccount, OndeEnv, SignIn};
10
+use serde_json::{Value, json};
11
+use std::collections::HashMap;
12
+
13
+const TOKEN: &str = "jwt-123";
14
+
15
+#[derive(Default)]
16
+struct Mock {
17
+ apps: Vec<Value>,
18
+ /// Every `(method, path, env)` the server saw.
19
+ calls: Vec<String>,
20
+}
21
+
22
+type Shared = Arc<Mutex<Mock>>;
23
+
24
+fn app(id: &str, name: &str, status: &str) -> Value {
25
+ json!({ "id": id, "name": name, "status": status, "app_id": id, "app_secret": format!("sec-{id}") })
26
+}
27
+
28
+fn authorized(headers: &HeaderMap) -> bool {
29
+ headers
30
+ .get("authorization")
31
+ .and_then(|v| v.to_str().ok())
32
+ .is_some_and(|v| v == format!("Bearer {TOKEN}"))
33
+}
34
+
35
+async fn serve(apps: Vec<Value>) -> (OndeAccount, Shared) {
36
+ let state: Shared = Arc::new(Mutex::new(Mock {
37
+ apps,
38
+ calls: vec![],
39
+ }));
40
+
41
+ async fn sign_in(
42
+ State(s): State<Shared>,
43
+ Query(q): Query<HashMap<String, String>>,
44
+ Json(body): Json<Value>,
45
+ ) -> (StatusCode, Json<Value>) {
46
+ s.lock()
47
+ .unwrap()
48
+ .calls
49
+ .push(format!("sign-in env={}", q["env"]));
50
+ if body["email"] == "wrong@x.io" {
51
+ return (
52
+ StatusCode::UNAUTHORIZED,
53
+ Json(json!({ "message": "Invalid password." })),
54
+ );
55
+ }
56
+ (
57
+ StatusCode::OK,
58
+ Json(match body["email"].as_str().unwrap() {
59
+ "ready@x.io" => {
60
+ json!({ "status": "ready", "accessToken": format!("Bearer {TOKEN}") })
61
+ }
62
+ "new@x.io" => json!({ "status": "notFound" }),
63
+ _ => json!({ "status": "incomplete", "errorCode": 100 }),
64
+ }),
65
+ )
66
+ }
67
+ async fn me(headers: HeaderMap) -> (StatusCode, Json<Value>) {
68
+ if !authorized(&headers) {
69
+ return (
70
+ StatusCode::UNAUTHORIZED,
71
+ Json(json!({ "error": "Unauthorized" })),
72
+ );
73
+ }
74
+ (
75
+ StatusCode::OK,
76
+ Json(json!({ "email": "ready@x.io", "name": "Ready", "can_create_gresiq_apps": true })),
77
+ )
78
+ }
79
+ async fn list(State(s): State<Shared>, headers: HeaderMap) -> (StatusCode, Json<Value>) {
80
+ if !authorized(&headers) {
81
+ return (StatusCode::UNAUTHORIZED, Json(json!({})));
82
+ }
83
+ (
84
+ StatusCode::OK,
85
+ Json(Value::Array(s.lock().unwrap().apps.clone())),
86
+ )
87
+ }
88
+ async fn create(State(s): State<Shared>, Json(body): Json<Value>) -> (StatusCode, Json<Value>) {
89
+ let mut s = s.lock().unwrap();
90
+ s.calls.push("create".into());
91
+ let created = app(
92
+ "new-1",
93
+ body["gresiq_app"]["name"].as_str().unwrap(),
94
+ "provisioning",
95
+ );
96
+ s.apps.push(created.clone());
97
+ (StatusCode::CREATED, Json(created))
98
+ }
99
+ async fn activate(
100
+ State(s): State<Shared>,
101
+ Path(id): Path<String>,
102
+ Json(body): Json<Value>,
103
+ ) -> Json<Value> {
104
+ let mut s = s.lock().unwrap();
105
+ s.calls
106
+ .push(format!("activate {id} {}", body["gresiq_app"]["status"]));
107
+ let found = s.apps.iter_mut().find(|a| a["id"] == id).unwrap();
108
+ found["status"] = json!("active");
109
+ Json(found.clone())
110
+ }
111
+
112
+ let router = Router::new()
113
+ .route("/api/auth/sign-in", post(sign_in))
114
+ .route("/api/auth/me", get(me))
115
+ .route("/api/gresiq/apps", get(list).post(create))
116
+ .route("/api/gresiq/apps/{id}", patch(activate))
117
+ .with_state(state.clone());
118
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
119
+ let addr = listener.local_addr().unwrap();
120
+ tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
121
+
122
+ let account = OndeAccount::with_base_url(&format!("http://{addr}")).unwrap();
123
+ (account, state)
124
+}
125
+
126
+#[tokio::test]
127
+async fn sign_in_outcomes_and_token_normalization() {
128
+ let (account, state) = serve(vec![]).await;
129
+
130
+ let SignIn::Ready(token) = account.sign_in("ready@x.io", "pw").await.unwrap() else {
131
+ panic!("expected ready");
132
+ };
133
+ assert_eq!(token.as_str(), TOKEN, "the Bearer prefix is stripped");
134
+ assert_eq!(format!("{token:?}"), "AccessToken(<redacted>)");
135
+
136
+ assert_eq!(
137
+ account.sign_in("new@x.io", "pw").await.unwrap(),
138
+ SignIn::NotFound
139
+ );
140
+ assert_eq!(
141
+ account.sign_in("unconfirmed@x.io", "pw").await.unwrap(),
142
+ SignIn::Incomplete {
143
+ error_code: Some(100)
144
+ }
145
+ );
146
+
147
+ assert!(matches!(
148
+ account.sign_in("wrong@x.io", "pw").await,
149
+ Err(Error::InvalidCredentials)
150
+ ));
151
+
152
+ let dev = account.clone().with_env(OndeEnv::Development);
153
+ dev.sign_in("new@x.io", "pw").await.unwrap();
154
+ let calls = state.lock().unwrap().calls.clone();
155
+ assert_eq!(calls[0], "sign-in env=production");
156
+ assert_eq!(calls[4], "sign-in env=development");
157
+}
158
+
159
+#[test]
160
+fn access_token_strips_repeated_prefixes() {
161
+ assert_eq!(AccessToken::new(" bearer Bearer abc ").as_str(), "abc");
162
+ assert_eq!(AccessToken::new("abc").as_str(), "abc");
163
+}
164
+
165
+#[tokio::test]
166
+async fn me_reads_the_profile() {
167
+ let (account, _) = serve(vec![]).await;
168
+ let profile = account.me(&AccessToken::new(TOKEN)).await.unwrap();
169
+ assert_eq!(profile.email, "ready@x.io");
170
+ assert!(profile.can_create);
171
+}
172
+
173
+#[tokio::test]
174
+async fn ensure_key_reuses_an_active_app() {
175
+ let (account, state) = serve(vec![
176
+ app("a1", "Other", "active"),
177
+ app("a2", "KaroKowe", "active"),
178
+ ])
179
+ .await;
180
+ let key = account
181
+ .ensure_key(&AccessToken::new(TOKEN), "KaroKowe")
182
+ .await
183
+ .unwrap();
184
+ assert_eq!(key.as_str(), "a2:sec-a2");
185
+ assert_eq!(format!("{key:?}"), "ApiKey(<redacted>)");
186
+ assert!(
187
+ state.lock().unwrap().calls.is_empty(),
188
+ "nothing was created or patched"
189
+ );
190
+}
191
+
192
+#[tokio::test]
193
+async fn ensure_key_activates_a_provisioning_app() {
194
+ let (account, state) = serve(vec![app("a1", "KaroKowe", "provisioning")]).await;
195
+ let key = account
196
+ .ensure_key(&AccessToken::new(TOKEN), "KaroKowe")
197
+ .await
198
+ .unwrap();
199
+ assert_eq!(key.as_str(), "a1:sec-a1");
200
+ assert_eq!(state.lock().unwrap().calls, vec![r#"activate a1 "active""#]);
201
+}
202
+
203
+#[tokio::test]
204
+async fn ensure_key_creates_then_activates_when_none_exists() {
205
+ let (account, state) = serve(vec![app("a1", "Other", "active")]).await;
206
+ let token = AccessToken::new(TOKEN);
207
+ let key = account.ensure_key(&token, "KaroKowe").await.unwrap();
208
+ assert_eq!(key.as_str(), "new-1:sec-new-1");
209
+ assert_eq!(
210
+ state.lock().unwrap().calls,
211
+ vec!["create".to_owned(), r#"activate new-1 "active""#.to_owned()]
212
+ );
213
+ // A second call finds it instead of creating another.
214
+ account.ensure_key(&token, "KaroKowe").await.unwrap();
215
+ assert_eq!(state.lock().unwrap().calls.len(), 2);
216
+}
217
+
218
+#[tokio::test]
219
+async fn ensure_key_refuses_a_suspended_app() {
220
+ let (account, _) = serve(vec![app("a1", "KaroKowe", "suspended")]).await;
221
+ let err = account
222
+ .ensure_key(&AccessToken::new(TOKEN), "KaroKowe")
223
+ .await
224
+ .unwrap_err();
225
+ assert!(matches!(err, Error::Suspended(name) if name == "KaroKowe"));
226
+}
227
+
228
+#[tokio::test]
229
+async fn an_expired_token_is_unauthorized() {
230
+ let (account, _) = serve(vec![]).await;
231
+ let stale = AccessToken::new("expired");
232
+ assert!(matches!(account.me(&stale).await, Err(Error::Unauthorized)));
233
+ assert!(matches!(
234
+ account.apps(&stale).await,
235
+ Err(Error::Unauthorized)
236
+ ));
237
+ assert!(matches!(
238
+ account.ensure_key(&stale, "KaroKowe").await,
239
+ Err(Error::Unauthorized)
240
+ ));
241
+}