Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ version = "5.6.0"
resolver = "2"
members = [
"render-conjure",
"witchcraft-jwt",
"witchcraft-server",
"witchcraft-server-config",
"witchcraft-server-ete",
Expand Down
11 changes: 11 additions & 0 deletions witchcraft-jwt/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "witchcraft-jwt"
edition = "2024"
version.workspace = true

[dependencies]
base64 = "0.22"
serde = "1"
serde_derive = "1"
serde_json = "1"
uuid = { version = "1.18.0", features = ["v4"] }
1 change: 1 addition & 0 deletions witchcraft-jwt/LICENSE
15 changes: 15 additions & 0 deletions witchcraft-jwt/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright 2025 Palantir Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub mod unverified_jwt;
149 changes: 149 additions & 0 deletions witchcraft-jwt/src/unverified_jwt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use serde::de::{Deserializer, Error, Unexpected, Visitor};
use serde_derive::Deserialize;
use std::fmt;
use uuid::Uuid;

#[derive(PartialEq, Eq, Debug, Deserialize, Clone)]
pub struct UnverifiedJwt {
#[serde(deserialize_with = "de_uuid")]
sub: Uuid,
#[serde(default, deserialize_with = "de_opt_uuid")]
sid: Option<Uuid>,
#[serde(default, deserialize_with = "de_opt_uuid")]
jti: Option<Uuid>,
#[serde(default, deserialize_with = "de_opt_uuid")]
org: Option<Uuid>,
#[serde(default)]
exp: Option<u32>,
}

impl UnverifiedJwt {
pub fn unverified_user_id(&self) -> Uuid {
self.sub
}

pub fn unverified_session_id(&self) -> Option<Uuid> {
self.sid
}

pub fn unverified_token_id(&self) -> Option<Uuid> {
self.jti
}

pub fn unverified_organization_id(&self) -> Option<Uuid> {
self.org
}

pub fn unverified_exp(&self) -> Option<u32> {
self.exp
}
}

impl UnverifiedJwt {
pub fn parse(s: &str) -> Option<Self> {
let mut it = s.split('.').skip(1);
let payload = it.next()?;
if it.count() != 1 {
return None;
}

let payload = URL_SAFE_NO_PAD.decode(payload).ok()?;

serde_json::from_slice(&payload).ok()
}
}

// To save space, we serialize UUIDs as base64 bytes rather than the normal hex format.
fn de_uuid<'de, D>(deserializer: D) -> Result<Uuid, D::Error>
where
D: Deserializer<'de>,
{
struct V;

impl Visitor<'_> for V {
type Value = Uuid;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("base64 encoded UUID")
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
let bytes = STANDARD
.decode(v)
.map_err(|_| Error::invalid_value(Unexpected::Str(v), &self))?;

Uuid::from_slice(&bytes).map_err(|_| Error::invalid_value(Unexpected::Str(v), &self))
}
}

deserializer.deserialize_str(V)
}

fn de_opt_uuid<'de, D>(deserializer: D) -> Result<Option<Uuid>, D::Error>
where
D: Deserializer<'de>,
{
struct V;

impl<'de2> Visitor<'de2> for V {
type Value = Option<Uuid>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("option")
}

fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}

fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}

fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de2>,
{
de_uuid(deserializer).map(Some)
}
}

deserializer.deserialize_option(V)
}

#[cfg(test)]
mod test {
use crate::unverified_jwt::UnverifiedJwt;

#[test]
fn parse() {
let token = "header.\
eyJzdWIiOiJ3NVAyV1FNQlEwNnB5WEl3U2xCLy9BPT0iLCJzaWQiOiJQOFpqMUQ1SVRlMjZUdGVLK1l1RFl3PT0\
iLCJqdGkiOiJwRm0wb1ZDSlQrQ0dWZFhmMmJLMy9RPT0iLCJvcmciOiJGQlMycTgvbFQvMnNBRktxZ09pUW13PT\
0iLCJleHAiOiAxNTc3ODY1NjAwfQ\
.signature";

let parsed = UnverifiedJwt::parse(token).unwrap();

let expected = UnverifiedJwt {
sub: "c393f659-0301-434e-a9c9-72304a507ffc".parse().unwrap(),
sid: Some("3fc663d4-3e48-4ded-ba4e-d78af98b8363".parse().unwrap()),
jti: Some("a459b4a1-5089-4fe0-8655-d5dfd9b2b7fd".parse().unwrap()),
org: Some("1414b6ab-cfe5-4ffd-ac00-52aa80e8909b".parse().unwrap()),
exp: Some(1577865600),
};

assert_eq!(expected, parsed);
}
}
2 changes: 1 addition & 1 deletion witchcraft-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ jemalloc = ["dep:tikv-jemalloc-ctl", "dep:tikv-jemallocator"]
arc-swap = "1"
async-compression = { version = "0.4", features = ["tokio", "gzip"] }
async-trait = "0.1"
base64 = "0.22"
bytes = "1"
conjure-error = "4"
conjure-http = "4"
Expand Down Expand Up @@ -114,6 +113,7 @@ witchcraft-logging-api = "1.0.0"
witchcraft-metrics = "1"
witchcraft-server-config = { version = "5.6.0", path = "../witchcraft-server-config" }
witchcraft-server-macros = { version = "5.6.0", path = "../witchcraft-server-macros" }
witchcraft-jwt = { version = "5.6.0", path = "../witchcraft-jwt" }
zipkin = "1.0"

