Skip to content

feat(meroctl): support alias listing #1276

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Jun 10, 2025
Merged
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
15 changes: 14 additions & 1 deletion crates/meroctl/src/cli/context/alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use reqwest::Client;

use crate::cli::{ApiError, ConnectionInfo, Environment};
use crate::common::{
create_alias, delete_alias, do_request, lookup_alias, resolve_alias, RequestType,
create_alias, delete_alias, do_request, list_aliases, lookup_alias, resolve_alias, RequestType,
};
use crate::output::{ErrorLine, WarnLine};

Expand Down Expand Up @@ -43,6 +43,9 @@ pub enum ContextAliasSubcommand {
#[arg(help = "Name of the alias to look up", default_value = "default")]
alias: Alias<ContextId>,
},

#[command(about = "List all context aliases", alias = "ls")]
List,
}

impl ContextAliasCommand {
Expand Down Expand Up @@ -132,6 +135,16 @@ impl ContextAliasCommand {
)
.await?;

environment.output.write(&res);
}
ContextAliasSubcommand::List => {
let res = list_aliases::<ContextId>(
&connection.api_url,
connection.auth_key.as_ref(),
None,
)
.await?;

environment.output.write(&res);
}
}
Expand Down
33 changes: 32 additions & 1 deletion crates/meroctl/src/cli/context/identity/alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use reqwest::Client;

use crate::cli::{ConnectionInfo, Environment};
use crate::common::{
create_alias, delete_alias, do_request, lookup_alias, resolve_alias, RequestType,
create_alias, delete_alias, do_request, list_aliases, lookup_alias, resolve_alias, RequestType,
};
use crate::output::ErrorLine;

Expand Down Expand Up @@ -91,6 +91,13 @@ pub enum ContextIdentityAliasSubcommand {
#[arg(long, short, default_value = "default")]
context: Alias<ContextId>,
},

#[command(about = "List all the aliases under the context", alias = "ls")]
List {
#[arg(help = "The context whose aliases need to be listed")]
#[arg(long, short, default_value = "default")]
context: Alias<ContextId>,
},
}

impl ContextIdentityAliasCommand {
Expand Down Expand Up @@ -224,6 +231,30 @@ impl ContextIdentityAliasCommand {

environment.output.write(&res);
}

ContextIdentityAliasSubcommand::List { context } => {
let resolve_response = resolve_alias(
&connection.api_url,
connection.auth_key.as_ref(),
context,
None,
)
.await?;

let context_id = resolve_response
.value()
.cloned()
.ok_or_eyre("Failed to resolve context: no value found")?;

let res = list_aliases::<PublicKey>(
&connection.api_url,
connection.auth_key.as_ref(),
Some(context_id),
)
.await?;

environment.output.write(&res);
}
}

