Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(service): harden Windows adapter contract
  • Loading branch information
Alanxtl committed Sep 3, 2026
commit 0ba05bcbffff4384ba780d9bcc2cb2525564b2e5
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,16 @@ uv tool install "powercontext[cli,server]==0.1.0"
# uv tool install "powercontext[cli,server] @ git+https://github.com/oceanbase/powercontext.git@master"
```

For a persistent personal Server that survives terminal closure and starts again after login, install the native current-user service:
For a persistent personal Server that survives terminal closure and can start again after login, install the native current-user service:

```bash
powercontext service install # Uninstall with `powercontext service uninstall`
powercontext service status
```

On Windows, the installer asks whether to enable startup at the next login when no login option is supplied; pressing
Enter keeps it disabled. Use `--start-on-login` or `--no-start-on-login` to choose explicitly.

If you want to use it foreground in a terminal, you can run:

```bash
Expand Down
5 changes: 4 additions & 1 deletion README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,16 @@ uv tool install "powercontext[cli,server]==0.1.0"
# uv tool install "powercontext[cli,server] @ git+https://github.com/oceanbase/powercontext.git@master"
```

如需让个人 Server 在终端关闭后继续运行,并在下次登录后再次启动,请安装原生当前用户服务:
如需让个人 Server 在终端关闭后继续运行,并可以在下次登录后再次启动,请安装原生当前用户服务:

```bash
powercontext service install # 卸载请运行 `powercontext service uninstall`
powercontext service status
```

在 Windows 上,未提供登录启动选项时,安装器会询问是否在下次登录时自动启动;直接按 Enter 的默认选择是不启用。
需要显式选择时,请使用 `--start-on-login` 或 `--no-start-on-login`。

如果想在终端以前台方式使用,可以运行:

```bash
Expand Down
5 changes: 4 additions & 1 deletion README_JP.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,17 @@ uv tool install "powercontext[cli,server]==0.1.0"
# uv tool install "powercontext[cli,server] @ git+https://github.com/oceanbase/powercontext.git@master"
```

ターミナルを閉じても動作を続け、次回ログイン時に再び起動する個人用 Server を実行するには、現在のユーザー用
ターミナルを閉じても動作を続け、次回ログイン時に再び起動できる個人用 Server を実行するには、現在のユーザー用
ネイティブサービスをインストールします:

```bash
powercontext service install # Uninstall with `powercontext service uninstall`
powercontext service status
```

Windows では、ログイン起動のオプションを指定しない場合、次回ログイン時の自動起動を有効にするか確認します。
Enter を押すと既定では無効のままです。明示的に選ぶ場合は `--start-on-login` または `--no-start-on-login` を指定します。

ターミナルでフォアグラウンド実行する場合は、次のコマンドを使用できます:

```bash
Expand Down
7 changes: 6 additions & 1 deletion docs/en/docs/how-to/deploy-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ powercontext service install
powercontext service status
```

On Windows, the command asks whether to enable startup at the current user's next login when neither
`--start-on-login` nor `--no-start-on-login` is supplied; pressing Enter keeps login auto-start disabled. Use either
option for a non-interactive choice.

Linux uses `systemd --user` and writes logs to the user journal. macOS uses a per-user LaunchAgent, and Windows uses a current-user Task Scheduler task; both write stdout and stderr below the PowerContext user data directory. `service status` reports the exact log selector or path.

For an explicit Server configuration, protect the environment file before installing:
Expand All @@ -34,7 +38,8 @@ On Windows, remove inherited access and grant the file only to the current user,
icacls $env:USERPROFILE\powercontext.env /inheritance:r /grant:r "$env:USERNAME:(F)" "SYSTEM:(F)" "Administrators:(F)"
```

The native definition stores only the absolute file path and non-content file identity metadata; it does not copy
The native definition stores only the absolute file path and non-content file identity metadata. On Windows this
includes the current user's owner SID, which is revalidated whenever the launcher starts. It does not copy
credentials or the caller's shell environment. Re-run `service install` after upgrading PowerContext or changing the
environment file. Remove the registration without deleting Server data or logs with:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ lifecycle commands.
The initial distribution contract is:

