Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(bots): plain text bot tokens (#4100)

Will Hutchinson62d3bc612bfa
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botToken.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botToken.ts
index b0c0fb01c7..789d8a1ffe 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/botToken.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botToken.ts
@@ -28,6 +28,6 @@ export interface BotToken {
last_used_at?: BotTokenLastUsedAt;
/** Revocation timestamp. */
revoked_at?: BotTokenRevokedAt;
- /** Token lookup prefix. */
- token_prefix: string;
+ /** Raw bearer token. */
+ token: string;
}
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 4d4c87f9bd..77a627c8cb 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -10196,7 +10196,7 @@
"BotToken": {
"type": "object",
"description": "Bot token metadata.",
- "required": ["id", "bot_id", "token_prefix", "created_at"],
+ "required": ["id", "bot_id", "token", "created_at"],
"properties": {
"bot_id": {
"$ref": "#/components/schemas/BotId",
@@ -10231,9 +10231,9 @@
"format": "date-time",
"description": "Revocation timestamp."
},
- "token_prefix": {
+ "token": {
"type": "string",
- "description": "Token lookup prefix."
+ "description": "Raw bearer token."
}
}
},
diff --git a/rust/cloud-storage/.sqlx/query-cbd3dc65e8a0068465b09cf9bf7e2ca71b6832b6c46a075b432cfc5266c05115.json b/rust/cloud-storage/.sqlx/query-13ca7c91a890393503f054cd200c45ae96ad56d3c48b4ee20b207c9bfa4bbc9f.json
similarity index 58%
rename from rust/cloud-storage/.sqlx/query-cbd3dc65e8a0068465b09cf9bf7e2ca71b6832b6c46a075b432cfc5266c05115.json
rename to rust/cloud-storage/.sqlx/query-13ca7c91a890393503f054cd200c45ae96ad56d3c48b4ee20b207c9bfa4bbc9f.json
index 7813ad5fa2..a6b29ad9aa 100644
--- a/rust/cloud-storage/.sqlx/query-cbd3dc65e8a0068465b09cf9bf7e2ca71b6832b6c46a075b432cfc5266c05115.json
+++ b/rust/cloud-storage/.sqlx/query-13ca7c91a890393503f054cd200c45ae96ad56d3c48b4ee20b207c9bfa4bbc9f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token_hash,\n bt.token_prefix,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n JOIN comms_channel_participants cp\n ON cp.channel_id = $1\n AND cp.user_id = ('bot|' || b.id::text)\n AND cp.left_at IS NULL\n WHERE bt.token_prefix = $2\n AND b.deleted_at IS NULL\n ",
+ "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n JOIN comms_channel_participants cp\n ON cp.channel_id = $1\n AND cp.user_id = ('bot|' || b.id::text)\n AND cp.left_at IS NULL\n WHERE bt.token = $2\n AND b.deleted_at IS NULL\n ",
"describe": {
"columns": [
{
@@ -15,41 +15,36 @@
},
{
"ordinal": 2,
- "name": "token_hash",
- "type_info": "Bytea"
- },
- {
- "ordinal": 3,
- "name": "token_prefix",
+ "name": "token",
"type_info": "Text"
},
{
- "ordinal": 4,
+ "ordinal": 3,
"name": "label",
"type_info": "Text"
},
{
- "ordinal": 5,
+ "ordinal": 4,
"name": "last_used_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 6,
+ "ordinal": 5,
"name": "expires_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 7,
+ "ordinal": 6,
"name": "revoked_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 8,
+ "ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 9,
+ "ordinal": 8,
"name": "kind",
"type_info": "Text"
}
@@ -64,7 +59,6 @@
false,
false,
false,
- false,
true,
true,
true,
@@ -73,5 +67,5 @@
false
]
},
- "hash": "cbd3dc65e8a0068465b09cf9bf7e2ca71b6832b6c46a075b432cfc5266c05115"
+ "hash": "13ca7c91a890393503f054cd200c45ae96ad56d3c48b4ee20b207c9bfa4bbc9f"
}
diff --git a/rust/cloud-storage/.sqlx/query-5b8af25b1f47229f74c98541bbd200ba0582eaece5a30939ed5527bc05970795.json b/rust/cloud-storage/.sqlx/query-d4e9676fcb9d7860e0e1f4c54bdc059688c703c58cbdc865b4c9bf25e9ddf354.json
similarity index 64%
rename from rust/cloud-storage/.sqlx/query-5b8af25b1f47229f74c98541bbd200ba0582eaece5a30939ed5527bc05970795.json
rename to rust/cloud-storage/.sqlx/query-d4e9676fcb9d7860e0e1f4c54bdc059688c703c58cbdc865b4c9bf25e9ddf354.json
index 8ae9384b70..e209218fea 100644
--- a/rust/cloud-storage/.sqlx/query-5b8af25b1f47229f74c98541bbd200ba0582eaece5a30939ed5527bc05970795.json
+++ b/rust/cloud-storage/.sqlx/query-d4e9676fcb9d7860e0e1f4c54bdc059688c703c58cbdc865b4c9bf25e9ddf354.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token_hash,\n bt.token_prefix,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n WHERE bt.token_prefix = $1\n AND b.deleted_at IS NULL\n ",
+ "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n WHERE bt.token = $1\n AND b.deleted_at IS NULL\n ",
"describe": {
"columns": [
{
@@ -15,41 +15,36 @@
},
{
"ordinal": 2,
- "name": "token_hash",
- "type_info": "Bytea"
- },
- {
- "ordinal": 3,
- "name": "token_prefix",
+ "name": "token",
"type_info": "Text"
},
{
- "ordinal": 4,
+ "ordinal": 3,
"name": "label",
"type_info": "Text"
},
{
- "ordinal": 5,
+ "ordinal": 4,
"name": "last_used_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 6,
+ "ordinal": 5,
"name": "expires_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 7,
+ "ordinal": 6,
"name": "revoked_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 8,
+ "ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 9,
+ "ordinal": 8,
"name": "kind",
"type_info": "Text"
}
@@ -63,7 +58,6 @@
false,
false,
false,
- false,
true,
true,
true,
@@ -72,5 +66,5 @@
false
]
},
- "hash": "5b8af25b1f47229f74c98541bbd200ba0582eaece5a30939ed5527bc05970795"
+ "hash": "d4e9676fcb9d7860e0e1f4c54bdc059688c703c58cbdc865b4c9bf25e9ddf354"
}
diff --git a/rust/cloud-storage/.sqlx/query-dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091.json b/rust/cloud-storage/.sqlx/query-e50a704e19cd5a0e8bf252e30dba739875031e24d8735ca4a02e9ee39bddddff.json
similarity index 75%
rename from rust/cloud-storage/.sqlx/query-dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091.json
rename to rust/cloud-storage/.sqlx/query-e50a704e19cd5a0e8bf252e30dba739875031e24d8735ca4a02e9ee39bddddff.json
index 15e39a719d..affe276cc0 100644
--- a/rust/cloud-storage/.sqlx/query-dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091.json
+++ b/rust/cloud-storage/.sqlx/query-e50a704e19cd5a0e8bf252e30dba739875031e24d8735ca4a02e9ee39bddddff.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO bot_tokens (\n id, bot_id, token_hash, token_prefix, label, expires_at\n )\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at\n ",
+ "query": "\n INSERT INTO bot_tokens (\n id, bot_id, token, label, expires_at\n )\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id, bot_id, token, label, last_used_at, expires_at, revoked_at, created_at\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "token_prefix",
+ "name": "token",
"type_info": "Text"
},
{
@@ -48,7 +48,6 @@
"Left": [
"Uuid",
"Uuid",
- "Bytea",
"Text",
"Text",
"Timestamptz"
@@ -65,5 +64,5 @@
false
]
},
- "hash": "dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091"
+ "hash": "e50a704e19cd5a0e8bf252e30dba739875031e24d8735ca4a02e9ee39bddddff"
}
diff --git a/rust/cloud-storage/.sqlx/query-33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6.json b/rust/cloud-storage/.sqlx/query-e6fcaa97f031c1da3526c816ee88e1abb3cf466142b51d7ed3838b5ea8a5b46e.json
similarity index 72%
rename from rust/cloud-storage/.sqlx/query-33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6.json
rename to rust/cloud-storage/.sqlx/query-e6fcaa97f031c1da3526c816ee88e1abb3cf466142b51d7ed3838b5ea8a5b46e.json
index 08cef514e3..e6ee19200f 100644
--- a/rust/cloud-storage/.sqlx/query-33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6.json
+++ b/rust/cloud-storage/.sqlx/query-e6fcaa97f031c1da3526c816ee88e1abb3cf466142b51d7ed3838b5ea8a5b46e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at\n FROM bot_tokens\n WHERE bot_id = $1\n AND revoked_at IS NULL\n ORDER BY created_at DESC, id DESC\n ",
+ "query": "\n SELECT id, bot_id, token, label, last_used_at, expires_at, revoked_at, created_at\n FROM bot_tokens\n WHERE bot_id = $1\n AND revoked_at IS NULL\n ORDER BY created_at DESC, id DESC\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "token_prefix",
+ "name": "token",
"type_info": "Text"
},
{
@@ -60,5 +60,5 @@
false
]
},
- "hash": "33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6"
+ "hash": "e6fcaa97f031c1da3526c816ee88e1abb3cf466142b51d7ed3838b5ea8a5b46e"
}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index f392dc9d70..12d28dd6e4 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1768,7 +1768,6 @@ dependencies = [
"rand 0.9.4",
"serde",
"serde_json",
- "sha2 0.10.9",
"sqlx",
"thiserror 2.0.18",
"tokio",
diff --git a/rust/cloud-storage/bots/Cargo.toml b/rust/cloud-storage/bots/Cargo.toml
index e710ae7ebc..4dfd2c9ada 100644
--- a/rust/cloud-storage/bots/Cargo.toml
+++ b/rust/cloud-storage/bots/Cargo.toml
@@ -36,7 +36,6 @@ model_user = { path = "../model_user", optional = true, features = ["axum"] }
rand = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, optional = true }
-sha2 = { workspace = true }
sqlx = { workspace = true, optional = true }
thiserror = { workspace = true }
tokio = { workspace = true, optional = true }
diff --git a/rust/cloud-storage/bots/src/domain/models.rs b/rust/cloud-storage/bots/src/domain/models.rs
index e505b62184..07fb381ea0 100644
--- a/rust/cloud-storage/bots/src/domain/models.rs
+++ b/rust/cloud-storage/bots/src/domain/models.rs
@@ -93,8 +93,8 @@ pub struct BotToken {
pub id: Uuid,
/// Owning bot id.
pub bot_id: BotId,
- /// Token lookup prefix.
- pub token_prefix: String,
+ /// Raw bearer token.
+ pub token: String,
/// Optional token label.
pub label: Option<String>,
/// Last successful use.
@@ -121,8 +121,6 @@ pub struct AuthenticatedBot {
pub struct BotTokenCandidate {
/// Token metadata.
pub token: BotToken,
- /// Stored token hash.
- pub token_hash: Vec<u8>,
/// Authenticated bot principal associated with the token.
pub bot: AuthenticatedBot,
}
@@ -195,7 +193,7 @@ pub struct CreateChannelScopedBotRequest {
pub token_expires_at: Option<DateTime<Utc>>,
}
-/// Response containing a newly minted token. The raw token is shown once.
+/// Response containing a newly minted token.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct CreateBotTokenResponse {
diff --git a/rust/cloud-storage/bots/src/domain/ports.rs b/rust/cloud-storage/bots/src/domain/ports.rs
index d5d12fc7cb..cd116a0608 100644
--- a/rust/cloud-storage/bots/src/domain/ports.rs
+++ b/rust/cloud-storage/bots/src/domain/ports.rs
@@ -28,8 +28,7 @@ pub trait BotRepo: Clone + Send + Sync + 'static {
owner: BotOwner,
created_by: MacroUserIdStr<'static>,
channel_id: Uuid,
- token_hash: Vec<u8>,
- token_prefix: String,
+ token: String,
req: CreateChannelScopedBotRequest,
) -> impl Future<Output = Result<(Bot, BotToken), Self::Err>> + Send;
@@ -84,8 +83,7 @@ pub trait BotRepo: Clone + Send + Sync + 'static {
fn create_token(
&self,
bot_id: BotId,
- token_hash: Vec<u8>,
- token_prefix: String,
+ token: String,
req: CreateBotTokenRequest,
) -> impl Future<Output = Result<BotToken, Self::Err>> + Send;
@@ -102,18 +100,18 @@ pub trait BotRepo: Clone + Send + Sync + 'static {
token_id: Uuid,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// Lookup token candidates by prefix.
- fn token_candidates(
+ /// Lookup a token candidate by exact raw token value.
+ fn token_candidate(
&self,
- token_prefix: &str,
- ) -> impl Future<Output = Result<Vec<BotTokenCandidate>, Self::Err>> + Send;
+ token: &str,
+ ) -> impl Future<Output = Result<Option<BotTokenCandidate>, Self::Err>> + Send;
- /// Lookup token candidates by channel and prefix.
- fn channel_token_candidates(
+ /// Lookup a channel-scoped token candidate by exact raw token value.
+ fn channel_token_candidate(
&self,
channel_id: Uuid,
- token_prefix: &str,
- ) -> impl Future<Output = Result<Vec<BotTokenCandidate>, Self::Err>> + Send;
+ token: &str,
+ ) -> impl Future<Output = Result<Option<BotTokenCandidate>, Self::Err>> + Send;
/// Mark a token as used.
fn mark_token_used(&self, token_id: Uuid)
diff --git a/rust/cloud-storage/bots/src/domain/service.rs b/rust/cloud-storage/bots/src/domain/service.rs
index e865c54a34..14968379c0 100644
--- a/rust/cloud-storage/bots/src/domain/service.rs
+++ b/rust/cloud-storage/bots/src/domain/service.rs
@@ -40,18 +40,13 @@ fn validate_handle(handle: &str) -> Result<(), BotError> {
Ok(())
}
-fn token_candidate_is_valid(
- candidate: &BotTokenCandidate,
- hash: &[u8],
- now: &DateTime<Utc>,
-) -> bool {
+fn token_candidate_is_valid(candidate: &BotTokenCandidate, now: &DateTime<Utc>) -> bool {
candidate.token.revoked_at.is_none()
&& candidate
.token
.expires_at
.as_ref()
.is_none_or(|expires_at| expires_at > now)
- && tokens::verify_hash(&candidate.token_hash, hash)
}
impl<R> BotServiceImpl<R>
@@ -115,24 +110,26 @@ where
}
}
- async fn authenticate_candidates(
+ async fn authenticate_candidate(
&self,
- candidates: Vec<BotTokenCandidate>,
- hash: &[u8],
+ candidate: Option<BotTokenCandidate>,
) -> Result<AuthenticatedBot, BotError> {
+ let Some(candidate) = candidate else {
+ return Err(BotError::Unauthorized);
+ };
+
let now = Utc::now();
- for candidate in candidates {
- if token_candidate_is_valid(&candidate, hash, &now) {
- let token_id = candidate.token.id;
- let bot = candidate.bot;
- self.repo
- .mark_token_used(token_id)
- .await
- .map_err(|err| BotError::Repo(err.into()))?;
- return Ok(bot);
- }
+ if !token_candidate_is_valid(&candidate, &now) {
+ return Err(BotError::Unauthorized);
}
- Err(BotError::Unauthorized)
+
+ let token_id = candidate.token.id;
+ let bot = candidate.bot;
+ self.repo
+ .mark_token_used(token_id)
+ .await
+ .map_err(|err| BotError::Repo(err.into()))?;
+ Ok(bot)
}
}
@@ -162,24 +159,18 @@ where
) -> Result<CreateChannelScopedBotResponse, BotError> {
validate_handle(&req.handle)?;
let owner = self.owner_for_request(caller.clone(), req.team_id).await?;
- let generated = tokens::generate_token();
+ let generated_token = tokens::generate_token();
let (bot, token) = self
.repo
- .create_channel_scoped_bot(
- owner,
- caller,
- channel_id,
- generated.hash,
- generated.prefix,
- req,
- )
+ .create_channel_scoped_bot(owner, caller, channel_id, generated_token, req)
.await
.map_err(|err| BotError::Repo(err.into()))?;
+ let bot_token = token.token.clone();
Ok(CreateChannelScopedBotResponse {
bot,
token,
- bot_token: generated.token,
+ bot_token,
})
}
@@ -279,15 +270,17 @@ where
req: CreateBotTokenRequest,
) -> Result<super::models::CreateBotTokenResponse, BotError> {
self.ensure_manageable(caller, bot_id).await?;
- let generated = tokens::generate_token();
+ let generated_token = tokens::generate_token();
let token = self
.repo
- .create_token(bot_id, generated.hash, generated.prefix, req)
+ .create_token(bot_id, generated_token, req)
.await
.map_err(|err| BotError::Repo(err.into()))?;
+ let bearer_token = token.token.clone();
+
Ok(super::models::CreateBotTokenResponse {
token,
- bearer_token: generated.token,
+ bearer_token,
})
}
@@ -323,14 +316,12 @@ where
}
async fn authenticate_token(&self, token: &str) -> Result<AuthenticatedBot, BotError> {
- let prefix = tokens::token_prefix(token).ok_or(BotError::Unauthorized)?;
- let hash = tokens::hash_token(token);
- let candidates = self
+ let candidate = self
.repo
- .token_candidates(prefix)
+ .token_candidate(token)
.await
.map_err(|err| BotError::Repo(err.into()))?;
- self.authenticate_candidates(candidates, &hash).await
+ self.authenticate_candidate(candidate).await
}
async fn authenticate_channel_token(
@@ -338,13 +329,11 @@ where
channel_id: Uuid,
token: &str,
) -> Result<AuthenticatedBot, BotError> {
- let prefix = tokens::token_prefix(token).ok_or(BotError::Unauthorized)?;
- let hash = tokens::hash_token(token);
- let candidates = self
+ let candidate = self
.repo
- .channel_token_candidates(channel_id, prefix)
+ .channel_token_candidate(channel_id, token)
.await
.map_err(|err| BotError::Repo(err.into()))?;
- self.authenticate_candidates(candidates, &hash).await
+ self.authenticate_candidate(candidate).await
}
}
diff --git a/rust/cloud-storage/bots/src/domain/tokens.rs b/rust/cloud-storage/bots/src/domain/tokens.rs
index 97013e1d0e..e931922a03 100644
--- a/rust/cloud-storage/bots/src/domain/tokens.rs
+++ b/rust/cloud-storage/bots/src/domain/tokens.rs
@@ -1,63 +1,18 @@
-//! Bot token generation and verification utilities.
+//! Bot token generation utilities.
use rand::RngCore;
-use sha2::{Digest, Sha256};
const TOKEN_SECRET_BYTES: usize = 32;
const TOKEN_PREFIX_BYTES: usize = 6;
-/// Generated raw token plus lookup prefix and hash.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct GeneratedBotToken {
- /// Raw bearer token.
- pub token: String,
- /// Lookup prefix.
- pub prefix: String,
- /// SHA-256 hash bytes.
- pub hash: Vec<u8>,
-}
-
/// Generate an `mbot_<prefix>_<secret>` token.
-pub fn generate_token() -> GeneratedBotToken {
+pub fn generate_token() -> String {
let mut secret = [0_u8; TOKEN_SECRET_BYTES];
rand::rng().fill_bytes(&mut secret);
let secret_hex = hex::encode(secret);
- let prefix = secret_hex[..TOKEN_PREFIX_BYTES * 2].to_string();
- let token = format!("mbot_{prefix}_{secret_hex}");
- let hash = hash_token(&token);
- GeneratedBotToken {
- token,
- prefix,
- hash,
- }
-}
-
-/// Extract the lookup prefix from a raw bot token.
-pub fn token_prefix(token: &str) -> Option<&str> {
- let mut parts = token.splitn(3, '_');
- match (parts.next(), parts.next(), parts.next()) {
- (Some("mbot"), Some(prefix), Some(secret)) if !prefix.is_empty() && !secret.is_empty() => {
- Some(prefix)
- }
- _ => None,
- }
-}
-
-/// SHA-256 hash a token.
-pub fn hash_token(token: &str) -> Vec<u8> {
- Sha256::digest(token.as_bytes()).to_vec()
-}
+ let prefix = &secret_hex[..TOKEN_PREFIX_BYTES * 2];
-/// Constant-time equality for token hashes.
-pub fn verify_hash(expected: &[u8], actual: &[u8]) -> bool {
- if expected.len() != actual.len() {
- return false;
- }
- expected
- .iter()
- .zip(actual.iter())
- .fold(0_u8, |acc, (a, b)| acc | (a ^ b))
- == 0
+ format!("mbot_{prefix}_{secret_hex}")
}
#[cfg(test)]
@@ -65,30 +20,29 @@ mod tests {
use super::*;
#[test]
- fn generated_token_has_prefix_and_hash() {
- let generated = generate_token();
-
- assert!(generated.token.starts_with("mbot_"));
- assert_eq!(
- token_prefix(&generated.token),
- Some(generated.prefix.as_str())
- );
- assert!(verify_hash(&generated.hash, &hash_token(&generated.token)));
+ fn generated_token_has_expected_shape() {
+ let token = generate_token();
+ let parts: Vec<_> = token.split('_').collect();
+
+ assert_eq!(parts.len(), 3);
+ assert_eq!(parts[0], "mbot");
+ assert_eq!(parts[1].len(), TOKEN_PREFIX_BYTES * 2);
+ assert_eq!(parts[2].len(), TOKEN_SECRET_BYTES * 2);
+ assert!(parts[2].starts_with(parts[1]));
}
#[test]
fn generated_token_is_url_path_safe() {
- let generated = generate_token();
+ let token = generate_token();
- assert!(generated.token.is_ascii());
+ assert!(token.is_ascii());
assert!(
- generated
- .token
+ token
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
);
- assert!(!generated.token.contains('/'));
- assert!(!generated.token.contains('?'));
- assert!(!generated.token.contains('#'));
+ assert!(!token.contains('/'));
+ assert!(!token.contains('?'));
+ assert!(!token.contains('#'));
}
}
diff --git a/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs b/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs
index 54286c23fb..e23ecb1d78 100644
--- a/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs
@@ -421,6 +421,8 @@ fn webhook_router(service: TestBotService, poster: TestChannelPoster) -> Router
fn scoped_bot_response(bot_id: BotId) -> CreateChannelScopedBotResponse {
let now = chrono::Utc::now();
+ let bot_token = "mbot_test_1234".to_string();
+
CreateChannelScopedBotResponse {
bot: Bot {
id: bot_id,
@@ -440,14 +442,14 @@ fn scoped_bot_response(bot_id: BotId) -> CreateChannelScopedBotResponse {
token: BotToken {
id: Uuid::new_v4(),
bot_id,
- token_prefix: "mbot_test".to_string(),
+ token: bot_token.clone(),
label: Some("webhook".to_string()),
last_used_at: None,
expires_at: None,
revoked_at: None,
created_at: now,
},
- bot_token: "mbot_test_1234".to_string(),
+ bot_token,
}
}
diff --git a/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs b/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs
index 3443f45491..1cb7e60cb2 100644
--- a/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs
+++ b/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs
@@ -90,7 +90,7 @@ impl TryFrom<BotRow> for Bot {
struct BotTokenRow {
id: Uuid,
bot_id: Uuid,
- token_prefix: String,
+ token: String,
label: Option<String>,
last_used_at: Option<DateTime<Utc>>,
expires_at: Option<DateTime<Utc>>,
@@ -103,7 +103,7 @@ impl From<BotTokenRow> for BotToken {
Self {
id: row.id,
bot_id: BotId::from_uuid(row.bot_id),
- token_prefix: row.token_prefix,
+ token: row.token,
label: row.label,
last_used_at: row.last_used_at,
expires_at: row.expires_at,
@@ -117,8 +117,7 @@ impl From<BotTokenRow> for BotToken {
struct TokenCandidateRow {
token_id: Uuid,
bot_id: Uuid,
- token_hash: Vec<u8>,
- token_prefix: String,
+ token: String,
label: Option<String>,
last_used_at: Option<DateTime<Utc>>,
expires_at: Option<DateTime<Utc>>,
@@ -137,7 +136,7 @@ impl TokenCandidateRow {
let token = BotToken {
id: self.token_id,
bot_id,
- token_prefix: self.token_prefix,
+ token: self.token,
label: self.label,
last_used_at: self.last_used_at,
expires_at: self.expires_at,
@@ -147,7 +146,6 @@ impl TokenCandidateRow {
Ok(BotTokenCandidate {
token,
- token_hash: self.token_hash,
bot: AuthenticatedBot { bot_id, kind },
})
}
@@ -214,8 +212,7 @@ impl BotRepo for PgBotsRepo {
owner: BotOwner,
created_by: MacroUserIdStr<'static>,
channel_id: Uuid,
- token_hash: Vec<u8>,
- token_prefix: String,
+ token: String,
req: CreateChannelScopedBotRequest,
) -> Result<(Bot, BotToken), Self::Err> {
let bot_id = BotId::from_uuid(macro_uuid::generate_uuid_v7());
@@ -277,15 +274,14 @@ impl BotRepo for PgBotsRepo {
BotTokenRow,
r#"
INSERT INTO bot_tokens (
- id, bot_id, token_hash, token_prefix, label, expires_at
+ id, bot_id, token, label, expires_at
)
- VALUES ($1, $2, $3, $4, $5, $6)
- RETURNING id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at
+ VALUES ($1, $2, $3, $4, $5)
+ RETURNING id, bot_id, token, label, last_used_at, expires_at, revoked_at, created_at
"#,
token_id,
bot_id.as_uuid(),
- token_hash,
- token_prefix,
+ token,
req.token_label,
req.token_expires_at,
)
@@ -545,8 +541,7 @@ impl BotRepo for PgBotsRepo {
async fn create_token(
&self,
bot_id: BotId,
- token_hash: Vec<u8>,
- token_prefix: String,
+ token: String,
req: CreateBotTokenRequest,
) -> Result<BotToken, Self::Err> {
let token_id = macro_uuid::generate_uuid_v7();
@@ -554,15 +549,14 @@ impl BotRepo for PgBotsRepo {
BotTokenRow,
r#"
INSERT INTO bot_tokens (
- id, bot_id, token_hash, token_prefix, label, expires_at
+ id, bot_id, token, label, expires_at
)
- VALUES ($1, $2, $3, $4, $5, $6)
- RETURNING id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at
+ VALUES ($1, $2, $3, $4, $5)
+ RETURNING id, bot_id, token, label, last_used_at, expires_at, revoked_at, created_at
"#,
token_id,
bot_id.as_uuid(),
- token_hash,
- token_prefix,
+ token,
req.label,
req.expires_at,
)
@@ -576,7 +570,7 @@ impl BotRepo for PgBotsRepo {
let rows = sqlx::query_as!(
BotTokenRow,
r#"
- SELECT id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at
+ SELECT id, bot_id, token, label, last_used_at, expires_at, revoked_at, created_at
FROM bot_tokens
WHERE bot_id = $1
AND revoked_at IS NULL
@@ -608,18 +602,14 @@ impl BotRepo for PgBotsRepo {
Ok(result.rows_affected() > 0)
}
- async fn token_candidates(
- &self,
- token_prefix: &str,
- ) -> Result<Vec<BotTokenCandidate>, Self::Err> {
- let rows = sqlx::query_as!(
+ async fn token_candidate(&self, token: &str) -> Result<Option<BotTokenCandidate>, Self::Err> {
+ let row = sqlx::query_as!(
TokenCandidateRow,
r#"
SELECT
bt.id AS token_id,
bt.bot_id,
- bt.token_hash,
- bt.token_prefix,
+ bt.token,
bt.label,
bt.last_used_at,
bt.expires_at,
@@ -628,33 +618,30 @@ impl BotRepo for PgBotsRepo {
b.kind
FROM bot_tokens bt
JOIN bots b ON b.id = bt.bot_id
- WHERE bt.token_prefix = $1
+ WHERE bt.token = $1
AND b.deleted_at IS NULL
"#,
- token_prefix,
+ token,
)
- .fetch_all(&self.pool)
+ .fetch_optional(&self.pool)
.await
- .context("failed to lookup bot token candidates")?;
+ .context("failed to lookup bot token candidate")?;
- rows.into_iter()
- .map(TokenCandidateRow::into_candidate)
- .collect()
+ row.map(TokenCandidateRow::into_candidate).transpose()
}
- async fn channel_token_candidates(
+ async fn channel_token_candidate(
&self,
channel_id: Uuid,
- token_prefix: &str,
- ) -> Result<Vec<BotTokenCandidate>, Self::Err> {
- let rows = sqlx::query_as!(
+ token: &str,
+ ) -> Result<Option<BotTokenCandidate>, Self::Err> {
+ let row = sqlx::query_as!(
TokenCandidateRow,
r#"
SELECT
bt.id AS token_id,
bt.bot_id,
- bt.token_hash,
- bt.token_prefix,
+ bt.token,
bt.label,
bt.last_used_at,
bt.expires_at,
@@ -667,19 +654,17 @@ impl BotRepo for PgBotsRepo {
ON cp.channel_id = $1
AND cp.user_id = ('bot|' || b.id::text)
AND cp.left_at IS NULL
- WHERE bt.token_prefix = $2
+ WHERE bt.token = $2
AND b.deleted_at IS NULL
"#,
channel_id,
- token_prefix,
+ token,
)
- .fetch_all(&self.pool)
+ .fetch_optional(&self.pool)
.await
- .context("failed to lookup channel bot token candidates")?;
+ .context("failed to lookup channel bot token candidate")?;
- rows.into_iter()
- .map(TokenCandidateRow::into_candidate)
- .collect()
+ row.map(TokenCandidateRow::into_candidate).transpose()
}
async fn mark_token_used(&self, token_id: Uuid) -> Result<(), Self::Err> {
diff --git a/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs b/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs
index 3d730e9f82..7db7ff8fad 100644
--- a/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs
@@ -3,7 +3,6 @@ use crate::domain::{
models::{CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest},
ports::{BotError, BotService},
service::BotServiceImpl,
- tokens,
};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::PgPool;
@@ -296,10 +295,7 @@ async fn create_channel_scoped_bot_creates_bot_participant_and_token(
assert_eq!(created.bot.created_by.as_deref(), Some(USER_OWNER));
assert_eq!(created.token.bot_id, created.bot.id);
assert_eq!(created.token.label.as_deref(), Some("Webhook"));
- assert_eq!(
- tokens::token_prefix(&created.bot_token),
- Some(created.token.token_prefix.as_str())
- );
+ assert_eq!(created.token.token, created.bot_token);
assert_eq!(
active_channel_participant_count(&pool, channel_id, created.bot.id).await?,
1
@@ -422,6 +418,8 @@ async fn revoke_token_prevents_future_authentication(pool: PgPool) -> anyhow::Re
)
.await?;
+ assert_eq!(created.token.token, created.bearer_token);
+
let authenticated = service.authenticate_token(&created.bearer_token).await?;
assert_eq!(authenticated.bot_id, bot.id);
assert_eq!(authenticated.kind, BotKind::Owned);
@@ -438,3 +436,73 @@ async fn revoke_token_prevents_future_authentication(pool: PgPool) -> anyhow::Re
Ok(())
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_tokens_returns_raw_token_for_manageable_bot(pool: PgPool) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let bot = service
+ .create_bot(user_id(USER_OWNER), create_req("listed-token"))
+ .await?;
+
+ let created = service
+ .create_token(
+ user_id(USER_OWNER),
+ bot.id,
+ CreateBotTokenRequest {
+ label: Some("Listable".to_string()),
+ expires_at: None,
+ },
+ )
+ .await?;
+
+ let tokens = service.list_tokens(user_id(USER_OWNER), bot.id).await?;
+
+ assert_eq!(tokens.len(), 1);
+ assert_eq!(tokens[0].id, created.token.id);
+ assert_eq!(tokens[0].bot_id, bot.id);
+ assert_eq!(tokens[0].token, created.bearer_token);
+ assert_eq!(tokens[0].label.as_deref(), Some("Listable"));
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn authenticate_channel_token_accepts_migrated_uuid_token(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let channel_id = Uuid::new_v4();
+ insert_channel(&pool, channel_id).await?;
+
+ let bot = service
+ .create_bot(user_id(USER_OWNER), create_req("migrated-uuid-token"))
+ .await?;
+ service
+ .add_bot_to_channel(user_id(USER_OWNER), channel_id, bot.id)
+ .await?;
+
+ let token_id = Uuid::new_v4();
+ let raw_token = Uuid::new_v4().to_string();
+ sqlx::query(
+ r#"
+ INSERT INTO bot_tokens (id, bot_id, token, label)
+ VALUES ($1, $2, $3, $4)
+ "#,
+ )
+ .bind(token_id)
+ .bind(bot.id.as_uuid())
+ .bind(&raw_token)
+ .bind("migrated row")
+ .execute(&pool)
+ .await?;
+
+ let authenticated = service
+ .authenticate_channel_token(channel_id, &raw_token)
+ .await?;
+
+ assert_eq!(authenticated.bot_id, bot.id);
+ assert_eq!(authenticated.kind, BotKind::Owned);
+ assert!(token_last_used_at(&pool, token_id).await?.is_some());
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260616120000_bot_tokens_raw_token.sql b/rust/cloud-storage/macro_db_client/migrations/20260616120000_bot_tokens_raw_token.sql
new file mode 100644
index 0000000000..c1161f592c
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260616120000_bot_tokens_raw_token.sql
@@ -0,0 +1,18 @@
+ALTER TABLE public.bot_tokens
+ ADD COLUMN token text;
+
+UPDATE public.bot_tokens
+SET token = gen_random_uuid()::text
+WHERE token IS NULL;
+
+ALTER TABLE public.bot_tokens
+ ALTER COLUMN token SET NOT NULL;
+
+DROP INDEX public.bot_tokens_token_prefix_idx;
+
+ALTER TABLE public.bot_tokens
+ DROP COLUMN token_hash,
+ DROP COLUMN token_prefix;
+
+CREATE UNIQUE INDEX bot_tokens_token_idx
+ ON public.bot_tokens (token);