Admin module: integrate with clan app

This commit is contained in:
Johannes Kirschbauer
2024-08-27 18:20:42 +02:00
parent 54139876b5
commit b601bab5a2
10 changed files with 109 additions and 15 deletions

View File

@@ -2,9 +2,12 @@
{ {
options.clan.admin = { options.clan.admin = {
allowedKeys = lib.mkOption { allowedKeys = lib.mkOption {
default = [ ]; default = { };
type = lib.types.listOf lib.types.str; type = lib.types.attrsOf lib.types.str;
description = "The allowed public keys for ssh access to the admin user"; description = "The allowed public keys for ssh access to the admin user";
example = {
"key_1" = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD...";
};
}; };
}; };
imports = [ imports = [
@@ -12,6 +15,6 @@
../root-password ../root-password
]; ];
config = { config = {
users.users.root.openssh.authorizedKeys.keys = config.clan.admin.allowedKeys; users.users.root.openssh.authorizedKeys.keys = builtins.attrValues config.clan.admin.allowedKeys;
}; };
} }

View File

@@ -17,6 +17,21 @@
} }
}, },
"services": { "services": {
"admin": {
"admin": {
"meta": {
"name": "Admin service"
},
"roles": {
"default": {
"tags": ["all"]
}
},
"config": {
"allowedKeys": { "keyfile_1": "rsa_..." }
}
}
},
"packages": { "packages": {
"editors": { "editors": {
"meta": { "meta": {

View File

@@ -5,12 +5,12 @@ from pathlib import Path
from types import ModuleType from types import ModuleType
# These imports are unused, but necessary for @API.register to run once. # These imports are unused, but necessary for @API.register to run once.
from clan_cli.api import directory, disk, mdns_discovery, modules from clan_cli.api import admin, directory, disk, mdns_discovery, modules
from clan_cli.arg_actions import AppendOptionAction from clan_cli.arg_actions import AppendOptionAction
from clan_cli.clan import show, update from clan_cli.clan import show, update
# API endpoints that are not used in the cli. # API endpoints that are not used in the cli.
__all__ = ["directory", "mdns_discovery", "modules", "update", "disk"] __all__ = ["directory", "mdns_discovery", "modules", "update", "disk", "admin"]
from . import ( from . import (
backups, backups,

View File

@@ -23,7 +23,10 @@ def get_admin_service(base_url: str) -> ServiceAdmin | None:
@API.register @API.register
def set_admin_service( def set_admin_service(
base_url: str, allowed_keys: list[str], instance_name: str = "admin" base_url: str,
allowed_keys: dict[str, str],
instance_name: str = "admin",
extra_machines: list[str] = [],
) -> None: ) -> None:
""" """
Set the admin service of a clan Set the admin service of a clan
@@ -34,20 +37,20 @@ def set_admin_service(
if not allowed_keys: if not allowed_keys:
raise ValueError("At least one key must be provided to ensure access") raise ValueError("At least one key must be provided to ensure access")
keys = [] keys = {}
for keyfile in allowed_keys: for name, keyfile in allowed_keys.items():
if not keyfile.startswith("/"): if not keyfile.startswith("/"):
raise ValueError(f"Keyfile '{keyfile}' must be an absolute path") raise ValueError(f"Keyfile '{keyfile}' must be an absolute path")
with open(keyfile) as f: with open(keyfile) as f:
pubkey = f.read() pubkey = f.read()
keys.append(pubkey) keys[name] = pubkey
instance = ServiceAdmin( instance = ServiceAdmin(
meta=ServiceMeta(name=instance_name), meta=ServiceMeta(name=instance_name),
roles=ServiceAdminRole( roles=ServiceAdminRole(
default=ServiceAdminRoleDefault( default=ServiceAdminRoleDefault(
config=AdminConfig(allowedKeys=keys), config=AdminConfig(allowedKeys=keys),
machines=[], machines=extra_machines,
tags=["all"], tags=["all"],
) )
), ),

View File

@@ -32,7 +32,7 @@ class Meta:
@dataclass @dataclass
class AdminConfig: class AdminConfig:
allowedKeys: list[str] = field(default_factory = list) allowedKeys: dict[str, str] | dict[str,Any] = field(default_factory = dict)
@dataclass @dataclass

View File

@@ -15,6 +15,7 @@ import { CreateMachine } from "./routes/machines/create";
import { HostList } from "./routes/hosts/view"; import { HostList } from "./routes/hosts/view";
import { Welcome } from "./routes/welcome"; import { Welcome } from "./routes/welcome";
import { Toaster } from "solid-toast"; import { Toaster } from "solid-toast";
import { Details } from "./routes/clan/details";
const client = new QueryClient(); const client = new QueryClient();
@@ -66,7 +67,7 @@ export const routes: AppRoute[] = [
], ],
}, },
{ {
path: "/clan", path: "/clans",
label: "Clans", label: "Clans",
icon: "groups", icon: "groups",
children: [ children: [
@@ -84,6 +85,7 @@ export const routes: AppRoute[] = [
path: "/:id", path: "/:id",
label: "Details", label: "Details",
hidden: true, hidden: true,
component: () => <Details />,
}, },
], ],
}, },

View File

@@ -0,0 +1,67 @@
import { callApi, SuccessData } from "@/src/api";
import { BackButton } from "@/src/components/BackButton";
import { useParams } from "@solidjs/router";
import { createQuery } from "@tanstack/solid-query";
import { createEffect, For, Match, Switch } from "solid-js";
import { Show } from "solid-js";
import { DiskView } from "../disk/view";
import { Accessor } from "solid-js";
type AdminData = SuccessData<"get_admin_service">["data"];
interface ClanDetailsProps {
admin: AdminData;
}
const ClanDetails = (props: ClanDetailsProps) => {
const items = () =>
Object.entries<string>(
(props.admin?.config?.allowedKeys as Record<string, string>) || {},
);
return (
<div>
<h1>Clan Details </h1>
<For each={items()}>
{([name, key]) => (
<div>
<span>{name}</span>
<span>{key}</span>
</div>
)}
</For>
</div>
);
};
export const Details = () => {
const params = useParams();
const clan_dir = window.atob(params.id);
const query = createQuery(() => ({
queryKey: [clan_dir, "get_admin_service"],
queryFn: async () => {
const result = await callApi("get_admin_service", {
base_url: clan_dir,
});
if (result.status === "error") throw new Error("Failed to fetch data");
return result.data || null;
},
}));
return (
<div class="p-2">
<BackButton />
<Show
when={!query.isLoading}
fallback={<span class="loading loading-lg"></span>}
>
<Switch>
<Match when={query.data}>
{(d) => <ClanDetails admin={query.data} />}
</Match>
</Switch>
{clan_dir}
</Show>
</div>
);
};

View File

@@ -17,6 +17,7 @@ export function CreateMachine() {
loc: activeURI() || "", loc: activeURI() || "",
}, },
machine: { machine: {
tags: ["all"],
deploy: { deploy: {
targetHost: "", targetHost: "",
}, },

View File

@@ -5,7 +5,8 @@ import { createQuery } from "@tanstack/solid-query";
import { useFloating } from "@/src/floating"; import { useFloating } from "@/src/floating";
import { autoUpdate, flip, hide, offset, shift } from "@floating-ui/dom"; import { autoUpdate, flip, hide, offset, shift } from "@floating-ui/dom";
import { EditClanForm } from "../clan/editClan"; import { EditClanForm } from "../clan/editClan";
import { useNavigate } from "@solidjs/router"; import { useNavigate, A } from "@solidjs/router";
import { fileURLToPath } from "url";
export const registerClan = async () => { export const registerClan = async () => {
try { try {
@@ -145,7 +146,9 @@ const ClanDetails = (props: ClanDetailsProps) => {
<div class="skeleton h-12 w-80" /> <div class="skeleton h-12 w-80" />
</Show> </Show>
<Show when={details.isSuccess}> <Show when={details.isSuccess}>
<div class="stat-value">{details.data?.name}</div> <A href={`/clans/${window.btoa(clan_dir)}`}>
<div class="stat-value underline">{details.data?.name}</div>
</A>
</Show> </Show>
<Show when={details.isSuccess && details.data?.description}> <Show when={details.isSuccess && details.data?.description}>
<div class="stat-desc text-lg">{details.data?.description}</div> <div class="stat-desc text-lg">{details.data?.description}</div>

View File

@@ -13,7 +13,7 @@ export const Welcome = () => {
<div class="flex flex-col items-start gap-2"> <div class="flex flex-col items-start gap-2">
<button <button
class="btn btn-primary w-full" class="btn btn-primary w-full"
onClick={() => navigate("/clan/create")} onClick={() => navigate("/clans/create")}
> >
Build your own Build your own
</button> </button>