```text
powercontext service install
powercontext service install [--start-on-login | --no-start-on-login]
powercontext service uninstall
powercontext service status
```
Expand All @@ -193,7 +193,9 @@ Install performs these steps:
endpoint with an invalid response is a conflict and fails before native state changes.
5. Render and validate an artifact containing the fixed ownership marker, package version, definition version, intended
endpoint, and launcher command.
6. Create or update only PowerContext's personal Server registration and enable it for future user logins.
6. Create or update only PowerContext's personal Server registration. On Windows, when neither login option is
supplied, ask whether to add the current-user login trigger; the prompt defaults to no. The explicit
`--start-on-login` and `--no-start-on-login` options select the behavior without prompting.
7. Start it immediately by default unless step 4 found an already-live PowerContext Server.
8. Report registration, definition, native manager, liveness, and log-location facts after the operation.

Expand Down Expand Up @@ -275,8 +277,9 @@ current-user domain, configures explicit PowerContext-owned per-user stdout and

### Windows

The Windows adapter is a `Task Scheduler` task triggered when the current user logs on. It runs as that user and never
as `SYSTEM`. A hidden process window is acceptable. The launcher redirects Server output to explicit
The Windows adapter is a `Task Scheduler` task triggered when login auto-start is selected. It runs as that user and
never as `SYSTEM`; when login auto-start is disabled, it has no login trigger. A hidden process window is acceptable.
The launcher redirects Server output to explicit
PowerContext-owned per-user log files because Task Scheduler history is not Server stdout or stderr. The adapter does
not install a Windows Service.

Expand All @@ -287,7 +290,9 @@ rendering and ownership tests.

## Configuration and credentials

The service installer records the executable, required arguments, and non-secret service metadata. It does not copy
The service installer records the executable, required arguments, and non-secret service metadata. For a Windows
environment file, that metadata includes the current user's owner SID and the launcher revalidates it on every start.
It does not copy
the caller's complete environment, shell profile, API keys, bearer tokens, or provider credentials into a native
registration artifact.

Expand Down
6 changes: 5 additions & 1 deletion docs/zh/docs/how-to/deploy-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ Linux 使用 `systemd --user`,日志进入 user journal;macOS 使用当前

`service status` 会返回精确的日志 selector 或路径。

在 Windows 上,如果没有提供 `--start-on-login` 或 `--no-start-on-login`,命令会询问是否在当前用户下次登录时
自动启动;直接按 Enter 的默认选择是不启用。需要非交互选择时,请提供其中一个选项。

使用显式 Server 配置时,先保护并验证环境文件:

```bash
Expand All @@ -34,7 +37,8 @@ powercontext service install --env-file /path/to/powercontext.env
icacls $env:USERPROFILE\powercontext.env /inheritance:r /grant:r "$env:USERNAME:(F)" "SYSTEM:(F)" "Administrators:(F)"
```

原生定义只记录环境文件的绝对路径和不含内容的文件 identity metadata,不复制 credential 或调用者的 shell environment。
原生定义只记录环境文件的绝对路径和不含内容的文件 identity metadata;在 Windows 上还记录当前用户的 owner SID,
launcher 每次启动都会重新校验它。不复制 credential 或调用者的 shell environment。
升级 PowerContext 或修改环境文件后应重新执行 `service install`。以下命令会删除注册,但保留 Server 数据和日志:

```bash
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,10 @@ powercontext service status
管理员安装模式。它们从本地 `ServerSettings` 推导 endpoint;根命令的 Client `--server-url` 选项和
`ClientSettings.server_url` 都不会选择 service target。

在 Windows 上,如果没有显式提供 `--start-on-login` 或 `--no-start-on-login`,Install 会询问是否启用当前用户
登录触发器,直接按 Enter 的默认选择是不启用。提供任一显式选项后不会再次询问;Linux 和 macOS 不提供关闭
其原生用户服务正常启动行为的选项。

### Install

Install 执行以下步骤:
Expand Down Expand Up @@ -263,7 +267,8 @@ version,使 status 和 uninstall 在兼容的 package rename 后仍能区分 P

## Configuration and credentials

服务安装器记录 executable、必需参数和不敏感的 service metadata。它不会把调用者的完整 environment、shell profile、
服务安装器记录 executable、必需参数和不敏感的 service metadata。Windows 环境文件的 metadata 还包含当前用户的
owner SID,launcher 每次启动都会重新校验该 SID。它不会把调用者的完整 environment、shell profile、
API key、bearer token 或 provider credential 复制进原生注册产物。

因此,初始个人服务模式依赖原生当前用户服务环境中可获得的配置。`powercontext service status` 和
Expand Down
173 changes: 150 additions & 23 deletions src/powercontext/service/adapters/windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import csv
import io
import json
import os
import shutil
import subprocess
Expand Down Expand Up @@ -95,6 +96,8 @@ def platform_support(self) -> tuple[SupportState, str]:
return SupportState.UNSUPPORTED, "Task Scheduler personal services are available only on Windows"
if shutil.which("schtasks.exe") is None:
return SupportState.UNSUPPORTED, "schtasks.exe is not installed or is not on PATH"
if shutil.which("powershell.exe") is None:
return SupportState.UNSUPPORTED, "powershell.exe is not installed or is not on PATH"
try:
account, sid = self._user_identity()
except ServiceError as error:
Expand Down Expand Up @@ -293,20 +296,26 @@ def remove(self) -> None:
self.artifact_path.unlink(missing_ok=True)

def manager_state(self) -> ManagerState:
result = self._run("/Query", "/TN", self.identifier, "/FO", "LIST", "/V", "/HRESULT", check=False)
if _is_task_not_found(result):
return ManagerState.INACTIVE
result = self._run_task_info(check=False)
if result.returncode != 0:
return ManagerState.UNKNOWN
values = _list_output(result.stdout)
status = values.get("status", "").casefold()
if status in {"running", "正在运行"}:
try:
values = json.loads(result.stdout)
except json.JSONDecodeError:
return ManagerState.UNKNOWN
if not isinstance(values, dict):
return ManagerState.UNKNOWN
status = values.get("State")
if not isinstance(status, str):
return ManagerState.UNKNOWN
status = status.casefold()
if status == "notfound":
return ManagerState.INACTIVE
if status == "running":
return ManagerState.ACTIVE
if status in {"ready", "disabled", "queued", "not running", "就绪", "已禁用"}:
last_result = _last_result(values.get("last result", ""))
if status in {"ready", "disabled", "queued"}:
last_result = _last_result(values.get("LastTaskResult"))
return ManagerState.FAILED if last_result not in {None, 0} else ManagerState.INACTIVE
if "could not start" in status or "failed" in status:
return ManagerState.FAILED
return ManagerState.UNKNOWN

def log_location(self, definition: ServiceDefinition | None) -> str | None:
Expand Down Expand Up @@ -338,6 +347,9 @@ def _task_mismatch(self, root: ET.Element, definition: ServiceDefinition) -> str
settings = _child(root, "Settings")
actions = _child(root, "Actions")
execute = _child(actions, "Exec") if actions is not None else None

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed, now check action、trigger、principal only

structure_mismatch = _task_structure_mismatch(root, definition)
if structure_mismatch is not None:
return structure_mismatch
if definition.start_on_login:
logon_matches = logon is not None and (
_text(logon, "Enabled").casefold() in {"", "true"}
Expand Down Expand Up @@ -397,6 +409,39 @@ def _run(self, *arguments: str, check: bool = True) -> subprocess.CompletedProce
raise ServiceError(f"schtasks.exe {arguments[0]} failed{detail}") # noqa: TRY003
return result

def _run_task_info(self, *, check: bool = True) -> subprocess.CompletedProcess[str]:
task_path, task_name = _task_path_and_name(self.identifier)
environment = os.environ.copy()
environment["POWERCONTEXT_TASK_PATH"] = task_path
environment["POWERCONTEXT_TASK_NAME"] = task_name
script = (
"$taskPath = $env:POWERCONTEXT_TASK_PATH; "
"$taskName = $env:POWERCONTEXT_TASK_NAME; "
"$task = Get-ScheduledTask -TaskPath $taskPath -TaskName $taskName -ErrorAction SilentlyContinue; "
"if ($null -eq $task) { "
"[pscustomobject]@{ State = 'NotFound'; LastTaskResult = 0 } | ConvertTo-Json -Compress; exit 0 "
"}; "
"$info = Get-ScheduledTaskInfo -TaskPath $taskPath -TaskName $taskName -ErrorAction SilentlyContinue; "
"if ($null -eq $info) { [Console]::Error.WriteLine('Task Scheduler info unavailable'); exit 1 }; "
"[pscustomobject]@{ State = [string]$task.State; LastTaskResult = [int64]$info.LastTaskResult } "
"| ConvertTo-Json -Compress"
)
try:
result = subprocess.run( # noqa: S603
["powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], # noqa: S607
capture_output=True,
text=True,
timeout=_COMMAND_TIMEOUT_SECONDS,
check=False,
env=environment,
)
except (OSError, subprocess.SubprocessError) as error:
raise ServiceError(f"failed to execute powershell.exe: {error}") from error # noqa: TRY003
if check and result.returncode != 0:
detail = _command_detail(result.stderr or result.stdout)
raise ServiceError(f"powershell.exe Task Scheduler state query failed{detail}") # noqa: TRY003
return result


def _launcher_arguments(definition: ServiceDefinition) -> list[str]:
log_dir = Path(definition.data_dir) / "logs"
Expand Down Expand Up @@ -449,6 +494,83 @@ def _child(parent: ET.Element | None, name: str) -> ET.Element | None:
return next((child for child in parent if _local_name(child.tag) == name), None)


def _has_exact_children(parent: ET.Element | None, expected: tuple[str, ...]) -> bool:
return parent is not None and tuple(_local_name(child.tag) for child in parent) == expected


def _has_exact_attributes(parent: ET.Element | None, expected: dict[str, str]) -> bool:
return parent is not None and parent.attrib == expected


def _has_children(
parent: ET.Element | None,
*,
required: tuple[str, ...],
optional: tuple[str, ...] = (),
) -> bool:
if parent is None:
return False
names = tuple(_local_name(child.tag) for child in parent)
return (
all(names.count(name) == 1 for name in required)
and all(names.count(name) <= 1 for name in optional)
and all(name in required or name in optional for name in names)
)


def _task_structure_mismatch(root: ET.Element, definition: ServiceDefinition) -> str | None:
triggers = _child(root, "Triggers")
principals = _child(root, "Principals")
actions = _child(root, "Actions")
return next(
(
mismatch
for mismatch in (
_action_structure_mismatch(actions),
_principal_structure_mismatch(principals),
_trigger_structure_mismatch(triggers, definition),
)
if mismatch is not None
),
None,
)


def _action_structure_mismatch(actions: ET.Element | None) -> str | None:
execute = _child(actions, "Exec")
if not _has_exact_attributes(actions, {"Context": "Author"}):
return "action attributes"
if not _has_exact_children(actions, ("Exec",)):
return "action structure"
if not _has_exact_attributes(execute, {}):
return "exec action attributes"
if not _has_exact_children(execute, ("Command", "Arguments", "WorkingDirectory")):
return "exec action structure"
return None


def _principal_structure_mismatch(principals: ET.Element | None) -> str | None:
principal = _child(principals, "Principal")
if not _has_exact_children(principals, ("Principal",)):
return "principal structure"
if not _has_exact_attributes(principal, {"id": "Author"}):
return "principal attributes"
if not _has_children(principal, required=("UserId", "LogonType"), optional=("RunLevel",)):
return "principal element structure"
return None


def _trigger_structure_mismatch(triggers: ET.Element | None, definition: ServiceDefinition) -> str | None:
logon = _child(triggers, "LogonTrigger")
if definition.start_on_login and not _has_exact_children(triggers, ("LogonTrigger",)):
return "trigger structure"
if definition.start_on_login and not _has_children(logon, required=("UserId",), optional=("Enabled",)):
return "logon trigger structure"
if not definition.start_on_login and triggers is not None and not _has_exact_children(triggers, ()):
return "trigger structure"
return None


def _text(parent: ET.Element | None, name: str) -> str:
child = _child(parent, name)
return "" if child is None or child.text is None else child.text.strip()
Expand All @@ -465,6 +587,13 @@ def _normalize_identifier(identifier: str) -> str:
return value


def _task_path_and_name(identifier: str) -> tuple[str, str]:
parent, separator, name = identifier.rpartition("\\")
if not separator or not name:
raise ValueError("Task Scheduler task identifier is invalid") # noqa: TRY003
return (parent + "\\") if parent else "\\", name


def _same_path(actual: str, expected: str) -> bool:
if not actual:
return False
Expand Down Expand Up @@ -506,19 +635,17 @@ def _is_task_not_found(result: subprocess.CompletedProcess[str]) -> bool:
return result.returncode & 0xFFFFFFFF == _TASK_NOT_FOUND_HRESULT


def _list_output(output: str) -> dict[str, str]:
values: dict[str, str] = {}
for line in output.splitlines():
key, separator, value = line.partition(":")
if separator:
values[key.strip().casefold()] = value.strip()
return values


def _last_result(value: str) -> int | None:
try:
result = int(value.strip(), 0)
except ValueError:
def _last_result(value: object) -> int | None:
if isinstance(value, bool):
return None
if isinstance(value, int):
result = value
elif isinstance(value, str):
try:
result = int(value.strip(), 0)
except ValueError:
return None
else:
return None
return None if result in _TASK_STATUS_RESULT_RANGE or result == _TASK_HAS_NOT_RUN_RESULT else result

Expand Down
Loading
Loading