mirror of
https://seed.radicle.dev/rad:z4V1sjrXqjvFdnCUbxPFqd5p4DtH5.git
synced 2026-11-21 14:20:42 +08:00
Rename http-server -> radicle-httpd
So that the directory name matches the crate name.
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::serde::timestamp;
|
||||
use time::{Duration, OffsetDateTime};
|
||||
|
||||
use radicle::crypto::PublicKey;
|
||||
use radicle::node::Alias;
|
||||
|
||||
use crate::api::error::Error;
|
||||
use crate::api::Context;
|
||||
|
||||
pub const UNAUTHORIZED_SESSIONS_EXPIRATION: Duration = Duration::seconds(60);
|
||||
pub const AUTHORIZED_SESSIONS_EXPIRATION: Duration = Duration::weeks(1);
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AuthState {
|
||||
Authorized,
|
||||
Unauthorized,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Session {
|
||||
pub status: AuthState,
|
||||
pub public_key: PublicKey,
|
||||
pub alias: Alias,
|
||||
#[serde(with = "timestamp")]
|
||||
pub issued_at: OffsetDateTime,
|
||||
#[serde(with = "timestamp")]
|
||||
pub expires_at: OffsetDateTime,
|
||||
}
|
||||
|
||||
pub async fn validate(ctx: &Context, token: &str) -> Result<(), Error> {
|
||||
let sessions_store = ctx.sessions.read().await;
|
||||
let session = sessions_store
|
||||
.get(token)
|
||||
.ok_or(Error::Auth("Unauthorized"))?;
|
||||
|
||||
if session.status != AuthState::Authorized || session.expires_at <= OffsetDateTime::now_utc() {
|
||||
return Err(Error::Auth("Unauthorized"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::Json;
|
||||
use serde_json::json;
|
||||
|
||||
/// Errors relating to the API backend.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// The entity was not found.
|
||||
#[error("entity not found")]
|
||||
NotFound,
|
||||
|
||||
/// An error occurred during an authentication process.
|
||||
#[error("could not authenticate: {0}")]
|
||||
Auth(&'static str),
|
||||
|
||||
/// An error occurred with env variables.
|
||||
#[error(transparent)]
|
||||
Env(#[from] std::env::VarError),
|
||||
|
||||
/// Profile error.
|
||||
#[error(transparent)]
|
||||
Profile(#[from] radicle::profile::Error),
|
||||
|
||||
/// Crypto error.
|
||||
#[error(transparent)]
|
||||
Crypto(#[from] radicle::crypto::Error),
|
||||
|
||||
/// Storage error.
|
||||
#[error(transparent)]
|
||||
Storage(#[from] radicle::storage::Error),
|
||||
|
||||
/// Cob cache error.
|
||||
#[error(transparent)]
|
||||
CobCache(#[from] radicle::cob::cache::Error),
|
||||
|
||||
/// Cob issue cache error.
|
||||
#[error(transparent)]
|
||||
CacheIssue(#[from] radicle::cob::issue::cache::Error),
|
||||
|
||||
/// Cob issue error.
|
||||
#[error(transparent)]
|
||||
CobIssue(#[from] radicle::cob::issue::Error),
|
||||
|
||||
/// Cob patch error.
|
||||
#[error(transparent)]
|
||||
CobPatch(#[from] radicle::cob::patch::Error),
|
||||
|
||||
/// Cob patch cache error.
|
||||
#[error(transparent)]
|
||||
CachePatch(#[from] radicle::cob::patch::cache::Error),
|
||||
|
||||
/// Cob store error.
|
||||
#[error(transparent)]
|
||||
CobStore(#[from] radicle::cob::store::Error),
|
||||
|
||||
/// Repository error.
|
||||
#[error(transparent)]
|
||||
Repository(#[from] radicle::storage::RepositoryError),
|
||||
|
||||
/// Routing error.
|
||||
#[error(transparent)]
|
||||
Routing(#[from] radicle::node::routing::Error),
|
||||
|
||||
/// Project doc error.
|
||||
#[error(transparent)]
|
||||
ProjectDoc(#[from] radicle::identity::doc::PayloadError),
|
||||
|
||||
/// Surf directory error.
|
||||
#[error(transparent)]
|
||||
SurfDir(#[from] radicle_surf::fs::error::Directory),
|
||||
|
||||
/// Surf error.
|
||||
#[error(transparent)]
|
||||
Surf(#[from] radicle_surf::Error),
|
||||
|
||||
/// Git2 error.
|
||||
#[error(transparent)]
|
||||
Git2(#[from] radicle::git::raw::Error),
|
||||
|
||||
/// Storage refs error.
|
||||
#[error(transparent)]
|
||||
StorageRef(#[from] radicle::storage::refs::Error),
|
||||
|
||||
/// Identity doc error.
|
||||
#[error(transparent)]
|
||||
IdentityDoc(#[from] radicle::identity::doc::DocError),
|
||||
|
||||
/// Tracking store error.
|
||||
#[error(transparent)]
|
||||
TrackingStore(#[from] radicle::node::policy::store::Error),
|
||||
|
||||
/// Node database error.
|
||||
#[error(transparent)]
|
||||
Database(#[from] radicle::node::db::Error),
|
||||
|
||||
/// Node error.
|
||||
#[error(transparent)]
|
||||
Node(#[from] radicle::node::Error),
|
||||
|
||||
/// Invalid update to issue or patch.
|
||||
#[error("{0}")]
|
||||
BadRequest(String),
|
||||
}
|
||||
|
||||
impl IntoResponse for Error {
|
||||
fn into_response(self) -> Response {
|
||||
let message = self.to_string();
|
||||
let (status, msg) = match self {
|
||||
Error::NotFound => (StatusCode::NOT_FOUND, None),
|
||||
Error::CobStore(e @ radicle::cob::store::Error::NotFound(_, _)) => {
|
||||
(StatusCode::NOT_FOUND, Some(e.to_string()))
|
||||
}
|
||||
Error::Auth(msg) => (StatusCode::UNAUTHORIZED, Some(msg.to_string())),
|
||||
Error::Crypto(msg) => (StatusCode::BAD_REQUEST, Some(msg.to_string())),
|
||||
Error::Surf(radicle_surf::Error::Git(e)) if radicle::git::is_not_found_err(&e) => {
|
||||
(StatusCode::NOT_FOUND, Some(e.message().to_owned()))
|
||||
}
|
||||
Error::Surf(radicle_surf::Error::Directory(
|
||||
e @ radicle_surf::fs::error::Directory::PathNotFound(_),
|
||||
)) => (StatusCode::NOT_FOUND, Some(e.to_string())),
|
||||
Error::Git2(e) if radicle::git::is_not_found_err(&e) => {
|
||||
(StatusCode::NOT_FOUND, Some(e.message().to_owned()))
|
||||
}
|
||||
Error::Git2(e) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Some(e.message().to_owned()),
|
||||
),
|
||||
Error::Storage(err) if err.is_not_found() => {
|
||||
(StatusCode::NOT_FOUND, Some(err.to_string()))
|
||||
}
|
||||
Error::Repository(err) if err.is_not_found() => {
|
||||
(StatusCode::NOT_FOUND, Some(err.to_string()))
|
||||
}
|
||||
Error::StorageRef(err) if err.is_not_found() => {
|
||||
(StatusCode::NOT_FOUND, Some(err.to_string()))
|
||||
}
|
||||
Error::BadRequest(msg) => (StatusCode::BAD_REQUEST, Some(msg)),
|
||||
other => {
|
||||
tracing::error!("Error: {message}");
|
||||
tracing::debug!("Error Debug: {:?}", other);
|
||||
|
||||
if cfg!(debug_assertions) {
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Some(other.to_string()))
|
||||
} else {
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, None)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let body = Json(json!({
|
||||
"error": msg.or_else(|| status.canonical_reason().map(|r| r.to_string())),
|
||||
"code": status.as_u16()
|
||||
}));
|
||||
|
||||
(status, body).into_response()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
//! Utilities for building JSON responses of our API.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::str;
|
||||
|
||||
use base64::prelude::{Engine, BASE64_STANDARD};
|
||||
use radicle::cob::{CodeLocation, Reaction};
|
||||
use radicle::patch::ReviewId;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use radicle::cob::issue::{Issue, IssueId};
|
||||
use radicle::cob::patch::{Merge, Patch, PatchId, Review};
|
||||
use radicle::cob::thread::{Comment, CommentId, Edit};
|
||||
use radicle::cob::{ActorId, Author};
|
||||
use radicle::git::RefString;
|
||||
use radicle::node::{Alias, AliasStore};
|
||||
use radicle::prelude::NodeId;
|
||||
use radicle::storage::{git, refs, RemoteRepository};
|
||||
use radicle_surf::blob::Blob;
|
||||
use radicle_surf::tree::{EntryKind, Tree};
|
||||
use radicle_surf::{Commit, Oid};
|
||||
|
||||
use crate::api::auth::Session;
|
||||
|
||||
/// Returns JSON of a commit.
|
||||
pub(crate) fn commit(commit: &Commit) -> Value {
|
||||
json!({
|
||||
"id": commit.id,
|
||||
"author": {
|
||||
"name": commit.author.name,
|
||||
"email": commit.author.email
|
||||
},
|
||||
"summary": commit.summary,
|
||||
"description": commit.description(),
|
||||
"parents": commit.parents,
|
||||
"committer": {
|
||||
"name": commit.committer.name,
|
||||
"email": commit.committer.email,
|
||||
"time": commit.committer.time.seconds()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns JSON of a session.
|
||||
pub(crate) fn session(session_id: String, session: &Session) -> Value {
|
||||
json!({
|
||||
"sessionId": session_id,
|
||||
"status": session.status,
|
||||
"publicKey": session.public_key,
|
||||
"alias": session.alias,
|
||||
"issuedAt": session.issued_at.unix_timestamp(),
|
||||
"expiresAt": session.expires_at.unix_timestamp()
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns JSON for a blob with a given `path`.
|
||||
pub(crate) fn blob<T: AsRef<[u8]>>(blob: &Blob<T>, path: &str) -> Value {
|
||||
json!({
|
||||
"binary": blob.is_binary(),
|
||||
"name": name_in_path(path),
|
||||
"content": blob_content(blob),
|
||||
"path": path,
|
||||
"lastCommit": commit(blob.commit())
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns a string for the blob content, encoded in base64 if binary.
|
||||
pub fn blob_content<T: AsRef<[u8]>>(blob: &Blob<T>) -> String {
|
||||
match str::from_utf8(blob.content()) {
|
||||
Ok(s) => s.to_owned(),
|
||||
Err(_) => BASE64_STANDARD.encode(blob.content()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns JSON for a tree with a given `path` and `stats`.
|
||||
pub(crate) fn tree(tree: &Tree, path: &str) -> Value {
|
||||
let prefix = Path::new(path);
|
||||
let entries = tree
|
||||
.entries()
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
json!({
|
||||
"path": prefix.join(entry.name()),
|
||||
"oid": entry.object_id(),
|
||||
"name": entry.name(),
|
||||
"kind": match entry.entry() {
|
||||
EntryKind::Tree(_) => "tree",
|
||||
EntryKind::Blob(_) => "blob",
|
||||
EntryKind::Submodule { .. } => "submodule"
|
||||
},
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
json!({
|
||||
"entries": &entries,
|
||||
"lastCommit": commit(tree.commit()),
|
||||
"name": name_in_path(path),
|
||||
"path": path,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns JSON for an `issue`.
|
||||
pub(crate) fn issue(id: IssueId, issue: Issue, aliases: &impl AliasStore) -> Value {
|
||||
json!({
|
||||
"id": id.to_string(),
|
||||
"author": author(&issue.author(), aliases.alias(issue.author().id())),
|
||||
"title": issue.title(),
|
||||
"state": issue.state(),
|
||||
"assignees": issue.assignees().map(|assignee|
|
||||
author(&Author::from(*assignee.as_key()), aliases.alias(assignee))
|
||||
).collect::<Vec<_>>(),
|
||||
"discussion": issue.comments().map(|(id, c)| issue_comment(id, c, aliases)).collect::<Vec<_>>(),
|
||||
"labels": issue.labels().collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns JSON for a `patch`.
|
||||
pub(crate) fn patch(
|
||||
id: PatchId,
|
||||
patch: Patch,
|
||||
repo: &git::Repository,
|
||||
aliases: &impl AliasStore,
|
||||
) -> Value {
|
||||
json!({
|
||||
"id": id.to_string(),
|
||||
"author": author(patch.author(), aliases.alias(patch.author().id())),
|
||||
"title": patch.title(),
|
||||
"state": patch.state(),
|
||||
"target": patch.target(),
|
||||
"labels": patch.labels().collect::<Vec<_>>(),
|
||||
"merges": patch.merges().map(|(nid, m)| merge(nid, m, aliases)).collect::<Vec<_>>(),
|
||||
"assignees": patch.assignees().map(|assignee|
|
||||
author(&Author::from(*assignee), aliases.alias(&assignee))
|
||||
).collect::<Vec<_>>(),
|
||||
"revisions": patch.revisions().map(|(id, rev)| {
|
||||
json!({
|
||||
"id": id,
|
||||
"author": author(rev.author(), aliases.alias(rev.author().id())),
|
||||
"description": rev.description(),
|
||||
"edits": rev.edits().map(|e| edit(e, aliases)).collect::<Vec<_>>(),
|
||||
"reactions": rev.reactions().iter().flat_map(|(location, reaction)| {
|
||||
reactions(reaction.iter().fold(BTreeMap::new(), |mut acc: BTreeMap<&Reaction, Vec<_>>, (author, emoji)| {
|
||||
acc.entry(emoji).or_default().push(author);
|
||||
acc
|
||||
}), location.as_ref(), aliases)
|
||||
}).collect::<Vec<_>>(),
|
||||
"base": rev.base(),
|
||||
"oid": rev.head(),
|
||||
"refs": get_refs(repo, patch.author().id(), &rev.head()).unwrap_or_default(),
|
||||
"discussions": rev.discussion().comments().map(|(id, c)| {
|
||||
patch_comment(id, c, aliases)
|
||||
}).collect::<Vec<_>>(),
|
||||
"timestamp": rev.timestamp().as_secs(),
|
||||
"reviews": patch.reviews_of(id).map(move |(id, r)| {
|
||||
review(id, r, aliases)
|
||||
}).collect::<Vec<_>>(),
|
||||
})
|
||||
}).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns JSON for a `reaction`.
|
||||
fn reactions(
|
||||
reactions: BTreeMap<&Reaction, Vec<&ActorId>>,
|
||||
location: Option<&CodeLocation>,
|
||||
aliases: &impl AliasStore,
|
||||
) -> Vec<Value> {
|
||||
reactions
|
||||
.into_iter()
|
||||
.map(|(emoji, authors)| {
|
||||
if let Some(l) = location {
|
||||
json!({ "location": l, "emoji": emoji, "authors": authors.into_iter().map(|a|
|
||||
author(&Author::from(*a), aliases.alias(a))
|
||||
).collect::<Vec<_>>()})
|
||||
} else {
|
||||
json!({ "emoji": emoji, "authors": authors.into_iter().map(|a|
|
||||
author(&Author::from(*a), aliases.alias(a))
|
||||
).collect::<Vec<_>>()})
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
/// Returns JSON for an `author` and fills in `alias` when present.
|
||||
pub(crate) fn author(author: &Author, alias: Option<Alias>) -> Value {
|
||||
match alias {
|
||||
Some(alias) => json!({
|
||||
"id": author.id,
|
||||
"alias": alias,
|
||||
}),
|
||||
None => json!(author),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns JSON for a patch `Merge` and fills in `alias` when present.
|
||||
fn merge(nid: &NodeId, merge: &Merge, aliases: &impl AliasStore) -> Value {
|
||||
json!({
|
||||
"author": author(&Author::from(*nid), aliases.alias(nid)),
|
||||
"commit": merge.commit,
|
||||
"timestamp": merge.timestamp.as_secs(),
|
||||
"revision": merge.revision,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns JSON for a patch `Review` and fills in `alias` when present.
|
||||
fn review(id: &ReviewId, review: &Review, aliases: &impl AliasStore) -> Value {
|
||||
let a = review.author();
|
||||
json!({
|
||||
"id": id,
|
||||
"author": author(a, aliases.alias(a.id())),
|
||||
"verdict": review.verdict(),
|
||||
"summary": review.summary(),
|
||||
"comments": review.comments().map(|(id, c)| review_comment(id, c, aliases)).collect::<Vec<_>>(),
|
||||
"timestamp": review.timestamp().as_secs(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns JSON for an `Edit`.
|
||||
fn edit(edit: &Edit, aliases: &impl AliasStore) -> Value {
|
||||
json!({
|
||||
"author": author(&Author::from(edit.author), aliases.alias(&edit.author)),
|
||||
"body": edit.body,
|
||||
"timestamp": edit.timestamp.as_secs(),
|
||||
"embeds": edit.embeds,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns JSON for a Issue `Comment`.
|
||||
fn issue_comment(id: &CommentId, comment: &Comment, aliases: &impl AliasStore) -> Value {
|
||||
json!({
|
||||
"id": *id,
|
||||
"author": author(&Author::from(comment.author()), aliases.alias(&comment.author())),
|
||||
"body": comment.body(),
|
||||
"edits": comment.edits().map(|e| edit(e, aliases)).collect::<Vec<_>>(),
|
||||
"embeds": comment.embeds().to_vec(),
|
||||
"reactions": reactions(comment.reactions(), None, aliases),
|
||||
"timestamp": comment.timestamp().as_secs(),
|
||||
"replyTo": comment.reply_to(),
|
||||
"resolved": comment.is_resolved(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns JSON for a Patch `Comment`.
|
||||
fn patch_comment(
|
||||
id: &CommentId,
|
||||
comment: &Comment<CodeLocation>,
|
||||
aliases: &impl AliasStore,
|
||||
) -> Value {
|
||||
json!({
|
||||
"id": *id,
|
||||
"author": author(&Author::from(comment.author()), aliases.alias(&comment.author())),
|
||||
"body": comment.body(),
|
||||
"edits": comment.edits().map(|e| edit(e, aliases)).collect::<Vec<_>>(),
|
||||
"embeds": comment.embeds().to_vec(),
|
||||
"reactions": reactions(comment.reactions(), None, aliases),
|
||||
"timestamp": comment.timestamp().as_secs(),
|
||||
"replyTo": comment.reply_to(),
|
||||
"location": comment.location(),
|
||||
"resolved": comment.is_resolved(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns JSON for a `Review`.
|
||||
fn review_comment(
|
||||
id: &CommentId,
|
||||
comment: &Comment<CodeLocation>,
|
||||
aliases: &impl AliasStore,
|
||||
) -> Value {
|
||||
json!({
|
||||
"id": *id,
|
||||
"author": author(&Author::from(comment.author()), aliases.alias(&comment.author())),
|
||||
"body": comment.body(),
|
||||
"edits": comment.edits().map(|e| edit(e, aliases)).collect::<Vec<_>>(),
|
||||
"embeds": comment.embeds().to_vec(),
|
||||
"reactions": reactions(comment.reactions(), None, aliases),
|
||||
"timestamp": comment.timestamp().as_secs(),
|
||||
"replyTo": comment.reply_to(),
|
||||
"location": comment.location(),
|
||||
"resolved": comment.is_resolved(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the name part of a path string.
|
||||
fn name_in_path(path: &str) -> &str {
|
||||
match path.rsplit('/').next() {
|
||||
Some(name) => name,
|
||||
None => path,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_refs(
|
||||
repo: &git::Repository,
|
||||
id: &ActorId,
|
||||
head: &Oid,
|
||||
) -> Result<Vec<RefString>, refs::Error> {
|
||||
let remote = repo.remote(id)?;
|
||||
let refs = remote
|
||||
.refs
|
||||
.iter()
|
||||
.filter_map(|(name, o)| {
|
||||
if o == head {
|
||||
Some(name.to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(refs)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
mod delegates;
|
||||
mod node;
|
||||
mod profile;
|
||||
mod projects;
|
||||
mod sessions;
|
||||
mod stats;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum::response::{IntoResponse, Json};
|
||||
use axum::routing::get;
|
||||
use axum::Router;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::api::{Context, API_VERSION, RADICLE_VERSION};
|
||||
|
||||
pub fn router(ctx: Context) -> Router {
|
||||
let root_router = Router::new()
|
||||
.route("/", get(root_handler))
|
||||
.with_state(ctx.clone());
|
||||
|
||||
let routes = Router::new()
|
||||
.merge(root_router)
|
||||
.merge(node::router(ctx.clone()))
|
||||
.merge(profile::router(ctx.clone()))
|
||||
.merge(sessions::router(ctx.clone()))
|
||||
.merge(delegates::router(ctx.clone()))
|
||||
.merge(projects::router(ctx.clone()))
|
||||
.merge(stats::router(ctx));
|
||||
|
||||
Router::new().nest("/v1", routes)
|
||||
}
|
||||
|
||||
async fn root_handler(State(ctx): State<Context>) -> impl IntoResponse {
|
||||
let response = json!({
|
||||
"message": "Welcome!",
|
||||
"service": "radicle-httpd",
|
||||
"version": format!("{}-{}", RADICLE_VERSION, env!("GIT_HEAD")),
|
||||
"apiVersion": API_VERSION,
|
||||
"nid": ctx.profile.public_key,
|
||||
"path": "/api/v1",
|
||||
"links": [
|
||||
{
|
||||
"href": "/projects",
|
||||
"rel": "projects",
|
||||
"type": "GET"
|
||||
},
|
||||
{
|
||||
"href": "/node",
|
||||
"rel": "node",
|
||||
"type": "GET"
|
||||
},
|
||||
{
|
||||
"href": "/delegates/:did/projects",
|
||||
"rel": "projects",
|
||||
"type": "GET"
|
||||
},
|
||||
{
|
||||
"href": "/profile",
|
||||
"rel": "profile",
|
||||
"type": "GET"
|
||||
},
|
||||
{
|
||||
"href": "/stats",
|
||||
"rel": "stats",
|
||||
"type": "GET"
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
Json(response)
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
use axum::extract::State;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
|
||||
use radicle::cob::Author;
|
||||
use radicle::identity::Did;
|
||||
use radicle::issue::cache::Issues as _;
|
||||
use radicle::node::routing::Store;
|
||||
use radicle::node::AliasStore;
|
||||
use radicle::patch::cache::Patches as _;
|
||||
use radicle::storage::{ReadRepository, ReadStorage};
|
||||
|
||||
use crate::api::error::Error;
|
||||
use crate::api::json;
|
||||
use crate::api::project::Info;
|
||||
use crate::api::Context;
|
||||
use crate::api::{PaginationQuery, ProjectQuery};
|
||||
use crate::axum_extra::{Path, Query};
|
||||
|
||||
pub fn router(ctx: Context) -> Router {
|
||||
Router::new()
|
||||
.route(
|
||||
"/delegates/:delegate/projects",
|
||||
get(delegates_projects_handler),
|
||||
)
|
||||
.with_state(ctx)
|
||||
}
|
||||
|
||||
/// List all projects which delegate is a part of.
|
||||
/// `GET /delegates/:delegate/projects`
|
||||
async fn delegates_projects_handler(
|
||||
State(ctx): State<Context>,
|
||||
Path(delegate): Path<Did>,
|
||||
Query(qs): Query<PaginationQuery>,
|
||||
) -> impl IntoResponse {
|
||||
let PaginationQuery {
|
||||
show,
|
||||
page,
|
||||
per_page,
|
||||
} = qs;
|
||||
let page = page.unwrap_or(0);
|
||||
let per_page = per_page.unwrap_or(10);
|
||||
let storage = &ctx.profile.storage;
|
||||
let db = &ctx.profile.database()?;
|
||||
let pinned = &ctx.profile.config.web.pinned;
|
||||
let mut projects = match show {
|
||||
ProjectQuery::All => storage
|
||||
.repositories()?
|
||||
.into_iter()
|
||||
.filter(|repo| repo.doc.visibility.is_public())
|
||||
.collect::<Vec<_>>(),
|
||||
ProjectQuery::Pinned => storage.repositories_by_id(pinned.repositories.iter())?,
|
||||
};
|
||||
projects.sort_by_key(|p| p.rid);
|
||||
|
||||
let infos = projects
|
||||
.into_iter()
|
||||
.filter_map(|id| {
|
||||
if !id.doc.delegates.iter().any(|d| *d == delegate) {
|
||||
return None;
|
||||
}
|
||||
let Ok(repo) = storage.repository(id.rid) else {
|
||||
return None;
|
||||
};
|
||||
let Ok((_, head)) = repo.head() else {
|
||||
return None;
|
||||
};
|
||||
let Ok(payload) = id.doc.project() else {
|
||||
return None;
|
||||
};
|
||||
let Ok(issues) = ctx.profile.issues(&repo) else {
|
||||
return None;
|
||||
};
|
||||
let Ok(issues) = issues.counts() else {
|
||||
return None;
|
||||
};
|
||||
let Ok(patches) = ctx.profile.patches(&repo) else {
|
||||
return None;
|
||||
};
|
||||
let Ok(patches) = patches.counts() else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let aliases = ctx.profile.aliases();
|
||||
let delegates = id
|
||||
.doc
|
||||
.delegates
|
||||
.into_iter()
|
||||
.map(|did| json::author(&Author::new(did), aliases.alias(did.as_key())))
|
||||
.collect::<Vec<_>>();
|
||||
let seeding = db.count(&id.rid).unwrap_or_default();
|
||||
|
||||
Some(Info {
|
||||
payload,
|
||||
delegates,
|
||||
threshold: id.doc.threshold,
|
||||
visibility: id.doc.visibility,
|
||||
head,
|
||||
issues,
|
||||
patches,
|
||||
id: id.rid,
|
||||
seeding,
|
||||
})
|
||||
})
|
||||
.skip(page * per_page)
|
||||
.take(per_page)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok::<_, Error>(Json(infos))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod routes {
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use axum::extract::connect_info::MockConnectInfo;
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::test::{self, get, CONTRIBUTOR_ALIAS, DID, HEAD, RID};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_delegates_projects() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let seed = test::seed(tmp.path());
|
||||
let app = super::router(seed.clone())
|
||||
.layer(MockConnectInfo(SocketAddr::from(([127, 0, 0, 1], 8080))));
|
||||
let response = get(
|
||||
&app,
|
||||
"/delegates/did:key:z6MknSLrJoTcukLrE435hVNQT4JUhbvWLX4kUzqkEStBU8Vi/projects?show=all",
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
StatusCode::OK,
|
||||
"failed response: {:?}",
|
||||
response.json().await
|
||||
);
|
||||
assert_eq!(
|
||||
response.json().await,
|
||||
json!([
|
||||
{
|
||||
"name": "hello-world",
|
||||
"description": "Rad repository for tests",
|
||||
"defaultBranch": "master",
|
||||
"delegates": [
|
||||
{
|
||||
"id": DID,
|
||||
"alias": CONTRIBUTOR_ALIAS
|
||||
}
|
||||
],
|
||||
"threshold": 1,
|
||||
"visibility": {
|
||||
"type": "public"
|
||||
},
|
||||
"head": HEAD,
|
||||
"patches": {
|
||||
"open": 1,
|
||||
"draft": 0,
|
||||
"archived": 0,
|
||||
"merged": 0,
|
||||
},
|
||||
"issues": {
|
||||
"open": 1,
|
||||
"closed": 0,
|
||||
},
|
||||
"id": RID,
|
||||
"seeding": 0,
|
||||
},
|
||||
{
|
||||
"name": "again-hello-world",
|
||||
"description": "Rad repository for sorting",
|
||||
"defaultBranch": "master",
|
||||
"delegates": [
|
||||
{
|
||||
"id": DID,
|
||||
"alias": CONTRIBUTOR_ALIAS
|
||||
},
|
||||
],
|
||||
"threshold": 1,
|
||||
"visibility": {
|
||||
"type": "public"
|
||||
},
|
||||
"head": "344dcd184df5bf37aab6c107fa9371a1c5b3321a",
|
||||
"patches": {
|
||||
"open": 0,
|
||||
"draft": 0,
|
||||
"archived": 0,
|
||||
"merged": 0,
|
||||
},
|
||||
"issues": {
|
||||
"open": 0,
|
||||
"closed": 0,
|
||||
},
|
||||
"id": "rad:z4GypKmh1gkEfmkXtarcYnkvtFUfE",
|
||||
"seeding": 0,
|
||||
}
|
||||
])
|
||||
);
|
||||
|
||||
let app = super::router(seed).layer(MockConnectInfo(SocketAddr::from((
|
||||
[192, 168, 13, 37],
|
||||
8080,
|
||||
))));
|
||||
let response = get(
|
||||
&app,
|
||||
"/delegates/did:key:z6MknSLrJoTcukLrE435hVNQT4JUhbvWLX4kUzqkEStBU8Vi/projects?show=all",
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
StatusCode::OK,
|
||||
"failed response: {:?}",
|
||||
response.json().await
|
||||
);
|
||||
assert_eq!(
|
||||
response.json().await,
|
||||
json!([
|
||||
{
|
||||
"name": "hello-world",
|
||||
"description": "Rad repository for tests",
|
||||
"defaultBranch": "master",
|
||||
"delegates": [
|
||||
{
|
||||
"id": DID,
|
||||
"alias": CONTRIBUTOR_ALIAS
|
||||
}
|
||||
],
|
||||
"threshold": 1,
|
||||
"visibility": {
|
||||
"type": "public"
|
||||
},
|
||||
"head": HEAD,
|
||||
"patches": {
|
||||
"open": 1,
|
||||
"draft": 0,
|
||||
"archived": 0,
|
||||
"merged": 0,
|
||||
},
|
||||
"issues": {
|
||||
"open": 1,
|
||||
"closed": 0,
|
||||
},
|
||||
"id": RID,
|
||||
"seeding": 0,
|
||||
},
|
||||
{
|
||||
"name": "again-hello-world",
|
||||
"description": "Rad repository for sorting",
|
||||
"defaultBranch": "master",
|
||||
"delegates": [
|
||||
{
|
||||
"id": DID,
|
||||
"alias": CONTRIBUTOR_ALIAS
|
||||
},
|
||||
],
|
||||
"threshold": 1,
|
||||
"visibility": {
|
||||
"type": "public"
|
||||
},
|
||||
"head": "344dcd184df5bf37aab6c107fa9371a1c5b3321a",
|
||||
"patches": {
|
||||
"open": 0,
|
||||
"draft": 0,
|
||||
"archived": 0,
|
||||
"merged": 0,
|
||||
},
|
||||
"issues": {
|
||||
"open": 0,
|
||||
"closed": 0,
|
||||
},
|
||||
"id": "rad:z4GypKmh1gkEfmkXtarcYnkvtFUfE",
|
||||
"seeding": 0,
|
||||
}
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
use axum::extract::State;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::{get, put};
|
||||
use axum::{Json, Router};
|
||||
use axum_auth::AuthBearer;
|
||||
use hyper::StatusCode;
|
||||
use serde_json::json;
|
||||
|
||||
use radicle::identity::RepoId;
|
||||
use radicle::node::routing::Store;
|
||||
use radicle::node::{
|
||||
policy::{Policy, SeedPolicy},
|
||||
AliasStore, Handle, NodeId, DEFAULT_TIMEOUT,
|
||||
};
|
||||
use radicle::Node;
|
||||
|
||||
use crate::api::error::Error;
|
||||
use crate::api::{self, Context, PoliciesQuery, RADICLE_VERSION};
|
||||
use crate::axum_extra::{Path, Query};
|
||||
|
||||
pub fn router(ctx: Context) -> Router {
|
||||
Router::new()
|
||||
.route("/node", get(node_handler))
|
||||
.route("/node/policies/repos", get(node_policies_repos_handler))
|
||||
.route(
|
||||
"/node/policies/repos/:rid",
|
||||
put(node_policies_seed_handler).delete(node_policies_unseed_handler),
|
||||
)
|
||||
.route("/nodes/:nid", get(nodes_handler))
|
||||
.route("/nodes/:nid/inventory", get(nodes_inventory_handler))
|
||||
.with_state(ctx)
|
||||
}
|
||||
|
||||
/// Return local node information.
|
||||
/// `GET /node`
|
||||
async fn node_handler(State(ctx): State<Context>) -> impl IntoResponse {
|
||||
let node = Node::new(ctx.profile.socket());
|
||||
let node_id = ctx.profile.public_key;
|
||||
let node_state = if node.is_running() {
|
||||
"running"
|
||||
} else {
|
||||
"stopped"
|
||||
};
|
||||
let config = match node.config() {
|
||||
Ok(config) => Some(config),
|
||||
Err(err) => {
|
||||
tracing::error!("Error getting node config: {:#}", err);
|
||||
None
|
||||
}
|
||||
};
|
||||
let response = json!({
|
||||
"id": node_id.to_string(),
|
||||
"version": format!("{}-{}", RADICLE_VERSION, env!("GIT_HEAD")),
|
||||
"config": config,
|
||||
"state": node_state,
|
||||
});
|
||||
|
||||
Ok::<_, Error>(Json(response))
|
||||
}
|
||||
|
||||
/// Return stored information about other nodes.
|
||||
/// `GET /nodes/:nid`
|
||||
async fn nodes_handler(State(ctx): State<Context>, Path(nid): Path<NodeId>) -> impl IntoResponse {
|
||||
let aliases = ctx.profile.aliases();
|
||||
let response = json!({
|
||||
"alias": aliases.alias(&nid),
|
||||
});
|
||||
|
||||
Ok::<_, Error>(Json(response))
|
||||
}
|
||||
|
||||
/// Return stored information about other nodes.
|
||||
/// `GET /nodes/:nid/inventory`
|
||||
async fn nodes_inventory_handler(
|
||||
State(ctx): State<Context>,
|
||||
Path(nid): Path<NodeId>,
|
||||
) -> impl IntoResponse {
|
||||
let db = &ctx.profile.database()?;
|
||||
let resources = db.get_resources(&nid)?;
|
||||
|
||||
Ok::<_, Error>(Json(resources))
|
||||
}
|
||||
|
||||
/// Return local repo policies information.
|
||||
/// `GET /node/policies/repos`
|
||||
async fn node_policies_repos_handler(State(ctx): State<Context>) -> impl IntoResponse {
|
||||
let policies = ctx.profile.policies()?;
|
||||
let mut repos = Vec::new();
|
||||
|
||||
for SeedPolicy { rid: id, policy } in policies.seed_policies()? {
|
||||
repos.push(json!({
|
||||
"id": id,
|
||||
"scope": policy.scope().unwrap_or_default(),
|
||||
"policy": Policy::from(policy),
|
||||
}));
|
||||
}
|
||||
|
||||
Ok::<_, Error>(Json(repos))
|
||||
}
|
||||
|
||||
/// Seed a new repo.
|
||||
/// `PUT /node/policies/repos/:rid`
|
||||
async fn node_policies_seed_handler(
|
||||
State(ctx): State<Context>,
|
||||
AuthBearer(token): AuthBearer,
|
||||
Path(project): Path<RepoId>,
|
||||
Query(qs): Query<PoliciesQuery>,
|
||||
) -> impl IntoResponse {
|
||||
api::auth::validate(&ctx, &token).await?;
|
||||
let mut node = Node::new(ctx.profile.socket());
|
||||
node.seed(project, qs.scope.unwrap_or_default())?;
|
||||
|
||||
if let Some(from) = qs.from {
|
||||
let results = node.fetch(project, from, DEFAULT_TIMEOUT)?;
|
||||
return Ok::<_, Error>((
|
||||
StatusCode::OK,
|
||||
Json(json!({ "success": true, "results": results })),
|
||||
));
|
||||
}
|
||||
Ok::<_, Error>((StatusCode::OK, Json(json!({ "success": true }))))
|
||||
}
|
||||
|
||||
/// Unseed a repo.
|
||||
/// `DELETE /node/policies/repos/:rid`
|
||||
async fn node_policies_unseed_handler(
|
||||
State(ctx): State<Context>,
|
||||
AuthBearer(token): AuthBearer,
|
||||
Path(project): Path<RepoId>,
|
||||
) -> impl IntoResponse {
|
||||
api::auth::validate(&ctx, &token).await?;
|
||||
let mut node = Node::new(ctx.profile.socket());
|
||||
node.unseed(project)?;
|
||||
|
||||
Ok::<_, Error>((StatusCode::OK, Json(json!({ "success": true }))))
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use axum::extract::{ConnectInfo, State};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::api::error::Error;
|
||||
use crate::api::Context;
|
||||
|
||||
pub fn router(ctx: Context) -> Router {
|
||||
Router::new()
|
||||
.route("/profile", get(profile_handler))
|
||||
.with_state(ctx)
|
||||
}
|
||||
|
||||
/// Return local profile information.
|
||||
/// `GET /profile`
|
||||
async fn profile_handler(
|
||||
State(ctx): State<Context>,
|
||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||
) -> impl IntoResponse {
|
||||
if !addr.ip().is_loopback() {
|
||||
return Err(Error::Auth("Profile data is only shown for localhost"));
|
||||
}
|
||||
|
||||
Ok::<_, Error>(Json(
|
||||
json!({ "config": ctx.profile.config, "home": ctx.profile.home.path() }),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod routes {
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use axum::extract::connect_info::MockConnectInfo;
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::test::{self, get};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_remote_profile() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let seed = test::seed(tmp.path());
|
||||
let app = super::router(seed.clone())
|
||||
.layer(MockConnectInfo(SocketAddr::from(([192, 168, 1, 1], 8080))));
|
||||
let response = get(&app, "/profile").await;
|
||||
|
||||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(
|
||||
response.json().await,
|
||||
json!({
|
||||
"error": "Profile data is only shown for localhost",
|
||||
"code": 401
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_profile() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let seed = test::seed(tmp.path());
|
||||
let app = super::router(seed.clone())
|
||||
.layer(MockConnectInfo(SocketAddr::from(([127, 0, 0, 1], 8080))));
|
||||
let response = get(&app, "/profile").await;
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
response.json().await,
|
||||
json!({
|
||||
"config": {
|
||||
"publicExplorer": "https://app.radicle.xyz/nodes/$host/$rid$path",
|
||||
"preferredSeeds": [
|
||||
"z6MkrLMMsiPWUcNPHcRajuMi9mDfYckSoJyPwwnknocNYPm7@seed.radicle.garden:8776",
|
||||
"z6Mkmqogy2qEM2ummccUthFEaaHvyYmYBYh3dbe9W4ebScxo@ash.radicle.garden:8776"
|
||||
],
|
||||
"web": { "pinned": { "repositories": [] } },
|
||||
"cli": {
|
||||
"hints": true
|
||||
},
|
||||
"node": {
|
||||
"alias": "seed",
|
||||
"listen": [],
|
||||
"peers": { "type": "dynamic" },
|
||||
"connect": [],
|
||||
"externalAddresses": [],
|
||||
"network": "main",
|
||||
"log": "INFO",
|
||||
"relay": "auto",
|
||||
"limits": {
|
||||
"routingMaxSize": 1000,
|
||||
"routingMaxAge": 604800,
|
||||
"gossipMaxAge": 1209600,
|
||||
"fetchConcurrency": 1,
|
||||
"maxOpenFiles": 4096,
|
||||
"rate": {
|
||||
"inbound": {
|
||||
"fillRate": 5.0,
|
||||
"capacity": 1024
|
||||
},
|
||||
"outbound": {
|
||||
"fillRate": 10.0,
|
||||
"capacity": 2048
|
||||
}
|
||||
},
|
||||
"connection": {
|
||||
"inbound": 128,
|
||||
"outbound": 16
|
||||
}
|
||||
},
|
||||
"workers": 8,
|
||||
"seedingPolicy": {
|
||||
"default": "block",
|
||||
}
|
||||
}
|
||||
},
|
||||
"home": seed.profile.path()
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,183 @@
|
||||
use std::iter::repeat_with;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::{post, put};
|
||||
use axum::{Json, Router};
|
||||
use axum_auth::AuthBearer;
|
||||
use hyper::StatusCode;
|
||||
use radicle::crypto::{PublicKey, Signature};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use crate::api::auth::{self, AuthState, Session};
|
||||
use crate::api::error::Error;
|
||||
use crate::api::json;
|
||||
use crate::api::Context;
|
||||
use crate::axum_extra::Path;
|
||||
|
||||
pub fn router(ctx: Context) -> Router {
|
||||
Router::new()
|
||||
.route("/sessions", post(session_create_handler))
|
||||
.route(
|
||||
"/sessions/:id",
|
||||
put(session_signin_handler)
|
||||
.get(session_handler)
|
||||
.delete(session_delete_handler),
|
||||
)
|
||||
.with_state(ctx)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct AuthChallenge {
|
||||
sig: Signature,
|
||||
pk: PublicKey,
|
||||
}
|
||||
|
||||
/// Create session.
|
||||
/// `POST /sessions`
|
||||
async fn session_create_handler(State(ctx): State<Context>) -> impl IntoResponse {
|
||||
let mut rng = fastrand::Rng::new();
|
||||
let session_id = repeat_with(|| rng.alphanumeric())
|
||||
.take(32)
|
||||
.collect::<String>();
|
||||
let signer = ctx.profile.signer().map_err(Error::from)?;
|
||||
let session = Session {
|
||||
status: AuthState::Unauthorized,
|
||||
public_key: *signer.public_key(),
|
||||
alias: ctx.profile.config.node.alias.clone(),
|
||||
issued_at: OffsetDateTime::now_utc(),
|
||||
expires_at: OffsetDateTime::now_utc()
|
||||
.checked_add(auth::UNAUTHORIZED_SESSIONS_EXPIRATION)
|
||||
.unwrap(),
|
||||
};
|
||||
let mut sessions = ctx.sessions.write().await;
|
||||
sessions.insert(session_id.clone(), session.clone());
|
||||
|
||||
Ok::<_, Error>((
|
||||
StatusCode::CREATED,
|
||||
Json(json::session(session_id, &session)),
|
||||
))
|
||||
}
|
||||
|
||||
/// Get a session.
|
||||
/// `GET /sessions/:id`
|
||||
async fn session_handler(
|
||||
State(ctx): State<Context>,
|
||||
Path(session_id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
let sessions = ctx.sessions.read().await;
|
||||
let session = sessions.get(&session_id).ok_or(Error::NotFound)?;
|
||||
|
||||
Ok::<_, Error>(Json(json::session(session_id, session)))
|
||||
}
|
||||
|
||||
/// Update session.
|
||||
/// `PUT /sessions/:id`
|
||||
async fn session_signin_handler(
|
||||
State(ctx): State<Context>,
|
||||
Path(session_id): Path<String>,
|
||||
Json(request): Json<AuthChallenge>,
|
||||
) -> impl IntoResponse {
|
||||
let mut sessions = ctx.sessions.write().await;
|
||||
let session = sessions.get_mut(&session_id).ok_or(Error::NotFound)?;
|
||||
if session.status == AuthState::Unauthorized {
|
||||
if session.public_key != request.pk {
|
||||
return Err(Error::Auth("Invalid public key"));
|
||||
}
|
||||
if session.expires_at <= OffsetDateTime::now_utc() {
|
||||
return Err(Error::Auth("Session expired"));
|
||||
}
|
||||
let payload = format!("{}:{}", session_id, request.pk);
|
||||
request
|
||||
.pk
|
||||
.verify(payload.as_bytes(), &request.sig)
|
||||
.map_err(Error::from)?;
|
||||
session.status = AuthState::Authorized;
|
||||
session.expires_at = OffsetDateTime::now_utc()
|
||||
.checked_add(auth::AUTHORIZED_SESSIONS_EXPIRATION)
|
||||
.unwrap();
|
||||
|
||||
return Ok::<_, Error>(Json(json!({ "success": true })));
|
||||
}
|
||||
|
||||
Err(Error::Auth("Session already authorized"))
|
||||
}
|
||||
|
||||
/// Delete session.
|
||||
/// `DELETE /sessions/:id`
|
||||
async fn session_delete_handler(
|
||||
State(ctx): State<Context>,
|
||||
AuthBearer(token): AuthBearer,
|
||||
Path(session_id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
if token != session_id {
|
||||
return Err(Error::Auth("Not authorized to delete this session"));
|
||||
}
|
||||
let mut sessions = ctx.sessions.write().await;
|
||||
sessions.remove_entry(&token).ok_or(Error::NotFound)?;
|
||||
|
||||
Ok::<_, Error>(Json(json!({ "success": true })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod routes {
|
||||
use crate::commands::web::{sign, SessionInfo};
|
||||
use axum::body::Body;
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use crate::api::auth::{AuthState, Session};
|
||||
use crate::test::{self, get, post, put};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ctx = test::seed(tmp.path());
|
||||
let app = super::router(ctx.to_owned());
|
||||
|
||||
// Create session.
|
||||
let response = post(&app, "/sessions", None, None).await;
|
||||
let status = response.status();
|
||||
let json = response.json().await;
|
||||
let session_info: SessionInfo = serde_json::from_value(json).unwrap();
|
||||
|
||||
assert_eq!(status, StatusCode::CREATED);
|
||||
|
||||
// Check that an unauthorized session has been created.
|
||||
let response = get(&app, format!("/sessions/{}", session_info.session_id)).await;
|
||||
let status = response.status();
|
||||
let json = response.json().await;
|
||||
let body: Session = serde_json::from_value(json).unwrap();
|
||||
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body.status, AuthState::Unauthorized);
|
||||
|
||||
// Create request body
|
||||
let signer = ctx.profile.signer().unwrap();
|
||||
let signature = sign(signer, &session_info).unwrap();
|
||||
let body = serde_json::to_vec(&super::AuthChallenge {
|
||||
sig: signature,
|
||||
pk: session_info.public_key,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let response = put(
|
||||
&app,
|
||||
format!("/sessions/{}", session_info.session_id),
|
||||
Some(Body::from(body)),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
// Check that session has been authorized.
|
||||
let response = get(&app, format!("/sessions/{}", session_info.session_id)).await;
|
||||
let status = response.status();
|
||||
let json = response.json().await;
|
||||
let body: Session = serde_json::from_value(json).unwrap();
|
||||
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body.status, AuthState::Authorized);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use axum::extract::State;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use serde_json::json;
|
||||
|
||||
use radicle::storage::ReadStorage;
|
||||
|
||||
use crate::api::error::Error;
|
||||
use crate::api::Context;
|
||||
|
||||
pub fn router(ctx: Context) -> Router {
|
||||
Router::new()
|
||||
.route("/stats", get(stats_handler))
|
||||
.with_state(ctx)
|
||||
}
|
||||
|
||||
/// Return the stats for the node.
|
||||
/// `GET /stats`
|
||||
async fn stats_handler(State(ctx): State<Context>) -> impl IntoResponse {
|
||||
let total = ctx.profile.storage.repositories()?.len();
|
||||
|
||||
Ok::<_, Error>(Json(json!({ "repos": { "total": total } })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod routes {
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::test::{self, get};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_stats() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let app = super::router(test::seed(tmp.path()));
|
||||
let response = get(&app, "/stats").await;
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.json().await, json!({ "repos": { "total": 3 } }));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user