diff --git a/src/App.tsx b/src/App.tsx index 3d68c6b..2b3a544 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -47,6 +47,7 @@ import OIDCClientsPage from "@/pages/org/OIDCClientsPage"; import CAsPage from "@/pages/org/CAsPage"; import DepartmentsPage from "@/pages/org/DepartmentsPage"; import PrincipalsPage from "@/pages/org/PrincipalsPage"; +import ApiKeysPage from "@/pages/org/ApiKeysPage"; import MyMembershipsPage from "@/pages/org/MyMembershipsPage"; import NetworksPage from "@/pages/org/NetworksPage"; import DevicesPage from "@/pages/org/DevicesPage"; @@ -184,6 +185,7 @@ function AppRoutes() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/components/navigation/AppSidebar.tsx b/src/components/navigation/AppSidebar.tsx index 4b68272..2c3307f 100644 --- a/src/components/navigation/AppSidebar.tsx +++ b/src/components/navigation/AppSidebar.tsx @@ -57,6 +57,7 @@ const orgAdminNavItems = [ { title: "Members", url: "/org/members", icon: Users }, { title: "Departments", url: "/org/departments", icon: Layers }, { title: "Principals", url: "/org/principals", icon: GitBranch }, + { title: "API Keys", url: "/org/api-keys", icon: Key }, { title: "Policies", url: "/org/policies", icon: Settings }, { title: "ZeroTier Networks", url: "/org/zerotier/networks", icon: Network }, { title: "ZeroTier Access", url: "/org/zerotier/access", icon: ShieldAlert }, diff --git a/src/lib/api.ts b/src/lib/api.ts index 23f3f5b..9322886 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -248,6 +248,38 @@ export interface LinkAccountResponse { linked_account: LinkedAccount; } +export interface OrganizationApiKey { + id: string; + organization_id: string; + name: string; + description: string | null; + key_hash?: string; // Usually excluded from responses for security + last_used_at: string | null; + is_revoked: boolean; + revoked_at: string | null; + revoke_reason: string | null; + created_at: string; + updated_at: string; +} + +export interface CertificateAuditLog { + id: string; + action: string; + certificate_serial: string; + key_id: string; + principals: string[]; + user_id: string; + user_email: string | null; + issued_at: string; + valid_after: string; + valid_before: string; + ip_address: string | null; + user_agent: string | null; + message: string | null; + success: boolean; + created_at: string; +} + class ApiError extends Error { code: number; type: string; @@ -954,14 +986,14 @@ export const api = { request<{ departments: Department[]; count: number }>(`/organizations/${orgId}/departments`, {}, true, requestConfig), // Create department - createDepartment: (orgId: string, name: string, description?: string, requestConfig?: RequestConfig) => + createDepartment: (orgId: string, name: string, description?: string, canSudo?: boolean, requestConfig?: RequestConfig) => request<{ department: Department }>(`/organizations/${orgId}/departments`, { method: 'POST', - body: JSON.stringify({ name, description }), + body: JSON.stringify({ name, description, can_sudo: canSudo }), }, true, requestConfig), // Update department - updateDepartment: (orgId: string, deptId: string, data: { name?: string; description?: string }, requestConfig?: RequestConfig) => + updateDepartment: (orgId: string, deptId: string, data: { name?: string; description?: string; can_sudo?: boolean }, requestConfig?: RequestConfig) => request<{ department: Department }>(`/organizations/${orgId}/departments/${deptId}`, { method: 'PATCH', body: JSON.stringify(data), @@ -1130,6 +1162,39 @@ export const api = { request<{ ca_id: string }>(`/organizations/${orgId}/cas/${caId}`, { method: 'DELETE', }, true, requestConfig), + + // Get API keys for organization + getApiKeys: (orgId: string, requestConfig?: RequestConfig) => + request<{ api_keys: OrganizationApiKey[]; count: number }>(`/organizations/${orgId}/api-keys`, {}, true, requestConfig), + + // Create new API key + createApiKey: (orgId: string, name: string, description?: string, requestConfig?: RequestConfig) => + request<{ api_key: OrganizationApiKey & { key?: string } }>(`/organizations/${orgId}/api-keys`, { + method: 'POST', + body: JSON.stringify({ name, description }), + }, true, requestConfig), + + // Update API key + updateApiKey: (orgId: string, keyId: string, data: { name?: string; description?: string }, requestConfig?: RequestConfig) => + request<{ api_key: OrganizationApiKey }>(`/organizations/${orgId}/api-keys/${keyId}`, { + method: 'PATCH', + body: JSON.stringify(data), + }, true, requestConfig), + + // Delete API key + deleteApiKey: (orgId: string, keyId: string, requestConfig?: RequestConfig) => + request<{ message: string }>(`/organizations/${orgId}/api-keys/${keyId}`, { + method: 'DELETE', + }, true, requestConfig), + + // Get certificate audit logs for organization + getCertificateAuditLogs: (orgId: string, params?: Record, requestConfig?: RequestConfig) => + request<{ audit_logs: CertificateAuditLog[]; count: number; page: number; per_page: number; pages: number }>( + `/organizations/${orgId}/certificates/audit${params ? '?' + new URLSearchParams(params).toString() : ''}`, + {}, + true, + requestConfig + ), }, invites: { @@ -1557,6 +1622,7 @@ export interface Department { organization_id: string; name: string; description: string | null; + can_sudo: boolean; created_at: string; updated_at: string; deleted_at: string | null; diff --git a/src/pages/org/ApiKeysPage.tsx b/src/pages/org/ApiKeysPage.tsx new file mode 100644 index 0000000..f4d07cc --- /dev/null +++ b/src/pages/org/ApiKeysPage.tsx @@ -0,0 +1,496 @@ +import { useState, useEffect, useRef } from "react"; +import { + Plus, Copy, Trash2, Loader2, AlertCircle, CheckCircle, Eye, EyeOff, MoreHorizontal, Edit2, Check +} from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; +import { api, OrganizationApiKey } from "@/lib/api"; +import { useToast } from "@/hooks/use-toast"; +import { useOrg } from "@/contexts/OrgContext"; +import { formatDate } from "@/lib/date"; +import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; + +interface NewApiKeyState { + key: string; + name: string; + description?: string; + createdAt: string; +} + +interface EditingKey { + id: string; + name: string; + description: string | null; +} + +function useCopyButton() { + const [copied, setCopied] = useState(false); + const copy = (text: string) => { + navigator.clipboard.writeText(text).then(() => { + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }); + }; + return { copied, copy }; +} + +export default function ApiKeysPage() { + const { toast } = useToast(); + const { selectedOrgId: orgId } = useOrg(); + const queryClient = useQueryClient(); + const { copy, copied } = useCopyButton(); + + const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false); + const [isEditDialogOpen, setIsEditDialogOpen] = useState(false); + const [newSecret, setNewSecret] = useState(null); + const [editingKey, setEditingKey] = useState(null); + const [showKey, setShowKey] = useState(false); + const [isCreating, setIsCreating] = useState(false); + + const nameRef = useRef(null); + const descriptionRef = useRef(null); + const editNameRef = useRef(null); + const editDescriptionRef = useRef(null); + + // Fetch API keys + const { data: apiKeysData, isLoading } = useQuery({ + queryKey: ['api-keys', orgId], + queryFn: () => orgId ? api.organizations.getApiKeys(orgId) : null, + enabled: !!orgId, + }); + + // Create API key mutation + const { mutate: createKey, isPending: isCreatingKey } = useMutation({ + mutationFn: () => { + if (!orgId) throw new Error('Organization ID not set'); + const name = nameRef.current?.value; + const description = descriptionRef.current?.value; + if (!name) throw new Error('Name is required'); + return api.organizations.createApiKey(orgId, name, description); + }, + onSuccess: (data) => { + const apiKey = data.api_key; + setNewSecret({ + key: apiKey.key || '', + name: apiKey.name, + description: apiKey.description || undefined, + createdAt: apiKey.created_at, + }); + setIsCreateDialogOpen(false); + if (nameRef.current) nameRef.current.value = ''; + if (descriptionRef.current) descriptionRef.current.value = ''; + queryClient.invalidateQueries({ queryKey: ['api-keys', orgId] }); + toast({ + title: 'API Key Created', + description: 'Store the key value securely - you won\'t be able to see it again.', + }); + }, + onError: () => { + toast({ + title: 'Failed to create API key', + description: 'Please try again.', + variant: 'destructive', + }); + }, + }); + + // Update API key mutation + const { mutate: updateKey, isPending: isUpdatingKey } = useMutation({ + mutationFn: () => { + if (!orgId || !editingKey) throw new Error('Required data missing'); + return api.organizations.updateApiKey(orgId, editingKey.id, { + name: editNameRef.current?.value, + description: editDescriptionRef.current?.value, + }); + }, + onSuccess: () => { + setIsEditDialogOpen(false); + queryClient.invalidateQueries({ queryKey: ['api-keys', orgId] }); + toast({ + title: 'API Key Updated', + description: 'Changes saved successfully.', + }); + }, + onError: () => { + toast({ + title: 'Failed to update API key', + description: 'Please try again.', + variant: 'destructive', + }); + }, + }); + + // Delete API key mutation + const { mutate: deleteKey, isPending: isDeletingKey } = useMutation({ + mutationFn: (keyId: string) => { + if (!orgId) throw new Error('Organization ID not set'); + return api.organizations.deleteApiKey(orgId, keyId); + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['api-keys', orgId] }); + toast({ + title: 'API Key Deleted', + description: 'The API key has been permanently removed.', + }); + }, + onError: () => { + toast({ + title: 'Failed to delete API key', + description: 'Please try again.', + variant: 'destructive', + }); + }, + }); + + const handleCreateKey = () => { + setIsCreating(true); + createKey(); + setIsCreating(false); + }; + + const handleEditKey = (key: OrganizationApiKey) => { + setEditingKey({ + id: key.id, + name: key.name, + description: key.description, + }); + setIsEditDialogOpen(true); + }; + + const handleUpdateKey = () => { + updateKey(); + }; + + const handleDeleteKey = (keyId: string) => { + if (confirm('Are you sure you want to delete this API key? This action cannot be undone.')) { + deleteKey(keyId); + } + }; + + const apiKeys = apiKeysData?.api_keys || []; + const activeKeys = apiKeys.filter(k => !k.is_revoked); + const revokedKeys = apiKeys.filter(k => k.is_revoked); + + if (isLoading) { + return ( +
+
+ +
+
+ ); + } + + return ( +
+
+

API Keys

+

+ Manage API keys for external integrations and programmatic access to your organization. +

+
+ + {/* New key notification */} + {newSecret && ( + + + + + New API Key Created + + + Store this key securely. You won't be able to see it again. + + + +
+ +

{newSecret.name}

+
+
+ + + {newSecret.key} + +
+ +
+
+ )} + + {/* Create button */} +
+ +
+ + {/* Active Keys */} + {activeKeys.length > 0 && ( +
+

Active Keys

+
+ {activeKeys.map((key) => ( + + +
+
+
+

{key.name}

+ {key.last_used_at && ( + + Last used: {formatDate(key.last_used_at)} + + )} +
+ {key.description && ( +

+ {key.description} +

+ )} +

+ Created {formatDate(key.created_at)} +

+
+ + + + + + handleEditKey(key)} + className="cursor-pointer" + > + + Edit + + + handleDeleteKey(key.id)} + className="text-destructive cursor-pointer" + disabled={isDeletingKey} + > + + Delete + + + +
+
+
+ ))} +
+
+ )} + + {/* Revoked Keys */} + {revokedKeys.length > 0 && ( +
+

Revoked Keys

+
+ {revokedKeys.map((key) => ( + + +
+
+

+ {key.name} +

+

+ Revoked {formatDate(key.revoked_at || '')} + {key.revoke_reason && ` - ${key.revoke_reason}`} +

+
+
+
+
+ ))} +
+
+ )} + + {/* Empty state */} + {apiKeys.length === 0 && ( + + + +

No API Keys

+

+ Create your first API key to enable external integrations. +

+ +
+
+ )} + + {/* Create Dialog */} + + + + Create API Key + + Create a new API key for external integrations. The key will be displayed only once. + + +
+
+ + +
+
+ +