Ok(())
Expand Down
54 changes: 49 additions & 5 deletions crates/meroctl/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use calimero_primitives::context::ContextId;
use calimero_primitives::identity::PublicKey;
use calimero_server_primitives::admin::{
AliasKind, CreateAliasRequest, CreateAliasResponse, CreateApplicationIdAlias,
CreateContextIdAlias, CreateContextIdentityAlias, DeleteAliasResponse, LookupAliasResponse,
CreateContextIdAlias, CreateContextIdentityAlias, DeleteAliasResponse, ListAliasesResponse,
LookupAliasResponse,
};
use camino::Utf8Path;
use chrono::Utc;
Expand Down Expand Up @@ -254,7 +255,7 @@ pub(crate) async fn create_alias<T>(
value: T,
) -> EyreResult<CreateAliasResponse>
where
T: ScopedAlias + UrlFragment + Serialize,
T: UrlFragment + Serialize,
T::Value: Serialize,
{
let prefix = "admin-api/dev/alias/create";
Expand Down Expand Up @@ -294,7 +295,7 @@ pub(crate) async fn delete_alias<T>(
scope: Option<T::Scope>,
) -> EyreResult<DeleteAliasResponse>
where
T: ScopedAlias + UrlFragment,
T: UrlFragment,
{
let prefix = "admin-api/dev/alias/delete";

Expand All @@ -312,14 +313,57 @@ where
Ok(response)
}

impl<T: fmt::Display> Report for ListAliasesResponse<T> {
fn report(&self) -> () {
let mut table = Table::new();
let _ = table.set_header(vec![
Cell::new("Value").fg(Color::Blue),
Cell::new("Alias").fg(Color::Blue),
]);

for (alias, value) in &self.data {
let _ = table.add_row(vec![
Cell::new(&value.to_string()),
Cell::new(alias.as_str()),
]);
}

println!("{table}");
}
}

pub(crate) async fn list_aliases<T>(
base_url: &Url,
keypair: Option<&Keypair>,
scope: Option<T::Scope>,
) -> EyreResult<ListAliasesResponse<T>>
where
T: Ord + UrlFragment + DeserializeOwned,
{
let prefix = "admin-api/dev/alias/list";

let kind = T::KIND;

let scope =
T::scoped(scope.as_ref()).map_or_else(Default::default, |scope| format!("/{}", scope));

let mut url = base_url.clone();
url.set_path(&format!("{prefix}/{kind}{scope}"));

let response: ListAliasesResponse<T> =
do_request(&Client::new(), url, None::<()>, keypair, RequestType::Get).await?;

Ok(response)
}

pub(crate) async fn lookup_alias<T>(
base_url: &Url,
keypair: Option<&Keypair>,
alias: Alias<T>,
scope: Option<T::Scope>,
) -> EyreResult<LookupAliasResponse<T>>
where
T: ScopedAlias + UrlFragment + DeserializeOwned,
T: UrlFragment + DeserializeOwned,
{
let prefix = "admin-api/dev/alias/lookup";

Expand Down Expand Up @@ -406,7 +450,7 @@ pub(crate) async fn resolve_alias<T>(
scope: Option<T::Scope>,
) -> EyreResult<ResolveResponse<T>>
where
T: ScopedAlias + UrlFragment + FromStr + DeserializeOwned,
T: UrlFragment + FromStr + DeserializeOwned,
{
let value = lookup_alias(base_url, keypair, alias, scope).await?;

Expand Down
10 changes: 4 additions & 6 deletions crates/node/primitives/src/client/alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,10 @@ impl NodeClient {
let (k, v) = (k?, v?);

if let Some(expected_scope) = &scope {
let Some(found_scope) = k.scope::<T>() else {
bail!("scope mismatch: {:?}", k);
};

if found_scope != *expected_scope {
break;
if let Some(found_scope) = k.scope::<T>() {
if found_scope != *expected_scope {
break;
}
}
}

Expand Down
18 changes: 6 additions & 12 deletions crates/node/src/interactive_cli/context/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ enum ContextIdentityAliasSubcommands {
#[command(about = "List context identity aliases", alias = "ls")]
List {
/// The context whose aliases we're listing
context: Option<Alias<ContextId>>,
#[arg(long, short, default_value = "default")]
context: Alias<ContextId>,
},
}

Expand Down Expand Up @@ -415,17 +416,10 @@ fn handle_alias_command(
c2 = "Identity",
c3 = "Alias",
);
let context_id = if let Some(ctx) = context {
node_client
.resolve_alias(ctx, None)?
.ok_or_eyre("unable to resolve context alias")?
} else {
let default_alias: Alias<ContextId> =
"default".parse().expect("'default' is a valid alias name");
node_client
.lookup_alias(default_alias, None)?
.ok_or_eyre("unable to resolve default context")?
};
let context_id = node_client
.resolve_alias(context, None)?
.ok_or_eyre("unable to resolve context alias")?;

for (alias, identity, scope) in
node_client.list_aliases::<PublicKey>(Some(context_id))?
{
Expand Down
28 changes: 27 additions & 1 deletion crates/primitives/src/alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
mod tests;

use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::str::FromStr;

Expand Down Expand Up @@ -34,7 +35,6 @@ impl ScopedAlias for ApplicationId {
type Scope = ();
}

#[derive(Eq, PartialEq)]
pub struct Alias<T> {
str: [u8; MAX_LENGTH],
len: u8,
Expand Down Expand Up @@ -101,6 +101,26 @@ impl<T> fmt::Debug for Alias<T> {
}
}

impl<T> Eq for Alias<T> {}

impl<T> PartialEq for Alias<T> {
fn eq(&self, other: &Self) -> bool {
self.str == other.str
}
}

impl<T> Ord for Alias<T> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.str.cmp(&other.str)
}
}

impl<T> PartialOrd for Alias<T> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}

impl<T> Serialize for Alias<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down Expand Up @@ -146,3 +166,9 @@ impl<'de, T> Deserialize<'de> for Alias<T> {
deserializer.deserialize_str(AliasVisitor(PhantomData))
}
}

impl<T> Hash for Alias<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_str().hash(state);
}
}
2 changes: 1 addition & 1 deletion crates/primitives/src/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl FromStr for PrivateKey {
}
}