[dev-dependencies]
Expand Down
143 changes: 1 addition & 142 deletions witchcraft-server/src/service/unverified_jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::service::{Layer, Service};
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use base64::Engine;
use conjure_object::Uuid;
use http::header::AUTHORIZATION;
use http::Request;
use serde::de::{Error, Unexpected, Visitor};
use serde::{Deserialize, Deserializer};
use std::fmt;
use witchcraft_jwt::unverified_jwt::UnverifiedJwt;

/// A layer which parses the request's bearer token (without verifying its validity) and adds it to the request's
/// extensions.
Expand Down Expand Up @@ -57,139 +52,3 @@ where
self.inner.call(req).await
}
}

#[derive(PartialEq, Eq, Debug, Deserialize, Clone)]
pub struct UnverifiedJwt {
#[serde(deserialize_with = "de_uuid")]
sub: Uuid,
#[serde(default, deserialize_with = "de_opt_uuid")]
sid: Option<Uuid>,
#[serde(default, deserialize_with = "de_opt_uuid")]
jti: Option<Uuid>,
#[serde(default, deserialize_with = "de_opt_uuid")]
org: Option<Uuid>,
}

impl UnverifiedJwt {
pub fn unverified_user_id(&self) -> Uuid {
self.sub
}

pub fn unverified_session_id(&self) -> Option<Uuid> {
self.sid
}

pub fn unverified_token_id(&self) -> Option<Uuid> {
self.jti
}

pub fn unverified_organization_id(&self) -> Option<Uuid> {
self.org
}
}

impl UnverifiedJwt {
fn parse(s: &str) -> Option<Self> {
let mut it = s.split('.').skip(1);
let payload = it.next()?;
if it.count() != 1 {
return None;
}

let payload = URL_SAFE_NO_PAD.decode(payload).ok()?;

serde_json::from_slice(&payload).ok()
}
}

// To save space, we serialize UUIDs as base64 bytes rather than the normal hex format.
fn de_uuid<'de, D>(deserializer: D) -> Result<Uuid, D::Error>
where
D: Deserializer<'de>,
{
struct V;

impl Visitor<'_> for V {
type Value = Uuid;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("base64 encoded UUID")
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
let bytes = STANDARD
.decode(v)
.map_err(|_| Error::invalid_value(Unexpected::Str(v), &self))?;

Uuid::from_slice(&bytes).map_err(|_| Error::invalid_value(Unexpected::Str(v), &self))
}
}

deserializer.deserialize_str(V)
}

fn de_opt_uuid<'de, D>(deserializer: D) -> Result<Option<Uuid>, D::Error>
where
D: Deserializer<'de>,
{
struct V;

impl<'de2> Visitor<'de2> for V {
type Value = Option<Uuid>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("option")
}

fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}

fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(None)
}

fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de2>,
{
de_uuid(deserializer).map(Some)
}
}

deserializer.deserialize_option(V)
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn parse() {
let token = "header.\
eyJzdWIiOiJ3NVAyV1FNQlEwNnB5WEl3U2xCLy9BPT0iLCJzaWQiOiJQOFpqMUQ1SVRlMjZUdGVLK1l1RFl3PT0\
iLCJqdGkiOiJwRm0wb1ZDSlQrQ0dWZFhmMmJLMy9RPT0iLCJvcmciOiJGQlMycTgvbFQvMnNBRktxZ09pUW13PT\
0iLCJleHAiOiAxNTc3ODY1NjAwfQ\
.signature";

let parsed = UnverifiedJwt::parse(token).unwrap();

let expected = UnverifiedJwt {
sub: "c393f659-0301-434e-a9c9-72304a507ffc".parse().unwrap(),
sid: Some("3fc663d4-3e48-4ded-ba4e-d78af98b8363".parse().unwrap()),
jti: Some("a459b4a1-5089-4fe0-8655-d5dfd9b2b7fd".parse().unwrap()),
org: Some("1414b6ab-cfe5-4ffd-ac00-52aa80e8909b".parse().unwrap()),
};

assert_eq!(expected, parsed);
}
}
2 changes: 1 addition & 1 deletion witchcraft-server/src/service/witchcraft_mdc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@

use crate::logging;
use crate::service::request_id::RequestId;
use crate::service::unverified_jwt::UnverifiedJwt;
use crate::service::{Layer, Service};
use http::Request;
use witchcraft_jwt::unverified_jwt::UnverifiedJwt;
use witchcraft_log::mdc;

/// A layer which injects Witchcraft-managed request state into the MDC.
Expand Down