Skip to content

Commit

Permalink
fix: work on auth, relax checks
Browse files Browse the repository at this point in the history
  • Loading branch information
Danny Browning committed Jul 24, 2024
1 parent e5dda9c commit f1508e8
Show file tree
Hide file tree
Showing 9 changed files with 278 additions and 115 deletions.
2 changes: 1 addition & 1 deletion api-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ To see how to make this your own, look here:
[README]((https://openapi-generator.tech))

- API version: 0.29.0
- Build date: 2024-07-23T17:26:31.452467-06:00[America/Denver]
- Build date: 2024-07-24T16:31:34.304262-06:00[America/Denver]



Expand Down
258 changes: 203 additions & 55 deletions api/src/auth.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ pub use resume_token::ResumeToken;

pub use server::{EventInsertResult, EventStore, InterestStore, Server};

mod auth;
#[cfg(test)]
mod tests;
mod auth;
26 changes: 15 additions & 11 deletions api/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ use std::{
sync::{Arc, Mutex},
};

use crate::auth;
use crate::auth::Operation;
use anyhow::Result;
use async_trait::async_trait;
use ceramic_api_server::models::{BadRequestResponse, ErrorResponse, EventData};
Expand All @@ -34,15 +36,13 @@ use ceramic_api_server::{
FeedEventsGetResponse, FeedResumeTokenGetResponse, InterestsPostResponse,
};
use ceramic_core::{Cid, EventId, Interest, Network, PeerId, StreamId};
use ceramic_event::ssi::jsonld::syntax::parse::Error::Stream;
use futures::TryFutureExt;
use recon::Key;
use swagger::{ApiError, ByteArray};
#[cfg(not(target_env = "msvc"))]
use tikv_jemalloc_ctl::epoch;
use tracing::{instrument, Level};
use ceramic_event::ssi::jsonld::syntax::parse::Error::Stream;
use crate::auth;
use crate::auth::Operation;

use crate::server::event::event_id_from_car;
use crate::ResumeToken;
Expand Down Expand Up @@ -780,10 +780,12 @@ where
) -> Result<FeedEventsGetResponse, ApiError> {
let filter = if self.authentication {
if let (Some(auth), Some(resource)) = (authorization, resource) {
auth::authenticate(&auth, Operation::Read, &resource).await.map_err(|err| {
tracing::debug!("Unauthorized: {err}");
ApiError("Unauthorized".to_string())
})?;
auth::authenticate(&auth, Operation::Read, &resource)
.await
.map_err(|err| {
tracing::debug!("Unauthorized: {err}");
ApiError("Unauthorized".to_string())
})?;
Some(resource)
} else {
return Err(ApiError("Unauthorized".to_string()));
Expand Down Expand Up @@ -895,10 +897,12 @@ where
) -> Result<EventsEventIdGetResponse, ApiError> {
if self.authentication {
if let (Some(bearer), Some(resource)) = (bearer, resource) {
auth::authenticate(&bearer, Operation::Read, &resource).await.map_err(|err| {
tracing::debug!("Unauthorized: {err}");
ApiError("Unauthorized".to_string())
})?;
auth::authenticate(&bearer, Operation::Read, &resource)
.await
.map_err(|err| {
tracing::debug!("Unauthorized: {err}");
ApiError("Unauthorized".to_string())
})?;
} else {
return Err(ApiError("Unauthorized".to_string()));
}
Expand Down
4 changes: 3 additions & 1 deletion api/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,9 @@ async fn test_events_event_id_get_by_event_id_success() {
.returning(move |_| Ok(Some(event_data.clone())));
let mock_interest = MockAccessInterestStoreTest::new();
let server = Server::new(peer_id, network, mock_interest, Arc::new(mock_event_store));
let result = server.events_event_id_get(event_id_str, None, None, &Context).await;
let result = server
.events_event_id_get(event_id_str, None, None, &Context)
.await;
let EventsEventIdGetResponse::Success(event) = result.unwrap() else {
panic!("Expected EventsEventIdGetResponse::Success but got another variant");
};
Expand Down
1 change: 1 addition & 0 deletions event/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod bytes;
pub mod unvalidated;

pub use ceramic_core::*;
pub use unvalidated::cid_from_dag_cbor;

#[cfg(test)]
pub mod tests {
Expand Down
3 changes: 2 additions & 1 deletion event/src/unvalidated/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ use cid::Cid;
use ipld_core::{codec::Codec, ipld::Ipld};
use serde_ipld_dagcbor::codec::DagCborCodec;

fn cid_from_dag_cbor(data: &[u8]) -> Cid {
/// Create a CID from a DAG-CBOR encoded data
pub fn cid_from_dag_cbor(data: &[u8]) -> Cid {
Cid::new_v1(
<DagCborCodec as Codec<Ipld>>::CODE,
Code::Sha2_256.digest(data),
Expand Down
95 changes: 51 additions & 44 deletions event/src/unvalidated/signed/cacao.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
//! Structures for encoding and decoding CACAO capability objects.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use ssi::jwk::Algorithm;
use std::collections::HashMap;

/// Capability object, see https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-74.md
#[derive(Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Capability {
/// Header for capability
#[serde(rename = "h")]
Expand All @@ -18,18 +19,18 @@ pub struct Capability {
}

/// Type of Capability Header
#[derive(Debug, Deserialize, Serialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum HeaderType {
/// EIP-4361 Capability
#[serde(rename="eip4361")]
#[serde(rename = "eip4361")]
EIP4361,
/// CAIP-122 Capability
#[serde(rename="caip122")]
#[serde(rename = "caip122")]
CAIP122,
}

/// Header for a Capability
#[derive(Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Header {
/// Type of the Capability Header
#[serde(rename = "t")]
Expand All @@ -40,40 +41,33 @@ pub struct Header {
pub type CapabilityTime = chrono::DateTime<chrono::Utc>;

/// Payload for a CACAO
#[derive(Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Payload {
/// Domain for payload
pub domain: String,

/// Issuer for payload. For capability will be DID in URI format
#[serde(rename = "iss")]
pub issuer: String,

/// Audience for payload
#[serde(rename = "aud")]
pub audience: String,

/// Version of payload
pub version: String,
/// Domain for payload
pub domain: String,

/// Nonce of payload
pub nonce: String,
/// Expiration time
#[serde(rename = "exp", skip_serializing_if = "Option::is_none")]
pub expiration: Option<CapabilityTime>,

/// Issued at time
#[serde(rename = "iat")]
pub issued_at: CapabilityTime,

/// Issuer for payload. For capability will be DID in URI format
#[serde(rename = "iss")]
pub issuer: String,

/// Not before time
#[serde(rename = "nbf", skip_serializing_if = "Option::is_none")]
pub not_before: Option<CapabilityTime>,

/// Expiration time
#[serde(rename = "exp", skip_serializing_if = "Option::is_none")]
pub expiration: Option<CapabilityTime>,

/// Subject of payload
#[serde(skip_serializing_if = "Option::is_none")]
pub statement: Option<String>,
/// Nonce of payload
pub nonce: String,

/// Request ID
#[serde(rename = "requestId", skip_serializing_if = "Option::is_none")]
Expand All @@ -82,10 +76,17 @@ pub struct Payload {
/// Resources
#[serde(skip_serializing_if = "Option::is_none")]
pub resources: Option<Vec<String>>,

/// Subject of payload
#[serde(skip_serializing_if = "Option::is_none")]
pub statement: Option<String>,

/// Version of payload
pub version: String,
}

/// Type of Signature
#[derive(Debug, Deserialize, Serialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum SignatureType {
/// EIP-191 Signature
#[serde(rename = "eip191")]
Expand All @@ -110,19 +111,23 @@ pub enum SignatureType {
JWS,
}

/// Known metadata type for signatures
#[derive(Debug, Deserialize, Serialize)]
pub struct KnownMetadata {
/// Algorithm for signature
pub alg: String,
/// capability for signature
pub cap: String,
/// Key ID for signature
pub kid: String,
impl SignatureType {
/// Convert signature type to algorithm
pub fn algorithm(&self) -> Algorithm {
match self {
SignatureType::EIP191 => Algorithm::ES256,
SignatureType::EIP1271 => Algorithm::ES256,
SignatureType::SolanaED25519 => Algorithm::EdDSA,
SignatureType::TezosED25519 => Algorithm::EdDSA,
SignatureType::StacksSECP256K1 => Algorithm::ES256K,
SignatureType::WebAuthNP256 => Algorithm::ES256,
SignatureType::JWS => Algorithm::ES256,
}
}
}

/// Values for unknown metadata
#[derive(Debug, Deserialize, Serialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum MetadataValue {
/// Boolean value
Expand All @@ -136,17 +141,19 @@ pub enum MetadataValue {
}

/// Metadata for signature
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum SignatureMetadata {
/// Known metadata
Known(KnownMetadata),
/// Unknown metadata
Unknown(HashMap<String, MetadataValue>),
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SignatureMetadata {
/// Algorithm for signature
pub alg: String,
/// Key ID for signature
pub kid: String,
/// Other metadata
#[serde(flatten)]
pub rest: HashMap<String, MetadataValue>,
}

/// Signature of a CACAO
#[derive(Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Signature {
/// Metadata for signature
#[serde(rename = "m")]
Expand Down
2 changes: 1 addition & 1 deletion one/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ struct DaemonOpts {
#[arg(
long,
default_value_t = false,
env = "CERAMIC_ONE_EXPERIMENTAL_AUTHENTICATION",
env = "CERAMIC_ONE_EXPERIMENTAL_AUTHENTICATION"
)]
experimental_authentication: bool,
}
Expand Down

0 comments on commit f1508e8

Please sign in to comment.