#[derive(Eq, Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Eq, Ord, Copy, Clone, Debug, PartialEq, PartialOrd, Serialize, Deserialize)]
#[cfg_attr(
feature = "borsh",
derive(borsh::BorshDeserialize, borsh::BorshSerialize)
Expand Down
15 changes: 15 additions & 0 deletions crates/server/primitives/src/admin.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::BTreeMap;

use calimero_context_config::repr::Repr;
use calimero_context_config::types::{Capability, ContextIdentity, ContextStorageEntry};
use calimero_context_config::{Proposal, ProposalWithApprovals};
Expand Down Expand Up @@ -253,6 +255,19 @@ impl GetContextIdentitiesResponse {
}
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListAliasesResponse<T> {
#[serde(bound(deserialize = "T: Ord + Deserialize<'de>"))]
pub data: BTreeMap<Alias<T>, T>,
}

impl<T> ListAliasesResponse<T> {
pub fn new(data: BTreeMap<Alias<T>, T>) -> Self {
Self { data }
}
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetContextClientKeysResponseData {
Expand Down
12 changes: 11 additions & 1 deletion crates/server/src/admin/handlers/alias.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use axum::routing::{post, Router};
use axum::routing::{get, post, Router};
use calimero_primitives::application::ApplicationId;
use calimero_primitives::context::ContextId;
use calimero_primitives::identity::PublicKey;

mod create_alias;
mod delete_alias;
mod list_aliases;
mod lookup_alias;

pub fn service() -> Router {
Expand Down Expand Up @@ -38,8 +39,17 @@ pub fn service() -> Router {
post(delete_alias::handler::<PublicKey>),
);

let list_routes = Router::new()
.route("/context", get(list_aliases::handler::<ContextId>))
.route("/application", get(list_aliases::handler::<ApplicationId>))
.route(
"/identity/:context",
get(list_aliases::handler::<PublicKey>),
);

Router::new()
.nest("/create", create_routes)
.nest("/lookup", lookup_routes)
.nest("/delete", delete_routes)
.nest("/list", list_routes)
}
37 changes: 37 additions & 0 deletions crates/server/src/admin/handlers/alias/list_aliases.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use std::sync::Arc;

use axum::extract::Path;
use axum::response::IntoResponse;
use axum::Extension;
use calimero_server_primitives::admin::ListAliasesResponse;
use calimero_store::key::{Aliasable, StoreScopeCompat};
use serde::Serialize;

use crate::admin::service::{parse_api_error, ApiResponse};
use crate::AdminState;

pub async fn handler<T>(
Extension(state): Extension<Arc<AdminState>>,
maybe_scope: Option<Path<T::Scope>>,
) -> impl IntoResponse
where
T: Aliasable + Serialize + From<[u8; 32]>,
T::Scope: Copy + PartialEq + StoreScopeCompat,
{
let scope = maybe_scope.map(|Path(s)| s);

let aliases = match state.node_client.list_aliases::<T>(scope) {
Ok(aliases) => aliases,
Err(err) => return parse_api_error(err).into_response(),
};

let aliases = aliases
.into_iter()
.map(|(alias, value, _scope)| (alias, value))
.collect();

ApiResponse {
payload: ListAliasesResponse::new(aliases),
}
.into_response()
}