diff --git a/README.md b/README.md
index 6963121ac..67fcb3efe 100644
--- a/README.md
+++ b/README.md
@@ -35,6 +35,11 @@ A built-in importer handles the move off Jira.
It ships as a single Go binary with the Svelte frontend built in, SQLite by default or PostgreSQL for data storage. No Java, no Elasticsearch cluster, no per-user pricing, and your data stays on your infrastructure.
+## Operator controls
+
+Deployment owners can apply immutable [operator controls](internal/operatorcontrols/README.md)
+without changing organization preferences or maintaining a separate application fork.
+
## Agents and automation
Windshift runs coding agents against your repositories. Agent Studio binds an agent to a workspace, launches it from a work item, and links the resulting pull request back to that item. Source control integrations cover GitHub, GitLab, Gitea, and Forgejo.
diff --git a/api/openapi-v2.json b/api/openapi-v2.json
index 10e999a3f..1deb43132 100644
--- a/api/openapi-v2.json
+++ b/api/openapi-v2.json
@@ -28079,6 +28079,165 @@
},
"type": "object"
},
+ "GetOperatorControlsResult": {
+ "additionalProperties": false,
+ "properties": {
+ "data": {
+ "additionalProperties": false,
+ "properties": {
+ "blocked_definitions": {
+ "description": "The blocked definitions value.",
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "description": "The id value.",
+ "type": "integer"
+ },
+ "kind": {
+ "description": "The kind value.",
+ "type": "string"
+ },
+ "name": {
+ "description": "The name value.",
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "kind",
+ "name"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "blocked_definitions_truncated": {
+ "description": "The blocked definitions truncated value.",
+ "type": "boolean"
+ },
+ "policy": {
+ "additionalProperties": false,
+ "description": "The policy value.",
+ "properties": {
+ "ai_denied_features": {
+ "description": "The ai denied features value.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "ai_max_output_tokens": {
+ "description": "The ai max output tokens value.",
+ "type": "integer"
+ },
+ "ai_models": {
+ "description": "The ai models value.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "deny": {
+ "description": "The deny value.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "import_admission_required": {
+ "description": "The import admission required value.",
+ "type": "boolean"
+ },
+ "limits": {
+ "additionalProperties": false,
+ "description": "The limits value.",
+ "properties": {
+ "ai_tokens_per_day": {
+ "description": "The ai tokens per day value.",
+ "type": "integer"
+ },
+ "attachment_bytes": {
+ "description": "The attachment bytes value.",
+ "type": "integer"
+ },
+ "automation_steps_per_day": {
+ "description": "The automation steps per day value.",
+ "type": "integer"
+ },
+ "blob_bytes": {
+ "description": "The blob bytes value.",
+ "type": "integer"
+ },
+ "concurrent_ai": {
+ "description": "The concurrent ai value.",
+ "type": "integer"
+ },
+ "concurrent_requests": {
+ "description": "The concurrent requests value.",
+ "type": "integer"
+ },
+ "concurrent_scripts": {
+ "description": "The concurrent scripts value.",
+ "type": "integer"
+ },
+ "concurrent_streams": {
+ "description": "The concurrent streams value.",
+ "type": "integer"
+ },
+ "mail_recipients_per_day": {
+ "description": "The mail recipients per day value.",
+ "type": "integer"
+ },
+ "requests_per_minute": {
+ "description": "The requests per minute value.",
+ "type": "integer"
+ },
+ "script_timeout_ms": {
+ "description": "The script timeout ms value.",
+ "type": "integer"
+ }
+ },
+ "type": "object"
+ },
+ "mail_mode": {
+ "description": "The mail mode value.",
+ "type": "string"
+ },
+ "mail_suspended": {
+ "description": "The mail suspended value.",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "deny",
+ "import_admission_required",
+ "limits"
+ ],
+ "type": "object"
+ },
+ "usage": {
+ "additionalProperties": {
+ "type": "integer"
+ },
+ "description": "The usage value.",
+ "type": "object"
+ }
+ },
+ "required": [
+ "blocked_definitions",
+ "blocked_definitions_truncated",
+ "policy",
+ "usage"
+ ],
+ "type": "object"
+ }
+ },
+ "required": [
+ "data"
+ ],
+ "type": "object"
+ },
"GetPacksResult": {
"additionalProperties": false,
"properties": {
@@ -118452,6 +118611,59 @@
]
}
},
+ "/operator-controls": {
+ "get": {
+ "description": "Read effective operator restrictions, current instance usage and blocked script definitions. Requires system administrator permission and admin:operator-controls:read for bearer tokens. Credentials and deployment paths are never returned. This read-only operation cannot modify operator policy.",
+ "operationId": "getOperatorControls",
+ "parameters": [],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GetOperatorControlsResult"
+ }
+ }
+ },
+ "description": "Read operator controls response."
+ },
+ "401": {
+ "$ref": "#/components/responses/AuthenticationError"
+ },
+ "403": {
+ "$ref": "#/components/responses/PermissionError"
+ },
+ "429": {
+ "$ref": "#/components/responses/RateLimitError"
+ },
+ "500": {
+ "$ref": "#/components/responses/InternalError"
+ },
+ "503": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorDocument"
+ }
+ }
+ },
+ "description": "Service Unavailable."
+ }
+ },
+ "security": [
+ {
+ "BearerAuth": []
+ }
+ ],
+ "summary": "Read operator controls",
+ "tags": [
+ "Administration"
+ ],
+ "x-required-scopes": [
+ "admin:operator-controls:read"
+ ]
+ }
+ },
"/packs": {
"get": {
"description": "List built-in framework packs. Results include only resources visible to the authenticated caller; collections use their documented stable order and bounds.",
diff --git a/frontend/src/lib/admin/adminComponentRoutes.js b/frontend/src/lib/admin/adminComponentRoutes.js
index ad7b1c6da..b9a269e8b 100644
--- a/frontend/src/lib/admin/adminComponentRoutes.js
+++ b/frontend/src/lib/admin/adminComponentRoutes.js
@@ -2,6 +2,7 @@
// when its route is active.
export const ADMIN_COMPONENT_LOADERS = {
general: () => import('../settings/GeneralSettings.svelte'),
+ 'operator-controls': () => import('../settings/OperatorControls.svelte'),
'custom-fields': () => import('../settings/CustomFields.svelte'),
workspaces: () => import('../workspaces/Workspaces.svelte'),
screens: () => import('../pages/Screens.svelte'),
diff --git a/frontend/src/lib/admin/adminNavigation.js b/frontend/src/lib/admin/adminNavigation.js
index 4e0b22c79..0a70601ee 100644
--- a/frontend/src/lib/admin/adminNavigation.js
+++ b/frontend/src/lib/admin/adminNavigation.js
@@ -65,6 +65,14 @@ export const adminGroups = [
icon: IconSettings,
descriptionKey: 'settings.adminItems.general.description',
},
+ {
+ id: 'operator-controls',
+ labelKey: 'operatorControls.title',
+ labelFallback: 'Operator controls',
+ icon: IconShield,
+ descriptionKey: 'operatorControls.description',
+ descriptionFallback: 'Read-only deployment restrictions and instance allowances.',
+ },
],
},
{
diff --git a/frontend/src/lib/locales/de/admin.js b/frontend/src/lib/locales/de/admin.js
index d73d58401..0ab9d13e7 100644
--- a/frontend/src/lib/locales/de/admin.js
+++ b/frontend/src/lib/locales/de/admin.js
@@ -3,6 +3,36 @@
* Includes: settings, roles, permissions
*/
export default {
+ operatorControls: {
+ title: 'Betreiberkontrollen',
+ description: 'Diese Bereitstellungsvorgaben sind schreibgeschützt. Änderungen an Einschränkungen oder Kontingenten nimmt der Instanzbetreiber vor. Organisationseinstellungen dürfen strenger sein, diese Obergrenzen aber nicht überschreiten.',
+ restricted: 'Diese Funktion wird vom Instanzbetreiber verwaltet.',
+ restrictions: 'Eingeschränkte Funktionen',
+ unrestricted: 'Keine zusätzlichen Funktionseinschränkungen.',
+ limits: 'Obergrenzen der Instanz',
+ usage: 'Verbrauch im aktuellen Zeitraum',
+ blockedDefinitions: 'Durch Betreiberkontrollen gesperrte Definitionen',
+ loadFailed: 'Betreiberkontrollen konnten nicht geladen werden.',
+ mailMode: 'E-Mail-Versandmodus',
+ importAdmission: 'Massenimporte benötigen eine Betreiberfreigabe.',
+ models: 'Verfügbare KI-Modelle',
+ truncated: 'Die ersten 1.000 gesperrten Definitionen werden angezeigt.',
+ labels: {
+ instance_lifecycle: 'Instanzlebenszyklus', maintenance: 'Wartungsvorgänge',
+ runtime_diagnostics: 'Laufzeitdiagnose', plugin_exec: 'Plugin-Befehlsausführung',
+ ldap: 'LDAP', server_scripts: 'Serverskripte', imports: 'Massenimporte',
+ mail_transport_management: 'E-Mail-Transportverwaltung', generic_mail: 'Generisches SMTP und IMAP',
+ mail: 'E-Mail-Versand', ai: 'KI-Generierung', ai_connection_management: 'KI-Verbindungsverwaltung',
+ attachment_bytes: 'Maximale Objektgröße (Bytes)', blob_bytes: 'Blob-Speicherkontingent (Bytes)',
+ concurrent_requests: 'Gleichzeitige Anfragen', concurrent_streams: 'Gleichzeitige Streams',
+ requests_per_minute: 'Anfragen pro Minute', script_timeout_ms: 'Skriptzeitlimit (Millisekunden)',
+ concurrent_scripts: 'Gleichzeitige Skripte', automation_steps_per_day: 'Automatisierungsschritte pro UTC-Tag',
+ mail_recipients_per_day: 'E-Mail-Empfängerversuche pro UTC-Tag', ai_tokens_per_day: 'KI-Token-Kontingent pro UTC-Tag',
+ concurrent_ai: 'Gleichzeitige KI-Aufrufe', requests: 'Anfrageversuche in dieser Minute',
+ automation_steps: 'Automatisierungsschritte heute', mail_recipients: 'E-Mail-Empfängerversuche heute',
+ ai_tokens: 'Heute angerechnete KI-Token',
+ },
+ },
settings: {
title: 'Einstellungen',
subtitle: 'Ihre Anwendungseinstellungen konfigurieren',
diff --git a/frontend/src/lib/locales/en/admin.js b/frontend/src/lib/locales/en/admin.js
index 18796b487..cce284b3d 100644
--- a/frontend/src/lib/locales/en/admin.js
+++ b/frontend/src/lib/locales/en/admin.js
@@ -4,6 +4,50 @@
*/
export default {
+ operatorControls: {
+ title: 'Operator controls',
+ description: 'These deployment controls are read-only. Contact the instance operator to change restrictions or allowances. Organization preferences can be more restrictive, but cannot exceed these ceilings.',
+ restricted: 'This capability is managed by the instance operator.',
+ restrictions: 'Restricted capabilities',
+ unrestricted: 'No additional capability restrictions.',
+ limits: 'Instance ceilings',
+ usage: 'Current interval usage',
+ blockedDefinitions: 'Definitions blocked by operator controls',
+ loadFailed: 'Could not load operator controls.',
+ mailMode: 'Mail delivery mode',
+ importAdmission: 'Bulk imports require operator admission.',
+ models: 'Available AI models',
+ truncated: 'The first 1,000 blocked definitions are shown.',
+ labels: {
+ instance_lifecycle: 'Instance lifecycle',
+ maintenance: 'Maintenance operations',
+ runtime_diagnostics: 'Runtime diagnostics',
+ plugin_exec: 'Plugin command execution',
+ ldap: 'LDAP',
+ server_scripts: 'Server scripts',
+ imports: 'Bulk imports',
+ mail_transport_management: 'Mail transport management',
+ generic_mail: 'Generic SMTP and IMAP',
+ mail: 'Mail delivery',
+ ai: 'AI generation',
+ ai_connection_management: 'AI connection management',
+ attachment_bytes: 'Maximum object size (bytes)',
+ blob_bytes: 'Blob storage allowance (bytes)',
+ concurrent_requests: 'Concurrent requests',
+ concurrent_streams: 'Concurrent streams',
+ requests_per_minute: 'Requests per minute',
+ script_timeout_ms: 'Script timeout (milliseconds)',
+ concurrent_scripts: 'Concurrent scripts',
+ automation_steps_per_day: 'Automation steps per UTC day',
+ mail_recipients_per_day: 'Mail recipient attempts per UTC day',
+ ai_tokens_per_day: 'AI token allowance per UTC day',
+ concurrent_ai: 'Concurrent AI calls',
+ requests: 'Request attempts this minute',
+ automation_steps: 'Automation steps today',
+ mail_recipients: 'Mail recipient attempts today',
+ ai_tokens: 'AI tokens charged today',
+ },
+ },
// Settings (merged from general and detailed settings sections)
settings: {
title: 'Settings',
diff --git a/frontend/src/lib/locales/fa/admin.js b/frontend/src/lib/locales/fa/admin.js
index b5a5fd4c5..da86749f1 100644
--- a/frontend/src/lib/locales/fa/admin.js
+++ b/frontend/src/lib/locales/fa/admin.js
@@ -1,4 +1,27 @@
export default {
+ "operatorControls": {
+ "title": "کنترلهای اپراتور",
+ "description": "این قوانین استقرار فقط خواندنی هستند. برای تغییر محدودیتها یا سهمیهها با اپراتور نمونه تماس بگیرید. تنظیمات سازمان میتوانند سختگیرانهتر باشند، اما نباید از این سقفها فراتر بروند.",
+ "restricted": "این قابلیت توسط اپراتور نمونه مدیریت میشود.",
+ "restrictions": "قابلیتهای محدودشده", "unrestricted": "محدودیت اضافی برای قابلیتها وجود ندارد.",
+ "limits": "سقفهای نمونه", "usage": "مصرف دوره فعلی", "blockedDefinitions": "تعریفهای مسدودشده توسط کنترلهای اپراتور",
+ "loadFailed": "بارگیری کنترلهای اپراتور ممکن نشد.", "mailMode": "حالت ارسال ایمیل",
+ "importAdmission": "واردسازی انبوه به مجوز اپراتور نیاز دارد.", "models": "مدلهای هوش مصنوعی موجود",
+ "truncated": "۱۰۰۰ تعریف مسدودشده اول نمایش داده میشود.",
+ "labels": {
+ "instance_lifecycle": "چرخه حیات نمونه", "maintenance": "عملیات نگهداری", "runtime_diagnostics": "عیبیابی زمان اجرا",
+ "plugin_exec": "اجرای فرمان افزونه", "ldap": "LDAP", "server_scripts": "اسکریپتهای سرور", "imports": "واردسازی انبوه",
+ "mail_transport_management": "مدیریت انتقال ایمیل", "generic_mail": "SMTP و IMAP عمومی", "mail": "ارسال ایمیل",
+ "ai": "تولید با هوش مصنوعی", "ai_connection_management": "مدیریت اتصالهای هوش مصنوعی",
+ "attachment_bytes": "حداکثر اندازه شیء (بایت)", "blob_bytes": "سهمیه فضای ذخیرهسازی اشیاء (بایت)",
+ "concurrent_requests": "درخواستهای همزمان", "concurrent_streams": "جریانهای همزمان", "requests_per_minute": "درخواست در دقیقه",
+ "script_timeout_ms": "مهلت اسکریپت (میلیثانیه)", "concurrent_scripts": "اسکریپتهای همزمان",
+ "automation_steps_per_day": "گامهای خودکارسازی در هر روز UTC", "mail_recipients_per_day": "تلاشهای ارسال به گیرندگان در هر روز UTC",
+ "ai_tokens_per_day": "سهمیه توکن هوش مصنوعی در هر روز UTC", "concurrent_ai": "فراخوانیهای همزمان هوش مصنوعی",
+ "requests": "تلاشهای درخواست در این دقیقه", "automation_steps": "گامهای خودکارسازی امروز",
+ "mail_recipients": "تلاشهای ارسال به گیرندگان امروز", "ai_tokens": "توکنهای هوش مصنوعی محاسبهشده امروز"
+ }
+ },
"settings": {
"title": "تنظیمات",
"subtitle": "تنظیمات برنامه خود را پیکربندی کنید",
diff --git a/frontend/src/lib/locales/fr/admin.js b/frontend/src/lib/locales/fr/admin.js
index 7b16cedce..a0a4f1923 100644
--- a/frontend/src/lib/locales/fr/admin.js
+++ b/frontend/src/lib/locales/fr/admin.js
@@ -4,6 +4,32 @@
*/
export default {
+ operatorControls: {
+ title: 'Contrôles de l’exploitant',
+ description: 'Ces règles de déploiement sont en lecture seule. Contactez l’exploitant de l’instance pour modifier les restrictions ou les quotas. Les préférences de l’organisation peuvent être plus strictes, mais ne peuvent pas dépasser ces plafonds.',
+ restricted: 'Cette fonctionnalité est gérée par l’exploitant de l’instance.',
+ restrictions: 'Fonctionnalités restreintes', unrestricted: 'Aucune restriction supplémentaire des fonctionnalités.',
+ limits: 'Plafonds de l’instance', usage: 'Utilisation sur la période actuelle',
+ blockedDefinitions: 'Définitions bloquées par les contrôles de l’exploitant',
+ loadFailed: 'Impossible de charger les contrôles de l’exploitant.', mailMode: 'Mode d’envoi des e-mails',
+ importAdmission: 'Les imports en masse nécessitent l’autorisation de l’exploitant.',
+ models: 'Modèles d’IA disponibles', truncated: 'Les 1 000 premières définitions bloquées sont affichées.',
+ labels: {
+ instance_lifecycle: 'Cycle de vie de l’instance', maintenance: 'Opérations de maintenance',
+ runtime_diagnostics: 'Diagnostics d’exécution', plugin_exec: 'Exécution de commandes par les extensions',
+ ldap: 'LDAP', server_scripts: 'Scripts serveur', imports: 'Imports en masse',
+ mail_transport_management: 'Gestion du transport des e-mails', generic_mail: 'SMTP et IMAP génériques',
+ mail: 'Envoi des e-mails', ai: 'Génération par IA', ai_connection_management: 'Gestion des connexions IA',
+ attachment_bytes: 'Taille maximale d’un objet (octets)', blob_bytes: 'Quota de stockage des objets (octets)',
+ concurrent_requests: 'Requêtes simultanées', concurrent_streams: 'Flux simultanés',
+ requests_per_minute: 'Requêtes par minute', script_timeout_ms: 'Délai maximal des scripts (millisecondes)',
+ concurrent_scripts: 'Scripts simultanés', automation_steps_per_day: 'Étapes d’automatisation par jour UTC',
+ mail_recipients_per_day: 'Tentatives par destinataire d’e-mail par jour UTC', ai_tokens_per_day: 'Quota de jetons IA par jour UTC',
+ concurrent_ai: 'Appels IA simultanés', requests: 'Tentatives de requêtes cette minute',
+ automation_steps: 'Étapes d’automatisation aujourd’hui', mail_recipients: 'Tentatives par destinataire d’e-mail aujourd’hui',
+ ai_tokens: 'Jetons IA comptabilisés aujourd’hui',
+ },
+ },
// Settings (merged from general and detailed settings sections)
settings: {
title: 'Paramètres',
diff --git a/frontend/src/lib/locales/pl/admin.js b/frontend/src/lib/locales/pl/admin.js
index fc55c4b97..643c1aa98 100644
--- a/frontend/src/lib/locales/pl/admin.js
+++ b/frontend/src/lib/locales/pl/admin.js
@@ -4,6 +4,32 @@
*/
export default {
+ operatorControls: {
+ title: 'Kontrole operatora',
+ description: 'Te zasady wdrożenia są tylko do odczytu. Aby zmienić ograniczenia lub przydziały, skontaktuj się z operatorem instancji. Preferencje organizacji mogą być bardziej restrykcyjne, ale nie mogą przekraczać tych limitów.',
+ restricted: 'Tą funkcją zarządza operator instancji.',
+ restrictions: 'Ograniczone funkcje', unrestricted: 'Brak dodatkowych ograniczeń funkcji.',
+ limits: 'Limity instancji', usage: 'Wykorzystanie w bieżącym okresie',
+ blockedDefinitions: 'Definicje zablokowane przez kontrole operatora',
+ loadFailed: 'Nie udało się wczytać kontroli operatora.', mailMode: 'Tryb dostarczania poczty',
+ importAdmission: 'Importy zbiorcze wymagają zgody operatora.',
+ models: 'Dostępne modele AI', truncated: 'Wyświetlono pierwsze 1000 zablokowanych definicji.',
+ labels: {
+ instance_lifecycle: 'Cykl życia instancji', maintenance: 'Operacje konserwacyjne',
+ runtime_diagnostics: 'Diagnostyka wykonania', plugin_exec: 'Wykonywanie poleceń wtyczek',
+ ldap: 'LDAP', server_scripts: 'Skrypty serwerowe', imports: 'Importy zbiorcze',
+ mail_transport_management: 'Zarządzanie transportem poczty', generic_mail: 'Ogólne SMTP i IMAP',
+ mail: 'Dostarczanie poczty', ai: 'Generowanie AI', ai_connection_management: 'Zarządzanie połączeniami AI',
+ attachment_bytes: 'Maksymalny rozmiar obiektu (bajty)', blob_bytes: 'Przydział miejsca na obiekty (bajty)',
+ concurrent_requests: 'Równoczesne żądania', concurrent_streams: 'Równoczesne strumienie',
+ requests_per_minute: 'Żądania na minutę', script_timeout_ms: 'Limit czasu skryptu (milisekundy)',
+ concurrent_scripts: 'Równoczesne skrypty', automation_steps_per_day: 'Kroki automatyzacji na dzień UTC',
+ mail_recipients_per_day: 'Próby wysyłki do odbiorców na dzień UTC', ai_tokens_per_day: 'Przydział tokenów AI na dzień UTC',
+ concurrent_ai: 'Równoczesne wywołania AI', requests: 'Próby żądań w tej minucie',
+ automation_steps: 'Dzisiejsze kroki automatyzacji', mail_recipients: 'Dzisiejsze próby wysyłki do odbiorców',
+ ai_tokens: 'Tokeny AI naliczone dzisiaj',
+ },
+ },
// Ustawienia (połączone z sekcji ustawień ogólnych i szczegółowych)
settings: {
title: 'Ustawienia',
diff --git a/frontend/src/lib/locales/ru/admin.js b/frontend/src/lib/locales/ru/admin.js
index 7e70a8153..db786aaf3 100644
--- a/frontend/src/lib/locales/ru/admin.js
+++ b/frontend/src/lib/locales/ru/admin.js
@@ -4,6 +4,32 @@
*/
export default {
+ operatorControls: {
+ title: 'Ограничения оператора',
+ description: 'Эти правила развёртывания доступны только для чтения. Для изменения ограничений или квот обратитесь к оператору экземпляра. Настройки организации могут быть строже, но не могут превышать эти пределы.',
+ restricted: 'Этой возможностью управляет оператор экземпляра.',
+ restrictions: 'Ограниченные возможности', unrestricted: 'Дополнительных ограничений возможностей нет.',
+ limits: 'Пределы экземпляра', usage: 'Использование за текущий период',
+ blockedDefinitions: 'Определения, заблокированные ограничениями оператора',
+ loadFailed: 'Не удалось загрузить ограничения оператора.', mailMode: 'Режим отправки почты',
+ importAdmission: 'Массовый импорт требует разрешения оператора.',
+ models: 'Доступные модели ИИ', truncated: 'Показаны первые 1000 заблокированных определений.',
+ labels: {
+ instance_lifecycle: 'Жизненный цикл экземпляра', maintenance: 'Операции обслуживания',
+ runtime_diagnostics: 'Диагностика выполнения', plugin_exec: 'Выполнение команд плагинов',
+ ldap: 'LDAP', server_scripts: 'Серверные скрипты', imports: 'Массовый импорт',
+ mail_transport_management: 'Управление почтовым транспортом', generic_mail: 'Обычные SMTP и IMAP',
+ mail: 'Отправка почты', ai: 'Генерация с ИИ', ai_connection_management: 'Управление подключениями ИИ',
+ attachment_bytes: 'Максимальный размер объекта (байты)', blob_bytes: 'Квота хранилища объектов (байты)',
+ concurrent_requests: 'Одновременные запросы', concurrent_streams: 'Одновременные потоки',
+ requests_per_minute: 'Запросов в минуту', script_timeout_ms: 'Время выполнения скрипта (миллисекунды)',
+ concurrent_scripts: 'Одновременные скрипты', automation_steps_per_day: 'Шагов автоматизации за сутки UTC',
+ mail_recipients_per_day: 'Попыток отправки получателям за сутки UTC', ai_tokens_per_day: 'Квота токенов ИИ за сутки UTC',
+ concurrent_ai: 'Одновременные вызовы ИИ', requests: 'Попытки запросов за текущую минуту',
+ automation_steps: 'Шаги автоматизации сегодня', mail_recipients: 'Попытки отправки получателям сегодня',
+ ai_tokens: 'Токены ИИ, учтённые сегодня',
+ },
+ },
settings: {
title: 'Настройки',
subtitle: 'Настройте параметры приложения',
diff --git a/frontend/src/lib/locales/zh-CN/admin.js b/frontend/src/lib/locales/zh-CN/admin.js
index 750b9a09b..c12743558 100644
--- a/frontend/src/lib/locales/zh-CN/admin.js
+++ b/frontend/src/lib/locales/zh-CN/admin.js
@@ -1,4 +1,23 @@
export default {
+ operatorControls: {
+ title: '运营方控制',
+ description: '这些部署规则为只读。请联系实例运营方更改限制或配额。组织偏好可以更加严格,但不能超过这些上限。',
+ restricted: '此功能由实例运营方管理。', restrictions: '受限功能', unrestricted: '没有额外的功能限制。',
+ limits: '实例上限', usage: '当前周期用量', blockedDefinitions: '被运营方控制阻止的定义',
+ loadFailed: '无法加载运营方控制。', mailMode: '邮件发送模式',
+ importAdmission: '批量导入需要运营方准入许可。', models: '可用的 AI 模型', truncated: '显示前 1,000 个被阻止的定义。',
+ labels: {
+ instance_lifecycle: '实例生命周期', maintenance: '维护操作', runtime_diagnostics: '运行时诊断',
+ plugin_exec: '插件命令执行', ldap: 'LDAP', server_scripts: '服务器脚本', imports: '批量导入',
+ mail_transport_management: '邮件传输管理', generic_mail: '通用 SMTP 和 IMAP', mail: '邮件发送',
+ ai: 'AI 生成', ai_connection_management: 'AI 连接管理', attachment_bytes: '最大对象大小(字节)',
+ blob_bytes: '对象存储配额(字节)', concurrent_requests: '并发请求数', concurrent_streams: '并发流数',
+ requests_per_minute: '每分钟请求数', script_timeout_ms: '脚本超时(毫秒)', concurrent_scripts: '并发脚本数',
+ automation_steps_per_day: '每个 UTC 日的自动化步骤数', mail_recipients_per_day: '每个 UTC 日的收件人发送尝试数',
+ ai_tokens_per_day: '每个 UTC 日的 AI 令牌配额', concurrent_ai: '并发 AI 调用数', requests: '本分钟的请求尝试数',
+ automation_steps: '今日自动化步骤数', mail_recipients: '今日收件人发送尝试数', ai_tokens: '今日计入用量的 AI 令牌数',
+ },
+ },
settings: {
title: '设置',
subtitle: '配置应用程序设置',
diff --git a/frontend/src/lib/pages/Admin.svelte b/frontend/src/lib/pages/Admin.svelte
index ff6427494..803e88882 100644
--- a/frontend/src/lib/pages/Admin.svelte
+++ b/frontend/src/lib/pages/Admin.svelte
@@ -24,6 +24,8 @@
import { resolveAdminGroups } from '../admin/adminNavigation.js';
import { isTypingInField } from '../utils/keyboardShortcuts.js';
import { isSystemAdmin } from '../stores/permissions.svelte.js';
+ import { capabilitiesStore } from '../stores/capabilities.svelte.js';
+ import AlertBox from '../components/AlertBox.svelte';
const ADMIN_DETAIL_ROUTES = [
{ prefix: '/admin/permission-sets/', tabId: 'permissions', componentKey: 'permission-set-detail' },
@@ -285,11 +287,15 @@
{#snippet activeAdminComponent()}
{#key adminComponentKey}
+ {#if adminComponentKey === 'system-import' && !capabilitiesStore.operatorAllows('imports')}
+
+ {:else}
+ {/if}
{/key}
{/snippet}
diff --git a/frontend/src/lib/settings/AIContainer.svelte b/frontend/src/lib/settings/AIContainer.svelte
index 0d1392720..1984f9299 100644
--- a/frontend/src/lib/settings/AIContainer.svelte
+++ b/frontend/src/lib/settings/AIContainer.svelte
@@ -6,6 +6,8 @@
import AgentTemplateManager from './AgentTemplateManager.svelte';
import WorkItemStalenessSettings from './WorkItemStalenessSettings.svelte';
import { t } from '../stores/i18n.svelte.js';
+ import { capabilitiesStore } from '../stores/capabilities.svelte.js';
+ import AlertBox from '../components/AlertBox.svelte';
let subtab = $derived($currentRoute.query?.subtab || 'connections');
@@ -28,7 +30,11 @@
{:else if subtab === 'staleness'}
{:else}
-
+ {#if capabilitiesStore.operatorAllows('ai_connection_management')}
+
+ {:else}
+
+ {/if}
{/if}
diff --git a/frontend/src/lib/settings/Diagnostics.svelte b/frontend/src/lib/settings/Diagnostics.svelte
index af12b763e..34ecc1df8 100644
--- a/frontend/src/lib/settings/Diagnostics.svelte
+++ b/frontend/src/lib/settings/Diagnostics.svelte
@@ -17,6 +17,10 @@
import SCMHealthSection from './diagnostics/SCMHealthSection.svelte';
import EmailIntakeSection from './diagnostics/EmailIntakeSection.svelte';
import { t } from '../stores/i18n.svelte.js';
+ import { capabilitiesStore } from '../stores/capabilities.svelte.js';
+ import AlertBox from '../components/AlertBox.svelte';
+
+ const runtimeTabs = new Set(['schedulers', 'domain-events', 'frac-index', 'runner-pools', 'database-pools', 'cache-memory']);
let diagnosticGroups = $derived([
{ label: t('diagnostics.groups.overview'), tabs: [{ id: 'clock', label: t('diagnostics.tabs.clock') }] },
@@ -51,6 +55,7 @@
})));
const subtab = $derived($currentRoute.query?.subtab || 'clock');
+ const runtimeRestricted = $derived(runtimeTabs.has(subtab) && !capabilitiesStore.operatorAllows('runtime_diagnostics'));
const activeGroup = $derived(
diagnosticGroups.find((group) => group.tabs.some((tab) => tab.id === subtab)) ?? diagnosticGroups[0]
);
@@ -70,7 +75,9 @@
{/if}
- {#if subtab === 'clock'}
+ {#if runtimeRestricted}
+
+ {:else if subtab === 'clock'}
{:else if subtab === 'actions'}
diff --git a/frontend/src/lib/settings/OperatorControls.svelte b/frontend/src/lib/settings/OperatorControls.svelte
new file mode 100644
index 000000000..a5a267abf
--- /dev/null
+++ b/frontend/src/lib/settings/OperatorControls.svelte
@@ -0,0 +1,97 @@
+
+
+
+
+
+ {#if loading}
+
+ {:else if error}
+
+ {:else}
+
+ {t('operatorControls.restrictions', 'Restricted capabilities')}
+ {#if status?.policy?.deny?.length}
+
+ {#each status.policy.deny as capability}
+ - {label(capability)}
+ {/each}
+
+ {:else}
+ {t('operatorControls.unrestricted', 'No additional capability restrictions.')}
+ {/if}
+ {#if status?.policy?.mail_mode}
+ {t('operatorControls.mailMode', 'Mail delivery mode')}: {status.policy.mail_mode}
+ {/if}
+ {#if status?.policy?.import_admission_required}
+ {t('operatorControls.importAdmission', 'Bulk imports require operator admission.')}
+ {/if}
+ {#if status?.policy?.ai_models?.length}
+ {t('operatorControls.models', 'Available AI models')}: {status.policy.ai_models.join(', ')}
+ {/if}
+
+
+ {t('operatorControls.limits', 'Instance ceilings')}
+
+ {#each limits as [name, value]}
+ - {label(name)}
- {value.toLocaleString()}
+ {/each}
+
+
+
+ {t('operatorControls.usage', 'Current interval usage')}
+
+ {#each Object.entries(status?.usage || {}) as [name, value]}
+ - {label(name)}
- {Number(value).toLocaleString()}
+ {/each}
+
+
+ {#if status?.blocked_definitions?.length}
+
+ {t('operatorControls.blockedDefinitions', 'Definitions blocked by operator controls')}
+
+ {#each status.blocked_definitions as definition}
+ -
+ {#if definition.kind === 'condition_set'}
+ {definition.name}
+ {:else}
+ {definition.name} ({definition.kind} #{definition.id})
+ {/if}
+
+ {/each}
+
+ {#if status.blocked_definitions_truncated}
+ {t('operatorControls.truncated', 'The first 1,000 blocked definitions are shown.')}
+ {/if}
+
+ {/if}
+ {/if}
+
diff --git a/frontend/src/lib/settings/SecuritySettings.svelte b/frontend/src/lib/settings/SecuritySettings.svelte
index 956f6f8e8..6768b4eb6 100644
--- a/frontend/src/lib/settings/SecuritySettings.svelte
+++ b/frontend/src/lib/settings/SecuritySettings.svelte
@@ -25,6 +25,7 @@
import { errorToast } from '../stores/toasts.svelte.js';
import PageHeader from '../layout/PageHeader.svelte';
import DescriptionText from '../components/DescriptionText.svelte';
+ import { capabilitiesStore } from '../stores/capabilities.svelte.js';
let loading = $state(true);
let saving = $state(false);
@@ -372,7 +373,8 @@
@@ -382,6 +384,9 @@
{/if}
+ {#if !capabilitiesStore.operatorAllows('plugin_exec')}
+
+ {/if}
diff --git a/frontend/src/lib/stores/capabilities.svelte.js b/frontend/src/lib/stores/capabilities.svelte.js
index b63922af7..ce9ed3aed 100644
--- a/frontend/src/lib/stores/capabilities.svelte.js
+++ b/frontend/src/lib/stores/capabilities.svelte.js
@@ -1,12 +1,10 @@
-/**
- * Store for tracking plugin capabilities.
- * Capabilities are loaded from /api/features and used to gate UI features.
- */
+/** Effective plugin capabilities and read-only deployment restrictions. */
class CapabilitiesStore {
/** @type {Set} */
capabilities = $state(new Set());
sshAvailable = $state(false);
+ operatorControls = $state(null);
loaded = $state(false);
#loadPromise = null;
#hydrationPromise = null;
@@ -16,6 +14,7 @@ class CapabilitiesStore {
if (!data) return;
this.capabilities = new Set(data.capabilities || []);
this.sshAvailable = data.ssh_available === true;
+ this.operatorControls = data.operator_controls || null;
this.loaded = true;
this.#finishHydration(true);
}
@@ -75,6 +74,7 @@ class CapabilitiesStore {
reset() {
this.capabilities = new Set();
this.sshAvailable = false;
+ this.operatorControls = null;
this.loaded = false;
this.#loadPromise = null;
this.#finishHydration(false);
@@ -88,6 +88,14 @@ class CapabilitiesStore {
has(name) {
return this.capabilities.has(name);
}
+
+ operatorAllows(name) {
+ if (name === 'mail' && this.operatorControls?.mail_suspended) return false;
+ if (name === 'mail' && this.operatorControls?.mail_mode === 'disabled') return false;
+ if (name === 'mail_transport_management' && this.operatorControls?.mail_mode === 'managed')
+ return false;
+ return !this.operatorControls?.deny?.includes(name);
+ }
}
export const capabilitiesStore = new CapabilitiesStore();
diff --git a/internal/auth/scopes.go b/internal/auth/scopes.go
index cd2bb22a3..984082edb 100644
--- a/internal/auth/scopes.go
+++ b/internal/auth/scopes.go
@@ -149,6 +149,7 @@ const (
// Admin scopes (require system admin role AND scope on token)
ScopeAdminUsersRead = "admin:users:read"
+ ScopeOperatorControlsRead = "admin:operator-controls:read"
ScopeAdminUsersWrite = "admin:users:write"
ScopeAdminGroupsRead = "admin:groups:read"
ScopeAdminGroupsWrite = "admin:groups:write"
@@ -269,6 +270,7 @@ var scopeCatalog = []ScopeInfo{
{Scope: ScopeMCPAccess, Resource: "mcp", ResourceLabel: "MCP server", Action: "access", Label: "Connect to the MCP server", Description: "Open the MCP transport. Each tool still requires the resource scopes above.", AgentDefault: true},
{Scope: ScopeAdminUsersRead, Resource: "admin:users", ResourceLabel: "Users (admin)", Action: "read", Label: "Read all users", Description: "Read every user account.", Admin: true},
+ {Scope: ScopeOperatorControlsRead, Resource: "admin:operator-controls", ResourceLabel: "Operator controls", Action: "read", Label: "Read operator controls", Description: "Read effective deployment restrictions and instance usage. Does not grant policy write access.", Admin: true},
{Scope: ScopeAdminUsersWrite, Resource: "admin:users", ResourceLabel: "Users (admin)", Action: "write", Label: "Manage all users", Description: "Create, update, and deactivate user accounts.", Admin: true},
{Scope: ScopeAdminGroupsRead, Resource: "admin:groups", ResourceLabel: "Groups (admin)", Action: "read", Label: "Read all groups", Description: "Read every group and its membership.", Admin: true},
{Scope: ScopeAdminGroupsWrite, Resource: "admin:groups", ResourceLabel: "Groups (admin)", Action: "write", Label: "Manage all groups", Description: "Create, update, and delete groups.", Admin: true},
diff --git a/internal/blobstore/blobstore.go b/internal/blobstore/blobstore.go
index 37a8ed38e..a3a5da267 100644
--- a/internal/blobstore/blobstore.go
+++ b/internal/blobstore/blobstore.go
@@ -16,6 +16,8 @@ import (
"path/filepath"
"sync"
"time"
+
+ "windshift/internal/operatorcontrols"
)
var (
@@ -45,11 +47,15 @@ type backend interface {
// all methods are nil-safe so callers can treat a missing store as "attachments
// are not enabled".
type Store struct {
- backend backend
- enabled bool
- local bool
- root string
- describe string
+ controls *operatorcontrols.Controls
+ quotaMu sync.Mutex
+ quotaKnown bool
+ quotaBytes int64
+ backend backend
+ enabled bool
+ local bool
+ root string
+ describe string
healthMu sync.Mutex
healthErr error
@@ -57,6 +63,13 @@ type Store struct {
healthTTL time.Duration
}
+// SetOperatorControls is called before the store is published to services.
+func (s *Store) SetOperatorControls(controls *operatorcontrols.Controls) {
+ if s != nil {
+ s.controls = controls
+ }
+}
+
const (
// defaultHealthCacheTTL keeps readiness ticks and status/bootstrap calls
// from issuing one object-store request per request handler.
@@ -143,6 +156,9 @@ func (s *Store) Put(ctx context.Context, storedPath string, r io.Reader, size in
}
ctx, cancel := withDefaultTimeout(ctx, 5*time.Minute)
defer cancel()
+ if limits := s.controls.Limits(); limits.AttachmentBytes > 0 || limits.BlobBytes > 0 {
+ return s.putLimited(ctx, storedPath, r, size, contentType)
+ }
return s.backend.put(ctx, storedPath, r, size, contentType)
}
@@ -161,6 +177,9 @@ func (s *Store) Remove(ctx context.Context, storedPath string) error {
}
ctx, cancel := withDefaultTimeout(ctx, time.Minute)
defer cancel()
+ if s.controls.Limits().BlobBytes > 0 {
+ return s.removeLimited(ctx, storedPath)
+ }
return s.backend.remove(ctx, storedPath)
}
diff --git a/internal/blobstore/quota.go b/internal/blobstore/quota.go
new file mode 100644
index 000000000..fbaa16d1b
--- /dev/null
+++ b/internal/blobstore/quota.go
@@ -0,0 +1,257 @@
+package blobstore
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "math"
+ "os"
+ "path/filepath"
+
+ "windshift/internal/operatorcontrols"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+)
+
+// Usage counts current physical objects, including staged and orphaned blobs.
+// One instance must exclusively own its root/prefix and be its only writer.
+type Usage struct {
+ Bytes int64 `json:"bytes"`
+ LimitBytes int64 `json:"limit_bytes"`
+ MaxFileBytes int64 `json:"max_file_bytes"`
+}
+
+func (s *Store) Usage(ctx context.Context) (Usage, error) {
+ if !s.Enabled() {
+ return Usage{}, nil
+ }
+ s.quotaMu.Lock()
+ defer s.quotaMu.Unlock()
+ if s.controls.Limits().BlobBytes == 0 {
+ s.quotaKnown = false
+ }
+ if err := s.loadQuota(ctx); err != nil {
+ return Usage{}, err
+ }
+ return Usage{Bytes: s.quotaBytes, LimitBytes: s.controls.Limits().BlobBytes, MaxFileBytes: s.controls.Limits().AttachmentBytes}, nil
+}
+
+func (s *Store) loadQuota(ctx context.Context) error {
+ if s.quotaKnown {
+ return nil
+ }
+ inventory, ok := s.backend.(interface {
+ usage(context.Context) (int64, error)
+ })
+ if !ok {
+ return errors.New("storage backend cannot account operator quota")
+ }
+ n, err := inventory.usage(ctx)
+ if err != nil {
+ return fmt.Errorf("reconcile blob usage: %w", err)
+ }
+ s.quotaBytes = n
+ s.quotaKnown = true
+ return nil
+}
+
+func (s *Store) objectSize(ctx context.Context, path string) (int64, error) {
+ object, err := s.backend.open(ctx, path)
+ if errors.Is(err, ErrNotFound) {
+ return 0, nil
+ }
+ if err != nil {
+ return 0, err
+ }
+ defer object.Close()
+ return object.Size(), nil
+}
+
+func (s *Store) putLimited(ctx context.Context, path string, r io.Reader, size int64, contentType string) error {
+ limits := s.controls.Limits()
+ if size < 0 || (limits.AttachmentBytes > 0 && size > limits.AttachmentBytes) {
+ return &operatorcontrols.LimitError{Resource: "attachment_bytes"}
+ }
+ reader, err := sizedReader(r, size)
+ if err != nil {
+ return err
+ }
+ s.quotaMu.Lock()
+ defer s.quotaMu.Unlock()
+ var oldSize int64
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if limits.BlobBytes > 0 {
+ if err := s.loadQuota(ctx); err != nil {
+ return err
+ }
+ oldSize, err = s.objectSize(ctx, path)
+ if err != nil {
+ return err
+ }
+ if size > oldSize && (s.quotaBytes > limits.BlobBytes || size-oldSize > limits.BlobBytes-s.quotaBytes) {
+ return &operatorcontrols.LimitError{Resource: "blob_bytes"}
+ }
+ }
+ bounded := io.Reader(&contextReader{ctx: ctx, reader: reader})
+ if seeker, ok := reader.(io.Seeker); ok {
+ bounded = &contextReadSeeker{contextReader: contextReader{ctx: ctx, reader: reader}, Seeker: seeker}
+ }
+ if err := s.backend.put(ctx, path, bounded, size, contentType); err != nil {
+ s.quotaKnown = false
+ return err
+ }
+ if limits.BlobBytes > 0 {
+ s.quotaBytes += size - oldSize
+ } else {
+ s.quotaKnown = false
+ }
+ return nil
+}
+
+type contextReader struct {
+ ctx context.Context
+ reader io.Reader
+}
+type contextReadSeeker struct {
+ contextReader
+ io.Seeker
+}
+
+func (r *contextReader) Read(p []byte) (int, error) {
+ if err := r.ctx.Err(); err != nil {
+ return 0, err
+ }
+ return r.reader.Read(p)
+}
+
+func (s *Store) removeLimited(ctx context.Context, path string) error {
+ s.quotaMu.Lock()
+ defer s.quotaMu.Unlock()
+ if err := s.loadQuota(ctx); err != nil {
+ return err
+ }
+ size, err := s.objectSize(ctx, path)
+ if err != nil {
+ return err
+ }
+ if err := s.backend.remove(ctx, path); err != nil {
+ s.quotaKnown = false
+ return err
+ }
+ s.quotaBytes -= size
+ if s.quotaBytes < 0 {
+ s.quotaKnown = false
+ }
+ return nil
+}
+
+func sizedReader(reader io.Reader, size int64) (io.Reader, error) {
+ if seeker, ok := reader.(io.Seeker); ok {
+ start, err := seeker.Seek(0, io.SeekCurrent)
+ if err != nil {
+ return nil, err
+ }
+ end, err := seeker.Seek(0, io.SeekEnd)
+ if err != nil {
+ return nil, err
+ }
+ if _, err := seeker.Seek(start, io.SeekStart); err != nil {
+ return nil, err
+ }
+ if end-start != size {
+ return nil, errors.New("blob size does not match content")
+ }
+ return reader, nil
+ }
+ return &exactReader{reader: reader, remaining: size}, nil
+}
+
+type exactReader struct {
+ reader io.Reader
+ remaining int64
+}
+
+func (r *exactReader) Read(p []byte) (int, error) {
+ if len(p) == 0 {
+ return 0, nil
+ }
+ if r.remaining == 0 {
+ var extra [1]byte
+ n, err := r.reader.Read(extra[:])
+ if n > 0 {
+ return 0, errors.New("blob exceeds declared size")
+ }
+ return 0, err
+ }
+ if int64(len(p)) > r.remaining {
+ p = p[:r.remaining]
+ }
+ n, err := r.reader.Read(p)
+ r.remaining -= int64(n)
+ if errors.Is(err, io.EOF) && r.remaining > 0 {
+ err = io.ErrUnexpectedEOF
+ }
+ return n, err
+}
+
+func (b *localBackend) usage(ctx context.Context) (int64, error) {
+ if _, err := os.Stat(b.root); errors.Is(err, os.ErrNotExist) {
+ return 0, nil
+ }
+ var total int64
+ err := filepath.WalkDir(b.root, func(_ string, entry fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if entry.Type()&os.ModeSymlink != 0 {
+ return ErrOutsideRoot
+ }
+ if entry.IsDir() {
+ return nil
+ }
+ info, err := entry.Info()
+ if err != nil {
+ return err
+ }
+ if !info.Mode().IsRegular() {
+ return errors.New("non-regular object in blob root")
+ }
+ if info.Size() > math.MaxInt64-total {
+ return errors.New("blob usage overflow")
+ }
+ total += info.Size()
+ return nil
+ })
+ return total, err
+}
+
+func (b *s3Backend) usage(ctx context.Context) (int64, error) {
+ prefix := b.prefix
+ if prefix != "" {
+ prefix += "/"
+ }
+ pages := s3.NewListObjectsV2Paginator(b.client, &s3.ListObjectsV2Input{Bucket: aws.String(b.bucket), Prefix: aws.String(prefix)})
+ var total int64
+ for pages.HasMorePages() {
+ page, err := pages.NextPage(ctx)
+ if err != nil {
+ return 0, err
+ }
+ for _, object := range page.Contents {
+ size := aws.ToInt64(object.Size)
+ if size < 0 || size > math.MaxInt64-total {
+ return 0, errors.New("invalid blob inventory size")
+ }
+ total += size
+ }
+ }
+ return total, nil
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 01d979082..5a66547f1 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -4,6 +4,8 @@ import (
"embed"
"os"
"time"
+
+ "windshift/internal/operatorcontrols"
)
// Config is the fully-resolved runtime configuration for the main windshift
@@ -11,6 +13,7 @@ import (
// server.New and every handler that previously read env vars directly.
// last review: ser, 210426
type Config struct {
+ OperatorPolicy operatorcontrols.Policy
// HTTP / network
Port string
BaseURL string
diff --git a/internal/config/load.go b/internal/config/load.go
index e19863a32..9a1004a25 100644
--- a/internal/config/load.go
+++ b/internal/config/load.go
@@ -12,6 +12,7 @@ import (
"time"
"windshift/internal/database"
+ "windshift/internal/operatorcontrols"
)
// Load parses CLI flags (via the default flag.CommandLine), reads env vars,
@@ -25,6 +26,7 @@ import (
func Load(frontend embed.FS, shutdownChan chan os.Signal) Config {
// Flag definitions mirror the historic main.go flags verbatim.
var (
+ operatorPolicyPath = flag.String("operator-policy", "", "Path to an operator-owned JSON controls file (changes require restart)")
portFlag = flag.String("port", "8080", "Port to run the HTTP server on")
portShort = flag.String("p", "8080", "Port to run the HTTP server on (shorthand)")
dbPath = flag.String("db", "windshift.db", "Database file path (SQLite)")
@@ -67,6 +69,12 @@ func Load(frontend embed.FS, shutdownChan chan os.Signal) Config {
memoryLimitMB = flag.Int("memory-limit-mb", DefaultMemoryLimitMB, "Total Windshift process memory budget in MiB")
)
flag.Parse()
+ policyPath := firstNonEmpty(os.Getenv("WINDSHIFT_OPERATOR_POLICY"), *operatorPolicyPath)
+ operatorPolicy, policyErr := operatorcontrols.Load(policyPath)
+ if policyErr != nil {
+ slog.Error("FATAL: invalid operator policy", "error", policyErr)
+ os.Exit(1)
+ }
// Track which flags were supplied explicitly so an alias, or a boolean set to
// its default value, is distinguishable from an omitted one.
@@ -216,6 +224,7 @@ func Load(frontend embed.FS, shutdownChan chan os.Signal) Config {
}
return Config{
+ OperatorPolicy: operatorPolicy,
Port: port,
BaseURL: resolvedBaseURL,
ContextPath: resolvedContextPath,
diff --git a/internal/database/migrations.go b/internal/database/migrations.go
index 871a33177..a268f80c0 100644
--- a/internal/database/migrations.go
+++ b/internal/database/migrations.go
@@ -3418,6 +3418,14 @@ CREATE INDEX IF NOT EXISTS idx_plane_import_mappings_windshift ON plane_import_m
SQLite: timeWorklogDraftsMigrationSQLite,
Postgres: timeWorklogDraftsMigrationPostgres,
},
+ {
+ Version: "20261113_operator_usage",
+ Name: "Persist instance-wide operator budget reservations",
+ CheckSQLite: sqliteTableCheck("operator_usage"),
+ CheckPostgres: pgTableCheck("operator_usage"),
+ SQLite: operatorUsageSchema,
+ Postgres: operatorUsageSchema,
+ },
{
Version: "20261125_session_remember_me",
Name: "Preserve the session lifetime choice through passkey authentication",
diff --git a/internal/database/operator_controls.go b/internal/database/operator_controls.go
new file mode 100644
index 000000000..f3483a5ab
--- /dev/null
+++ b/internal/database/operator_controls.go
@@ -0,0 +1,23 @@
+package database
+
+import "windshift/internal/operatorcontrols"
+
+type controlledDatabase struct {
+ Database
+ controls *operatorcontrols.Controls
+}
+
+func (db *controlledDatabase) OperatorControls() *operatorcontrols.Controls { return db.controls }
+
+func (db *controlledDatabase) InstanceID() uint64 {
+ if source, ok := db.Database.(interface{ InstanceID() uint64 }); ok {
+ return source.InstanceID()
+ }
+ return 0
+}
+
+// WithOperatorControls carries one instance's immutable deployment policy to
+// shared services, including services constructed by tools and background jobs.
+func WithOperatorControls(db Database, controls *operatorcontrols.Controls) Database {
+ return &controlledDatabase{Database: db, controls: controls}
+}
diff --git a/internal/database/operator_usage_schema.go b/internal/database/operator_usage_schema.go
new file mode 100644
index 000000000..1f64faedf
--- /dev/null
+++ b/internal/database/operator_usage_schema.go
@@ -0,0 +1,8 @@
+package database
+
+const operatorUsageSchema = `CREATE TABLE operator_usage (
+ resource TEXT NOT NULL,
+ period BIGINT NOT NULL,
+ used BIGINT NOT NULL CHECK (used >= 0),
+ PRIMARY KEY (resource, period)
+);`
diff --git a/internal/database/schema/system.sql b/internal/database/schema/system.sql
index 7955cdc15..0b4af729f 100644
--- a/internal/database/schema/system.sql
+++ b/internal/database/schema/system.sql
@@ -1,5 +1,12 @@
-- System tables (settings, labels, reviews, plugins, audit, etc.)
+CREATE TABLE IF NOT EXISTS operator_usage (
+ resource TEXT NOT NULL,
+ period BIGINT NOT NULL,
+ used BIGINT NOT NULL CHECK (used >= 0),
+ PRIMARY KEY (resource, period)
+);
+
-- Schema migrations registry. Source of truth for which migrations have
-- been applied. Paired with internal/database/migrations.go (the Catalog).
-- The boostrap CREATE in Initialize() makes this table available before
diff --git a/internal/database/schema/system_postgres.sql b/internal/database/schema/system_postgres.sql
index ea4a9918c..897dbf855 100644
--- a/internal/database/schema/system_postgres.sql
+++ b/internal/database/schema/system_postgres.sql
@@ -568,3 +568,9 @@ CREATE TABLE IF NOT EXISTS pending_custom_field_cleanups (
);
CREATE INDEX IF NOT EXISTS idx_pending_cfv_cleanups_status ON pending_custom_field_cleanups(status, created_at);
+CREATE TABLE IF NOT EXISTS operator_usage (
+ resource TEXT NOT NULL,
+ period BIGINT NOT NULL,
+ used BIGINT NOT NULL CHECK (used >= 0),
+ PRIMARY KEY (resource, period)
+);
diff --git a/internal/email/credentials.go b/internal/email/credentials.go
index 7a9fec9f1..becbafbfe 100644
--- a/internal/email/credentials.go
+++ b/internal/email/credentials.go
@@ -15,6 +15,7 @@ import (
"windshift/internal/database"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
)
const encryptedSecretPrefix = "enc:v1:"
@@ -259,6 +260,9 @@ func (m *CredentialManager) GetProviderForChannel(ctx context.Context, channelID
// Fall back to basic IMAP (generic provider with channel's IMAP credentials)
if config.IMAPHost != "" {
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.GenericMail); err != nil {
+ return nil, nil, err
+ }
provider := NewGenericProvider(config.IMAPHost, config.IMAPPort, config.IMAPEncryption)
return provider, &config, nil
}
@@ -329,6 +333,9 @@ func (m *CredentialManager) GetProvider(ctx context.Context, providerID int) (Pr
return NewGoogleProvider(ep.OAuthClientID, clientSecret, scopes), nil
case models.EmailProviderTypeGeneric:
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.GenericMail); err != nil {
+ return nil, err
+ }
return NewGenericProvider(ep.IMAPHost, ep.IMAPPort, ep.IMAPEncryption), nil
default:
diff --git a/internal/handlers/channels.go b/internal/handlers/channels.go
index 1df1f6009..81e7ee7b4 100644
--- a/internal/handlers/channels.go
+++ b/internal/handlers/channels.go
@@ -785,6 +785,15 @@ func (h *ChannelHandler) TestChannelConfig(w http.ResponseWriter, r *http.Reques
return
}
channelType := channel.Type
+ configBytes, marshalErr := json.Marshal(testData.Config)
+ if marshalErr != nil {
+ respondInternalError(w, r, marshalErr)
+ return
+ }
+ if err := h.service.CheckTransportConfig(ctx, id, string(configBytes)); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
if channelType == "smtp" && testData.Config.SMTPPassword == "" {
rawConfig, configErr := h.service.GetConfig(ctx, id)
if configErr != nil {
diff --git a/internal/handlers/diagnostics.go b/internal/handlers/diagnostics.go
index 40e59ded8..ffc940a5a 100644
--- a/internal/handlers/diagnostics.go
+++ b/internal/handlers/diagnostics.go
@@ -19,6 +19,7 @@ import (
"windshift/internal/llm"
"windshift/internal/logger"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/scheduler"
"windshift/internal/services"
@@ -32,6 +33,7 @@ import (
// webhook_deliveries, scheduler_runs) and is read-only except for the manual
// purge endpoints, which delete old rows on demand.
type DiagnosticsHandler struct {
+ controls *operatorcontrols.Controls
sessionManager *auth.SessionManager
databaseDiagRepo *repository.DatabaseDiagnosticsRepository
actionRepo *repository.ActionRepository
@@ -82,6 +84,7 @@ func NewDiagnosticsHandler(
channelRepo *repository.ChannelRepository,
) *DiagnosticsHandler {
return &DiagnosticsHandler{
+ controls: operatorcontrols.From(settingsRepo),
sessionManager: sessionManager,
databaseDiagRepo: databaseDiagRepo,
actionRepo: actionRepo,
@@ -175,7 +178,11 @@ func (h *DiagnosticsHandler) GetEmailIntakeDiagnostics(w http.ResponseWriter, r
// cache allocation/traffic counters for this replica.
//
// GET /api/admin/diagnostics/cache-memory
-func (h *DiagnosticsHandler) GetCacheMemory(w http.ResponseWriter, _ *http.Request) {
+func (h *DiagnosticsHandler) GetCacheMemory(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
var memory runtime.MemStats
runtime.ReadMemStats(&memory)
caches := cacheutil.Snapshots()
@@ -456,7 +463,11 @@ func (h *DiagnosticsHandler) UpdateRecurrenceVolumeSettings(w http.ResponseWrite
// cardinality, SQL, latency, pool, failure, and side-effect counters.
//
// GET /api/admin/diagnostics/bulk-operations
-func (h *DiagnosticsHandler) GetBulkOperations(w http.ResponseWriter, _ *http.Request) {
+func (h *DiagnosticsHandler) GetBulkOperations(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
if h.bulkOperations == nil {
respondJSONOK(w, services.BulkOperationStats{Operations: map[string]services.BulkOperationKindStats{}})
return
@@ -468,7 +479,11 @@ func (h *DiagnosticsHandler) GetBulkOperations(w http.ResponseWriter, _ *http.Re
// lifetime counters. Delivery history remains on the persisted endpoints.
//
// GET /api/admin/diagnostics/webhook-dispatch
-func (h *DiagnosticsHandler) GetWebhookDispatch(w http.ResponseWriter, _ *http.Request) {
+func (h *DiagnosticsHandler) GetWebhookDispatch(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
if h.webhookSender == nil {
respondJSONOK(w, webhook.DispatchStats{})
return
@@ -480,7 +495,11 @@ func (h *DiagnosticsHandler) GetWebhookDispatch(w http.ResponseWriter, _ *http.R
// coalescing, latency, and response-size counters.
//
// GET /api/admin/diagnostics/transition-matrix
-func (h *DiagnosticsHandler) GetTransitionMatrix(w http.ResponseWriter, _ *http.Request) {
+func (h *DiagnosticsHandler) GetTransitionMatrix(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
if h.transitionMatrix == nil {
respondJSONOK(w, services.TransitionMatrixStats{})
return
@@ -492,7 +511,11 @@ func (h *DiagnosticsHandler) GetTransitionMatrix(w http.ResponseWriter, _ *http.
// counters. In a multi-instance deployment each replica reports its own view.
//
// GET /api/admin/diagnostics/session-validation-cache
-func (h *DiagnosticsHandler) GetSessionValidationCache(w http.ResponseWriter, _ *http.Request) {
+func (h *DiagnosticsHandler) GetSessionValidationCache(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
stats := h.sessionManager.SessionValidationCacheStats()
respondJSONOK(w, map[string]any{
"enabled": stats.Enabled,
@@ -553,7 +576,11 @@ const databasePoolSaturationThresholdPercent = 90
// distinguish connection starvation from query execution latency.
//
// GET /api/admin/diagnostics/database-pool
-func (h *DiagnosticsHandler) GetDatabasePool(w http.ResponseWriter, _ *http.Request) {
+func (h *DiagnosticsHandler) GetDatabasePool(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
stats := h.databaseDiagRepo.PoolStats()
pools := make([]DatabasePoolSnapshot, 0, len(stats))
healthy := true
@@ -640,6 +667,10 @@ func (h *DiagnosticsHandler) GetDatabasePool(w http.ResponseWriter, _ *http.Requ
//
// GET /api/admin/diagnostics/frac-index
func (h *DiagnosticsHandler) GetFracIndexState(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
dbState, err := h.fracIndexRepo.GetDBStats()
if err != nil {
respondInternalError(w, r, err)
@@ -698,6 +729,10 @@ type GlobalRankMigrationControlRequest struct {
//
// POST /api/admin/diagnostics/frac-index/migration
func (h *DiagnosticsHandler) ControlGlobalRankMigration(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.Maintenance); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
req, ok := decodeJSON[GlobalRankMigrationControlRequest](w, r)
if !ok {
return
@@ -907,6 +942,10 @@ type PurgeWebhookDeliveriesRequest struct {
//
// POST /api/admin/diagnostics/webhook-deliveries/purge
func (h *DiagnosticsHandler) PurgeWebhookDeliveries(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.Maintenance); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
req, ok := decodeJSON[PurgeWebhookDeliveriesRequest](w, r)
if !ok {
return
@@ -941,6 +980,10 @@ func (h *DiagnosticsHandler) PurgeWebhookDeliveries(w http.ResponseWriter, r *ht
//
// GET /api/admin/diagnostics/scheduler-runs
func (h *DiagnosticsHandler) GetSchedulerRuns(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
q := r.URL.Query()
since, err := parseSinceDuration(q.Get("since"), 24*time.Hour)
@@ -985,6 +1028,10 @@ func (h *DiagnosticsHandler) GetSchedulerRuns(w http.ResponseWriter, r *http.Req
//
// GET /api/admin/diagnostics/scheduler-stats
func (h *DiagnosticsHandler) GetSchedulerStats(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
since, err := parseSinceDuration(r.URL.Query().Get("since"), 24*time.Hour)
if err != nil {
respondValidationError(w, r, err.Error())
@@ -1007,6 +1054,10 @@ func (h *DiagnosticsHandler) GetSchedulerStats(w http.ResponseWriter, r *http.Re
//
// POST /api/admin/diagnostics/scheduler-runs/purge
func (h *DiagnosticsHandler) PurgeSchedulerRuns(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.Maintenance); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
req, ok := decodeJSON[PurgeWebhookDeliveriesRequest](w, r)
if !ok {
return
diff --git a/internal/handlers/diagnostics_runner_pools.go b/internal/handlers/diagnostics_runner_pools.go
index 8e9998de5..4bf2a0bba 100644
--- a/internal/handlers/diagnostics_runner_pools.go
+++ b/internal/handlers/diagnostics_runner_pools.go
@@ -6,6 +6,7 @@ import (
"time"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
)
// runnerPoolDiag is one pool's health snapshot for the admin Diagnostics
@@ -33,6 +34,10 @@ type runnerPoolDiag struct {
//
// GET /api/admin/diagnostics/runner-pools
func (h *DiagnosticsHandler) GetRunnerPools(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
if h.runnerRepo == nil || h.agentRunRepo == nil {
respondJSONOK(w, []runnerPoolDiag{})
return
diff --git a/internal/handlers/domain_event_diagnostics.go b/internal/handlers/domain_event_diagnostics.go
index 04692e26f..4dea661ef 100644
--- a/internal/handlers/domain_event_diagnostics.go
+++ b/internal/handlers/domain_event_diagnostics.go
@@ -10,6 +10,7 @@ import (
"unicode/utf8"
"windshift/internal/events"
+ "windshift/internal/operatorcontrols"
"windshift/internal/utils"
)
@@ -68,6 +69,10 @@ type domainEventFailureDiagnostic struct {
//
// GET /api/admin/diagnostics/domain-events
func (h *DiagnosticsHandler) GetDomainEvents(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.RuntimeDiagnostics); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
if h.eventStore == nil {
respondInternalError(w, r, errors.New("domain event store not configured"))
return
@@ -191,6 +196,10 @@ func (h *DiagnosticsHandler) SkipDomainEvent(w http.ResponseWriter, r *http.Requ
}
func (h *DiagnosticsHandler) changeDomainEventDelivery(w http.ResponseWriter, r *http.Request, action string) {
+ if err := h.controls.Check(operatorcontrols.Maintenance); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
if h.eventStore == nil {
respondInternalError(w, r, errors.New("domain event store not configured"))
return
diff --git a/internal/handlers/email_providers.go b/internal/handlers/email_providers.go
index cc49955e3..affb7108c 100644
--- a/internal/handlers/email_providers.go
+++ b/internal/handlers/email_providers.go
@@ -17,6 +17,7 @@ import (
"windshift/internal/email"
"windshift/internal/logger"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/sanitize"
"windshift/internal/services"
@@ -279,6 +280,10 @@ func (h *EmailProviderHandler) CreateEmailProvider(w http.ResponseWriter, r *htt
)
normalizeEmailProviderRequest(&req)
if req.Type == models.EmailProviderTypeGeneric {
+ if err := operatorcontrols.From(h.db).Check(operatorcontrols.GenericMail); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
if req.IMAPPort == 0 {
req.IMAPPort = 993
}
@@ -372,6 +377,10 @@ func (h *EmailProviderHandler) UpdateEmailProvider(w http.ResponseWriter, r *htt
)
normalizeEmailProviderRequest(&req)
if req.Type == models.EmailProviderTypeGeneric {
+ if err := operatorcontrols.From(h.db).Check(operatorcontrols.GenericMail); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
if req.IMAPPort == 0 {
req.IMAPPort = 993
}
diff --git a/internal/handlers/errors.go b/internal/handlers/errors.go
index 860798018..1cd9a23a4 100644
--- a/internal/handlers/errors.go
+++ b/internal/handlers/errors.go
@@ -7,6 +7,7 @@ import (
"net/http"
"windshift/internal/jira"
+ "windshift/internal/operatorcontrols"
"windshift/internal/restapi"
)
@@ -90,6 +91,23 @@ func respondValidationError(w http.ResponseWriter, r *http.Request, message stri
// it is logged at debug level and answered with 408 instead. The actual error
// message is logged but not exposed to the client.
func respondInternalError(w http.ResponseWriter, r *http.Request, err error) {
+ var denied *operatorcontrols.DeniedError
+ if errors.As(err, &denied) {
+ restapi.RespondError(w, r, restapi.NewAPIError(http.StatusForbidden, "operator_restricted", denied.Error()))
+ return
+ }
+ var limited *operatorcontrols.LimitError
+ if errors.As(err, &limited) {
+ if limited.Status() == http.StatusTooManyRequests {
+ w.Header().Set("Retry-After", "60")
+ }
+ restapi.RespondError(w, r, restapi.NewAPIError(limited.Status(), "operator_limit_exceeded", limited.Error()))
+ return
+ }
+ if errors.Is(err, operatorcontrols.ErrBudgetUnavailable) {
+ restapi.RespondError(w, r, restapi.NewAPIError(http.StatusServiceUnavailable, "operator_budget_unavailable", err.Error()))
+ return
+ }
// A canceled context means the client went away while the request was in
// flight (navigation or reload). That is expected control flow, not a server
// fault, so it must not be logged as an internal error.
diff --git a/internal/handlers/features.go b/internal/handlers/features.go
index 7f9b87ace..5712b1d13 100644
--- a/internal/handlers/features.go
+++ b/internal/handlers/features.go
@@ -3,6 +3,7 @@ package handlers
import (
"net/http"
+ "windshift/internal/operatorcontrols"
"windshift/internal/plugins"
)
@@ -10,24 +11,33 @@ import (
type FeaturesHandler struct {
pluginManager *plugins.Manager
sshEnabled bool
+ controls *operatorcontrols.Controls
}
// NewFeaturesHandler creates a new features handler.
-func NewFeaturesHandler(pluginManager *plugins.Manager, sshEnabled bool) *FeaturesHandler {
- return &FeaturesHandler{pluginManager: pluginManager, sshEnabled: sshEnabled}
+func NewFeaturesHandler(pluginManager *plugins.Manager, sshEnabled bool, controls ...*operatorcontrols.Controls) *FeaturesHandler {
+ h := &FeaturesHandler{pluginManager: pluginManager, sshEnabled: sshEnabled}
+ if len(controls) > 0 {
+ h.controls = controls[0]
+ }
+ return h
}
// Snapshot returns feature discovery data for callers that need to compose it
// into a larger response without making an internal HTTP request.
func (h *FeaturesHandler) Snapshot() FeaturesResponse {
+ policy := h.controls.Snapshot()
resp := FeaturesResponse{
Edition: "community",
SAMLAvailable: true,
- LDAPAvailable: true,
+ LDAPAvailable: h.controls.Allowed(operatorcontrols.LDAP),
SCIMAvailable: true,
SSHAvailable: h.sshEnabled,
Plugins: make([]string, 0),
Capabilities: make([]string, 0),
+ OperatorControls: FeatureOperatorControls{
+ Deny: policy.Deny, MailMode: policy.MailMode, MailSuspended: policy.MailSuspended,
+ },
}
if h.pluginManager != nil {
@@ -41,15 +51,23 @@ func (h *FeaturesHandler) Snapshot() FeaturesResponse {
return resp
}
+// FeatureOperatorControls is the public capability projection, not the admin policy.
+type FeatureOperatorControls struct {
+ Deny []operatorcontrols.Capability `json:"deny"`
+ MailMode string `json:"mail_mode,omitempty"`
+ MailSuspended bool `json:"mail_suspended,omitempty"`
+}
+
// FeaturesResponse represents the available features and installed plugins.
type FeaturesResponse struct {
- Edition string `json:"edition"`
- SAMLAvailable bool `json:"saml_available"`
- LDAPAvailable bool `json:"ldap_available"`
- SCIMAvailable bool `json:"scim_available"`
- SSHAvailable bool `json:"ssh_available"`
- Plugins []string `json:"plugins"`
- Capabilities []string `json:"capabilities"`
+ OperatorControls FeatureOperatorControls `json:"operator_controls"`
+ Edition string `json:"edition"`
+ SAMLAvailable bool `json:"saml_available"`
+ LDAPAvailable bool `json:"ldap_available"`
+ SCIMAvailable bool `json:"scim_available"`
+ SSHAvailable bool `json:"ssh_available"`
+ Plugins []string `json:"plugins"`
+ Capabilities []string `json:"capabilities"`
}
// GetFeatures handles GET /api/features (public, no auth required).
diff --git a/internal/handlers/jira_connector.go b/internal/handlers/jira_connector.go
index 60f703dd7..79402060e 100644
--- a/internal/handlers/jira_connector.go
+++ b/internal/handlers/jira_connector.go
@@ -14,6 +14,7 @@ import (
"windshift/internal/jira"
"windshift/internal/jiraimport"
"windshift/internal/logger"
+ "windshift/internal/operatorcontrols"
"windshift/internal/sanitize"
"windshift/internal/services"
"windshift/internal/sso"
@@ -42,6 +43,14 @@ type JiraImportHandler struct {
importWatchers bool
// importConcurrency bounds in-flight Jira requests for independent work.
importConcurrency int
+ importAdmission operatorcontrols.ImportAdmission
+}
+
+// WithImportAdmission supplies a host/fleet permit implementation. It is used
+// only when immutable operator policy requires admission; nil uses host locks.
+func (h *JiraImportHandler) WithImportAdmission(admission operatorcontrols.ImportAdmission) *JiraImportHandler {
+ h.importAdmission = admission
+ return h
}
func (h *JiraImportHandler) WithAuthorizationCacheInvalidator(invalidator *services.AuthorizationCacheInvalidator) *JiraImportHandler {
@@ -98,6 +107,10 @@ func NewJiraImportHandler(db database.Database, sessionSecret, capturePayloadsDi
// Connect handles POST /api/admin/jira-import/connect
func (h *JiraImportHandler) Connect(w http.ResponseWriter, r *http.Request) {
+ if err := operatorcontrols.From(h.db).Check(operatorcontrols.Imports); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
req, ok := decodeJSON[JiraConnectRequest](w, r)
if !ok {
return
@@ -169,6 +182,10 @@ func (h *JiraImportHandler) Connect(w http.ResponseWriter, r *http.Request) {
// expired or revoked token is recoverable without deleting the connection and
// its import provenance.
func (h *JiraImportHandler) UpdateConnection(w http.ResponseWriter, r *http.Request) {
+ if err := operatorcontrols.From(h.db).Check(operatorcontrols.Imports); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
connectionID := r.PathValue("connectionId")
req, ok := decodeJSON[JiraConnectionUpdateRequest](w, r)
if !ok {
@@ -360,6 +377,9 @@ func (h *JiraImportHandler) DeleteConnection(w http.ResponseWriter, r *http.Requ
// getClientForConnection retrieves stored credentials and creates a Jira client
func (h *JiraImportHandler) getClientForConnection(_ context.Context, connectionID string) (jira.Client, error) {
+ if err := operatorcontrols.From(h.db).Check(operatorcontrols.Imports); err != nil {
+ return nil, err
+ }
connection, err := h.imports.UseConnection(connectionID)
if err != nil {
return nil, fmt.Errorf("connection not found: %w", err)
diff --git a/internal/handlers/jira_import_execution.go b/internal/handlers/jira_import_execution.go
index d5bc21e56..4cfa4fe50 100644
--- a/internal/handlers/jira_import_execution.go
+++ b/internal/handlers/jira_import_execution.go
@@ -15,6 +15,7 @@ import (
"windshift/internal/jira"
"windshift/internal/jiraimport"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/services"
"windshift/internal/xray"
@@ -42,6 +43,43 @@ func (h *JiraImportHandler) executeImport(jobID string, req StartImportRequest)
}
h.setJobToken(jobID, token)
defer h.clearJobToken(jobID)
+ controls := operatorcontrols.From(h.db)
+ if err := controls.Check(operatorcontrols.Imports); err != nil {
+ h.updateJobStatus(jobID, "failed", "operator_restricted", nil, err.Error())
+ return
+ }
+ if admission, wait := controls.ImportAdmission(); admission != nil {
+ if h.importAdmission != nil {
+ admission = h.importAdmission
+ }
+ h.updateJobStatus(jobID, "running", "admission_waiting", nil, "")
+ waitCtx, stopWaiting := context.WithTimeout(ctx, wait)
+ waitCtx = operatorcontrols.WithImportEstimate(waitCtx, operatorcontrols.ImportEstimate{JobID: jobID, Projects: len(req.ProjectKeys), AssetSchemas: len(req.AssetSchemaIDs), WorkerCeiling: h.importConcurrency, AttachmentCeilingBytes: controls.Limits().AttachmentBytes, BlobAllowanceBytes: controls.Limits().BlobBytes})
+ heartbeatCtx, stopHeartbeat := context.WithCancel(waitCtx)
+ heartbeatDone := make(chan struct{})
+ go func() { defer close(heartbeatDone); h.renewJiraImportLease(heartbeatCtx, jobID, stopWaiting) }()
+ release, err := admission.Acquire(waitCtx)
+ if err == nil && waitCtx.Err() != nil {
+ release()
+ err = waitCtx.Err()
+ }
+ stopHeartbeat()
+ <-heartbeatDone
+ stopWaiting()
+ if err != nil {
+ h.updateJobStatus(jobID, "failed", "admission_denied", nil, "Operator import admission was unavailable, canceled or exceeded its wait bound.")
+ return
+ }
+ defer release()
+ ctx = controls.WithImportPermit(ctx)
+ if owned, err := h.imports.RenewLease(jobID, token); err != nil || !owned {
+ return
+ }
+ if err := controls.Check(operatorcontrols.Imports); err != nil {
+ h.updateJobStatus(jobID, "failed", "operator_restricted", nil, err.Error())
+ return
+ }
+ }
// Look up the user who initiated this job so imported workspaces can grant
// them admin access. Without this the importer would create workspaces with
@@ -215,6 +253,10 @@ func (h *JiraImportHandler) renewJiraImportLease(ctx context.Context, jobID stri
slog.String("component", "jira"),
slog.String("job_id", jobID),
slog.Any("error", err))
+ if admission, _ := operatorcontrols.From(h.db).ImportAdmission(); admission != nil {
+ onLost()
+ return
+ }
continue
}
if !renewed {
diff --git a/internal/handlers/jira_importer.go b/internal/handlers/jira_importer.go
index 17efcd5f2..21946f95f 100644
--- a/internal/handlers/jira_importer.go
+++ b/internal/handlers/jira_importer.go
@@ -14,6 +14,7 @@ import (
"windshift/internal/jiraimport"
"windshift/internal/logger"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/restapi"
"windshift/internal/sanitize"
@@ -235,6 +236,26 @@ func (h *JiraImportHandler) validateJiraEntityMappings(req StartImportRequest) e
// StartImport handles POST /api/admin/jira-import/start
// Starts a background import job and returns immediately with the job ID
func (h *JiraImportHandler) StartImport(w http.ResponseWriter, r *http.Request) {
+ if err := operatorcontrols.From(h.db).Check(operatorcontrols.Imports); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
+ controls := operatorcontrols.From(h.db)
+ ceiling := 0
+ if admission, _ := controls.ImportAdmission(); admission != nil {
+ ceiling = 1
+ }
+ releaseAdmission, err := controls.Acquire(r.Context(), "import_jobs", ceiling)
+ if err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
+ handedOff := false
+ defer func() {
+ if !handedOff {
+ releaseAdmission()
+ }
+ }()
req, ok := decodeJSON[StartImportRequest](w, r)
if !ok {
return
@@ -343,7 +364,8 @@ func (h *JiraImportHandler) StartImport(w http.ResponseWriter, r *http.Request)
}
// Start the import in a background goroutine
- go h.executeImport(jobID, req) //nolint:gosec // G118: an import job must outlive its initiating HTTP request.
+ handedOff = true
+ go func() { defer releaseAdmission(); h.executeImport(jobID, req) }() //nolint:gosec // G118: an import job must outlive its initiating HTTP request.
respondJSONOK(w, StartImportResponse{
JobID: jobID,
diff --git a/internal/handlers/ldap.go b/internal/handlers/ldap.go
index 59aee555e..99c7b5c8c 100644
--- a/internal/handlers/ldap.go
+++ b/internal/handlers/ldap.go
@@ -11,6 +11,7 @@ import (
ldapPkg "windshift/internal/ldap"
"windshift/internal/logger"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/sanitize"
"windshift/internal/sso"
"windshift/internal/utils"
@@ -180,6 +181,10 @@ func (h *LDAPHandler) GetConfig(w http.ResponseWriter, r *http.Request) {
// CreateConfig handles POST /api/admin/ldap/configs
func (h *LDAPHandler) CreateConfig(w http.ResponseWriter, r *http.Request) {
+ if err := operatorcontrols.From(h.db).Check(operatorcontrols.LDAP); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
req, ok := decodeJSON[LDAPConfigRequest](w, r)
if !ok {
return
@@ -283,6 +288,10 @@ func (h *LDAPHandler) CreateConfig(w http.ResponseWriter, r *http.Request) {
// UpdateConfig handles PUT /api/admin/ldap/configs/{id}
func (h *LDAPHandler) UpdateConfig(w http.ResponseWriter, r *http.Request) {
+ if err := operatorcontrols.From(h.db).Check(operatorcontrols.LDAP); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
id, ok := requireIDParam(w, r, "id")
if !ok {
return
@@ -435,6 +444,10 @@ func (h *LDAPHandler) DeleteConfig(w http.ResponseWriter, r *http.Request) {
// TestConnection handles POST /api/admin/ldap/configs/{id}/test
func (h *LDAPHandler) TestConnection(w http.ResponseWriter, r *http.Request) {
+ if err := operatorcontrols.From(h.db).Check(operatorcontrols.LDAP); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
id, ok := requireIDParam(w, r, "id")
if !ok {
return
@@ -487,6 +500,10 @@ func (h *LDAPHandler) TestConnection(w http.ResponseWriter, r *http.Request) {
// TriggerSync handles POST /api/admin/ldap/configs/{id}/sync
func (h *LDAPHandler) TriggerSync(w http.ResponseWriter, r *http.Request) {
+ if err := operatorcontrols.From(h.db).Check(operatorcontrols.LDAP); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
id, ok := requireIDParam(w, r, "id")
if !ok {
return
diff --git a/internal/handlers/runner_broker.go b/internal/handlers/runner_broker.go
index 7c10fe306..7d05fde5b 100644
--- a/internal/handlers/runner_broker.go
+++ b/internal/handlers/runner_broker.go
@@ -217,6 +217,7 @@ func (h *RunnerBrokerHandler) ProxyLLM(w http.ResponseWriter, r *http.Request) {
pricing := h.llmConns.ModelPricing(llm.ProviderType(cfg.ProviderType), cfg.Model)
request.EnablePromptCache = cfg.Protocol == llm.APIContractAnthropic && pricing != nil && pricing.HasCompleteCacheRates()
client := llm.NewProviderClient(llm.ConnectionConfig{
+ Controls: cfg.Controls,
ProviderType: llm.ProviderType(cfg.ProviderType), Model: cfg.Model,
APIKey: cfg.APIKey, BaseURL: cfg.BaseURL, ProviderConfig: cfg.ProviderConfig,
Timeout: llmResponseHeaderTimeout,
diff --git a/internal/handlers/security_settings.go b/internal/handlers/security_settings.go
index be1a16d24..aaf238309 100644
--- a/internal/handlers/security_settings.go
+++ b/internal/handlers/security_settings.go
@@ -119,6 +119,13 @@ func (h *SecuritySettingsHandler) UpdateSecuritySettings(w http.ResponseWriter,
sanitize.Apply(&settings.APIKeyCreationPolicy, sanitize.ShortIdentifier)
before := h.loadSecuritySettings()
+ if settings.PluginCLIExecEnabled && !before.PluginCLIExecEnabled {
+ // Validate immutable controls before persisting any other preference.
+ if err := h.settings.CheckPluginExecution(); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
+ }
if err := h.settings.Upsert(
"calendar_feed_enabled", boolToString(settings.CalendarFeedEnabled),
diff --git a/internal/handlers/system.go b/internal/handlers/system.go
index 87dcadffd..8ffdcc51e 100644
--- a/internal/handlers/system.go
+++ b/internal/handlers/system.go
@@ -5,23 +5,34 @@ import (
"net/http"
"os"
"time"
+
+ "windshift/internal/operatorcontrols"
)
// SystemHandler handles system-level operations like shutdown
type SystemHandler struct {
shutdownChan chan os.Signal
+ controls *operatorcontrols.Controls
}
// NewSystemHandler creates a new system handler with a shutdown channel
-func NewSystemHandler(shutdownChan chan os.Signal) *SystemHandler {
- return &SystemHandler{
+func NewSystemHandler(shutdownChan chan os.Signal, controls ...*operatorcontrols.Controls) *SystemHandler {
+ h := &SystemHandler{
shutdownChan: shutdownChan,
}
+ if len(controls) > 0 {
+ h.controls = controls[0]
+ }
+ return h
}
// Shutdown handles graceful shutdown requests
// POST /api/shutdown
func (h *SystemHandler) Shutdown(w http.ResponseWriter, r *http.Request) {
+ if err := h.controls.Check(operatorcontrols.Lifecycle); err != nil {
+ respondInternalError(w, r, err)
+ return
+ }
slog.Info("shutdown requested via API")
// Send success response immediately
diff --git a/internal/ldap/sync.go b/internal/ldap/sync.go
index c35bba7c0..e2088c10e 100644
--- a/internal/ldap/sync.go
+++ b/internal/ldap/sync.go
@@ -12,6 +12,7 @@ import (
"windshift/internal/database"
"windshift/internal/logger"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/sso"
)
@@ -48,6 +49,9 @@ type SyncResult struct {
// The supplied context cancels database lookups inside the sync; LDAP-library
// I/O is unaffected (the upstream client does not accept context).
func (s *SyncService) SyncUsers(ctx context.Context, config *models.LDAPConfig) (*SyncResult, error) {
+ if err := operatorcontrols.From(s.db).Check(operatorcontrols.LDAP); err != nil {
+ return nil, err
+ }
result := &SyncResult{}
// Create sync status record
diff --git a/internal/llm/client.go b/internal/llm/client.go
index 5cf5eb476..f50c6c76f 100644
--- a/internal/llm/client.go
+++ b/internal/llm/client.go
@@ -4,6 +4,8 @@ import (
"context"
"strings"
"time"
+
+ "windshift/internal/operatorcontrols"
)
// DefaultRequestTimeout bounds a single in-product AI operation end to end. It
@@ -53,6 +55,7 @@ func NewClient(cfg Config) Client {
// ConnectionConfig holds configuration for creating a provider-specific client.
type ConnectionConfig struct {
+ Controls *operatorcontrols.Controls
ProviderType ProviderType
Model string
APIKey string
@@ -73,7 +76,7 @@ func NewProviderClient(cfg ConnectionConfig) Client {
baseURL = provider.BaseURL
}
- return newFantasyClient(fantasyClientOptions{
+ return WithOperatorControls(newFantasyClient(fantasyClientOptions{
baseURL: baseURL,
model: cfg.Model,
apiKey: cfg.APIKey,
@@ -83,7 +86,7 @@ func NewProviderClient(cfg ConnectionConfig) Client {
timeout: cfg.Timeout,
userAgent: provider.UserAgent,
sessionHeader: provider.SessionHeader,
- })
+ }), cfg.Controls, cfg.Model)
}
// ResolveGenerationProtocol resolves the connection once into the protocol
diff --git a/internal/llm/manager.go b/internal/llm/manager.go
index a875c0fd2..753617d9b 100644
--- a/internal/llm/manager.go
+++ b/internal/llm/manager.go
@@ -7,12 +7,14 @@ import (
"errors"
"fmt"
"log/slog"
+ "slices"
"strings"
"sync"
"time"
"windshift/internal/database"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/sso"
)
@@ -50,7 +52,7 @@ func NewConnectionManager(db database.Database, encryption *sso.SecretEncryption
return &ConnectionManager{
db: db,
encryption: encryption,
- fallback: fallback,
+ fallback: WithOperatorControls(fallback, operatorcontrols.From(db), ""),
}
}
@@ -138,6 +140,9 @@ type resolvedConnection struct {
// signature narrow (just a Client) avoids churning its many callers while
// still letting PromptConnection name the provider/model in its logs.
func (m *ConnectionManager) resolve(connectionID int) (*resolvedConnection, error) {
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.AI); err != nil {
+ return nil, err
+ }
var row *sql.Row
if connectionID > 0 {
row = m.db.QueryRow(
@@ -188,6 +193,7 @@ func (m *ConnectionManager) resolve(connectionID int) (*resolvedConnection, erro
return &resolvedConnection{
client: NewProviderClient(ConnectionConfig{
+ Controls: operatorcontrols.From(m.db),
ProviderType: ProviderType(providerType),
Model: model,
APIKey: apiKey,
@@ -297,6 +303,7 @@ func (m *ConnectionManager) MaxOutputTokens(connectionID int) int {
// resolve the admin-selected provider for a coding-agent run (the model id for
// the agent container; the key + base URL stay server-side in the llm-proxy).
type ConnectionRuntimeConfig struct {
+ Controls *operatorcontrols.Controls `json:"-"`
ProviderType string
APIFormat string
Model string
@@ -317,7 +324,10 @@ type ConnectionRuntimeConfig struct {
// is intentionally narrower than GetConnection and is only used after callers
// have already authorized access to the selected connection.
func (m *ConnectionManager) ConnectionRuntime(ctx context.Context, connectionID int) (*ConnectionRuntimeConfig, error) {
- cfg := &ConnectionRuntimeConfig{}
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.AI); err != nil {
+ return nil, err
+ }
+ cfg := &ConnectionRuntimeConfig{Controls: operatorcontrols.From(m.db)}
var apiKeyEncrypted, baseURLNull, providerConfig sql.NullString
err := m.db.QueryRowContext(ctx,
`SELECT provider_type, model, api_key_encrypted, base_url, provider_config
@@ -558,6 +568,9 @@ type CreateConnectionRequest struct {
// CreateConnection creates a new LLM connection.
func (m *ConnectionManager) CreateConnection(req CreateConnectionRequest) (*ConnectionInfo, error) {
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.AIConnections); err != nil {
+ return nil, err
+ }
var encryptedKey sql.NullString
if req.APIKey != "" {
encrypted, err := m.encryption.Encrypt(req.APIKey)
@@ -610,6 +623,9 @@ type UpdateConnectionRequest struct {
// UpdateConnection updates an existing LLM connection.
func (m *ConnectionManager) UpdateConnection(id int, req UpdateConnectionRequest) (*ConnectionInfo, error) {
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.AIConnections); err != nil {
+ return nil, err
+ }
// If setting as default, clear existing defaults
if req.IsDefault {
if _, err := m.db.ExecWrite("UPDATE llm_connections SET is_default = false WHERE is_default = true AND id != ?", id); err != nil {
@@ -651,6 +667,9 @@ func (m *ConnectionManager) UpdateConnection(id int, req UpdateConnectionRequest
// DeleteConnection deletes an LLM connection.
func (m *ConnectionManager) DeleteConnection(id int) error {
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.AIConnections); err != nil {
+ return err
+ }
_, err := m.db.ExecWrite("DELETE FROM llm_connections WHERE id = ?", id)
return err
}
@@ -686,6 +705,9 @@ type CatalogRuntime struct {
// GetCatalogRuntimeForProvider returns auth/base URL from the preferred enabled
// connection for a provider. It returns nil when no enabled connection exists.
func (m *ConnectionManager) GetCatalogRuntimeForProvider(providerType ProviderType) (*CatalogRuntime, error) {
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.AIConnections); err != nil {
+ return nil, err
+ }
return m.catalogRuntimeFromRow(m.db.QueryRow(
`SELECT id, api_key_encrypted, base_url FROM llm_connections
WHERE provider_type = ? AND is_enabled = true
@@ -699,6 +721,9 @@ func (m *ConnectionManager) GetCatalogRuntimeForProvider(providerType ProviderTy
// connection, and the connection's provider type so callers can validate it
// against route parameters.
func (m *ConnectionManager) GetCatalogRuntimeForConnection(connectionID int) (ProviderType, *CatalogRuntime, error) {
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.AIConnections); err != nil {
+ return "", nil, err
+ }
var providerType string
row := m.db.QueryRow(
`SELECT provider_type, id, api_key_encrypted, base_url FROM llm_connections
@@ -746,6 +771,12 @@ func (m *ConnectionManager) decryptCatalogRuntime(id int, apiKeyEncrypted, baseU
// TestConnection tests a connection by creating a client and calling Health.
func (m *ConnectionManager) TestConnection(id int) error {
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.AIConnections); err != nil {
+ return err
+ }
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.AI); err != nil {
+ return err
+ }
var providerType, model string
var apiKeyEncrypted, baseURL, providerConfig sql.NullString
err := m.db.QueryRow(
@@ -764,6 +795,7 @@ func (m *ConnectionManager) TestConnection(id int) error {
}
client := NewProviderClient(ConnectionConfig{
+ Controls: operatorcontrols.From(m.db),
ProviderType: ProviderType(providerType),
Model: model,
APIKey: apiKey,
@@ -893,6 +925,9 @@ func (m *ConnectionManager) ResolveForFeature(featureKey string) (Client, error)
// - Mode == Default (or no entry) → uses override if > 0, else the default
// enabled connection.
func (m *ConnectionManager) ResolveForFeatureWithOverride(featureKey string, userOverrideConnectionID int) (Client, error) {
+ if err := m.checkOperatorFeature(featureKey); err != nil {
+ return nil, err
+ }
cfg, err := LoadAIFeaturesConfig(m.db)
if err != nil {
return nil, err
@@ -910,6 +945,9 @@ func (m *ConnectionManager) ResolveForFeatureWithOverride(featureKey string, use
// reports the wrong model because it re-derived the policy is worse than one
// that reports nothing.
func (m *ConnectionManager) ResolveForFeatureWithIdentity(featureKey string, userOverrideConnectionID int) (Client, ConnectionDescriptor, error) {
+ if err := m.checkOperatorFeature(featureKey); err != nil {
+ return nil, ConnectionDescriptor{}, err
+ }
cfg, err := LoadAIFeaturesConfig(m.db)
if err != nil {
return nil, ConnectionDescriptor{}, err
@@ -928,6 +966,17 @@ type featureResolution struct {
connectionID int // 0 means "use the default enabled connection"
}
+func (m *ConnectionManager) checkOperatorFeature(feature string) error {
+ controls := operatorcontrols.From(m.db)
+ if err := controls.Check(operatorcontrols.AI); err != nil {
+ return err
+ }
+ if policy := controls.AI(); policy != nil && slices.Contains(policy.DeniedFeatures, feature) {
+ return &operatorcontrols.DeniedError{Capability: operatorcontrols.AI}
+ }
+ return nil
+}
+
// decideFeatureResolution is the pure policy function. Extracted so the rules
// can be unit-tested without spinning up a database or a manager.
func decideFeatureResolution(fc models.AIFeatureConfig, userOverrideConnectionID int) featureResolution {
diff --git a/internal/llm/operator_controls.go b/internal/llm/operator_controls.go
new file mode 100644
index 000000000..cab888db1
--- /dev/null
+++ b/internal/llm/operator_controls.go
@@ -0,0 +1,129 @@
+package llm
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "slices"
+ "time"
+
+ "windshift/internal/operatorcontrols"
+)
+
+type controlledClient struct {
+ Client
+ controls *operatorcontrols.Controls
+ model string
+}
+
+// WithOperatorControls protects every call in a tool loop, not just its first
+// HTTP request. The fallback client and runner broker use this same boundary.
+func WithOperatorControls(client Client, controls *operatorcontrols.Controls, model string) Client {
+ if controls == nil || client == nil {
+ return client
+ }
+ if existing, ok := client.(*controlledClient); ok && existing.controls == controls {
+ return client
+ }
+ return &controlledClient{Client: client, controls: controls, model: model}
+}
+
+func (c *controlledClient) Available() bool {
+ return c.controls.Allowed(operatorcontrols.AI) && c.Client.Available()
+}
+
+func (c *controlledClient) Health(ctx context.Context) error {
+ if err := c.controls.Check(operatorcontrols.AI); err != nil {
+ return err
+ }
+ if !c.controls.Active() {
+ return c.Client.Health(ctx)
+ }
+ request := ConnectionProbeRequest()
+ request.Model = c.model
+ _, err := c.Complete(ctx, request)
+ if err != nil && !isCompletionTokenLimitError(err) {
+ return fmt.Errorf("%w: %w", ErrConnectionFailed, err)
+ }
+ return nil
+}
+
+func (c *controlledClient) Complete(ctx context.Context, request CompletionRequest) (*CompletionResponse, error) {
+ if err := c.controls.Check(operatorcontrols.AI); err != nil {
+ return nil, err
+ }
+ policy := c.controls.AI()
+ model := c.model
+ if model == "" {
+ model = request.Model
+ }
+ if policy != nil {
+ if len(policy.AllowedModels) > 0 && !slices.Contains(policy.AllowedModels, model) {
+ return nil, &operatorcontrols.DeniedError{Capability: operatorcontrols.AI}
+ }
+ if policy.MaxOutputTokens > 0 && (request.MaxTokens <= 0 || request.MaxTokens > policy.MaxOutputTokens) {
+ request.MaxTokens = policy.MaxOutputTokens
+ }
+ if c.model != "" {
+ request.Model = c.model
+ }
+ }
+ release, err := c.controls.Acquire(ctx, "ai", c.controls.Limits().ConcurrentAI)
+ if err != nil {
+ return nil, err
+ }
+ defer release()
+ finish := func(int64) error { return nil }
+ var reservation int64
+ if c.controls.Limits().AITokensPerDay > 0 {
+ if policy == nil {
+ return nil, operatorcontrols.ErrBudgetUnavailable
+ }
+ reservation = policy.CallTokenReservation
+ encoded, err := json.Marshal(request)
+ if err != nil {
+ return nil, err
+ }
+ // Leave explicit framing headroom and reject oversized requests before
+ // contacting a paid provider. The operator qualifies the total envelope.
+ if len(request.Messages) > 100 || int64(len(encoded)) > reservation-int64(request.MaxTokens)-8192 {
+ return nil, &operatorcontrols.LimitError{Resource: "ai_request_tokens"}
+ }
+ finish, err = c.controls.Reserve(ctx, "ai_tokens", reservation, c.controls.Limits().AITokensPerDay, 24*time.Hour)
+ if err != nil {
+ return nil, err
+ }
+ }
+ response, err := c.Client.Complete(ctx, request)
+ if err != nil {
+ return nil, err
+ }
+ if response == nil {
+ return nil, errors.New("AI provider returned no response")
+ }
+ if reservation > 0 {
+ usage := response.Usage
+ if usage.PromptTokens < 0 || usage.CompletionTokens < 0 || usage.CacheReadTokens < 0 || usage.CacheWriteTokens < 0 || usage.TotalTokens < 0 {
+ return nil, errors.New("AI provider returned invalid usage")
+ }
+ // Cache categories may overlap provider prompt totals. Over-counting is
+ // preferable to granting free credit when their reporting is ambiguous.
+ var actual int64
+ for _, tokens := range []int{usage.PromptTokens, usage.CompletionTokens, usage.CacheReadTokens, usage.CacheWriteTokens} {
+ if int64(tokens) > reservation-actual {
+ return nil, errors.New("AI usage exceeded qualified operator call envelope")
+ }
+ actual += int64(tokens)
+ }
+ actual = max(actual, int64(usage.TotalTokens))
+ if actual > 0 && actual <= reservation {
+ if err := finish(actual); err != nil {
+ return nil, fmt.Errorf("settle operator AI allowance: %w", err)
+ }
+ } else if actual > reservation {
+ return nil, errors.New("AI usage exceeded qualified operator call envelope")
+ }
+ }
+ return response, nil
+}
diff --git a/internal/middleware/operator_controls.go b/internal/middleware/operator_controls.go
new file mode 100644
index 000000000..ef2b414b0
--- /dev/null
+++ b/internal/middleware/operator_controls.go
@@ -0,0 +1,62 @@
+package middleware
+
+import (
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+
+ "windshift/internal/operatorcontrols"
+ "windshift/internal/restapi"
+)
+
+// OperatorAdmission applies aggregate instance ceilings independently of users,
+// tokens and workspaces. Health, metrics and static assets retain recovery access.
+func OperatorAdmission(controls *operatorcontrols.Controls) func(http.Handler) http.Handler {
+ return func(next http.Handler) http.Handler {
+ limits := controls.Limits()
+ if limits.ConcurrentRequests == 0 && limits.ConcurrentStreams == 0 && limits.RequestsPerMinute == 0 {
+ return next
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ path := r.URL.Path
+ if !strings.HasPrefix(path, "/api/") && !strings.HasPrefix(path, "/rest/") && !strings.HasPrefix(path, "/scim/") && path != "/mcp" {
+ next.ServeHTTP(w, r)
+ return
+ }
+ resource, ceiling := "requests", limits.ConcurrentRequests
+ if isStreamingPath(path) {
+ resource, ceiling = "streams", limits.ConcurrentStreams
+ }
+ release, err := controls.Acquire(r.Context(), resource, ceiling)
+ if err == nil {
+ defer release()
+ err = controls.Consume(r.Context(), "requests", 1, limits.RequestsPerMinute, time.Minute)
+ }
+ if err != nil {
+ status, code, message := http.StatusServiceUnavailable, "operator_budget_unavailable", "Operator budget admission is unavailable"
+ var limited *operatorcontrols.LimitError
+ if errors.As(err, &limited) {
+ status, code, message = limited.Status(), "operator_limit_exceeded", limited.Error()
+ }
+ if status == http.StatusTooManyRequests {
+ w.Header().Set("Retry-After", "60")
+ }
+ if strings.HasPrefix(path, "/api/v2/") || strings.HasPrefix(path, "/rest/api/v2/") {
+ requestID := "req_" + uuid.NewString()
+ w.Header().Set("X-Request-ID", requestID)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": code, "message": message}, "request_id": requestID})
+ } else {
+ restapi.RespondError(w, r, restapi.NewAPIError(status, code, message))
+ }
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+ }
+}
diff --git a/internal/operatorcontrols/README.md b/internal/operatorcontrols/README.md
new file mode 100644
index 000000000..be3d127fa
--- /dev/null
+++ b/internal/operatorcontrols/README.md
@@ -0,0 +1,148 @@
+# Operator controls
+
+Use `--operator-policy /run/windshift/operator-policy.json` or
+`WINDSHIFT_OPERATOR_POLICY=/run/windshift/operator-policy.json` to load an
+operator-owned JSON file at startup. The environment variable takes precedence.
+Unknown fields, invalid capabilities and negative ceilings reject startup.
+Omitting the file preserves self-managed behavior; zero ceilings add no limit.
+Changes require a controlled restart. Do not mount this file writable by the
+application or give organization administrators access to the process/container.
+
+An example restrictive policy (numbers are illustrative, **not capacity claims**):
+
+```json
+{
+ "deny": [
+ "instance_lifecycle", "maintenance", "runtime_diagnostics", "plugin_exec",
+ "ldap", "server_scripts", "imports", "generic_mail", "ai",
+ "ai_connection_management"
+ ],
+ "limits": {
+ "attachment_bytes": 10485760,
+ "blob_bytes": 1073741824,
+ "concurrent_requests": 16,
+ "concurrent_streams": 4,
+ "requests_per_minute": 600,
+ "automation_steps_per_day": 10000,
+ "mail_recipients_per_day": 1000
+ },
+ "mail": { "mode": "disabled" }
+}
+```
+
+Continue to configure existing startup controls separately: disable plugins,
+keep local/private network connections and TLS verification bypass disabled,
+leave SSH/MCP/coding-agent execution opt-in, and set memory/cache, database
+deadline, per-user admission, polling and outbox limits. This policy does not
+replace those controls or turn workspaces into isolation boundaries. Each
+customer instance retains its own application, database and storage boundary.
+
+## Authority matrix
+
+| Operation | Authority when restricted |
+| --- | --- |
+| Shutdown | Deployment/process supervisor; no tenant operator API |
+| Rank migration, domain-event replay/skip, scheduler/webhook history purge | Operator maintenance only |
+| Runtime cache/database/runner/scheduler/domain-event diagnostics | Operator only |
+| Action logs, customer delivery errors, ordinary organization administration | Existing user permissions; not blanket disabled |
+| Plugin CLI execution | Operator gate intersects persisted organization preference |
+| LDAP writes, test and sync | Operator gate; existing records retained for migration |
+| Script authoring/import/execution | Operator gate; read/remove definitions remains possible |
+| Attachment preference | Organization may tighten operator per-object ceiling |
+| Bulk imports | Operator gate and optional host admission |
+| Mail transports and AI connections | Operator gate; normal permissions still required |
+
+First-admin setup continues to use the existing one-time provisioning mechanism.
+Operator controls do not introduce a second setup path or a privileged account.
+Read effective controls at `/api/v2/operator-controls` (session) or
+`/rest/api/v2/operator-controls` (bearer), requiring system administrator
+permission. Bearer tokens additionally require `admin:operator-controls:read`.
+The admin page and shell discovery never return relay credentials, storage
+locations or the import admission directory. There is no policy write API.
+Public `/api/features` discovery (also used by shell bootstrap) exposes only
+effective capability denials and mail mode/suspension. Numeric ceilings, AI model
+allowlists, AI feature restrictions and import admission configuration status
+are available only through the authenticated administrator endpoint above.
+
+## Accounting and failure behavior
+
+- Request/stream concurrency is instance-wide and released on handler return,
+ including cancellation/panic. Static assets, health and metrics are outside
+ admission so deployment recovery remains possible. HTTP rate attempts use
+ fixed UTC minutes; automation steps, mail recipient attempts and AI tokens use
+ fixed UTC days. Counters persist in `operator_usage` on SQLite/PostgreSQL;
+ restart does not grant a fresh allowance. Only the current interval is read;
+ old counter rows may be removed by operator database maintenance.
+- Automation reserves one unit before each dispatched node, including nested
+ iterator work and asset flows. Exhaustion stops dispatch and records the
+ failure in the execution trace. Already completed side effects are not rolled
+ back. Durable event failures remain in the existing retry/terminal-delivery
+ workflow; inspect before replaying partially completed effects.
+- Blob quotas count current physical files/objects, including staged/orphaned
+ objects, not attachment rows. Inventory is rebuilt after restart or ambiguous
+ write/delete failure. Writes/deletes serialize within the store. The instance
+ must exclusively own its local root or S3 prefix and be its **only writer**.
+ S3 requires `ListObjectsV2`, `HeadObject`, `PutObject` and `DeleteObject` access.
+ Versions, backups, database/WAL, import staging and temporary space are not a
+ complete disk quota: enforce filesystem/container/object-store limits too.
+- Denied capabilities return `403 operator_restricted`; storage ceilings return
+ `413 operator_limit_exceeded`; work admission returns
+ `429 operator_limit_exceeded`. HTTP overload includes `Retry-After: 60`.
+ Unavailable required budget storage fails closed. Legacy adapters retain
+ their legacy error envelope; v2 uses its standard envelope.
+
+## Optional host import admission
+
+Remove `imports` from `deny` and add:
+
+```json
+"imports": { "admission_directory": "/run/windshift-imports", "slots": 1, "wait_seconds": 300 }
+```
+
+Provision the same operator-owned **local host directory** into all participating
+instances. Do not unlink/replace the slot files while any instance is running.
+OS file locks release on process death; no shared application database is used.
+This is not cross-host fencing and is not qualified for network filesystems.
+The worker reports `admission_waiting`, holds a bounded job lease while waiting,
+then either executes with a permit or reports `admission_denied`. At most one
+pending import request per instance is admitted locally. Other bulk importers
+are disabled when this admission policy is required, unless nested under an
+already admitted Jira import. Fleet failover/placement remains external.
+An injected `ImportAdmission` can read non-secret `ImportEstimate` inputs from
+its context (project/schema counts, worker and storage ceilings). Total issue
+and blob estimates are explicitly unknown until readiness has established them;
+an external admission implementation must not interpret unknown totals as zero.
+
+## Optional managed mail
+
+`mail.mode` is `tenant`, `disabled` or `managed`; `suspended: true` stops sends.
+Managed mode requires `host`, `port`, verified TLS `encryption` (`starttls`,
+`tls` or `ssl`), fixed bare `from_address`, optional `from_name`, `username`
+and `password`, plus `relay_abuse_controls: true`. That confirmation means the
+operator has actually configured and qualified suppression, bounce and complaint
+handling at the relay. The application cannot verify those external controls.
+**Do not launch shared delivery until that qualification is complete.**
+Tenant credentials cannot change managed transport or choose another sender.
+Mail attempts share the daily recipient budget, including tests and auth mail;
+there is no undocumented security-mail exemption. Failed/ambiguous attempts
+remain charged. Existing outbox retry/diagnostic behavior remains in use;
+operators must monitor delayed security mail and restore capacity deliberately.
+`generic_mail` can be denied independently of approved OAuth mailbox intake.
+
+## Optional AI
+
+The safe unqualified default is to deny `ai` and `ai_connection_management`.
+For qualified models, `ai` accepts `allowed_models`, `denied_features`,
+`max_output_tokens` and `call_token_reservation`; `limits` accepts
+`ai_tokens_per_day` and `concurrent_ai`. The reservation must cover the complete
+qualified provider-call envelope, including retries, framing, media and hidden
+tokens, and fit within the daily allowance. The application additionally bounds
+serialized input and clamps output before upstream calls. A byte estimate is
+**not** a universal tokenizer/media/pricing guarantee. Do not offer funded models
+until their envelope has been qualified externally. Unknown or failed usage
+retains the full reservation; known usage refunds only verified unused units.
+Per-run broker quotas and conversation admission remain separate controls.
+
+Timeout/concurrency ceilings for enabled scripts (`script_timeout_ms`,
+`concurrent_scripts`) are not heap/process isolation. Keep untrusted scripts
+disabled until a separately bounded worker design is available.
diff --git a/internal/operatorcontrols/budget.go b/internal/operatorcontrols/budget.go
new file mode 100644
index 000000000..003720ab0
--- /dev/null
+++ b/internal/operatorcontrols/budget.go
@@ -0,0 +1,72 @@
+package operatorcontrols
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+)
+
+// BudgetStore must reserve atomically and persist reservations before effects.
+// A crashed or ambiguous operation keeps its reservation, never free credit.
+type BudgetStore interface {
+ Reserve(context.Context, string, int64, int64, int64) error
+ Refund(context.Context, string, int64, int64) error
+ Used(context.Context, string, int64) (int64, error)
+}
+
+var ErrBudgetUnavailable = errors.New("operator budget store unavailable")
+
+// Reserve charges a fixed UTC interval. Finish refunds only known unused units;
+// omitting it leaves the reservation charged across restarts.
+func (c *Controls) Reserve(ctx context.Context, resource string, amount, ceiling int64, interval time.Duration) (finish func(int64) error, err error) {
+ if c == nil || ceiling == 0 {
+ return func(int64) error { return nil }, ctx.Err()
+ }
+ if amount < 0 || interval < time.Second {
+ return nil, errors.New("invalid operator reservation")
+ }
+ if amount > ceiling {
+ return nil, &LimitError{Resource: resource}
+ }
+ if c.store == nil {
+ return nil, ErrBudgetUnavailable
+ }
+ period := c.now().Unix() / int64(interval/time.Second)
+ if err := c.store.Reserve(ctx, resource, period, amount, ceiling); err != nil {
+ return nil, err
+ }
+ var once sync.Once
+ var finishErr error
+ return func(actual int64) error {
+ once.Do(func() {
+ if actual < 0 || actual > amount {
+ finishErr = fmt.Errorf("invalid actual usage for %s", resource)
+ return
+ }
+ if actual == amount {
+ return
+ }
+ cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer cancel()
+ finishErr = c.store.Refund(cleanupCtx, resource, period, amount-actual)
+ })
+ return finishErr
+ }, nil
+}
+
+func (c *Controls) Consume(ctx context.Context, resource string, amount, ceiling int64, interval time.Duration) error {
+ _, err := c.Reserve(ctx, resource, amount, ceiling, interval)
+ return err
+}
+
+func (c *Controls) Used(ctx context.Context, resource string, interval time.Duration) (int64, error) {
+ if c == nil || c.store == nil {
+ return 0, nil
+ }
+ if interval < time.Second {
+ return 0, errors.New("invalid operator budget interval")
+ }
+ return c.store.Used(ctx, resource, c.now().Unix()/int64(interval/time.Second))
+}
diff --git a/internal/operatorcontrols/controls.go b/internal/operatorcontrols/controls.go
new file mode 100644
index 000000000..766902614
--- /dev/null
+++ b/internal/operatorcontrols/controls.go
@@ -0,0 +1,166 @@
+package operatorcontrols
+
+import (
+ "context"
+ "slices"
+ "sync"
+ "time"
+)
+
+// Controls holds an immutable policy and the instance's admission state.
+type Controls struct {
+ policy Policy
+ mu sync.Mutex
+ active map[string]int
+ store BudgetStore
+ now func() time.Time
+}
+
+func New(policy Policy, stores ...BudgetStore) (*Controls, error) {
+ if err := policy.Validate(); err != nil {
+ return nil, err
+ }
+ policy.Deny = slices.Clone(policy.Deny)
+ if policy.Mail != nil {
+ mail := *policy.Mail
+ policy.Mail = &mail
+ }
+ if policy.AI != nil {
+ ai := *policy.AI
+ ai.AllowedModels = slices.Clone(ai.AllowedModels)
+ ai.DeniedFeatures = slices.Clone(ai.DeniedFeatures)
+ policy.AI = &ai
+ }
+ if policy.Imports != nil {
+ imports := *policy.Imports
+ policy.Imports = &imports
+ }
+ c := &Controls{policy: policy, active: make(map[string]int), now: time.Now}
+ if len(stores) > 0 {
+ c.store = stores[0]
+ }
+ return c, nil
+}
+
+func (c *Controls) Check(capability Capability) error {
+ if c != nil && c.policy.Mail != nil {
+ m := c.policy.Mail
+ if capability == MailSend && (m.Mode == "disabled" || m.Suspended) {
+ return &DeniedError{Capability: MailSend}
+ }
+ if capability == MailTransport && m.Mode == "managed" {
+ return &DeniedError{Capability: MailTransport}
+ }
+ }
+ if c != nil && slices.Contains(c.policy.Deny, capability) {
+ return &DeniedError{Capability: capability}
+ }
+ return nil
+}
+
+// NewWithClock supplies the interval clock before the controls are published.
+func NewWithClock(policy Policy, store BudgetStore, now func() time.Time) (*Controls, error) {
+ c, err := New(policy, store)
+ if err != nil {
+ return nil, err
+ }
+ if now != nil {
+ c.now = now
+ }
+ return c, nil
+}
+
+func (c *Controls) Allowed(capability Capability) bool { return c.Check(capability) == nil }
+
+func (c *Controls) Active() bool {
+ return c != nil && (len(c.policy.Deny) > 0 || c.policy.Limits != (Limits{}) || c.policy.Mail != nil || c.policy.AI != nil || c.policy.Imports != nil)
+}
+func (c *Controls) Limits() Limits {
+ if c == nil {
+ return Limits{}
+ }
+ return c.policy.Limits
+}
+
+type Snapshot struct {
+ Deny []Capability `json:"deny"`
+ Limits Limits `json:"limits"`
+ MailMode string `json:"mail_mode,omitempty"`
+ MailSuspended bool `json:"mail_suspended,omitempty"`
+ AIModels []string `json:"ai_models,omitempty"`
+ AIDeniedFeatures []string `json:"ai_denied_features,omitempty"`
+ AIMaxOutputTokens int `json:"ai_max_output_tokens,omitempty"`
+ ImportAdmissionRequired bool `json:"import_admission_required"`
+}
+
+func (c *Controls) Snapshot() Snapshot {
+ if c == nil {
+ return Snapshot{Deny: []Capability{}}
+ }
+ view := Snapshot{Deny: slices.Clone(c.policy.Deny), Limits: c.policy.Limits, ImportAdmissionRequired: c.policy.Imports != nil}
+ if view.Deny == nil {
+ view.Deny = []Capability{}
+ }
+ for _, capability := range capabilities {
+ if !c.Allowed(capability) && !slices.Contains(view.Deny, capability) {
+ view.Deny = append(view.Deny, capability)
+ }
+ }
+ if c.policy.Mail != nil {
+ view.MailMode = c.policy.Mail.Mode
+ view.MailSuspended = c.policy.Mail.Suspended
+ }
+ if c.policy.AI != nil {
+ view.AIModels = slices.Clone(c.policy.AI.AllowedModels)
+ view.AIDeniedFeatures = slices.Clone(c.policy.AI.DeniedFeatures)
+ view.AIMaxOutputTokens = c.policy.AI.MaxOutputTokens
+ }
+ return view
+}
+
+func (c *Controls) Mail() *MailPolicy {
+ if c == nil || c.policy.Mail == nil {
+ return nil
+ }
+ policy := *c.policy.Mail
+ return &policy
+}
+
+func (c *Controls) AI() *AIPolicy {
+ if c == nil || c.policy.AI == nil {
+ return nil
+ }
+ ai := *c.policy.AI
+ ai.AllowedModels = slices.Clone(ai.AllowedModels)
+ ai.DeniedFeatures = slices.Clone(ai.DeniedFeatures)
+ return &ai
+}
+
+// Acquire never queues goroutines. A permit belongs to one operation, not a user.
+func (c *Controls) Acquire(ctx context.Context, resource string, ceiling int) (func(), error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if c == nil || ceiling == 0 {
+ return func() {}, nil
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.active[resource] >= ceiling {
+ return nil, &LimitError{Resource: resource}
+ }
+ c.active[resource]++
+ var once sync.Once
+ return func() { once.Do(func() { c.mu.Lock(); defer c.mu.Unlock(); c.active[resource]-- }) }, nil
+}
+
+type LimitError struct{ Resource string }
+
+func (e *LimitError) Error() string { return "operator limit reached: " + e.Resource }
+
+func (e *LimitError) Status() int {
+ if e.Resource == "attachment_bytes" || e.Resource == "blob_bytes" {
+ return 413
+ }
+ return 429
+}
diff --git a/internal/operatorcontrols/import_admission.go b/internal/operatorcontrols/import_admission.go
new file mode 100644
index 000000000..263791c2b
--- /dev/null
+++ b/internal/operatorcontrols/import_admission.go
@@ -0,0 +1,121 @@
+package operatorcontrols
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "sync"
+ "time"
+)
+
+var ErrAdmissionUnavailable = errors.New("operator import admission unavailable")
+
+// ImportAdmission is the application boundary for operator-controlled batch
+// capacity. Implementations must hold the permit until Release, including on
+// cancellation while the worker unwinds.
+type ImportAdmission interface {
+ Acquire(context.Context) (func(), error)
+}
+
+// ImportEstimate carries non-secret planning inputs to admission. Nil totals
+// mean readiness has not established an estimate, not zero-cost work.
+type ImportEstimate struct {
+ JobID string
+ Projects int
+ AssetSchemas int
+ WorkerCeiling int
+ AttachmentCeilingBytes int64
+ BlobAllowanceBytes int64
+ EstimatedIssues *int64
+ EstimatedBlobBytes *int64
+}
+
+type importEstimateKey struct{}
+
+func WithImportEstimate(ctx context.Context, estimate ImportEstimate) context.Context {
+ return context.WithValue(ctx, importEstimateKey{}, estimate)
+}
+
+func ImportEstimateFromContext(ctx context.Context) (ImportEstimate, bool) {
+ estimate, ok := ctx.Value(importEstimateKey{}).(ImportEstimate)
+ return estimate, ok
+}
+
+// FileImportAdmission coordinates isolated instances sharing one local host
+// directory. Locks release on process death. Cross-host fencing is external.
+type FileImportAdmission struct {
+ Directory string
+ Slots int
+}
+
+func (a FileImportAdmission) TryAcquire(ctx context.Context) (func(), error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ root, err := os.OpenRoot(a.Directory)
+ if err != nil {
+ return nil, fmt.Errorf("%w: open admission directory", ErrAdmissionUnavailable)
+ }
+ defer func() { _ = root.Close() }()
+ for slot := 0; slot < a.Slots; slot++ {
+ file, err := root.OpenFile(fmt.Sprintf("import-%d.lock", slot), os.O_CREATE|os.O_RDWR, 0o600)
+ if err != nil {
+ return nil, fmt.Errorf("%w: open admission slot", ErrAdmissionUnavailable)
+ }
+ locked, err := tryImportLock(file)
+ if err != nil {
+ _ = file.Close()
+ return nil, fmt.Errorf("%w: lock admission slot", ErrAdmissionUnavailable)
+ }
+ if locked {
+ var once sync.Once
+ return func() { once.Do(func() { _ = file.Close() }) }, nil
+ }
+ _ = file.Close()
+ }
+ return nil, &LimitError{Resource: "import_slots"}
+}
+
+func (a FileImportAdmission) Acquire(ctx context.Context) (func(), error) {
+ ticker := time.NewTicker(200 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ release, err := a.TryAcquire(ctx)
+ var limited *LimitError
+ if !errors.As(err, &limited) {
+ return release, err
+ }
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-ticker.C:
+ }
+ }
+}
+
+func (c *Controls) ImportAdmission() (ImportAdmission, time.Duration) {
+ if c == nil || c.policy.Imports == nil {
+ return nil, 0
+ }
+ p := c.policy.Imports
+ return FileImportAdmission{Directory: p.AdmissionDirectory, Slots: p.Slots}, time.Duration(p.WaitSeconds) * time.Second
+}
+
+type importPermitKey struct{}
+
+func (c *Controls) WithImportPermit(ctx context.Context) context.Context {
+ return context.WithValue(ctx, importPermitKey{}, c)
+}
+
+// CheckImport keeps other bulk importers unavailable when only Jira admission is qualified.
+// Nested work in an admitted Jira import shares its existing permit.
+func (c *Controls) CheckImport(ctx context.Context, kind string) error {
+ if err := c.Check(Imports); err != nil {
+ return err
+ }
+ if c != nil && c.policy.Imports != nil && kind != "jira" && ctx.Value(importPermitKey{}) != c {
+ return &DeniedError{Capability: Imports}
+ }
+ return nil
+}
diff --git a/internal/operatorcontrols/import_lock_other.go b/internal/operatorcontrols/import_lock_other.go
new file mode 100644
index 000000000..fcf2e8950
--- /dev/null
+++ b/internal/operatorcontrols/import_lock_other.go
@@ -0,0 +1,7 @@
+//go:build !linux && !darwin && !windows
+
+package operatorcontrols
+
+import "os"
+
+func tryImportLock(_ *os.File) (bool, error) { return false, ErrAdmissionUnavailable }
diff --git a/internal/operatorcontrols/import_lock_unix.go b/internal/operatorcontrols/import_lock_unix.go
new file mode 100644
index 000000000..5afe27836
--- /dev/null
+++ b/internal/operatorcontrols/import_lock_unix.go
@@ -0,0 +1,18 @@
+//go:build linux || darwin
+
+package operatorcontrols
+
+import (
+ "errors"
+ "os"
+
+ "golang.org/x/sys/unix"
+)
+
+func tryImportLock(file *os.File) (bool, error) {
+ err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB)
+ if errors.Is(err, unix.EWOULDBLOCK) {
+ return false, nil
+ }
+ return err == nil, err
+}
diff --git a/internal/operatorcontrols/import_lock_windows.go b/internal/operatorcontrols/import_lock_windows.go
new file mode 100644
index 000000000..26b21bcf0
--- /dev/null
+++ b/internal/operatorcontrols/import_lock_windows.go
@@ -0,0 +1,16 @@
+package operatorcontrols
+
+import (
+ "errors"
+ "os"
+
+ "golang.org/x/sys/windows"
+)
+
+func tryImportLock(file *os.File) (bool, error) {
+ err := windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &windows.Overlapped{})
+ if errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
+ return false, nil
+ }
+ return err == nil, err
+}
diff --git a/internal/operatorcontrols/policy.go b/internal/operatorcontrols/policy.go
new file mode 100644
index 000000000..2a783de5b
--- /dev/null
+++ b/internal/operatorcontrols/policy.go
@@ -0,0 +1,186 @@
+// Package operatorcontrols enforces deployment-owned restrictions independently
+// of organization settings and user permissions.
+package operatorcontrols
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/mail"
+ "os"
+ "slices"
+)
+
+type Capability string
+
+const (
+ Lifecycle Capability = "instance_lifecycle"
+ Maintenance Capability = "maintenance"
+ RuntimeDiagnostics Capability = "runtime_diagnostics"
+ PluginExec Capability = "plugin_exec"
+ LDAP Capability = "ldap"
+ Scripts Capability = "server_scripts"
+ Imports Capability = "imports"
+ MailTransport Capability = "mail_transport_management"
+ GenericMail Capability = "generic_mail"
+ AI Capability = "ai"
+ AIConnections Capability = "ai_connection_management"
+ MailSend Capability = "mail"
+)
+
+var capabilities = []Capability{Lifecycle, Maintenance, RuntimeDiagnostics, PluginExec, LDAP, Scripts, Imports, MailTransport, GenericMail, AI, AIConnections, MailSend}
+
+// Policy is operator input, not an application preference. Zero values preserve
+// unrestricted self-managed behavior. Limits of zero mean no additional ceiling.
+type Policy struct {
+ Deny []Capability `json:"deny,omitempty"`
+ Limits Limits `json:"limits,omitempty"`
+ Mail *MailPolicy `json:"mail,omitempty"`
+ AI *AIPolicy `json:"ai,omitempty"`
+ Imports *ImportPolicy `json:"imports,omitempty"`
+}
+
+type ImportPolicy struct {
+ AdmissionDirectory string `json:"admission_directory"`
+ Slots int `json:"slots"`
+ WaitSeconds int `json:"wait_seconds"`
+}
+
+type AIPolicy struct {
+ AllowedModels []string `json:"allowed_models,omitempty"`
+ DeniedFeatures []string `json:"denied_features,omitempty"`
+ MaxOutputTokens int `json:"max_output_tokens,omitempty"`
+ // CallTokenReservation must cover the qualified model's complete input and
+ // output envelope. Unknown usage retains this full amount.
+ CallTokenReservation int64 `json:"call_token_reservation,omitempty"`
+}
+
+// MailPolicy selects an operator relay responsible for suppression, bounce
+// and complaint handling. Credentials never enter tenant persistence/discovery.
+type MailPolicy struct {
+ Mode string `json:"mode"`
+ Suspended bool `json:"suspended,omitempty"`
+ Host string `json:"host,omitempty"`
+ Port int `json:"port,omitempty"`
+ Encryption string `json:"encryption,omitempty"`
+ Username string `json:"username,omitempty"`
+ Password string `json:"password,omitempty"`
+ FromAddress string `json:"from_address,omitempty"`
+ FromName string `json:"from_name,omitempty"`
+ RelayAbuseControls bool `json:"relay_abuse_controls,omitempty"`
+}
+
+type Limits struct {
+ AttachmentBytes int64 `json:"attachment_bytes,omitempty"`
+ BlobBytes int64 `json:"blob_bytes,omitempty"`
+ ConcurrentRequests int `json:"concurrent_requests,omitempty"`
+ ConcurrentStreams int `json:"concurrent_streams,omitempty"`
+ RequestsPerMinute int64 `json:"requests_per_minute,omitempty"`
+ ScriptTimeoutMS int `json:"script_timeout_ms,omitempty"`
+ ConcurrentScripts int `json:"concurrent_scripts,omitempty"`
+ AutomationStepsPerDay int64 `json:"automation_steps_per_day,omitempty"`
+ MailRecipientsPerDay int64 `json:"mail_recipients_per_day,omitempty"`
+ AITokensPerDay int64 `json:"ai_tokens_per_day,omitempty"`
+ ConcurrentAI int `json:"concurrent_ai,omitempty"`
+}
+
+func (p Policy) Validate() error {
+ if p.Imports != nil && (p.Imports.AdmissionDirectory == "" || p.Imports.Slots < 1 || p.Imports.Slots > 64 || p.Imports.WaitSeconds < 1 || p.Imports.WaitSeconds > 3600) {
+ return errors.New("import admission requires an operator directory, 1–64 slots and a 1–3600 second wait bound")
+ }
+ if p.AI != nil {
+ if p.AI.MaxOutputTokens < 0 || p.AI.CallTokenReservation < 0 {
+ return errors.New("AI operator bounds must not be negative")
+ }
+ for _, model := range p.AI.AllowedModels {
+ if model == "" {
+ return errors.New("operator AI model must not be empty")
+ }
+ }
+ }
+ if p.Limits.AITokensPerDay > 0 && (p.AI == nil || len(p.AI.AllowedModels) == 0 || p.AI.CallTokenReservation <= 0 || p.AI.MaxOutputTokens <= 0 || p.AI.CallTokenReservation > p.Limits.AITokensPerDay || p.AI.CallTokenReservation <= int64(p.AI.MaxOutputTokens) || p.AI.CallTokenReservation-int64(p.AI.MaxOutputTokens) <= 8192) {
+ return errors.New("AI daily allowance requires an affordable qualified call reservation and output cap")
+ }
+ if p.Mail != nil {
+ switch p.Mail.Mode {
+ case "tenant", "disabled":
+ case "managed":
+ m := p.Mail
+ if m.Host == "" || m.Port < 1 || m.Port > 65535 || (m.Encryption != "tls" && m.Encryption != "ssl" && m.Encryption != "starttls") {
+ return errors.New("managed mail requires a host, port and verified TLS transport")
+ }
+ if !m.RelayAbuseControls {
+ return errors.New("managed mail requires relay suppression, bounce and complaint controls")
+ }
+ address, err := mail.ParseAddress(m.FromAddress)
+ if err != nil || address.Address != m.FromAddress {
+ return errors.New("managed mail requires a fixed bare sender address")
+ }
+ default:
+ return errors.New("invalid operator mail mode")
+ }
+ }
+ for _, capability := range p.Deny {
+ if !slices.Contains(capabilities, capability) {
+ return fmt.Errorf("unknown operator capability %q", capability)
+ }
+ }
+ limits := p.Limits
+ for name, value := range map[string]int64{
+ "attachment_bytes": limits.AttachmentBytes, "blob_bytes": limits.BlobBytes,
+ "concurrent_requests": int64(limits.ConcurrentRequests), "concurrent_streams": int64(limits.ConcurrentStreams),
+ "requests_per_minute": limits.RequestsPerMinute, "script_timeout_ms": int64(limits.ScriptTimeoutMS),
+ "concurrent_scripts": int64(limits.ConcurrentScripts), "automation_steps_per_day": limits.AutomationStepsPerDay,
+ "mail_recipients_per_day": limits.MailRecipientsPerDay, "ai_tokens_per_day": limits.AITokensPerDay,
+ "concurrent_ai": int64(limits.ConcurrentAI),
+ } {
+ if value < 0 {
+ return fmt.Errorf("operator limit %s must not be negative", name)
+ }
+ }
+ return nil
+}
+
+// Load rejects unknown fields and trailing data so configuration typos fail closed.
+func Load(path string) (Policy, error) {
+ if path == "" {
+ return Policy{}, nil
+ }
+ data, err := os.ReadFile(path) //nolint:gosec // operator-owned startup path
+ if err != nil {
+ return Policy{}, fmt.Errorf("read operator policy: %w", err)
+ }
+ if len(data) > 64*1024 {
+ return Policy{}, errors.New("operator policy exceeds 64 KiB")
+ }
+ if bytes.Equal(bytes.TrimSpace(data), []byte("null")) {
+ return Policy{}, errors.New("operator policy must be an object")
+ }
+ decoder := json.NewDecoder(bytes.NewReader(data))
+ decoder.DisallowUnknownFields()
+ var policy Policy
+ if err := decoder.Decode(&policy); err != nil {
+ return Policy{}, fmt.Errorf("decode operator policy: %w", err)
+ }
+ var extra any
+ if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
+ return Policy{}, errors.New("operator policy contains trailing data")
+ }
+ return policy, policy.Validate()
+}
+
+type DeniedError struct{ Capability Capability }
+
+func (e *DeniedError) Error() string {
+ return fmt.Sprintf("%s is disabled by operator policy", e.Capability)
+}
+
+// From follows the instance's injected carrier rather than global process state.
+func From(source any) *Controls {
+ if carrier, ok := source.(interface{ OperatorControls() *Controls }); ok {
+ return carrier.OperatorControls()
+ }
+ return nil
+}
diff --git a/internal/plugins/cli_host.go b/internal/plugins/cli_host.go
index 81205e2ec..99f5e183f 100644
--- a/internal/plugins/cli_host.go
+++ b/internal/plugins/cli_host.go
@@ -11,6 +11,7 @@ import (
"strings"
"time"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
extism "github.com/extism/go-sdk"
@@ -160,6 +161,9 @@ func (m *Manager) cliExecHostFunction(ctx context.Context, plugin *extism.Curren
// effect immediately. Missing database wiring, absent settings, and read
// failures all leave this security-sensitive capability disabled.
func (m *Manager) cliExecEnabled() (bool, error) {
+ if err := operatorcontrols.From(m.db).Check(operatorcontrols.PluginExec); err != nil {
+ return false, err
+ }
if m.db == nil {
return false, nil
}
diff --git a/internal/repository/actionutil/flow_runner.go b/internal/repository/actionutil/flow_runner.go
index 5a807ee7b..a07d3f418 100644
--- a/internal/repository/actionutil/flow_runner.go
+++ b/internal/repository/actionutil/flow_runner.go
@@ -36,6 +36,8 @@ type FlowOptions struct {
// TotalSteps is a shared counter across nested flows — an iterator body
// shares the outer flow's budget. Nil means the runner keeps its own.
TotalSteps *int
+ // AdmitStep reserves aggregate capacity before dispatch, including iterators.
+ AdmitStep func(context.Context) error
// OnStep is invoked for every recorded step, in order. Engines use it to
// mirror steps into their execution context while the flow runs, since
// condition edges and iterators read earlier results mid-flow.
@@ -115,6 +117,13 @@ func RunFlow[N RunnerNode, E ActionEdge](execCtx context.Context, nodes []N, edg
continue
}
+ if opts.AdmitStep != nil && (opts.MaxSteps == 0 || *total < opts.MaxSteps) {
+ if err := opts.AdmitStep(execCtx); err != nil {
+ now := time.Now()
+ record(models.StepResult{NodeID: node.GetID(), NodeType: models.ActionNodeType(node.GetNodeType()), Status: models.ActionStatusFailed, StartedAt: now, CompletedAt: &now, ErrorMessage: err.Error()})
+ return run, err
+ }
+ }
*total++
if opts.MaxSteps > 0 && *total > opts.MaxSteps {
now := time.Now()
diff --git a/internal/repository/operator_usage_repository.go b/internal/repository/operator_usage_repository.go
new file mode 100644
index 000000000..8d305e639
--- /dev/null
+++ b/internal/repository/operator_usage_repository.go
@@ -0,0 +1,63 @@
+package repository
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+
+ "windshift/internal/database"
+ "windshift/internal/operatorcontrols"
+)
+
+type OperatorUsageRepository struct{ db database.Database }
+
+func NewOperatorUsageRepository(db database.Database) *OperatorUsageRepository {
+ return &OperatorUsageRepository{db: db}
+}
+
+func (r *OperatorUsageRepository) Reserve(ctx context.Context, resource string, period, amount, ceiling int64) error {
+ if amount < 0 || amount > ceiling {
+ return &operatorcontrols.LimitError{Resource: resource}
+ }
+ result, err := r.db.ExecWriteContext(ctx, `INSERT INTO operator_usage (resource, period, used) VALUES (?, ?, ?)
+ ON CONFLICT (resource, period) DO UPDATE SET used = operator_usage.used + excluded.used
+ WHERE operator_usage.used <= ?`, resource, period, amount, ceiling-amount)
+ if err != nil {
+ return err
+ }
+ n, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return &operatorcontrols.LimitError{Resource: resource}
+ }
+ return nil
+}
+
+func (r *OperatorUsageRepository) Refund(ctx context.Context, resource string, period, amount int64) error {
+ if amount < 0 {
+ return errors.New("negative operator usage refund")
+ }
+ result, err := r.db.ExecWriteContext(ctx, `UPDATE operator_usage SET used = used - ? WHERE resource = ? AND period = ? AND used >= ?`, amount, resource, period, amount)
+ if err != nil {
+ return err
+ }
+ n, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n != 1 {
+ return errors.New("operator usage reservation missing")
+ }
+ return nil
+}
+
+func (r *OperatorUsageRepository) Used(ctx context.Context, resource string, period int64) (int64, error) {
+ var used int64
+ err := r.db.QueryRowContext(ctx, `SELECT used FROM operator_usage WHERE resource = ? AND period = ?`, resource, period).Scan(&used)
+ if errors.Is(err, sql.ErrNoRows) {
+ return 0, nil
+ }
+ return used, err
+}
diff --git a/internal/repository/system_setting_repository.go b/internal/repository/system_setting_repository.go
index bbe16036b..8653400c3 100644
--- a/internal/repository/system_setting_repository.go
+++ b/internal/repository/system_setting_repository.go
@@ -6,6 +6,7 @@ import (
"fmt"
"windshift/internal/database"
+ "windshift/internal/operatorcontrols"
)
// SystemSettingRepository provides data access for the system_settings table.
@@ -18,9 +19,23 @@ func NewSystemSettingRepository(db database.Database) *SystemSettingRepository {
return &SystemSettingRepository{db: db}
}
+func (r *SystemSettingRepository) CheckPluginExecution() error {
+ return operatorcontrols.From(r.db).Check(operatorcontrols.PluginExec)
+}
+
+func (r *SystemSettingRepository) OperatorControls() *operatorcontrols.Controls {
+ if r == nil {
+ return nil
+ }
+ return operatorcontrols.From(r.db)
+}
+
// GetValue returns the value for the given setting key. The second return
// value indicates whether the key exists and has a non-NULL value.
func (r *SystemSettingRepository) GetValue(key string) (value string, ok bool, err error) {
+ if key == "plugin_cli_exec_enabled" && !operatorcontrols.From(r.db).Allowed(operatorcontrols.PluginExec) {
+ return "false", true, nil
+ }
var val sql.NullString
err = r.db.QueryRow("SELECT value FROM system_settings WHERE key = ?", key).Scan(&val)
if errors.Is(err, sql.ErrNoRows) {
@@ -39,6 +54,11 @@ func (r *SystemSettingRepository) GetValue(key string) (value string, ok bool, e
// doesn't already exist. valueType, description, and category are only used
// for a fresh insert.
func (r *SystemSettingRepository) Upsert(key, value, valueType, description, category string) error {
+ if key == "plugin_cli_exec_enabled" && value != "false" {
+ if err := operatorcontrols.From(r.db).Check(operatorcontrols.PluginExec); err != nil {
+ return err
+ }
+ }
result, err := r.db.ExecWrite(`
UPDATE system_settings SET value = ?, updated_at = CURRENT_TIMESTAMP
WHERE key = ?
diff --git a/internal/restapi/v2/contract-metadata.json b/internal/restapi/v2/contract-metadata.json
index 30698aecf..841be1218 100644
--- a/internal/restapi/v2/contract-metadata.json
+++ b/internal/restapi/v2/contract-metadata.json
@@ -9141,6 +9141,23 @@
]
}
},
+ "/operator-controls": {
+ "get": {
+ "description": "Read effective operator restrictions, current instance usage and blocked script definitions. Requires system administrator permission and admin:operator-controls:read for bearer tokens. Credentials and deployment paths are never returned. This read-only operation cannot modify operator policy.",
+ "parameters": [],
+ "responses": {
+ "401": {},
+ "403": {},
+ "429": {},
+ "500": {},
+ "503": {}
+ },
+ "summary": "Read operator controls",
+ "tags": [
+ "Administration"
+ ]
+ }
+ },
"/packs": {
"get": {
"description": "List built-in framework packs. Results include only resources visible to the authenticated caller; collections use their documented stable order and bounds.",
diff --git a/internal/restapi/v2/error.go b/internal/restapi/v2/error.go
index c1b841275..2a460ff16 100644
--- a/internal/restapi/v2/error.go
+++ b/internal/restapi/v2/error.go
@@ -10,6 +10,7 @@ import (
"net/http"
"windshift/internal/contextkeys"
+ "windshift/internal/operatorcontrols"
)
// Handler is the v2 transport boundary. Failures are written only by Adapt.
@@ -79,6 +80,20 @@ func Adapt(handler Handler) http.Handler {
func writeError(w http.ResponseWriter, requestID string, err error) {
var apiErr *Error
+ var denied *operatorcontrols.DeniedError
+ var limited *operatorcontrols.LimitError
+ switch {
+ case errors.As(err, &denied):
+ err = newError(http.StatusForbidden, "operator_restricted", denied.Error())
+ case errors.As(err, &limited):
+ limitErr := newError(limited.Status(), "operator_limit_exceeded", limited.Error())
+ if limited.Status() == http.StatusTooManyRequests {
+ limitErr.Headers = http.Header{"Retry-After": []string{"60"}}
+ }
+ err = limitErr
+ case errors.Is(err, operatorcontrols.ErrBudgetUnavailable):
+ err = newError(http.StatusServiceUnavailable, "operator_budget_unavailable", err.Error())
+ }
if !errors.As(err, &apiErr) {
apiErr = internalError(err)
}
diff --git a/internal/restapi/v2/operator_controls.go b/internal/restapi/v2/operator_controls.go
new file mode 100644
index 000000000..f8bc74d36
--- /dev/null
+++ b/internal/restapi/v2/operator_controls.go
@@ -0,0 +1,23 @@
+package v2
+
+import (
+ "net/http"
+
+ "windshift/internal/services"
+)
+
+func registerOperatorControlsRoutes(builder *routeBuilder, deps Deps) {
+ builder.Read("/operator-controls", AuthAuthenticated, []string{"admin:operator-controls:read"}, func(r *http.Request) (services.OperatorControlsStatus, error) {
+ if _, err := requireSystemAdmin(r, deps); err != nil {
+ return services.OperatorControlsStatus{}, err
+ }
+ if deps.OperatorControls == nil {
+ return services.OperatorControlsStatus{}, newError(http.StatusServiceUnavailable, "operator_controls_unavailable", "Operator controls discovery is unavailable")
+ }
+ status, err := deps.OperatorControls.Status(r.Context())
+ if err != nil {
+ return services.OperatorControlsStatus{}, internalError(err)
+ }
+ return status, nil
+ })
+}
diff --git a/internal/restapi/v2/router.go b/internal/restapi/v2/router.go
index 271185a00..464ea3e1d 100644
--- a/internal/restapi/v2/router.go
+++ b/internal/restapi/v2/router.go
@@ -626,6 +626,7 @@ type actionApplication interface {
// Deps lists every required v2 dependency. Construction has no fallbacks.
type Deps struct {
+ OperatorControls *services.OperatorControlsService
PasskeyLogin passkeyLoginHTTP
PasskeyLoginLimiter requestLimiter
CustomerAccess customerAccessHTTP
@@ -956,6 +957,7 @@ func buildRoutes(deps Deps) []route {
registerWorklogRoutes(&builder, deps)
registerTimeRoutes(&builder, deps)
registerAdminRoutes(&builder, deps)
+ registerOperatorControlsRoutes(&builder, deps)
registerAdminIntegrationRoutes(&builder, deps)
registerPageRoutes(&builder, deps)
registerCommentRoutes(&builder, deps)
@@ -1091,6 +1093,9 @@ func appendUniqueParameter(parameters []ParameterMetadata, candidate ParameterMe
}
func applyParameterCorrections(route *Route) {
+ if route.Path == "/operator-controls" {
+ route.Description = "Read effective operator restrictions, current instance usage and blocked script definitions. Requires system administrator permission and admin:operator-controls:read for bearer tokens. Credentials and deployment paths are never returned. This read-only operation cannot modify operator policy."
+ }
if strings.HasPrefix(route.Path, "/admin/") && route.Exposure == ExposureBoth {
route.Description += " Requires system administrator permission and the declared bearer token scope. Responses use the standard v2 envelope."
if route.Path == "/admin/audit-logs/since" {
diff --git a/internal/server/server.go b/internal/server/server.go
index 8d8bd9fba..983bd4363 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -43,6 +43,7 @@ import (
"windshift/internal/middleware"
"windshift/internal/models"
"windshift/internal/objecttranslation"
+ "windshift/internal/operatorcontrols"
"windshift/internal/plugins"
"windshift/internal/portalwebauthn"
"windshift/internal/ratelimit"
@@ -323,6 +324,11 @@ func (s *Server) initialize() error {
if err = s.db.Initialize(); err != nil {
return fmt.Errorf("failed to initialize database: %w", err)
}
+ controls, err := operatorcontrols.New(cfg.OperatorPolicy, repository.NewOperatorUsageRepository(s.db))
+ if err != nil {
+ return fmt.Errorf("operator controls: %w", err)
+ }
+ s.db = database.WithOperatorControls(s.db, controls)
if err = database.ValidateCanonicalSchemaCheckpoint(s.db); err != nil {
return fmt.Errorf("database startup refused: %w", err)
}
@@ -704,6 +710,7 @@ func (s *Server) initialize() error {
if storageErr != nil {
return fmt.Errorf("initialize attachment storage: %w", storageErr)
}
+ attachmentStorage.SetOperatorControls(controls)
if attachmentStorage.Enabled() {
if attachmentStorage.Backend() == config.StorageBackendS3 {
// The S3 probe retries transient failures and tolerates an
@@ -1251,7 +1258,7 @@ func (s *Server) initialize() error {
itemHandler.SetActionService(s.actionService)
itemLinkService.WithActionEmitter(s.actionService)
- scriptEngine := services.NewScriptEngine()
+ scriptEngine := services.NewScriptEngine(controls)
conditionService := services.NewConditionService(s.db, permService, scriptEngine)
approvalService := services.NewApprovalService(s.db, leaveRepo, workflowService)
@@ -1584,13 +1591,13 @@ func (s *Server) initialize() error {
s.ldapHandler = handlers.NewLDAPHandler(s.db, ldapSyncService, ssoHandler.GetEncryption())
ldapHandler := s.ldapHandler
- featuresHandler := handlers.NewFeaturesHandler(s.pluginManager, cfg.SSH.Enabled)
+ featuresHandler := handlers.NewFeaturesHandler(s.pluginManager, cfg.SSH.Enabled, controls)
shutdownChan := cfg.ShutdownChan
if shutdownChan == nil {
shutdownChan = make(chan os.Signal, 1)
}
- systemHandler := handlers.NewSystemHandler(shutdownChan)
+ systemHandler := handlers.NewSystemHandler(shutdownChan, controls)
llmConnHandler := handlers.NewLLMConnectionHandler(llmManager, logger.NewAuditor(s.db), llmModelCache, llmModelRefresher)
workItemStalenessHandler := handlers.NewWorkItemStalenessHandler(
@@ -2117,6 +2124,7 @@ func (s *Server) initialize() error {
ItemDetail: itemDetailApplication,
ItemLifecycle: services.NewItemLifecycleService(s.db, permService),
TicketImport: services.NewTicketImportService(s.db, permService, importScratch),
+ OperatorControls: services.NewOperatorControlsService(s.db, attachmentStorage),
SessionMiddleware: authMiddleware.OptionalAuth,
SearchAllowed: s.searchLimiter.AllowRequest,
DBRequestTimeout: s.config.DB.RequestTimeout,
@@ -2265,7 +2273,7 @@ func (s *Server) initialize() error {
// Recovery converts panics before the metrics layer records the final status.
securityMiddleware := createSecurityHeaders(enableHTTPS, cfg.UseProxy, additionalProxyIPs, jiraHosts.Allowed, securitySettingsHandler.ExternalImagesAllowed)
compressionMiddleware := middleware.CreateCompressionMiddleware(cfg.UseProxy)
- applicationHandler := middleware.Recovery(compressionMiddleware(securityMiddleware(s.metrics.CaptureRoutePattern(mux))))
+ applicationHandler := middleware.Recovery(compressionMiddleware(securityMiddleware(middleware.OperatorAdmission(controls)(s.metrics.CaptureRoutePattern(mux)))))
handler := s.metrics.Instrument(applicationHandler)
handler = withContextPath(handler, cfg.ContextPath)
diff --git a/internal/services/action_engine_iterator.go b/internal/services/action_engine_iterator.go
index 9b358d3b3..70924ea4b 100644
--- a/internal/services/action_engine_iterator.go
+++ b/internal/services/action_engine_iterator.go
@@ -130,6 +130,7 @@ func (as *ActionService) runBodyOnce(
MaxSteps: maxStepsPerFlow,
BudgetExceededErr: errStepBudgetExceeded,
TotalSteps: &ctx.TotalSteps,
+ AdmitStep: automationStepAdmission(as.db),
}, func(node *models.ActionNode, step *models.StepResult, markExecuted func(int)) error {
// Iterators inside iterator bodies are valid — recurse.
if node.NodeType.IsIterator() {
diff --git a/internal/services/action_service.go b/internal/services/action_service.go
index bf5f25cc2..471017ff6 100644
--- a/internal/services/action_service.go
+++ b/internal/services/action_service.go
@@ -24,6 +24,7 @@ import (
"windshift/internal/llm"
"windshift/internal/logger"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/repository/actionutil"
"windshift/internal/utils"
@@ -767,6 +768,7 @@ func (as *ActionService) executeActionForEvent(executionCtx context.Context, act
MaxSteps: maxStepsPerFlow,
BudgetExceededErr: errStepBudgetExceeded,
TotalSteps: &ctx.TotalSteps,
+ AdmitStep: automationStepAdmission(as.db),
OnStep: func(step *models.StepResult) { ctx.StepResults = append(ctx.StepResults, *step) },
}, func(node *models.ActionNode, step *models.StepResult, markExecuted func(int)) error {
var err error
@@ -937,6 +939,11 @@ func (as *ActionService) bindExecutionRevision(action *models.Action, log *model
// precedence over the legacy switch so new node types can ship without
// touching this function.
func (as *ActionService) executeNode(node *models.ActionNode, ctx *models.ExecutionContext, stepResult *models.StepResult) error {
+ if string(node.NodeType) == "execute_script" {
+ if err := operatorcontrols.From(as.db).Check(operatorcontrols.Scripts); err != nil {
+ return err
+ }
+ }
if exec, ok := as.lookupNodeExecutor(node.NodeType); ok {
return exec.Execute(node, ctx, stepResult)
}
diff --git a/internal/services/asset_action_service.go b/internal/services/asset_action_service.go
index 911bc71cd..be84884bd 100644
--- a/internal/services/asset_action_service.go
+++ b/internal/services/asset_action_service.go
@@ -16,6 +16,7 @@ import (
"windshift/internal/database"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/repository/actionutil"
"windshift/internal/sanitize"
@@ -385,6 +386,11 @@ func (as *AssetActionService) executeActionWithResultForEvent(executionCtx conte
if event == nil {
return nil, fmt.Errorf("asset action event is required")
}
+ steps := 0
+ maxSteps := 0
+ if operatorcontrols.From(as.db).Limits().AutomationStepsPerDay > 0 {
+ maxSteps = maxStepsPerFlow
+ }
startTime := time.Now()
// Get or create execution chain
@@ -455,8 +461,12 @@ func (as *AssetActionService) executeActionWithResultForEvent(executionCtx conte
// Execute nodes
_, err := actionutil.RunFlow(executionCtx, action.Nodes, action.Edges, actionutil.FlowOptions{
- TriggerNodeType: string(models.AssetNodeTrigger),
- OnStep: func(step *models.StepResult) { ctx.StepResults = append(ctx.StepResults, *step) },
+ TriggerNodeType: string(models.AssetNodeTrigger),
+ MaxSteps: maxSteps,
+ BudgetExceededErr: errStepBudgetExceeded,
+ TotalSteps: &steps,
+ AdmitStep: automationStepAdmission(as.db),
+ OnStep: func(step *models.StepResult) { ctx.StepResults = append(ctx.StepResults, *step) },
}, func(node *models.AssetActionNode, step *models.StepResult, _ func(int)) error {
if err := as.executeNode(node, ctx, step); err != nil {
slog.Warn("asset action node execution failed",
@@ -555,6 +565,11 @@ func (as *AssetActionService) loadAssetVariables(ctx *models.AssetActionExecutio
}
func (as *AssetActionService) executeNode(node *models.AssetActionNode, ctx *models.AssetActionExecutionContext, stepResult *models.StepResult) error {
+ if string(node.NodeType) == "execute_script" {
+ if err := operatorcontrols.From(as.db).Check(operatorcontrols.Scripts); err != nil {
+ return err
+ }
+ }
switch node.NodeType {
case models.AssetNodeCreateItem:
return as.executeCreateItem(node, ctx, stepResult)
diff --git a/internal/services/asset_import_service.go b/internal/services/asset_import_service.go
index 4bd5d68c6..72e5bb4fb 100644
--- a/internal/services/asset_import_service.go
+++ b/internal/services/asset_import_service.go
@@ -1,6 +1,7 @@
package services
import (
+ "context"
"encoding/json"
"errors"
"fmt"
@@ -20,6 +21,7 @@ import (
"windshift/internal/database"
"windshift/internal/logger"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/sanitize"
)
@@ -124,6 +126,9 @@ func (s *AssetApplicationService) WithImportStorage(path string) *AssetApplicati
}
func (s *AssetApplicationService) UploadCSV(userID, setID int, filename string, hasHeader bool, delimiterName string, source io.Reader) (AssetCSVUpload, error) {
+ if err := operatorcontrols.From(s.db).CheckImport(context.Background(), "assets"); err != nil {
+ return AssetCSVUpload{}, err
+ }
if err := s.require(userID, setID, AssetPermissionKeyAdmin); err != nil {
return AssetCSVUpload{}, err
}
@@ -141,6 +146,9 @@ func (s *AssetApplicationService) UploadCSV(userID, setID int, filename string,
}
func (s *AssetApplicationService) StartImport(userID, setID int, actor AuditActor, input StartAssetImport) (AssetImportJob, error) {
+ if err := operatorcontrols.From(s.db).CheckImport(context.Background(), "assets"); err != nil {
+ return AssetImportJob{}, err
+ }
if err := s.require(userID, setID, AssetPermissionKeyAdmin); err != nil {
return AssetImportJob{}, err
}
diff --git a/internal/services/attachment_settings_service.go b/internal/services/attachment_settings_service.go
index 5407e8f78..faaed6603 100644
--- a/internal/services/attachment_settings_service.go
+++ b/internal/services/attachment_settings_service.go
@@ -7,10 +7,12 @@ import (
"errors"
"fmt"
"log/slog"
+ "time"
"windshift/internal/blobstore"
"windshift/internal/database"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
)
// AttachmentSettingsService encapsulates business logic for attachment settings.
@@ -79,6 +81,9 @@ func (s *AttachmentSettingsService) Get() (*models.AttachmentSettings, error) {
if errors.Is(err, sql.ErrNoRows) {
// No settings in database, return defaults
+ if ceiling := operatorcontrols.From(s.db).Limits().AttachmentBytes; ceiling > 0 && settings.MaxFileSize > ceiling {
+ settings.MaxFileSize = ceiling
+ }
return settings, nil
}
@@ -86,11 +91,20 @@ func (s *AttachmentSettingsService) Get() (*models.AttachmentSettings, error) {
return nil, fmt.Errorf("failed to get attachment settings: %w", err)
}
+ if ceiling := operatorcontrols.From(s.db).Limits().AttachmentBytes; ceiling > 0 && settings.MaxFileSize > ceiling {
+ settings.MaxFileSize = ceiling
+ }
+ if operatorcontrols.From(s.db).Active() {
+ settings.AttachmentPath = ""
+ }
return settings, nil
}
// Update modifies attachment settings by ID.
func (s *AttachmentSettingsService) Update(settingsID int, req *models.AttachmentSettingsRequest) (*models.AttachmentSettings, error) {
+ if ceiling := operatorcontrols.From(s.db).Limits().AttachmentBytes; ceiling > 0 && req.MaxFileSize > ceiling {
+ return nil, &operatorcontrols.LimitError{Resource: "attachment_bytes"}
+ }
// Validate max file size
if req.MaxFileSize <= 0 {
return nil, fmt.Errorf("max file size must be greater than 0")
@@ -133,10 +147,11 @@ func (s *AttachmentSettingsService) Update(settingsID int, req *models.Attachmen
// AttachmentStatus represents the status of the attachment system.
type AttachmentStatus struct {
- Enabled bool `json:"enabled"`
- AttachmentPath string `json:"attachment_path"`
- Backend string `json:"backend"`
- Writable bool `json:"writable"`
+ Usage *blobstore.Usage `json:"usage,omitempty"`
+ Enabled bool `json:"enabled"`
+ AttachmentPath string `json:"attachment_path"`
+ Backend string `json:"backend"`
+ Writable bool `json:"writable"`
}
// GetStatus returns the attachment system status (enabled/disabled, backend,
@@ -148,6 +163,18 @@ func (s *AttachmentSettingsService) GetStatus() (*AttachmentStatus, error) {
Backend: s.storage.Backend(),
Writable: false,
}
+ if controls := operatorcontrols.From(s.db); controls.Active() {
+ status.AttachmentPath = ""
+ if controls.Limits().BlobBytes > 0 {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ usage, err := s.storage.Usage(ctx)
+ if err != nil {
+ return nil, err
+ }
+ status.Usage = &usage
+ }
+ }
var enabled bool
err := s.db.QueryRow(`
diff --git a/internal/services/automation_operator_controls.go b/internal/services/automation_operator_controls.go
new file mode 100644
index 000000000..509570627
--- /dev/null
+++ b/internal/services/automation_operator_controls.go
@@ -0,0 +1,19 @@
+package services
+
+import (
+ "context"
+ "time"
+
+ "windshift/internal/database"
+ "windshift/internal/operatorcontrols"
+)
+
+func automationStepAdmission(db database.Database) func(context.Context) error {
+ controls := operatorcontrols.From(db)
+ if controls.Limits().AutomationStepsPerDay == 0 {
+ return nil
+ }
+ return func(ctx context.Context) error {
+ return controls.Consume(ctx, "automation_steps", 1, controls.Limits().AutomationStepsPerDay, 24*time.Hour)
+ }
+}
diff --git a/internal/services/channel_config_update_service.go b/internal/services/channel_config_update_service.go
index 02daf1cf0..6ffed7ea6 100644
--- a/internal/services/channel_config_update_service.go
+++ b/internal/services/channel_config_update_service.go
@@ -150,6 +150,9 @@ func (s *ChannelConfigUpdateService) Update(ctx context.Context, actorUserID, ch
if err := json.Unmarshal(configJSON, &final); err != nil {
return false, channelConfigInvalid("Channel config fields have invalid types")
}
+ if err := s.channels.CheckTransportConfig(ctx, channelID, string(configJSON)); err != nil {
+ return false, err
+ }
if err := s.validate(ctx, actorUserID, channel, incoming, stored, &final); err != nil {
return false, err
diff --git a/internal/services/channel_operator_controls.go b/internal/services/channel_operator_controls.go
new file mode 100644
index 000000000..d9bd1f5ad
--- /dev/null
+++ b/internal/services/channel_operator_controls.go
@@ -0,0 +1,51 @@
+package services
+
+import (
+ "context"
+ "encoding/json"
+
+ "windshift/internal/models"
+ "windshift/internal/operatorcontrols"
+)
+
+func (s *ChannelService) checkChannelPolicy(kind, raw string) error {
+ controls := operatorcontrols.From(s.db)
+ if controls.Allowed(operatorcontrols.GenericMail) && controls.Allowed(operatorcontrols.MailTransport) {
+ return nil
+ }
+ if kind == "smtp" {
+ if err := controls.Check(operatorcontrols.MailTransport); err != nil {
+ return err
+ }
+ return controls.Check(operatorcontrols.GenericMail)
+ }
+ if kind != "email" && kind != "imap" {
+ return nil
+ }
+ var config models.ChannelConfig
+ if raw != "" {
+ if err := json.Unmarshal([]byte(raw), &config); err != nil {
+ return err
+ }
+ }
+ if kind == "imap" || config.IMAPHost != "" {
+ return controls.Check(operatorcontrols.GenericMail)
+ }
+ return nil
+}
+
+func (s *ChannelService) CheckTransportMutation(ctx context.Context, id int) error {
+ channel, err := s.repo.FindByID(ctx, id)
+ if err != nil {
+ return err
+ }
+ return s.checkChannelPolicy(channel.Type, channel.Config)
+}
+
+func (s *ChannelService) CheckTransportConfig(ctx context.Context, id int, raw string) error {
+ channel, err := s.repo.FindByID(ctx, id)
+ if err != nil {
+ return err
+ }
+ return s.checkChannelPolicy(channel.Type, raw)
+}
diff --git a/internal/services/channel_service.go b/internal/services/channel_service.go
index a8e7e137d..4e6136ef3 100644
--- a/internal/services/channel_service.go
+++ b/internal/services/channel_service.go
@@ -192,6 +192,9 @@ type ChannelCreateRequest struct {
// Create creates a new channel
func (s *ChannelService) Create(ctx context.Context, req ChannelCreateRequest) (*models.Channel, error) {
+ if err := s.checkChannelPolicy(req.Type, req.Config); err != nil {
+ return nil, err
+ }
if req.Name == "" || req.Type == "" || req.Direction == "" {
return nil, fmt.Errorf("name, type, and direction are required")
}
@@ -281,6 +284,9 @@ type ChannelUpdateRequest struct {
// Update updates an existing channel
func (s *ChannelService) Update(ctx context.Context, id int, req ChannelUpdateRequest) (*models.Channel, error) {
+ if err := s.CheckTransportMutation(ctx, id); err != nil {
+ return nil, err
+ }
if req.Name == "" {
return nil, fmt.Errorf("%w: name is required", ErrInvalidChannelField)
}
@@ -313,6 +319,9 @@ func (s *ChannelService) Update(ctx context.Context, id int, req ChannelUpdateRe
// Delete removes a channel
func (s *ChannelService) Delete(ctx context.Context, id int) error {
+ if err := s.CheckTransportMutation(ctx, id); err != nil {
+ return err
+ }
// Check if channel is plugin-managed
isPluginManaged, err := s.repo.IsPluginManaged(ctx, id)
if err != nil {
@@ -335,12 +344,18 @@ func (s *ChannelService) UpdateLastActivity(ctx context.Context, id int) error {
// SetStatus updates only the status column. Plugin-managed channels are
// rejected at the SQL level (plugin_name IS NULL), surfacing as ErrNotFound.
func (s *ChannelService) SetStatus(ctx context.Context, id int, status string) error {
+ if err := s.CheckTransportMutation(ctx, id); err != nil {
+ return err
+ }
return database.WithTx(s.db, func(tx database.Tx) error {
return s.repo.SetStatus(ctx, tx, id, status)
})
}
func (s *ChannelService) SetStatusIfConfigUnchanged(ctx context.Context, id int, status, expectedConfig string) (bool, error) {
+ if err := s.CheckTransportMutation(ctx, id); err != nil {
+ return false, err
+ }
return database.WithTxResult(s.db, func(tx database.Tx) (bool, error) {
return s.repo.SetStatusIfConfigUnchanged(ctx, tx, id, status, expectedConfig)
})
@@ -348,6 +363,9 @@ func (s *ChannelService) SetStatusIfConfigUnchanged(ctx context.Context, id int,
// UpdateConfig updates only the config column with caller-prepared JSON.
func (s *ChannelService) UpdateConfig(ctx context.Context, id int, config string) error {
+ if err := s.CheckTransportConfig(ctx, id, config); err != nil {
+ return err
+ }
return database.WithTx(s.db, func(tx database.Tx) error {
return s.repo.UpdateConfig(ctx, tx, id, config)
})
@@ -355,6 +373,9 @@ func (s *ChannelService) UpdateConfig(ctx context.Context, id int, config string
// UpdateConfigIfUnchanged avoids losing a concurrent channel-config edit.
func (s *ChannelService) UpdateConfigIfUnchanged(ctx context.Context, id int, expectedConfig, expectedStatus, config string) (bool, error) {
+ if err := s.CheckTransportConfig(ctx, id, config); err != nil {
+ return false, err
+ }
return database.WithTxResult(s.db, func(tx database.Tx) (bool, error) {
return s.repo.UpdateConfigIfUnchanged(ctx, tx, id, expectedConfig, expectedStatus, config)
})
diff --git a/internal/services/condition_service.go b/internal/services/condition_service.go
index 4086f4bd2..0e04055ec 100644
--- a/internal/services/condition_service.go
+++ b/internal/services/condition_service.go
@@ -9,6 +9,7 @@ import (
"windshift/internal/database"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
)
@@ -21,6 +22,9 @@ type ConditionService struct {
// NewConditionService creates a new condition service.
func NewConditionService(db database.Database, permService *PermissionService, scriptEngine *ScriptEngine) *ConditionService {
+ if controls := operatorcontrols.From(db); controls != nil {
+ scriptEngine = NewScriptEngine(controls)
+ }
return &ConditionService{
db: db,
permService: permService,
@@ -161,6 +165,13 @@ type TransitionWithID struct {
}
func (s *ConditionService) evaluateConditions(ctx context.Context, conditions []conditionRow, logicMode string, userID int, item map[string]any) (allowed bool, failureMessage string, err error) {
+ for _, condition := range conditions {
+ if condition.ConditionType == models.ConditionTypeScript {
+ if err := operatorcontrols.From(s.db).Check(operatorcontrols.Scripts); err != nil {
+ return false, "", err
+ }
+ }
+ }
// Validators are hard gates: every validator must pass regardless of the
// binding's logic mode. Conditions then decide availability under logicMode.
var conditionRules []conditionRow
@@ -351,6 +362,9 @@ func conditionFieldValue(fieldIdentifier string, item map[string]any) any {
}
func (s *ConditionService) evaluateScript(ctx context.Context, configJSON string, userID int, item map[string]any) (bool, error) {
+ if err := operatorcontrols.From(s.db).Check(operatorcontrols.Scripts); err != nil {
+ return false, err
+ }
var cfg models.ConditionScriptConfig
if err := json.Unmarshal([]byte(configJSON), &cfg); err != nil {
return false, fmt.Errorf("invalid script config: %w", err)
diff --git a/internal/services/condition_set_application_service.go b/internal/services/condition_set_application_service.go
index 371099bd0..288919c3e 100644
--- a/internal/services/condition_set_application_service.go
+++ b/internal/services/condition_set_application_service.go
@@ -12,6 +12,7 @@ import (
"windshift/internal/database"
"windshift/internal/logger"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/sanitize"
)
@@ -276,6 +277,11 @@ func (s *ConditionSetApplicationService) validateTransitions(workflowID int, tra
return governanceValidation("transition does not belong to workflow")
}
for _, condition := range transition.Conditions {
+ if condition.ConditionType == models.ConditionTypeScript {
+ if err := operatorcontrols.From(s.db).Check(operatorcontrols.Scripts); err != nil {
+ return err
+ }
+ }
if err := validateConditionInput(condition); err != nil {
return err
}
diff --git a/internal/services/config_set_import_service.go b/internal/services/config_set_import_service.go
index 8335c2c0f..8f847b4ea 100644
--- a/internal/services/config_set_import_service.go
+++ b/internal/services/config_set_import_service.go
@@ -12,6 +12,7 @@ import (
"windshift/internal/database"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
)
@@ -45,6 +46,22 @@ func NewConfigSetImportService(db database.Database, repo *repository.Configurat
// ErrDefaultEntityConflict the transaction has not been started; on any
// other error it has been rolled back.
func (s *ConfigSetImportService) Import(ctx context.Context, tpl *ConfigSetTemplate) (configSetID int, warnings []string, err error) {
+ if err := operatorcontrols.From(s.db).CheckImport(ctx, "configuration_set"); err != nil {
+ return 0, nil, err
+ }
+ if tpl != nil {
+ for _, set := range tpl.Payload.ConditionSets {
+ for _, transition := range set.TransitionConditions {
+ for _, condition := range transition.Conditions {
+ if condition.Type == models.ConditionTypeScript {
+ if err := operatorcontrols.From(s.db).Check(operatorcontrols.Scripts); err != nil {
+ return 0, nil, err
+ }
+ }
+ }
+ }
+ }
+ }
if err := s.validateEnvelope(tpl); err != nil {
return 0, nil, err
}
diff --git a/internal/services/configuration_set_provisioning.go b/internal/services/configuration_set_provisioning.go
index f389ab35c..105c73557 100644
--- a/internal/services/configuration_set_provisioning.go
+++ b/internal/services/configuration_set_provisioning.go
@@ -10,6 +10,7 @@ import (
"windshift/internal/database"
"windshift/internal/logger"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/sanitize"
)
@@ -212,6 +213,16 @@ func (s *ConfigurationSetProvisioningService) ValidateGovernanceRefs(cs *models.
}
func (s *ConfigurationSetProvisioningService) validateConditionSetWorkflow(conditionSetID int, workflowID *int, field string) error {
+ controls := operatorcontrols.From(s.db)
+ if !controls.Allowed(operatorcontrols.Scripts) {
+ var scripts bool
+ if err := s.db.QueryRow(`SELECT EXISTS(SELECT 1 FROM condition_set_transitions cst JOIN conditions c ON c.condition_set_transition_id=cst.id WHERE cst.condition_set_id=? AND c.condition_type='script')`, conditionSetID).Scan(&scripts); err != nil {
+ return err
+ }
+ if scripts {
+ return controls.Check(operatorcontrols.Scripts)
+ }
+ }
var conditionSetWorkflowID int
err := s.db.QueryRow(`SELECT workflow_id FROM condition_sets WHERE id = ?`, conditionSetID).Scan(&conditionSetWorkflowID)
if errors.Is(err, sql.ErrNoRows) {
diff --git a/internal/services/operator_controls_service.go b/internal/services/operator_controls_service.go
new file mode 100644
index 000000000..519ff1b86
--- /dev/null
+++ b/internal/services/operator_controls_service.go
@@ -0,0 +1,85 @@
+package services
+
+import (
+ "context"
+ "time"
+
+ "windshift/internal/blobstore"
+ "windshift/internal/database"
+ "windshift/internal/operatorcontrols"
+)
+
+type OperatorBlockedDefinition struct {
+ Kind string `json:"kind"`
+ ID int `json:"id"`
+ Name string `json:"name"`
+}
+
+type OperatorControlsStatus struct {
+ Policy operatorcontrols.Snapshot `json:"policy"`
+ Usage map[string]int64 `json:"usage"`
+ BlockedDefinitions []OperatorBlockedDefinition `json:"blocked_definitions"`
+ BlockedDefinitionsTruncated bool `json:"blocked_definitions_truncated"`
+}
+
+type OperatorControlsService struct {
+ db database.Database
+ storage *blobstore.Store
+}
+
+func NewOperatorControlsService(db database.Database, stores ...*blobstore.Store) *OperatorControlsService {
+ s := &OperatorControlsService{db: db}
+ if len(stores) > 0 {
+ s.storage = stores[0]
+ }
+ return s
+}
+
+// Status projects non-secret deployment policy and migration blockers without
+// modifying persisted organization preferences or executable definitions.
+func (s *OperatorControlsService) Status(ctx context.Context) (OperatorControlsStatus, error) {
+ controls := operatorcontrols.From(s.db)
+ status := OperatorControlsStatus{Policy: controls.Snapshot(), Usage: map[string]int64{}, BlockedDefinitions: []OperatorBlockedDefinition{}}
+ for resource, interval := range map[string]time.Duration{"requests": time.Minute, "automation_steps": 24 * time.Hour, "mail_recipients": 24 * time.Hour, "ai_tokens": 24 * time.Hour} {
+ used, err := controls.Used(ctx, resource, interval)
+ if err != nil {
+ return status, err
+ }
+ status.Usage[resource] = used
+ }
+ if controls.Limits().BlobBytes > 0 && s.storage.Enabled() {
+ usage, err := s.storage.Usage(ctx)
+ if err != nil {
+ return status, err
+ }
+ status.Usage["blob_bytes"] = usage.Bytes
+ }
+ if !controls.Allowed(operatorcontrols.Scripts) {
+ rows, err := s.db.QueryContext(ctx, `SELECT DISTINCT 'condition_set' AS kind, cs.id AS definition_id, cs.name FROM condition_sets cs
+ JOIN condition_set_transitions transitions ON transitions.condition_set_id=cs.id
+ JOIN conditions conditions ON conditions.condition_set_transition_id=transitions.id
+ WHERE conditions.condition_type='script'
+ UNION SELECT DISTINCT 'action' AS kind, a.id, a.name FROM actions a JOIN action_nodes n ON n.action_id=a.id WHERE n.node_type='execute_script'
+ UNION SELECT DISTINCT 'asset_action' AS kind, a.id, a.name FROM asset_actions a JOIN asset_action_nodes n ON n.action_id=a.id WHERE n.node_type='execute_script'
+ ORDER BY kind, definition_id LIMIT 1001`)
+ if err != nil {
+ return status, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ definition := OperatorBlockedDefinition{}
+ if err := rows.Scan(&definition.Kind, &definition.ID, &definition.Name); err != nil {
+ return status, err
+ }
+ status.BlockedDefinitions = append(status.BlockedDefinitions, definition)
+ }
+ if err := rows.Err(); err != nil {
+ return status, err
+ }
+ if len(status.BlockedDefinitions) > 1000 {
+ status.BlockedDefinitions = status.BlockedDefinitions[:1000]
+ status.BlockedDefinitionsTruncated = true
+ }
+ }
+ return status, nil
+}
diff --git a/internal/services/pack_apply_service.go b/internal/services/pack_apply_service.go
index 1e8c15b5d..cc6b71d34 100644
--- a/internal/services/pack_apply_service.go
+++ b/internal/services/pack_apply_service.go
@@ -11,6 +11,7 @@ import (
"windshift/internal/database"
"windshift/internal/logger"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
)
@@ -129,6 +130,9 @@ func (s *PackApplyService) Verify(ctx context.Context, req PackApplyRequest) (*P
// Apply provisions a new workspace from the pack. Framework packs only apply
// to new workspaces: the target name must not already exist.
func (s *PackApplyService) Apply(ctx context.Context, req PackApplyRequest) (*PackApplyReport, error) {
+ if err := operatorcontrols.From(s.db).CheckImport(ctx, "pack"); err != nil {
+ return nil, err
+ }
report, err := s.newReport(req)
if err != nil {
return nil, err
@@ -160,6 +164,9 @@ func (s *PackApplyService) Apply(ctx context.Context, req PackApplyRequest) (*Pa
// already-existing workspace. The caller owns workspace creation and plugin
// verification; this is the shared tail of Apply and create-from-template-pack.
func (s *PackApplyService) ApplyToWorkspace(ctx context.Context, actor AuditActor, workspaceID int, archive *PackArchive) (*PackApplyReport, error) {
+ if err := operatorcontrols.From(s.db).CheckImport(ctx, "pack"); err != nil {
+ return nil, err
+ }
req := PackApplyRequest{Archive: archive, Actor: actor}
report, err := s.newReport(req)
if err != nil {
diff --git a/internal/services/page_attachment_upload_service.go b/internal/services/page_attachment_upload_service.go
index 06aac5040..2cbfebded 100644
--- a/internal/services/page_attachment_upload_service.go
+++ b/internal/services/page_attachment_upload_service.go
@@ -16,6 +16,7 @@ import (
"windshift/internal/blobstore"
"windshift/internal/database"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
)
@@ -244,11 +245,17 @@ func loadAttachmentSettings(db database.Database) (*models.AttachmentSettings, e
FROM attachment_settings ORDER BY id DESC LIMIT 1
`).Scan(&settings.MaxFileSize, &settings.AllowedMimeTypes, &settings.AttachmentPath, &settings.Enabled)
if errors.Is(err, sql.ErrNoRows) {
+ if ceiling := operatorcontrols.From(db).Limits().AttachmentBytes; ceiling > 0 && settings.MaxFileSize > ceiling {
+ settings.MaxFileSize = ceiling
+ }
return settings, nil
}
if err != nil {
return nil, err
}
+ if ceiling := operatorcontrols.From(db).Limits().AttachmentBytes; ceiling > 0 && settings.MaxFileSize > ceiling {
+ settings.MaxFileSize = ceiling
+ }
return settings, nil
}
diff --git a/internal/services/script_engine.go b/internal/services/script_engine.go
index e5498ec15..d0d707eb7 100644
--- a/internal/services/script_engine.go
+++ b/internal/services/script_engine.go
@@ -7,6 +7,8 @@ import (
"math"
"time"
+ "windshift/internal/operatorcontrols"
+
"github.com/grafana/sobek"
)
@@ -23,11 +25,15 @@ const (
// runtime would let one script change what later executions observe. Creating a
// runtime costs a couple of microseconds, which is cheap enough that pooling is
// not worth the cross-execution isolation risk.
-type ScriptEngine struct{}
+type ScriptEngine struct{ controls *operatorcontrols.Controls }
// NewScriptEngine creates a new script engine.
-func NewScriptEngine() *ScriptEngine {
- return &ScriptEngine{}
+func NewScriptEngine(controls ...*operatorcontrols.Controls) *ScriptEngine {
+ e := &ScriptEngine{}
+ if len(controls) > 0 {
+ e.controls = controls[0]
+ }
+ return e
}
// Execute runs a JavaScript script with the given variables and returns the result
@@ -38,6 +44,14 @@ func NewScriptEngine() *ScriptEngine {
// The exported Go value is safe to use after this function returns; no sobek.Value
// escapes the runtime (which is NOT goroutine-safe).
func (e *ScriptEngine) Execute(ctx context.Context, script string, vars map[string]any, timeoutMs int) (any, error) {
+ if err := e.controls.Check(operatorcontrols.Scripts); err != nil {
+ return nil, err
+ }
+ release, err := e.controls.Acquire(ctx, "scripts", e.controls.Limits().ConcurrentScripts)
+ if err != nil {
+ return nil, err
+ }
+ defer release()
if len(script) > maxScriptLength {
return nil, fmt.Errorf("script exceeds maximum length of %d bytes", maxScriptLength)
}
@@ -45,6 +59,9 @@ func (e *ScriptEngine) Execute(ctx context.Context, script string, vars map[stri
if timeoutMs <= 0 {
timeoutMs = defaultScriptTimeoutMs
}
+ if ceiling := e.controls.Limits().ScriptTimeoutMS; ceiling > 0 && timeoutMs > ceiling {
+ timeoutMs = ceiling
+ }
// A fresh runtime per call is the only way to guarantee that built-ins and
// their prototypes are pristine; there is no realm reset in sobek.
diff --git a/internal/services/sla_import_service.go b/internal/services/sla_import_service.go
index bf571a3cf..a2c8f69a7 100644
--- a/internal/services/sla_import_service.go
+++ b/internal/services/sla_import_service.go
@@ -14,6 +14,7 @@ import (
"windshift/internal/database"
"windshift/internal/jira"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/sla"
)
@@ -172,6 +173,9 @@ func (s *SLAImportService) Preview(ctx context.Context, workspaceID int, documen
// Import applies a document in merge or replace mode.
func (s *SLAImportService) Import(ctx context.Context, workspaceID int, document SLAImportDocument, mode string) (*SLAImportResult, error) {
+ if err := operatorcontrols.From(s.db).CheckImport(ctx, "sla"); err != nil {
+ return nil, err
+ }
if mode != SLAImportModeMerge && mode != SLAImportModeReplace {
return nil, fmt.Errorf("%w: mode must be merge or replace", ErrSLAImportInvalid)
}
diff --git a/internal/services/ticket_import_service.go b/internal/services/ticket_import_service.go
index 2fb8d95f4..10f255e76 100644
--- a/internal/services/ticket_import_service.go
+++ b/internal/services/ticket_import_service.go
@@ -16,6 +16,7 @@ import (
"windshift/internal/itemevents"
"windshift/internal/logger"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/sanitize"
"windshift/internal/validation"
@@ -57,6 +58,9 @@ type TicketImportStaged = csvimport.StagedUpload
// Upload stages a CSV file for a workspace import.
func (s *TicketImportService) Upload(ctx context.Context, userID, workspaceID int, filename string, hasHeader bool, delimiterName string, source io.Reader) (*TicketImportStaged, error) {
+ if err := operatorcontrols.From(s.db).CheckImport(ctx, "tickets"); err != nil {
+ return nil, err
+ }
if err := s.require(userID, workspaceID, models.PermissionItemCreate); err != nil {
return nil, err
}
@@ -95,6 +99,9 @@ type TicketImportJob struct {
// The upload ID doubles as the job ID, so re-issuing the same start request
// returns the existing job instead of running the file twice.
func (s *TicketImportService) Start(ctx context.Context, actor AuditActor, workspaceID int, input TicketImportStart) (*TicketImportJob, error) {
+ if err := operatorcontrols.From(s.db).CheckImport(ctx, "tickets"); err != nil {
+ return nil, err
+ }
if err := s.require(actor.UserID, workspaceID, models.PermissionItemCreate); err != nil {
return nil, err
}
diff --git a/internal/services/workspace_bundle_import.go b/internal/services/workspace_bundle_import.go
index 7a48ac84e..dc741197f 100644
--- a/internal/services/workspace_bundle_import.go
+++ b/internal/services/workspace_bundle_import.go
@@ -13,6 +13,7 @@ import (
"windshift/internal/database"
"windshift/internal/logger"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
)
@@ -131,6 +132,9 @@ func (s *WorkspaceBundleImportService) Import(ctx context.Context, actor AuditAc
// ImportWithOptions applies the bundle with optional idempotent resolution.
func (s *WorkspaceBundleImportService) ImportWithOptions(ctx context.Context, actor AuditActor, workspaceID int, bundle *WorkspaceBundle, opts *WorkspaceBundleImportOptions) (*WorkspaceBundleImportResult, error) {
+ if err := operatorcontrols.From(s.db).CheckImport(ctx, "workspace_bundle"); err != nil {
+ return nil, err
+ }
if bundle == nil || bundle.Payload.Pages == nil && bundle.Payload.Items == nil &&
bundle.Payload.PageLabels == nil && bundle.Payload.Labels == nil && bundle.Payload.ItemLinks == nil &&
bundle.Payload.ViewSettings == nil && bundle.Payload.SLAs == nil &&
diff --git a/internal/smtp/notification_sender.go b/internal/smtp/notification_sender.go
index 89abc8cb2..55594e34e 100644
--- a/internal/smtp/notification_sender.go
+++ b/internal/smtp/notification_sender.go
@@ -29,6 +29,7 @@ import (
"windshift/internal/emailutil"
"windshift/internal/i18n"
"windshift/internal/models"
+ "windshift/internal/operatorcontrols"
"windshift/internal/repository"
"windshift/internal/utils"
)
@@ -385,6 +386,13 @@ func (s *NotificationSMTPSender) IsSMTPConfigured() bool {
// getSMTPConfig retrieves the active SMTP configuration
func (s *NotificationSMTPSender) getSMTPConfig() (*models.ChannelConfig, error) {
+ controls := operatorcontrols.From(s.db)
+ if err := controls.Check(operatorcontrols.MailSend); err != nil {
+ return nil, err
+ }
+ if managed := controls.Mail(); managed != nil && managed.Mode == "managed" {
+ return managedSMTPConfig(managed), nil
+ }
query := `
SELECT COALESCE(config, '{}') FROM channels
WHERE type = 'smtp' AND direction = 'outbound'
@@ -716,6 +724,18 @@ func formatMessageIDHeader(value string) string {
// encryption-aware sender, even the channel-test path that loads raw config
// from the DB on its own.
func (s *NotificationSMTPSender) dispatchContext(ctx context.Context, config *models.ChannelConfig, toEmail string, message []byte) error {
+ controls := operatorcontrols.From(s.db)
+ if err := controls.Check(operatorcontrols.MailSend); err != nil {
+ return err
+ }
+ if managed := controls.Mail(); managed != nil && managed.Mode == "managed" {
+ if config == nil || config.SMTPFromEmail != managed.FromAddress {
+ return &operatorcontrols.DeniedError{Capability: operatorcontrols.MailTransport}
+ }
+ config = managedSMTPConfig(managed)
+ } else if err := controls.Check(operatorcontrols.GenericMail); err != nil {
+ return err
+ }
if err := ctx.Err(); err != nil {
return err
}
@@ -736,7 +756,13 @@ func (s *NotificationSMTPSender) dispatchContext(ctx context.Context, config *mo
if err := ValidateTransport(config); err != nil {
return err
}
- password, err := decryptOrLegacy(s.encryption, config.SMTPPassword)
+ if err := controls.Consume(ctx, "mail_recipients", 1, controls.Limits().MailRecipientsPerDay, 24*time.Hour); err != nil {
+ return err
+ }
+ password := config.SMTPPassword
+ if managed := controls.Mail(); managed == nil || managed.Mode != "managed" {
+ password, err = decryptOrLegacy(s.encryption, config.SMTPPassword)
+ }
if err != nil {
return err
}
@@ -778,6 +804,10 @@ func (s *NotificationSMTPSender) dispatchContext(ctx context.Context, config *mo
return nil
}
+func managedSMTPConfig(policy *operatorcontrols.MailPolicy) *models.ChannelConfig {
+ return &models.ChannelConfig{SMTPHost: policy.Host, SMTPPort: policy.Port, SMTPEncryption: policy.Encryption, SMTPUsername: policy.Username, SMTPPassword: policy.Password, SMTPAuthMethod: "auto", SMTPFromEmail: policy.FromAddress, SMTPFromName: policy.FromName}
+}
+
// acquireSession returns a live session for the config, preferring an idle
// pooled connection. Callers release it when the send finishes.
func (s *NotificationSMTPSender) acquireSession(ctx context.Context, fingerprint, addr, mode string, auth smtp.Auth, skipTLSVerify bool) (*smtpSession, error) {