Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1dbbcff5d5 | |||
| f080b0034f | |||
| 57d0f12000 | |||
| 0dbc744471 | |||
| 7a912bddab | |||
| 24211c318b | |||
| 630e0a3cdf | |||
| 797d0f4462 |
@@ -23,19 +23,438 @@
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
import dotenv
|
||||
from textual.app import App, ComposeResult
|
||||
from textual.containers import Vertical
|
||||
from textual.message import Message
|
||||
from textual.reactive import reactive
|
||||
from textual.screen import Screen
|
||||
from textual.widgets import (
|
||||
Button,
|
||||
DirectoryTree,
|
||||
Footer,
|
||||
Header,
|
||||
Static,
|
||||
Tab,
|
||||
Tabs,
|
||||
)
|
||||
import urllib3
|
||||
|
||||
from models.agent import Agent
|
||||
from models.policy import Policy
|
||||
from services.API import AirlockAPIWrapper
|
||||
from services.security import getAPI
|
||||
from TUI.TUI import run_Loxide
|
||||
from utils.configmanager import get_system_value
|
||||
from utils.setup import setup
|
||||
from utils.utils import irtang
|
||||
from TUI.Screens.moveagentworkflowscreen import MoveAgentWorkflowScreen
|
||||
from TUI.Screens.otpactivityscreen import OTPActivitiesScreen
|
||||
from TUI.Screens.otprevokescreen import OTPRevokeScreen
|
||||
from TUI.Screens.otpworkflowscreen import OTPWorkflowScreen
|
||||
from TUI.Screens.policyprepworkflowscreen import PolicyPrepWorkflowScreen
|
||||
from TUI.Screens.quietagentworkflowscreen import QuietAgentWorkflowScreen
|
||||
from TUI.Themes.theme_amber_terminal import get_amber_terminal_theme
|
||||
from TUI.Themes.theme_retro_terminal import get_retro_terminal_theme
|
||||
from TUI.Themes.themeselector import ThemeSelector
|
||||
from TUI.Widgets.agentmoveoperations import AgentMoveOperations
|
||||
from TUI.Widgets.multiagentselector import MultiAgentSelector
|
||||
from TUI.Widgets.policytreewidget import PolicyTreeWidget
|
||||
from TUI.Widgets.resultsdisplay import ResultsDisplay
|
||||
from utils.configmanager import (
|
||||
get_system_value,
|
||||
get_user_value,
|
||||
load_env,
|
||||
save_user_config,
|
||||
)
|
||||
from utils.setup import get_base_directory, setup
|
||||
from utils.utils import irtang, open_directory
|
||||
|
||||
dotenv.load_dotenv()
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GLOBAL STASH
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_APP_RESTART_REASON = None
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# helper to persist TEXTUAL_THEME to *user* config and mirror to .env
|
||||
# ---------------------------------------------------------------------------
|
||||
def _persist_user_theme(theme_name: str) -> None:
|
||||
"""
|
||||
Store the chosen Textual theme in the user's config using the config manager.
|
||||
No need to touch .env - config manager handles everything.
|
||||
"""
|
||||
base_dir = get_base_directory()
|
||||
config_dir = base_dir / "config"
|
||||
|
||||
try:
|
||||
save_user_config(config_dir, {"TEXTUAL_THEME": theme_name})
|
||||
logger.debug("Updated user config with TEXTUAL_THEME=%s", theme_name)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to save TEXTUAL_THEME: %s", exc)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1) SCREEN
|
||||
# ---------------------------------------------------------------------------
|
||||
class MainMenuScreen(Screen):
|
||||
api: AirlockAPIWrapper
|
||||
current_tab = reactive("")
|
||||
|
||||
BUTTON_DEFS = {
|
||||
"agent_actions": [
|
||||
(
|
||||
"🖥️ - Find agent, Move agent, or Generate One Time Pass",
|
||||
"move_agent_workflow_button",
|
||||
),
|
||||
("🎫 - Review and approve OTP Activities", "otp_activities_button"),
|
||||
("🛑 - Revoke Active OTP Session", "otp_revoke_button"),
|
||||
],
|
||||
"policy": [
|
||||
("⚖️ - Prepare Policy For Enforcement", "policy_prep_button"),
|
||||
("🔕 - Find and Move Quiet Hosts to Enforcement", "find_quiet_button"),
|
||||
],
|
||||
}
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.extras = get_user_value("EXTRAS", str, "NOTTODAY")
|
||||
wd = load_env("WORKING_DIR") or os.getcwd()
|
||||
if not os.path.isdir(wd):
|
||||
wd = os.getcwd()
|
||||
self.working_dir = wd
|
||||
|
||||
def _make_buttons_for(self, tab_id: str) -> Vertical:
|
||||
defs = self.BUTTON_DEFS.get(tab_id, [])
|
||||
buttons = []
|
||||
for label, btn_id in defs:
|
||||
btn = Button(label, id=btn_id)
|
||||
btn.styles.width = "100%"
|
||||
buttons.append(btn)
|
||||
return Vertical(*buttons)
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
yield Header(show_clock=True, icon="⚙")
|
||||
|
||||
tabs = [
|
||||
Tab("Tree View", id="p_tree"),
|
||||
Tab("Agents", id="agent_actions"),
|
||||
Tab("Directory", id="dir"),
|
||||
Tab("Settings", id="settings"),
|
||||
]
|
||||
|
||||
if self.extras == "POLICYPREP":
|
||||
tabs.insert(2, Tab("Policy Prep", id="policy"))
|
||||
|
||||
yield Tabs(*tabs, id="tabs")
|
||||
yield Vertical(id="content")
|
||||
yield Footer()
|
||||
|
||||
def on_mount(self) -> None:
|
||||
self.switch_tab("agent_actions")
|
||||
|
||||
# focus helpers
|
||||
def _get_content_buttons(self) -> list[Button]:
|
||||
content = self.query_one("#content", Vertical)
|
||||
return list(content.query(Button))
|
||||
|
||||
def _focus_first_button(self) -> None:
|
||||
buttons = self._get_content_buttons()
|
||||
if buttons:
|
||||
buttons[0].focus()
|
||||
|
||||
def _focus_tabs(self) -> None:
|
||||
tabs = self.query_one("#tabs", Tabs)
|
||||
tabs.focus()
|
||||
|
||||
def _focus_nearby_button(self, direction: int) -> None:
|
||||
buttons = self._get_content_buttons()
|
||||
if not buttons:
|
||||
return
|
||||
|
||||
try:
|
||||
current = next(i for i, b in enumerate(buttons) if b.has_focus)
|
||||
except StopIteration:
|
||||
if direction > 0:
|
||||
buttons[0].focus()
|
||||
else:
|
||||
buttons[-1].focus()
|
||||
return
|
||||
|
||||
if direction < 0 and current == 0:
|
||||
self._focus_tabs()
|
||||
return
|
||||
|
||||
new_index = current + direction
|
||||
if 0 <= new_index < len(buttons):
|
||||
buttons[new_index].focus()
|
||||
|
||||
def switch_tab(self, tab_id: str) -> None:
|
||||
self.current_tab = tab_id
|
||||
content = self.query_one("#content", Vertical)
|
||||
content.remove_children()
|
||||
|
||||
if tab_id in self.BUTTON_DEFS:
|
||||
content.mount(self._make_buttons_for(tab_id))
|
||||
self.call_later(self._focus_first_button)
|
||||
elif tab_id == "dir":
|
||||
content.mount(DirectoryTree(self.working_dir, id="dir_tree"))
|
||||
elif tab_id == "p_tree":
|
||||
content.mount(PolicyTreeWidget(self.app.policies, self.app.devices))
|
||||
elif tab_id == "settings":
|
||||
content.mount(ThemeSelector())
|
||||
else:
|
||||
content.mount(Static(f"Unknown tab: {tab_id}"))
|
||||
|
||||
def on_tabs_tab_activated(self, event: Tabs.TabActivated) -> None:
|
||||
self.switch_tab(event.tab.id)
|
||||
|
||||
def on_multi_agent_selector_agents_selected(
|
||||
self, message: MultiAgentSelector.AgentsSelected
|
||||
) -> None:
|
||||
"""Handle selected agents from AgentSelector."""
|
||||
global _APP_RESTART_REASON
|
||||
selected_agents = message.selected_agents
|
||||
logger.info("Selected agents: %s", selected_agents)
|
||||
# TODO: Implement actual handling of selected agents
|
||||
_APP_RESTART_REASON = ("multi_agent_action", selected_agents)
|
||||
self.app.exit()
|
||||
|
||||
def on_theme_selector_theme_selected(
|
||||
self, message: ThemeSelector.ThemeSelected
|
||||
) -> None:
|
||||
"""Handle theme selection from ThemeSelector."""
|
||||
global _APP_RESTART_REASON
|
||||
_persist_user_theme(message.theme_name)
|
||||
_APP_RESTART_REASON = ("restart",)
|
||||
self.app.exit()
|
||||
|
||||
def on_agent_move_operations_operation_complete(
|
||||
self, message: AgentMoveOperations.OperationComplete
|
||||
) -> None:
|
||||
"""Handle completion of agent move operation - show results."""
|
||||
logger.info(
|
||||
"Agent move operation completed: %s, %d successful, %d unsuccessful",
|
||||
message.operation,
|
||||
len(message.successful),
|
||||
len(message.unsuccessful),
|
||||
)
|
||||
|
||||
# Format results for display
|
||||
successful_text = "\n".join(
|
||||
[f"{agent.hostname}" for agent, _ in message.successful]
|
||||
)
|
||||
unsuccessful_text = "\n".join(
|
||||
[f"{agent.hostname}: {error}" for agent, error in message.unsuccessful]
|
||||
)
|
||||
|
||||
# Remove the operations widget
|
||||
try:
|
||||
ops_widget = self.query_one(AgentMoveOperations)
|
||||
ops_widget.remove()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Show results
|
||||
self.query_one("#content", Vertical).mount(
|
||||
ResultsDisplay(message.operation, successful_text, unsuccessful_text)
|
||||
)
|
||||
|
||||
def on_results_display_go_back(self, message: ResultsDisplay.GoBack) -> None:
|
||||
"""Handle back button from results display."""
|
||||
try:
|
||||
results_widget = self.query_one(ResultsDisplay)
|
||||
results_widget.remove()
|
||||
except Exception:
|
||||
pass
|
||||
# Return to main menu
|
||||
self.app.pop_screen()
|
||||
|
||||
def on_directory_tree_file_selected(
|
||||
self, event: DirectoryTree.FileSelected
|
||||
) -> None:
|
||||
path = event.path
|
||||
logger.debug("Directory file selected: %s", path)
|
||||
try:
|
||||
open_directory(str(path))
|
||||
except Exception as exc:
|
||||
logger.error("Failed to open %s: %s", path, exc)
|
||||
self.app.bell()
|
||||
|
||||
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||
button_id = event.button.id
|
||||
logger.debug("Button pressed: %s", button_id)
|
||||
|
||||
match button_id:
|
||||
case "move_agent_workflow_button":
|
||||
self.app.push_screen(MoveAgentWorkflowScreen(self.app.devices))
|
||||
event.stop()
|
||||
|
||||
case "otp_generate_button":
|
||||
self.app.push_screen(OTPWorkflowScreen(self.app.devices))
|
||||
event.stop()
|
||||
|
||||
case "find_quiet_button":
|
||||
self.app.push_screen(
|
||||
QuietAgentWorkflowScreen(self.app.api, self.app.policies)
|
||||
)
|
||||
event.stop()
|
||||
return
|
||||
|
||||
case "otp_activities_button":
|
||||
self.app.push_screen(OTPActivitiesScreen())
|
||||
event.stop()
|
||||
return
|
||||
|
||||
case "otp_revoke_button":
|
||||
self.app.push_screen(OTPRevokeScreen())
|
||||
event.stop()
|
||||
return
|
||||
|
||||
case "policy_prep_button":
|
||||
# Use the new TUI workflow screen instead of legacy
|
||||
self.app.push_screen(
|
||||
PolicyPrepWorkflowScreen(self.app.api, self.app.policies)
|
||||
)
|
||||
event.stop()
|
||||
return
|
||||
|
||||
case _:
|
||||
self.app.bell()
|
||||
logger.warning("Unknown button pressed: %s", button_id)
|
||||
return
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2) APP
|
||||
# ---------------------------------------------------------------------------
|
||||
class Loxide(App[Message]):
|
||||
api: AirlockAPIWrapper
|
||||
working_dir: str
|
||||
policies: Optional[list[Policy]]
|
||||
devices: Optional[list[Agent]]
|
||||
|
||||
CSS = """
|
||||
#logo {
|
||||
width: 100%;
|
||||
content-align: center middle;
|
||||
text-align: center;
|
||||
}
|
||||
"""
|
||||
BINDINGS = [
|
||||
("q", "quit", "Quit"),
|
||||
("f", "open_fe", "Launch Explorer"),
|
||||
("r", "refresh", "Refresh"),
|
||||
]
|
||||
|
||||
def __init__(self, api: AirlockAPIWrapper):
|
||||
self._textual_theme = get_user_value("TEXTUAL_THEME", str, "textual-dark")
|
||||
super().__init__()
|
||||
self.api = api
|
||||
wd = load_env("WORKING_DIR") or os.getcwd()
|
||||
if not os.path.isdir(wd):
|
||||
wd = os.getcwd()
|
||||
self.working_dir = wd
|
||||
# Initial data load
|
||||
self.refresh_data()
|
||||
|
||||
def refresh_data(self) -> None:
|
||||
"""Public method to refresh policies and devices from the API."""
|
||||
try:
|
||||
self.policies = [
|
||||
Policy(**row.to_dict())
|
||||
for _, row in self.api.policy_find_all().iterrows()
|
||||
]
|
||||
self.devices = [
|
||||
Agent(**row.to_dict())
|
||||
for _, row in self.api.agent_find_all().iterrows()
|
||||
]
|
||||
if self.policies and self.devices:
|
||||
for agent in self.devices:
|
||||
agent.enrich_with_policies(self.policies)
|
||||
logger.debug(
|
||||
f"Enriched {len(self.devices)} agents with policy information"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to load policies/devices: %s", exc)
|
||||
self.policies = None
|
||||
self.devices = None
|
||||
|
||||
def on_mount(self, api: AirlockAPIWrapper) -> None:
|
||||
self.register_theme(get_retro_terminal_theme())
|
||||
self.register_theme(get_amber_terminal_theme())
|
||||
self.theme = self._textual_theme
|
||||
self.push_screen(MainMenuScreen())
|
||||
|
||||
def action_refresh(self) -> None:
|
||||
self.refresh_data()
|
||||
|
||||
def action_quit(self) -> None:
|
||||
global _APP_RESTART_REASON
|
||||
_APP_RESTART_REASON = None
|
||||
self.exit()
|
||||
|
||||
def action_open_fe(self) -> None:
|
||||
"""Open the working directory in the OS file manager (footer binding)."""
|
||||
path_to_open = self.working_dir or os.getcwd()
|
||||
try:
|
||||
open_directory(path_to_open)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to open directory %s: %s", path_to_open, exc)
|
||||
self.bell() # optional feedback
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3) PUBLIC ENTRYPOINT
|
||||
# ---------------------------------------------------------------------------
|
||||
def run_Loxide(api: AirlockAPIWrapper) -> None:
|
||||
global _APP_RESTART_REASON
|
||||
base_dir = get_base_directory()
|
||||
env_path = base_dir / ".env"
|
||||
dotenv.load_dotenv(dotenv_path=env_path, override=True)
|
||||
|
||||
max_attempts = 5
|
||||
attempts = 0
|
||||
|
||||
while attempts < max_attempts:
|
||||
attempts += 1
|
||||
logger.debug("Starting app loop iteration (attempt %d)", attempts)
|
||||
_APP_RESTART_REASON = None
|
||||
app = Loxide(api)
|
||||
|
||||
try:
|
||||
app.run()
|
||||
except SystemExit as exc:
|
||||
if exc.code != 0:
|
||||
logger.debug("Caught SystemExit from Textual: %s", exc)
|
||||
raise
|
||||
|
||||
reason = _APP_RESTART_REASON
|
||||
logger.debug("After app.run(), _APP_RESTART_REASON = %r", reason)
|
||||
|
||||
if not reason:
|
||||
logger.debug("No restart reason, exiting loop")
|
||||
break
|
||||
|
||||
if reason[0] == "restart":
|
||||
logger.debug("Restarting app loop")
|
||||
continue
|
||||
|
||||
if reason[0] == "multi_agent_action":
|
||||
logger.info("Multi-agent action with selected agents: %s", reason[1])
|
||||
continue
|
||||
|
||||
logger.error("Unknown restart reason: %r", reason)
|
||||
break
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4) MAIN FUNCTION
|
||||
# ---------------------------------------------------------------------------
|
||||
def main():
|
||||
irtang()
|
||||
# Determine working directory, setup directory, configure logging, sent env, get API and URL if not already stored
|
||||
|
||||
+1594
-278
File diff suppressed because it is too large
Load Diff
-444
@@ -1,444 +0,0 @@
|
||||
# Copyright (C) 2025 James Brotosky, Brandon Wickline
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as published
|
||||
# by the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
import dotenv
|
||||
from textual.app import App, ComposeResult
|
||||
from textual.containers import Vertical
|
||||
from textual.message import Message
|
||||
from textual.reactive import reactive
|
||||
from textual.screen import Screen
|
||||
from textual.widgets import (
|
||||
Button,
|
||||
DirectoryTree,
|
||||
Footer,
|
||||
Header,
|
||||
Static,
|
||||
Tab,
|
||||
Tabs,
|
||||
)
|
||||
|
||||
from models.agent import Agent
|
||||
from models.policy import Policy
|
||||
from services.API import AirlockAPIWrapper
|
||||
from TUI.Screens.moveagentworkflowscreen import MoveAgentWorkflowScreen
|
||||
from TUI.Screens.otpactivityscreen import OTPActivitiesScreen
|
||||
from TUI.Screens.otprevokescreen import OTPRevokeScreen
|
||||
from TUI.Screens.otpworkflowscreen import OTPWorkflowScreen
|
||||
from TUI.Screens.policyprepworkflowscreen import PolicyPrepWorkflowScreen
|
||||
from TUI.Screens.quietagentworkflowscreen import QuietAgentWorkflowScreen
|
||||
from TUI.Themes.theme_amber_terminal import get_amber_terminal_theme
|
||||
from TUI.Themes.theme_retro_terminal import get_retro_terminal_theme
|
||||
from TUI.Themes.themeselector import ThemeSelector
|
||||
from TUI.Widgets.agentmoveoperations import AgentMoveOperations
|
||||
from TUI.Widgets.multiagentselector import MultiAgentSelector
|
||||
from TUI.Widgets.policytreewidget import PolicyTreeWidget
|
||||
from TUI.Widgets.resultsdisplay import ResultsDisplay
|
||||
from utils.configmanager import get_user_value, load_env, save_user_config
|
||||
from utils.setup import get_base_directory
|
||||
from utils.utils import open_directory
|
||||
|
||||
dotenv.load_dotenv()
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GLOBAL STASH
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_APP_RESTART_REASON = None
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# helper to persist TEXTUAL_THEME to *user* config and mirror to .env
|
||||
# ---------------------------------------------------------------------------
|
||||
def _persist_user_theme(theme_name: str) -> None:
|
||||
"""
|
||||
Store the chosen Textual theme in the user's config using the config manager.
|
||||
No need to touch .env - config manager handles everything.
|
||||
"""
|
||||
base_dir = get_base_directory()
|
||||
config_dir = base_dir / "config"
|
||||
|
||||
try:
|
||||
save_user_config(config_dir, {"TEXTUAL_THEME": theme_name})
|
||||
logger.debug("Updated user config with TEXTUAL_THEME=%s", theme_name)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to save TEXTUAL_THEME: %s", exc)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1) SCREEN
|
||||
# ---------------------------------------------------------------------------
|
||||
class MainMenuScreen(Screen):
|
||||
api: AirlockAPIWrapper
|
||||
current_tab = reactive("")
|
||||
|
||||
BUTTON_DEFS = {
|
||||
"agent_actions": [
|
||||
(
|
||||
"🖥️ - Find agent, Move agent, or Generate One Time Pass",
|
||||
"move_agent_workflow_button",
|
||||
),
|
||||
("🎫 - Review and approve OTP Activities", "otp_activities_button"),
|
||||
("🛑 - Revoke Active OTP Session", "otp_revoke_button"),
|
||||
],
|
||||
"policy": [
|
||||
("⚖️ - Prepare Policy For Enforcement", "policy_prep_button"),
|
||||
("🔕 - Find and Move Quiet Hosts to Enforcement", "find_quiet_button"),
|
||||
],
|
||||
}
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.extras = get_user_value("EXTRAS", str, "NOTTODAY")
|
||||
wd = load_env("WORKING_DIR") or os.getcwd()
|
||||
if not os.path.isdir(wd):
|
||||
wd = os.getcwd()
|
||||
self.working_dir = wd
|
||||
|
||||
def _make_buttons_for(self, tab_id: str) -> Vertical:
|
||||
defs = self.BUTTON_DEFS.get(tab_id, [])
|
||||
buttons = []
|
||||
for label, btn_id in defs:
|
||||
btn = Button(label, id=btn_id)
|
||||
btn.styles.width = "100%"
|
||||
buttons.append(btn)
|
||||
return Vertical(*buttons)
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
yield Header(show_clock=True, icon="⚙")
|
||||
|
||||
tabs = [
|
||||
Tab("Tree View", id="p_tree"),
|
||||
Tab("Agents", id="agent_actions"),
|
||||
Tab("Directory", id="dir"),
|
||||
Tab("Settings", id="settings"),
|
||||
]
|
||||
|
||||
if self.extras == "POLICYPREP":
|
||||
tabs.insert(2, Tab("Policy Prep", id="policy"))
|
||||
|
||||
yield Tabs(*tabs, id="tabs")
|
||||
yield Vertical(id="content")
|
||||
yield Footer()
|
||||
|
||||
def on_mount(self) -> None:
|
||||
self.switch_tab("agent_actions")
|
||||
|
||||
# focus helpers
|
||||
def _get_content_buttons(self) -> list[Button]:
|
||||
content = self.query_one("#content", Vertical)
|
||||
return list(content.query(Button))
|
||||
|
||||
def _focus_first_button(self) -> None:
|
||||
buttons = self._get_content_buttons()
|
||||
if buttons:
|
||||
buttons[0].focus()
|
||||
|
||||
def _focus_tabs(self) -> None:
|
||||
tabs = self.query_one("#tabs", Tabs)
|
||||
tabs.focus()
|
||||
|
||||
def _focus_nearby_button(self, direction: int) -> None:
|
||||
buttons = self._get_content_buttons()
|
||||
if not buttons:
|
||||
return
|
||||
|
||||
try:
|
||||
current = next(i for i, b in enumerate(buttons) if b.has_focus)
|
||||
except StopIteration:
|
||||
if direction > 0:
|
||||
buttons[0].focus()
|
||||
else:
|
||||
buttons[-1].focus()
|
||||
return
|
||||
|
||||
if direction < 0 and current == 0:
|
||||
self._focus_tabs()
|
||||
return
|
||||
|
||||
new_index = current + direction
|
||||
if 0 <= new_index < len(buttons):
|
||||
buttons[new_index].focus()
|
||||
|
||||
def switch_tab(self, tab_id: str) -> None:
|
||||
self.current_tab = tab_id
|
||||
content = self.query_one("#content", Vertical)
|
||||
content.remove_children()
|
||||
|
||||
if tab_id in self.BUTTON_DEFS:
|
||||
content.mount(self._make_buttons_for(tab_id))
|
||||
self.call_later(self._focus_first_button)
|
||||
elif tab_id == "dir":
|
||||
content.mount(DirectoryTree(self.working_dir, id="dir_tree"))
|
||||
elif tab_id == "p_tree":
|
||||
content.mount(PolicyTreeWidget(self.app.policies, self.app.devices))
|
||||
elif tab_id == "settings":
|
||||
content.mount(ThemeSelector())
|
||||
else:
|
||||
content.mount(Static(f"Unknown tab: {tab_id}"))
|
||||
|
||||
def on_tabs_tab_activated(self, event: Tabs.TabActivated) -> None:
|
||||
self.switch_tab(event.tab.id)
|
||||
|
||||
def on_multi_agent_selector_agents_selected(
|
||||
self, message: MultiAgentSelector.AgentsSelected
|
||||
) -> None:
|
||||
"""Handle selected agents from AgentSelector."""
|
||||
global _APP_RESTART_REASON
|
||||
selected_agents = message.selected_agents
|
||||
logger.info("Selected agents: %s", selected_agents)
|
||||
# TODO: Implement actual handling of selected agents
|
||||
_APP_RESTART_REASON = ("multi_agent_action", selected_agents)
|
||||
self.app.exit()
|
||||
|
||||
def on_theme_selector_theme_selected(
|
||||
self, message: ThemeSelector.ThemeSelected
|
||||
) -> None:
|
||||
"""Handle theme selection from ThemeSelector."""
|
||||
global _APP_RESTART_REASON
|
||||
_persist_user_theme(message.theme_name)
|
||||
_APP_RESTART_REASON = ("restart",)
|
||||
self.app.exit()
|
||||
|
||||
def on_agent_move_operations_operation_complete(
|
||||
self, message: AgentMoveOperations.OperationComplete
|
||||
) -> None:
|
||||
"""Handle completion of agent move operation - show results."""
|
||||
logger.info(
|
||||
"Agent move operation completed: %s, %d successful, %d unsuccessful",
|
||||
message.operation,
|
||||
len(message.successful),
|
||||
len(message.unsuccessful),
|
||||
)
|
||||
|
||||
# Format results for display
|
||||
successful_text = "\n".join(
|
||||
[f"{agent.hostname}" for agent, _ in message.successful]
|
||||
)
|
||||
unsuccessful_text = "\n".join(
|
||||
[f"{agent.hostname}: {error}" for agent, error in message.unsuccessful]
|
||||
)
|
||||
|
||||
# Remove the operations widget
|
||||
try:
|
||||
ops_widget = self.query_one(AgentMoveOperations)
|
||||
ops_widget.remove()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Show results
|
||||
self.query_one("#content", Vertical).mount(
|
||||
ResultsDisplay(message.operation, successful_text, unsuccessful_text)
|
||||
)
|
||||
|
||||
def on_results_display_go_back(self, message: ResultsDisplay.GoBack) -> None:
|
||||
"""Handle back button from results display."""
|
||||
try:
|
||||
results_widget = self.query_one(ResultsDisplay)
|
||||
results_widget.remove()
|
||||
except Exception:
|
||||
pass
|
||||
# Return to main menu
|
||||
self.app.pop_screen()
|
||||
|
||||
def on_directory_tree_file_selected(
|
||||
self, event: DirectoryTree.FileSelected
|
||||
) -> None:
|
||||
path = event.path
|
||||
logger.debug("Directory file selected: %s", path)
|
||||
try:
|
||||
open_directory(str(path))
|
||||
except Exception as exc:
|
||||
logger.error("Failed to open %s: %s", path, exc)
|
||||
self.app.bell()
|
||||
|
||||
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||
button_id = event.button.id
|
||||
logger.debug("Button pressed: %s", button_id)
|
||||
|
||||
match button_id:
|
||||
case "move_agent_workflow_button":
|
||||
self.app.push_screen(MoveAgentWorkflowScreen(self.app.devices))
|
||||
event.stop()
|
||||
|
||||
case "otp_generate_button":
|
||||
self.app.push_screen(OTPWorkflowScreen(self.app.devices))
|
||||
event.stop()
|
||||
|
||||
case "find_quiet_button":
|
||||
self.app.push_screen(
|
||||
QuietAgentWorkflowScreen(self.app.api, self.app.policies)
|
||||
)
|
||||
event.stop()
|
||||
return
|
||||
|
||||
case "otp_activities_button":
|
||||
self.app.push_screen(OTPActivitiesScreen())
|
||||
event.stop()
|
||||
return
|
||||
|
||||
case "otp_revoke_button":
|
||||
self.app.push_screen(OTPRevokeScreen())
|
||||
event.stop()
|
||||
return
|
||||
|
||||
case "policy_prep_button":
|
||||
# Use the new TUI workflow screen instead of legacy
|
||||
self.app.push_screen(
|
||||
PolicyPrepWorkflowScreen(self.app.api, self.app.policies)
|
||||
)
|
||||
event.stop()
|
||||
return
|
||||
|
||||
case _:
|
||||
self.app.bell()
|
||||
logger.warning("Unknown button pressed: %s", button_id)
|
||||
return
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2) APP
|
||||
# ---------------------------------------------------------------------------
|
||||
class Loxide(App[Message]):
|
||||
api: AirlockAPIWrapper
|
||||
working_dir: str
|
||||
policies: Optional[list[Policy]]
|
||||
devices: Optional[list[Agent]]
|
||||
|
||||
CSS = """
|
||||
#logo {
|
||||
width: 100%;
|
||||
content-align: center middle;
|
||||
text-align: center;
|
||||
}
|
||||
"""
|
||||
BINDINGS = [
|
||||
("q", "quit", "Quit"),
|
||||
("f", "open_fe", "Launch Explorer"),
|
||||
("r", "refresh", "Refresh"),
|
||||
]
|
||||
|
||||
def __init__(self, api: AirlockAPIWrapper):
|
||||
self._textual_theme = get_user_value("TEXTUAL_THEME", str, "textual-dark")
|
||||
super().__init__()
|
||||
self.api = api
|
||||
wd = load_env("WORKING_DIR") or os.getcwd()
|
||||
if not os.path.isdir(wd):
|
||||
wd = os.getcwd()
|
||||
self.working_dir = wd
|
||||
# Initial data load
|
||||
self.refresh_data()
|
||||
|
||||
def refresh_data(self) -> None:
|
||||
"""Public method to refresh policies and devices from the API."""
|
||||
try:
|
||||
self.policies = [
|
||||
Policy(**row.to_dict())
|
||||
for _, row in self.api.policy_find_all().iterrows()
|
||||
]
|
||||
self.devices = [
|
||||
Agent(**row.to_dict())
|
||||
for _, row in self.api.agent_find_all().iterrows()
|
||||
]
|
||||
if self.policies and self.devices:
|
||||
for agent in self.devices:
|
||||
agent.enrich_with_policies(self.policies)
|
||||
logger.debug(
|
||||
f"Enriched {len(self.devices)} agents with policy information"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to load policies/devices: %s", exc)
|
||||
self.policies = None
|
||||
self.devices = None
|
||||
|
||||
def on_mount(self, api: AirlockAPIWrapper) -> None:
|
||||
self.register_theme(get_retro_terminal_theme())
|
||||
self.register_theme(get_amber_terminal_theme())
|
||||
self.theme = self._textual_theme
|
||||
self.push_screen(MainMenuScreen())
|
||||
|
||||
def action_refresh(self) -> None:
|
||||
self.refresh_data()
|
||||
|
||||
def action_quit(self) -> None:
|
||||
global _APP_RESTART_REASON
|
||||
_APP_RESTART_REASON = None
|
||||
self.exit()
|
||||
|
||||
def action_open_fe(self) -> None:
|
||||
"""Open the working directory in the OS file manager (footer binding)."""
|
||||
path_to_open = self.working_dir or os.getcwd()
|
||||
try:
|
||||
open_directory(path_to_open)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to open directory %s: %s", path_to_open, exc)
|
||||
self.bell() # optional feedback
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3) PUBLIC ENTRYPOINT
|
||||
# ---------------------------------------------------------------------------
|
||||
def run_Loxide(api: AirlockAPIWrapper) -> None:
|
||||
global _APP_RESTART_REASON
|
||||
base_dir = get_base_directory()
|
||||
env_path = base_dir / ".env"
|
||||
dotenv.load_dotenv(dotenv_path=env_path, override=True)
|
||||
|
||||
max_attempts = 5
|
||||
attempts = 0
|
||||
|
||||
while attempts < max_attempts:
|
||||
attempts += 1
|
||||
logger.debug("Starting app loop iteration (attempt %d)", attempts)
|
||||
_APP_RESTART_REASON = None
|
||||
app = Loxide(api)
|
||||
|
||||
try:
|
||||
app.run()
|
||||
except SystemExit as exc:
|
||||
if exc.code != 0:
|
||||
logger.debug("Caught SystemExit from Textual: %s", exc)
|
||||
raise
|
||||
|
||||
reason = _APP_RESTART_REASON
|
||||
logger.debug("After app.run(), _APP_RESTART_REASON = %r", reason)
|
||||
|
||||
if not reason:
|
||||
logger.debug("No restart reason, exiting loop")
|
||||
break
|
||||
|
||||
if reason[0] == "restart":
|
||||
logger.debug("Restarting app loop")
|
||||
continue
|
||||
|
||||
if reason[0] == "multi_agent_action":
|
||||
logger.info("Multi-agent action with selected agents: %s", reason[1])
|
||||
continue
|
||||
|
||||
logger.error("Unknown restart reason: %r", reason)
|
||||
break
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4) DEV
|
||||
# ---------------------------------------------------------------------------
|
||||
if __name__ == "__main__":
|
||||
api = AirlockAPIWrapper()
|
||||
run_Loxide(api)
|
||||
+22
-22
@@ -88,9 +88,9 @@ def sortHashes(
|
||||
):
|
||||
working_dir = load_env("WORKING_DIR")
|
||||
history_days = Selector.select_value(
|
||||
prompt="Enter how many days of history to pull (1–150): ",
|
||||
prompt="Enter how many days of history to pull (1-365): ",
|
||||
value_type=int,
|
||||
valid_range=(1, 150),
|
||||
valid_range=(1, 365),
|
||||
)
|
||||
|
||||
logger.debug(f"{history_days} day selected for history")
|
||||
@@ -655,7 +655,7 @@ def section_header(title):
|
||||
|
||||
def printEnforceChecklist(selected_policies, destination_policy, destination_allowlist):
|
||||
working_dir = load_env("WORKING_DIR")
|
||||
section_header("Prepare to Enforce Policy ")
|
||||
section_header("Prepare to Enforce Policy")
|
||||
print(
|
||||
colorText(
|
||||
"\nSequentially follow these steps to prepare a policy for enforcement:",
|
||||
@@ -670,11 +670,11 @@ def printEnforceChecklist(selected_policies, destination_policy, destination_all
|
||||
)
|
||||
)
|
||||
if not selected_policies:
|
||||
print(colorText(" [✗] No policies have been chosen", "red"))
|
||||
print(colorText(" [âŒ] No policies have been chosen", "red"))
|
||||
else:
|
||||
print(colorText("The following policies have been chosen:", "green"))
|
||||
for policy in selected_policies:
|
||||
print(colorText(f" [✓] {policy.name}", "green"))
|
||||
print(colorText(f" [✅] {policy.name}", "green"))
|
||||
|
||||
# Step 2: Destination Policy and Allowlist
|
||||
print(
|
||||
@@ -683,22 +683,22 @@ def printEnforceChecklist(selected_policies, destination_policy, destination_all
|
||||
if destination_policy:
|
||||
print(
|
||||
colorText(
|
||||
f" [✓] {destination_policy[0].name} has been selected as the destination policy",
|
||||
f" [✅] {destination_policy[0].name} has been selected as the destination policy",
|
||||
"green",
|
||||
)
|
||||
)
|
||||
else:
|
||||
print(colorText(" [✗] No destination policy has been chosen", "red"))
|
||||
print(colorText(" [âŒ] No destination policy has been chosen", "red"))
|
||||
|
||||
if destination_allowlist:
|
||||
print(
|
||||
colorText(
|
||||
f" [✓] {destination_allowlist[0].name} has been selected as allowlist",
|
||||
f" [✅] {destination_allowlist[0].name} has been selected as allowlist",
|
||||
"green",
|
||||
)
|
||||
)
|
||||
else:
|
||||
print(colorText(" [✗] No allowlist has been chosen", "red"))
|
||||
print(colorText(" [âŒ] No allowlist has been chosen", "red"))
|
||||
|
||||
# Step 3: Data Preparation
|
||||
print(
|
||||
@@ -713,9 +713,9 @@ def printEnforceChecklist(selected_policies, destination_policy, destination_all
|
||||
print(
|
||||
colorText(
|
||||
(
|
||||
" [✓] Data has been fetched"
|
||||
" [✅] Data has been fetched"
|
||||
if os.path.exists(review_path)
|
||||
else " [✗] Data has not been fetched"
|
||||
else " [âŒ] Data has not been fetched"
|
||||
),
|
||||
"green" if os.path.exists(review_path) else "red",
|
||||
)
|
||||
@@ -723,7 +723,7 @@ def printEnforceChecklist(selected_policies, destination_policy, destination_all
|
||||
else:
|
||||
print(
|
||||
colorText(
|
||||
" [✗] No policies selected, cannot check data fetch status", "red"
|
||||
" [âŒ] No policies selected, cannot check data fetch status", "red"
|
||||
)
|
||||
)
|
||||
|
||||
@@ -756,9 +756,9 @@ def printEnforceChecklist(selected_policies, destination_policy, destination_all
|
||||
print(
|
||||
colorText(
|
||||
(
|
||||
" [✓] Reviewed hashes have been loaded"
|
||||
" [✅] Reviewed hashes have been loaded"
|
||||
if os.path.exists(approved_path)
|
||||
else " [✗] Reviewed hashes have not been loaded"
|
||||
else " [âŒ] Reviewed hashes have not been loaded"
|
||||
),
|
||||
"green" if os.path.exists(approved_path) else "red",
|
||||
)
|
||||
@@ -766,9 +766,9 @@ def printEnforceChecklist(selected_policies, destination_policy, destination_all
|
||||
print(
|
||||
colorText(
|
||||
(
|
||||
" [✓] Path review list created"
|
||||
" [✅] Path review list created"
|
||||
if os.path.exists(second_review_path)
|
||||
else " [✗] Path review list has not been created"
|
||||
else " [âŒ] Path review list has not been created"
|
||||
),
|
||||
"green" if os.path.exists(second_review_path) else "red",
|
||||
)
|
||||
@@ -776,7 +776,7 @@ def printEnforceChecklist(selected_policies, destination_policy, destination_all
|
||||
else:
|
||||
print(
|
||||
colorText(
|
||||
" [✗] No policies selected, cannot check reviewed hashes or path list",
|
||||
" [âŒ] No policies selected, cannot check reviewed hashes or path list",
|
||||
"red",
|
||||
)
|
||||
)
|
||||
@@ -812,9 +812,9 @@ def printEnforceChecklist(selected_policies, destination_policy, destination_all
|
||||
print(
|
||||
colorText(
|
||||
(
|
||||
" [✓] Reviewed path list detected"
|
||||
" [✅] Reviewed path list detected"
|
||||
if os.path.exists(reviewed_path)
|
||||
else " [✗] Path review list has not been detected"
|
||||
else " [âŒ] Path review list has not been detected"
|
||||
),
|
||||
"green" if os.path.exists(reviewed_path) else "red",
|
||||
)
|
||||
@@ -825,9 +825,9 @@ def printEnforceChecklist(selected_policies, destination_policy, destination_all
|
||||
print(
|
||||
colorText(
|
||||
(
|
||||
" [✓] Preflight Path Exclusion List has been generated"
|
||||
" [✅] Preflight Path Exclusion List has been generated"
|
||||
if preflight_ready
|
||||
else " [✗] Preflight Path Exclusion List has not been generated"
|
||||
else " [âŒ] Preflight Path Exclusion List has not been generated"
|
||||
),
|
||||
"green" if preflight_ready else "red",
|
||||
)
|
||||
@@ -835,7 +835,7 @@ def printEnforceChecklist(selected_policies, destination_policy, destination_all
|
||||
else:
|
||||
print(
|
||||
colorText(
|
||||
" [✗] No policies selected, cannot check preflight status", "red"
|
||||
" [âŒ] No policies selected, cannot check preflight status", "red"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
Generated
+339
-588
File diff suppressed because it is too large
Load Diff
+10
-12
@@ -1,33 +1,31 @@
|
||||
[package]
|
||||
name = "airlock_libs"
|
||||
version = "5.2.1"
|
||||
version = "6.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
chrono = "0.4.42"
|
||||
indicatif = "0.18.2"
|
||||
mongodb = "3.3.0"
|
||||
opentelemetry = { version = "0.18.0", features = ["rt-tokio", "metrics", "trace"] }
|
||||
opentelemetry-otlp = { version = "0.11.0", features = ["trace", "metrics"] }
|
||||
opentelemetry-semantic-conventions = { version = "0.10.0" }
|
||||
opentelemetry-proto = { version = "0.1.0"}
|
||||
opentelemetry = { version = "0.27.0", features = ["logs", "metrics", "trace"] }
|
||||
opentelemetry-otlp = { version = "0.27.0", features = ["trace", "metrics", "grpc-tonic", "http-proto", "tls", "reqwest-client", "reqwest-rustls"] }
|
||||
opentelemetry-semantic-conventions = { version = "0.27.0" }
|
||||
opentelemetry-proto = { version = "0.27.0"}
|
||||
pyo3 = { version = "0.27.0", features = ["extension-module", "generate-import-lib"] }
|
||||
reqwest = { version = "0.12.24", features = ["json", "native-tls"] }
|
||||
reqwest = { version = "0.12.24", features = ["json", "native-tls", "rustls-tls"] }
|
||||
serde = "1.0.228"
|
||||
serde-pyobject = "0.8.0"
|
||||
serde_json = "1.0.145"
|
||||
tokio = { version = "1.48.0", features = ["full"] }
|
||||
tonic = { version = "0.8.2", features = ["tls-roots"] }
|
||||
tonic = { version = "0.12.3", features = ["tls-roots"] }
|
||||
tracing = "0.1.41"
|
||||
tracing-subscriber = "0.3.20"
|
||||
tracing-opentelemetry = "0.32.0"
|
||||
pyo3-async-runtimes = { version = "0.27.0", features = ["async-std", "tokio"] }
|
||||
crossbeam = "0.8.4"
|
||||
log = "0.4.29"
|
||||
flexi_logger = "0.31.7"
|
||||
opentelemetry-appender-log = "0.27.0"
|
||||
opentelemetry_sdk = { version = "0.27.0", features = ["rt-tokio", "testing", "trace"] }
|
||||
|
||||
[package.metadata.maturin]
|
||||
generate-abi-stubs = true
|
||||
@@ -40,4 +38,4 @@ codegen-units = 1
|
||||
panic = 'abort'
|
||||
strip = true
|
||||
debug-assertions = false
|
||||
overflow-checks = false
|
||||
overflow-checks = true
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "maturin"
|
||||
|
||||
[project]
|
||||
name = "airlock_libs"
|
||||
version = "5.2.1"
|
||||
version = "6.1.0"
|
||||
description = "Airlock Digital API Wrapper"
|
||||
readme = "README.md"
|
||||
license = { text = "AGPL-3.0-only" }
|
||||
|
||||
@@ -8,7 +8,32 @@ pub struct TelemetryConfig {
|
||||
}
|
||||
|
||||
impl TelemetryConfig {
|
||||
pub fn load() -> Self {
|
||||
pub fn init_tracer() -> opentelemetry_sdk::trace::TracerProvider {
|
||||
let cfg: TelemetryConfig = TelemetryConfig::load();
|
||||
if !cfg.TELEMETRY {
|
||||
return TracerProvider::builder().build();
|
||||
}
|
||||
let endpoint = cfg.TELEM_URL.unwrap_or_default();
|
||||
let channel = Channel::from_shared(endpoint.clone())
|
||||
.unwrap()
|
||||
.tls_config(ClientTlsConfig::new().with_native_roots())
|
||||
.unwrap()
|
||||
.connect_lazy();
|
||||
let exporter = opentelemetry_otlp::SpanExporter::builder()
|
||||
.with_tonic()
|
||||
.with_endpoint(endpoint.clone())
|
||||
.with_channel(channel)
|
||||
.build()
|
||||
.expect("Failed to build exporter");
|
||||
opentelemetry_sdk::trace::TracerProvider::builder()
|
||||
.with_simple_exporter(exporter)
|
||||
.with_resource(Resource::new(vec![KeyValue::new(
|
||||
"service.name",
|
||||
"LoxideLibs",
|
||||
)]))
|
||||
.build()
|
||||
}
|
||||
fn load() -> Self {
|
||||
let cfg_path = get_base_directory().join("config\\user_config.json");
|
||||
if !cfg_path.exists() {
|
||||
return Self {
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
pub use chrono::{Duration, Local, NaiveDate};
|
||||
pub use crossbeam::channel::unbounded;
|
||||
pub use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle};
|
||||
pub use mongodb::bson::oid::ObjectId;
|
||||
pub use opentelemetry::global::shutdown_tracer_provider;
|
||||
pub use opentelemetry::sdk::Resource;
|
||||
pub use opentelemetry::global::GlobalTracerProvider;
|
||||
pub use opentelemetry::trace::noop::NoopTracerProvider;
|
||||
pub use opentelemetry::trace::{Status, TraceContextExt, TraceError};
|
||||
pub use opentelemetry::{Context, KeyValue, sdk::trace as sdktrace, trace::Tracer};
|
||||
pub use opentelemetry::{Key, global};
|
||||
pub use opentelemetry::trace::{Status, TraceContextExt, Tracer};
|
||||
pub use opentelemetry::*;
|
||||
pub use opentelemetry_otlp::ExportConfig;
|
||||
pub use opentelemetry_otlp::WithExportConfig;
|
||||
pub use opentelemetry_otlp::WithTonicConfig;
|
||||
pub use opentelemetry_sdk::Resource;
|
||||
pub use opentelemetry_sdk::trace::{Config, TracerProvider};
|
||||
pub use pyo3::{prelude::*, types::PyString};
|
||||
pub use pyo3_async_runtimes::async_std;
|
||||
pub use reqwest::{
|
||||
Client,
|
||||
header::{HeaderMap, HeaderName, HeaderValue},
|
||||
};
|
||||
pub use serde::{Deserialize, Serialize};
|
||||
pub use serde_json::Value;
|
||||
pub use std::sync::{Arc, Mutex};
|
||||
pub use std::thread;
|
||||
pub use std::{
|
||||
collections::HashMap,
|
||||
env,
|
||||
@@ -25,3 +29,4 @@ pub use std::{
|
||||
path::PathBuf,
|
||||
str::FromStr,
|
||||
};
|
||||
pub use tonic::transport::{Channel, ClientTlsConfig};
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
use crate::modules::datatypes::*;
|
||||
use crate::prelude::*;
|
||||
use crossbeam::channel::unbounded;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
|
||||
#[pyfunction]
|
||||
pub fn pull_policy_exec_histories(
|
||||
py: Python<'_>,
|
||||
@@ -11,9 +9,10 @@ pub fn pull_policy_exec_histories(
|
||||
exec_types: String,
|
||||
days: i64,
|
||||
) -> Py<PyString> {
|
||||
let data = PyData::extract_data(py, &py_self);
|
||||
let headers = data.headers;
|
||||
let base_url = data.base_url;
|
||||
println!();
|
||||
let data: PyData = PyData::extract_data(py, &py_self);
|
||||
let headers: HeaderMap = data.headers;
|
||||
let base_url: String = data.base_url;
|
||||
let handle: thread::JoinHandle<String> = std::thread::spawn(move || {
|
||||
let rt: tokio::runtime::Runtime = match tokio::runtime::Runtime::new() {
|
||||
Ok(rt) => rt,
|
||||
@@ -22,10 +21,9 @@ pub fn pull_policy_exec_histories(
|
||||
std::process::abort();
|
||||
}
|
||||
};
|
||||
rt.block_on(async {
|
||||
let _ = init_tracer();
|
||||
});
|
||||
let tracer: global::BoxedTracer = global::tracer("global_tracer");
|
||||
let tracer_provider = rt.block_on(async { TelemetryConfig::init_tracer() });
|
||||
global::set_tracer_provider(tracer_provider.clone());
|
||||
let tracer: global::BoxedTracer = global::tracer("tracer");
|
||||
let _cx: Context = Context::new();
|
||||
let file_path: PathBuf = format!(
|
||||
"{}\\cache\\chunkinator.json",
|
||||
@@ -106,7 +104,8 @@ pub fn pull_policy_exec_histories(
|
||||
}
|
||||
}
|
||||
});
|
||||
let cutoff: chrono::NaiveDateTime = Local::now().naive_local() - Duration::days(days);
|
||||
let cutoff: chrono::NaiveDateTime =
|
||||
Local::now().naive_local() - chrono::Duration::days(days);
|
||||
let (tx, rx) = unbounded::<Vec<Group>>();
|
||||
let pb_clone = progress_bar.clone();
|
||||
thread::spawn(move || {
|
||||
@@ -181,7 +180,7 @@ pub fn pull_policy_exec_histories(
|
||||
.unwrap()
|
||||
.enable_steady_tick(std::time::Duration::from_millis(100));
|
||||
let span: opentelemetry::trace::SpanRef<'_> = cx.span();
|
||||
span.set_attribute(Key::new("Days").string(days.to_string()));
|
||||
span.set_attribute(KeyValue::new("Days", days));
|
||||
span.set_attribute(KeyValue::new("Policy Name", policy_names.clone()));
|
||||
loop {
|
||||
let execution_histories = tracer.in_span(checkpoint_number.to_string(), |cx| {
|
||||
@@ -237,8 +236,10 @@ pub fn pull_policy_exec_histories(
|
||||
std::process::abort();
|
||||
}
|
||||
};
|
||||
tracer_provider
|
||||
.shutdown()
|
||||
.expect("Failed to Shutdown Tracer Provdier");
|
||||
drop(tx);
|
||||
shutdown_tracer_provider();
|
||||
return_data.to_string()
|
||||
});
|
||||
let gil_value: String = handle.join().unwrap();
|
||||
@@ -312,26 +313,3 @@ pub fn get_base_directory() -> PathBuf {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn init_tracer() -> Result<Option<sdktrace::Tracer>, TraceError> {
|
||||
let cfg: TelemetryConfig = TelemetryConfig::load();
|
||||
if !cfg.TELEMETRY {
|
||||
global::set_tracer_provider(NoopTracerProvider::new());
|
||||
return Ok(None);
|
||||
}
|
||||
let endpoint: String = cfg.TELEM_URL.unwrap_or_default();
|
||||
let tracer: sdktrace::Tracer =
|
||||
opentelemetry_otlp::new_pipeline()
|
||||
.tracing()
|
||||
.with_exporter(
|
||||
opentelemetry_otlp::new_exporter()
|
||||
.tonic()
|
||||
.with_endpoint(endpoint),
|
||||
)
|
||||
.with_trace_config(sdktrace::config().with_resource(Resource::new(vec![
|
||||
KeyValue::new("service.name", "LoxideLibs"),
|
||||
])))
|
||||
.install_simple()
|
||||
.unwrap();
|
||||
Ok(Some(tracer))
|
||||
}
|
||||
|
||||
+18
-6
@@ -1,14 +1,26 @@
|
||||
# Core TUI dependencies
|
||||
textual==6.5.0
|
||||
|
||||
# API and data handling
|
||||
Requests==2.32.5
|
||||
pandas==2.3.3
|
||||
numpy==2.3.4
|
||||
|
||||
# Database
|
||||
pymongo==4.15.3
|
||||
|
||||
# Security and encryption
|
||||
cryptography==46.0.3
|
||||
keyring==25.6.0
|
||||
numpy==2.3.4
|
||||
pandas==2.3.3
|
||||
pymongo==4.15.3
|
||||
|
||||
# Environment management
|
||||
python-dotenv==1.2.1
|
||||
Requests==2.32.5
|
||||
textual==6.5.0
|
||||
|
||||
# Utilities
|
||||
tqdm==4.67.1
|
||||
urllib3==2.5.0
|
||||
pyperclip==1.11.0
|
||||
|
||||
# Custom/Private packages
|
||||
--extra-index-url https://git.racooncity.org/api/packages/brotoskyj/pypi/simple/
|
||||
airlock_libs==5.2.1
|
||||
airlock_libs==6.1.0
|
||||
+15
-15
@@ -38,9 +38,9 @@ logger = logging.getLogger(__name__)
|
||||
def devicehistory(api: AirlockAPIWrapper, outputjson: bool):
|
||||
agents = selectAgents(api)
|
||||
history_days = Selector.select_value(
|
||||
prompt="Enter how many days of history to pull (1–150): ",
|
||||
prompt="Enter how many days of history to pull (1–365): ",
|
||||
value_type=int,
|
||||
valid_range=(1, 150),
|
||||
valid_range=(1, 365),
|
||||
)
|
||||
|
||||
if not agents or not history_days:
|
||||
@@ -60,7 +60,7 @@ def devicehistory(api: AirlockAPIWrapper, outputjson: bool):
|
||||
except Exception as e:
|
||||
print(
|
||||
colorText(
|
||||
f"❌ Error retrieving history for {agent.hostname}: {e}", "red"
|
||||
f"⌠Error retrieving history for {agent.hostname}: {e}", "red"
|
||||
)
|
||||
)
|
||||
continue
|
||||
@@ -139,7 +139,7 @@ def findAgents(api, return_dataframe):
|
||||
|
||||
print(
|
||||
colorText(
|
||||
f"\n✓ Matched devices exported to: {working_dir}\\{filename}",
|
||||
f"\n✓ Matched devices exported to: {working_dir}\\{filename}",
|
||||
"green",
|
||||
)
|
||||
)
|
||||
@@ -148,7 +148,7 @@ def findAgents(api, return_dataframe):
|
||||
|
||||
|
||||
def collect_device_names() -> List[str]:
|
||||
print(colorText("🖥�� Device Search", "cyan"))
|
||||
print(colorText("🖥�� Device Search", "cyan"))
|
||||
print(
|
||||
colorText(
|
||||
"Enter the device hostnames you'd like to search for, one per line.", "cyan"
|
||||
@@ -185,7 +185,7 @@ def collect_device_names() -> List[str]:
|
||||
else:
|
||||
print(
|
||||
colorText(
|
||||
f"⚠️ Invalid input: '{stripped_line}' — only letters, numbers, underscores, spaces, and hyphens are allowed.",
|
||||
f"âš ï¸ Invalid input: '{stripped_line}' — only letters, numbers, underscores, spaces, and hyphens are allowed.",
|
||||
"yellow",
|
||||
)
|
||||
)
|
||||
@@ -235,8 +235,8 @@ def show_unmatched(
|
||||
]
|
||||
|
||||
if unmatched:
|
||||
logger.debug(f"⚠️ No matches for: {', '.join(unmatched)}")
|
||||
print(colorText(f"⚠️ No matches for: {', '.join(unmatched)}", "yellow"))
|
||||
logger.debug(f"âš ï¸ No matches for: {', '.join(unmatched)}")
|
||||
print(colorText(f"âš ï¸ No matches for: {', '.join(unmatched)}", "yellow"))
|
||||
|
||||
|
||||
def enrich_agents(agents: List["Agent"], policies: List["Policy"]):
|
||||
@@ -248,7 +248,7 @@ def selectAgents(api: "AirlockAPIWrapper") -> List["Agent"]:
|
||||
device_names = collect_device_names()
|
||||
if not device_names:
|
||||
logger.debug("No device names entered")
|
||||
print(colorText("⚠️ No device names entered.", "red"))
|
||||
print(colorText("âš ï¸ No device names entered.", "red"))
|
||||
return []
|
||||
|
||||
use_exact = choose_match_type()
|
||||
@@ -261,11 +261,11 @@ def selectAgents(api: "AirlockAPIWrapper") -> List["Agent"]:
|
||||
show_unmatched(device_names, matched_agents, use_exact)
|
||||
|
||||
if not matched_agents:
|
||||
logger.debug("❌ No matching devices found.")
|
||||
print(colorText("❌ No matching devices found.", "red"))
|
||||
logger.debug("⌠No matching devices found.")
|
||||
print(colorText("⌠No matching devices found.", "red"))
|
||||
return []
|
||||
|
||||
print(colorText(f"✓ Found {len(matched_agents)} matching device(s).", "green"))
|
||||
print(colorText(f"✓ Found {len(matched_agents)} matching device(s).", "green"))
|
||||
logger.info("Matched agent hostnames:")
|
||||
rows = (len(matched_agents) + 2) // 3 # 3 columns
|
||||
for row in range(rows):
|
||||
@@ -283,8 +283,8 @@ def selectAgents(api: "AirlockAPIWrapper") -> List["Agent"]:
|
||||
)
|
||||
|
||||
if not matched_agents:
|
||||
logger.debug("❌ No matching devices remain after refinement.")
|
||||
print(colorText("❌ No matching devices remain after refinement.", "red"))
|
||||
logger.debug("⌠No matching devices remain after refinement.")
|
||||
print(colorText("⌠No matching devices remain after refinement.", "red"))
|
||||
return []
|
||||
|
||||
enrich_agents(matched_agents, policies)
|
||||
@@ -302,7 +302,7 @@ def moveAgentToRelatedPolicy(
|
||||
Args:
|
||||
api: AirlockAPIWrapper instance.
|
||||
agent: Agent object.
|
||||
policy_relationship_map: Dict mapping enforcement â–€ –€™ audit.
|
||||
policy_relationship_map: Dict mapping enforcement â–€ –€™ audit.
|
||||
mode: 'audit' to move to audit, 'enforcement' to move to enforcement.
|
||||
"""
|
||||
policy_relationship_map = get_system_json("POLICY_MAP_ENF_AUD", "{}")
|
||||
|
||||
Reference in New Issue
Block a user