Skip to content

Commit 68d23d4

Browse files
authored
Remove spacetimedb-core as a dep of cli (#2244)
1 parent 76a52ca commit 68d23d4

26 files changed

Lines changed: 320 additions & 317 deletions

File tree

Cargo.lock

Lines changed: 14 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
[workspace]
22
members = [
3+
"crates/auth",
34
"crates/bench",
45
"crates/bindings-sys",
56
"crates/bindings",
@@ -93,6 +94,7 @@ rust-version = "1.84.0"
9394

9495
[workspace.dependencies]
9596
spacetimedb = { path = "crates/bindings", version = "1.1.0" }
97+
spacetimedb-auth = { path = "crates/auth", version = "1.1.0" }
9698
spacetimedb-bindings-macro = { path = "crates/bindings-macro", version = "1.1.0" }
9799
spacetimedb-bindings-sys = { path = "crates/bindings-sys", version = "1.1.0" }
98100
spacetimedb-cli = { path = "crates/cli", version = "1.1.0" }
@@ -187,6 +189,7 @@ itertools = "0.12"
187189
itoa = "1"
188190
jsonwebtoken = { package = "spacetimedb-jsonwebtoken", version = "9.3.0" }
189191
junction = "1"
192+
jwks = { package = "spacetimedb-jwks", version = "0.1.3" }
190193
lazy_static = "1.4.0"
191194
log = "0.4.17"
192195
memchr = "2"

crates/auth/Cargo.toml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
[package]
2+
name = "spacetimedb-auth"
3+
version.workspace = true
4+
edition.workspace = true
5+
rust-version.workspace = true
6+
7+
[dependencies]
8+
spacetimedb-lib.workspace = true
9+
10+
anyhow.workspace = true
11+
serde.workspace = true
12+
serde_with.workspace = true
13+
jsonwebtoken.workspace = true
14+
15+
[dev-dependencies]
16+
serde_json.workspace = true
Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
use crate::identity::Identity;
21
pub use jsonwebtoken::errors::Error as JwtError;
32
pub use jsonwebtoken::errors::ErrorKind as JwtErrorKind;
43
pub use jsonwebtoken::{DecodingKey, EncodingKey};
54
use serde::Deserializer;
65
use serde::{Deserialize, Serialize};
6+
use spacetimedb_lib::Identity;
77
use std::time::SystemTime;
88

9-
use super::token_validation::TokenValidationError;
10-
119
// These are the claims that can be attached to a request/connection.
1210
#[serde_with::serde_as]
1311
#[derive(Debug, Serialize, Deserialize)]
@@ -72,39 +70,33 @@ pub struct IncomingClaims {
7270
}
7371

7472
impl TryInto<SpacetimeIdentityClaims> for IncomingClaims {
75-
type Error = TokenValidationError;
73+
type Error = anyhow::Error;
7674

77-
fn try_into(self) -> Result<SpacetimeIdentityClaims, TokenValidationError> {
75+
fn try_into(self) -> anyhow::Result<SpacetimeIdentityClaims> {
7876
// The issuer and subject must be less than 128 bytes.
7977
if self.issuer.len() > 128 {
80-
return Err(TokenValidationError::Other(anyhow::anyhow!(
81-
"Issuer too long: {:?}",
82-
self.issuer
83-
)));
78+
return Err(anyhow::anyhow!("Issuer too long: {:?}", self.issuer));
8479
}
8580
if self.subject.len() > 128 {
86-
return Err(TokenValidationError::Other(anyhow::anyhow!(
87-
"Subject too long: {:?}",
88-
self.subject
89-
)));
81+
return Err(anyhow::anyhow!("Subject too long: {:?}", self.subject));
9082
}
9183
// The issuer and subject must be non-empty.
9284
if self.issuer.is_empty() {
93-
return Err(TokenValidationError::Other(anyhow::anyhow!("Issuer empty")));
85+
return Err(anyhow::anyhow!("Issuer empty"));
9486
}
9587
if self.subject.is_empty() {
96-
return Err(TokenValidationError::Other(anyhow::anyhow!("Subject empty")));
88+
return Err(anyhow::anyhow!("Subject empty"));
9789
}
9890

9991
let computed_identity = Identity::from_claims(&self.issuer, &self.subject);
10092
// If an identity is provided, it must match the computed identity.
10193
if let Some(token_identity) = self.identity {
10294
if token_identity != computed_identity {
103-
return Err(TokenValidationError::Other(anyhow::anyhow!(
95+
return Err(anyhow::anyhow!(
10496
"Identity mismatch: token identity {:?} does not match computed identity {:?}",
10597
token_identity,
106-
computed_identity
107-
)));
98+
computed_identity,
99+
));
108100
}
109101
}
110102

crates/auth/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pub mod identity;

crates/cli/Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ bench = false
2121
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
2222

2323
[dependencies]
24+
spacetimedb-auth.workspace = true
2425
spacetimedb-client-api-messages.workspace = true
25-
spacetimedb-core.workspace = true
26-
spacetimedb-data-structures.workspace = true
26+
spacetimedb-data-structures = { workspace = true, features = ["serde"] }
2727
spacetimedb-fs-utils.workspace = true
2828
spacetimedb-lib.workspace = true
2929
spacetimedb-paths.workspace = true

crates/cli/src/api.rs

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,9 @@ use std::ops::Add;
33

44
use reqwest::{header, Client, RequestBuilder};
55
use serde::Deserialize;
6-
use serde_json::value::RawValue;
76

8-
use spacetimedb::json::client_api::StmtStatsJson;
97
use spacetimedb_lib::db::raw_def::v9::RawModuleDefV9;
108
use spacetimedb_lib::de::serde::DeserializeWrapper;
11-
use spacetimedb_lib::sats::ProductType;
129
use spacetimedb_lib::Identity;
1310

1411
use crate::util::{AuthHeader, ResponseExt};
@@ -86,16 +83,8 @@ impl ClientApi {
8683
}
8784
}
8885

89-
// Sync with spacetimedb::json::client_api::StmtResultJson
90-
#[derive(Debug, Clone, Deserialize)]
91-
pub struct StmtResultJson<'a> {
92-
pub schema: ProductType,
93-
#[serde(borrow)]
94-
pub rows: Vec<&'a RawValue>,
95-
pub total_duration_micros: u64,
96-
#[serde(default)]
97-
pub stats: StmtStatsJson,
98-
}
86+
pub(crate) type SqlStmtResult<'a> =
87+
spacetimedb_client_api_messages::http::SqlStmtResult<&'a serde_json::value::RawValue>;
9988

10089
#[derive(Debug, Clone, Deserialize, Default)]
10190
pub struct StmtStats {
@@ -126,8 +115,8 @@ impl Add for StmtStats {
126115
}
127116
}
128117

129-
impl From<&StmtResultJson<'_>> for StmtStats {
130-
fn from(value: &StmtResultJson<'_>) -> Self {
118+
impl From<&SqlStmtResult<'_>> for StmtStats {
119+
fn from(value: &SqlStmtResult<'_>) -> Self {
131120
Self {
132121
total_duration_micros: value.total_duration_micros,
133122
rows_inserted: value.stats.rows_inserted,

crates/cli/src/config.rs

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ use crate::errors::CliError;
22
use crate::util::{contains_protocol, host_or_url_to_host_and_protocol};
33
use anyhow::Context;
44
use jsonwebtoken::DecodingKey;
5-
use spacetimedb::config::{set_opt_value, set_table_opt_value};
65
use spacetimedb_fs_utils::atomic_write;
76
use spacetimedb_paths::cli::CliTomlPath;
87
use std::collections::HashMap;
@@ -822,6 +821,53 @@ Update the server's fingerprint with:
822821
}
823822
}
824823

824+
/// Update the value of a key in a `TOML` document, preserving the formatting and comments of the original value.
825+
///
826+
/// ie:
827+
///
828+
/// ```toml;no_run
829+
/// # Moving key = value to key = new_value
830+
/// old = "value" # Comment
831+
/// new = "new_value" # Comment
832+
/// ```
833+
fn copy_value_with_decor(old_value: Option<&toml_edit::Item>, new_value: &str) -> toml_edit::Item {
834+
match old_value {
835+
Some(toml_edit::Item::Value(toml_edit::Value::String(old_value))) => {
836+
// Creates a new `toml_edit::Value` with the same formatting as the old value.
837+
let mut new = toml_edit::Value::String(toml_edit::Formatted::new(new_value.to_string()));
838+
let decor = new.decor_mut();
839+
// Copy the comments and formatting from the old value.
840+
*decor = old_value.decor().clone();
841+
new.into()
842+
}
843+
_ => new_value.into(),
844+
}
845+
}
846+
847+
/// Set the value of a key in a `TOML` document, removing the key if the value is `None`.
848+
///
849+
/// **NOTE**: This function will preserve the formatting and comments of the original value.
850+
pub fn set_opt_value(doc: &mut toml_edit::DocumentMut, key: &str, value: Option<&str>) {
851+
let old_value = doc.get(key);
852+
if let Some(new) = value {
853+
doc[key] = copy_value_with_decor(old_value, new);
854+
} else {
855+
doc.remove(key);
856+
}
857+
}
858+
859+
/// Set the value of a key in a `TOML` table, removing the key if the value is `None`.
860+
///
861+
/// **NOTE**: This function will preserve the formatting and comments of the original value.
862+
pub fn set_table_opt_value(table: &mut toml_edit::Table, key: &str, value: Option<&str>) {
863+
let old_value = table.get(key);
864+
if let Some(new) = value {
865+
table[key] = copy_value_with_decor(old_value, new);
866+
} else {
867+
table.remove(key);
868+
}
869+
}
870+
825871
#[cfg(test)]
826872
mod tests {
827873
use super::*;

crates/cli/src/subcommands/call.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,8 @@ use anyhow::{bail, Context, Error};
77
use clap::{Arg, ArgMatches};
88
use convert_case::{Case, Casing};
99
use itertools::Itertools;
10-
use spacetimedb::Identity;
1110
use spacetimedb_lib::sats::{self, AlgebraicType, Typespace};
12-
use spacetimedb_lib::ProductTypeElement;
11+
use spacetimedb_lib::{Identity, ProductTypeElement};
1312
use spacetimedb_schema::def::{ModuleDef, ReducerDef};
1413
use std::fmt::Write;
1514

crates/cli/src/subcommands/generate/mod.rs

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
#![warn(clippy::uninlined_format_args)]
22

3+
use anyhow::Context;
34
use clap::parser::ValueSource;
45
use clap::Arg;
56
use clap::ArgAction::Set;
67
use core::mem;
78
use fs_err as fs;
8-
use spacetimedb::host::wasmtime::{Mem, MemView, WasmPointee as _};
99
use spacetimedb_lib::de::serde::DeserializeWrapper;
1010
use spacetimedb_lib::{bsatn, RawModuleDefV8};
1111
use spacetimedb_lib::{RawModuleDef, MODULE_ABI_MAJOR_VERSION};
@@ -298,13 +298,13 @@ fn extract_descriptions_from_module(module: wasmtime::Module) -> anyhow::Result<
298298
message_ptr: u32,
299299
message_len: u32| {
300300
let (mem, _) = WasmCtx::mem_env(&mut caller);
301-
let slice = mem.deref_slice(message_ptr, message_len).unwrap();
301+
let slice = deref_slice(mem, message_ptr, message_len).unwrap();
302302
println!("from wasm: {}", String::from_utf8_lossy(slice));
303303
},
304304
)?;
305305
linker.func_wrap(module_name, "bytes_sink_write", WasmCtx::bytes_sink_write)?;
306306
let instance = linker.instantiate(&mut store, &module)?;
307-
let memory = Mem::extract(&instance, &mut store)?;
307+
let memory = instance.get_memory(&mut store, "memory").context("no memory export")?;
308308
store.data_mut().mem = Some(memory);
309309

310310
let mut preinits = instance
@@ -329,19 +329,30 @@ fn extract_descriptions_from_module(module: wasmtime::Module) -> anyhow::Result<
329329
}
330330

331331
struct WasmCtx {
332-
mem: Option<Mem>,
332+
mem: Option<wasmtime::Memory>,
333333
sink: Vec<u8>,
334334
}
335335

336+
fn deref_slice(mem: &[u8], offset: u32, len: u32) -> anyhow::Result<&[u8]> {
337+
anyhow::ensure!(offset != 0, "ptr is null");
338+
mem.get(offset as usize..)
339+
.and_then(|s| s.get(..len as usize))
340+
.context("pointer out of bounds")
341+
}
342+
343+
fn read_u32(mem: &[u8], offset: u32) -> anyhow::Result<u32> {
344+
Ok(u32::from_le_bytes(deref_slice(mem, offset, 4)?.try_into().unwrap()))
345+
}
346+
336347
impl WasmCtx {
337-
pub fn get_mem(&self) -> Mem {
348+
pub fn get_mem(&self) -> wasmtime::Memory {
338349
self.mem.expect("Initialized memory")
339350
}
340351

341-
fn mem_env<'a>(ctx: impl Into<StoreContextMut<'a, Self>>) -> (&'a mut MemView, &'a mut Self) {
352+
fn mem_env<'a>(ctx: impl Into<StoreContextMut<'a, Self>>) -> (&'a mut [u8], &'a mut Self) {
342353
let ctx = ctx.into();
343354
let mem = ctx.data().get_mem();
344-
mem.view_and_store_mut(ctx)
355+
mem.data_and_store_mut(ctx)
345356
}
346357

347358
pub fn bytes_sink_write(
@@ -357,9 +368,9 @@ impl WasmCtx {
357368
let (mem, env) = Self::mem_env(&mut caller);
358369

359370
// Read `buffer_len`, i.e., the capacity of `buffer` pointed to by `buffer_ptr`.
360-
let buffer_len = u32::read_from(mem, buffer_len_ptr)?;
371+
let buffer_len = read_u32(mem, buffer_len_ptr)?;
361372
// Write `buffer` to `sink`.
362-
let buffer = mem.deref_slice(buffer_ptr, buffer_len)?;
373+
let buffer = deref_slice(mem, buffer_ptr, buffer_len)?;
363374
env.sink.extend(buffer);
364375

365376
Ok(0)

0 commit comments

Comments
 (0)