session

package
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 31 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package session 实现 XOps v2 全量会话、提权、探测、持久 PTY、隧道转发与多路复用控制面用例服务 (ADR-008 / ADR-009 / ADR-010 / ADR-011 / Plan P2.5-T2 & P3-T2)。

核心安全、并发与所有权不变量:

  • 能力门控与连接池嵌套序恒为 gate.WithAuthorized[C] 包裹 pool.WithLease,严禁反序或绕过护栏, 并向 Authorized.ReportOutcome 上报强类型 ExecutionOutcome(确保 OutcomeUnknown 绝不降级);
  • 提权执行(sudo/su/doas)经 PrivilegeEscalationPort 与 security.CanonicalScopeEscalated 校验, 口令仅经 SecretVault.WithSecret 或 InteractionPort.PromptSecret 借用透传(本包 0 SecretBox.Use);
  • 两阶段远端 Shell 探针经 ShellProbePort 执行并严格失败关闭校验(拒绝非法/未知方言,零盲猜回退);
  • 跨请求持久 PTY、-L/-R/-D/StreamLocal/TUN 转发与 ControlMaster 一律经 pool.RegisterLeaseHandleWith 绑定池钉选可撤销 TransportConn,杜绝失效 *pool.Lease 复用与 //xops:borrowed 逃逸,吊销即止、0 泄漏;
  • ControlMaster 控制面门控一律消费 ControlPolicy.EffectiveMaster() / EffectivePersist() 失败关闭投影;
  • 全部后台协程受 core/conc.Nursery 监督(0 裸 go、0 goleak、0 time.Sleep),禁导 core/osfs 与 sshnet。

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNilContext             = sessplan.ErrNilContext
	ErrInvalidConfig          = sessplan.ErrInvalidConfig
	ErrServiceNotInitialized  = sessplan.ErrServiceNotInitialized
	ErrInvalidRequest         = sessplan.ErrInvalidRequest
	ErrInvalidRequestTTY      = sessplan.ErrInvalidRequestTTY
	ErrPortUnavailable        = sessplan.ErrPortUnavailable
	ErrInvalidProbeResult     = sessplan.ErrInvalidProbeResult
	ErrEscalationScopeChanged = sessplan.ErrEscalationScopeChanged
	ErrPTYClosed              = sessplan.ErrPTYClosed
	ErrControlMasterDisabled  = sessplan.ErrControlMasterDisabled
	ErrMuxMasterUnavailable   = sessplan.ErrMuxMasterUnavailable
	ErrMuxPersistExpired      = sessplan.ErrMuxPersistExpired
	ErrEscapeDisconnected     = sessplan.ErrEscapeDisconnected
)

本包导出的规范化哨兵错误(只读重导出自内部叶包 sessplan),供 core/engine 与上层测试以 errors.Is 精确区分故障类别。

Functions

func TryDialMuxClient

func TryDialMuxClient(ctx context.Context, muxPort ports.MuxSocketPort, env ports.EnvPort, interaction ports.InteractionPort, hop plan.HopSpec, dig plan.HopDigest) (ports.TransportConn, bool, error)

TryDialMuxClient 按 ControlPolicy 生效投影执行透明客户端 ControlMaster 附着(INV-C4 / ADR-019 A2,供 core/engine 拨号适配复用)。

func TryDialMuxClientWithForwardAgent added in v1.3.0

func TryDialMuxClientWithForwardAgent(
	ctx context.Context,
	muxPort ports.MuxSocketPort,
	env ports.EnvPort,
	interaction ports.InteractionPort,
	hop plan.HopSpec,
	dig plan.HopDigest,
	requestedAgent algebraic.Option[inventory.AgentSpec],
) (ports.TransportConn, bool, error)

TryDialMuxClientWithForwardAgent 是 TryDialMuxClient 的显式 ForwardAgent 规格入口(ADR-019 A2 5×4 复用矩阵): 在 ControlMaster=auto/autoask 下若 CheckForwardAgentCompat 返回 ErrPermissionDenied 或 ErrUnsupported, 立即关闭复用连接并返回 (nil, false, nil) 触发独立直连回退;其余模式直接返回错误。

Types

type ActivateSSHForwardsRequest added in v1.3.0

type ActivateSSHForwardsRequest struct {
	ExplicitCLI bool
	Plan        plan.SealedConnectionPlan
	Policy      option.EffectivePolicy
	NodeID      string
	Risk        algebraic.Option[security.RiskLevel]
	Approval    algebraic.Option[gate.ApprovalSubmission]
}

ActivateSSHForwardsRequest 描述显式 CLI ssh 路径下按 EffectivePolicy 门控激活持久化转发与 TUN 的输入。 必须显式设置 ExplicitCLI=true(零值严格失败关闭),确保 ProbeShell/MCP/SFTP 等非 CLI 路径绝不隐式触发。

type ControlMasterInfo

type ControlMasterInfo struct {
	// contains filtered or unexported fields
}

ControlMasterInfo 封装 ControlMaster 启动或复用已有主进程的不可变结果;零值恒无效并失败关闭。

func (ControlMasterInfo) Done

func (i ControlMasterInfo) Done() <-chan struct{}

Done 返回只读完成信号通道:受管主进程退出并完成监听清理后关闭;复用外部主进程时返回已关闭通道;零值/无效返回 nil。

func (ControlMasterInfo) EffectiveMaster

func (i ControlMasterInfo) EffectiveMaster() option.ControlMasterMode

func (ControlMasterInfo) EffectivePersist

func (i ControlMasterInfo) EffectivePersist() option.ControlPersistSpec

func (ControlMasterInfo) Handle

func (ControlMasterInfo) IsValid

func (i ControlMasterInfo) IsValid() bool

ControlMasterInfo 零值安全只读访问器与响应式停机等待方法(供 entry/muxdaemon 零轮询阻塞等待)。

func (ControlMasterInfo) IsZero

func (i ControlMasterInfo) IsZero() bool

func (ControlMasterInfo) MasterPID

func (i ControlMasterInfo) MasterPID() uint32

func (ControlMasterInfo) ReusedExisting

func (i ControlMasterInfo) ReusedExisting() bool

func (ControlMasterInfo) SocketPath

func (i ControlMasterInfo) SocketPath() pathalg.LocalSourcePath

func (ControlMasterInfo) Wait

func (i ControlMasterInfo) Wait(ctx context.Context) error

Wait 阻塞等待 ControlMaster 退出或 ctx 取消:

  • 零值/无效时严格失败关闭返回 ErrInvalidRequest;ctx == nil 返回 ErrNilContext;
  • 复用已有外部主进程时直接按 ctx 状态返回 nil / ctx.Err();
  • 正常 -O exit / -O stop 与 ControlPersist 空闲到期(ErrMuxPersistExpired)映射为 nil,其余传输故障原样透传(即使句柄已自动回收)。

type ControlMasterRequest

type ControlMasterRequest struct {
	Plan                 plan.SealedConnectionPlan
	NodeID               string
	Policy               algebraic.Option[option.EffectivePolicy]
	ForwardAgent         algebraic.Option[option.ForwardAgentSpec]
	IdentityAgent        algebraic.Option[option.IdentityAgentSpec]
	ExplicitForwardAgent bool
	ForwardBindOptions   algebraic.Option[ports.ForwardBindOptions]
	Risk                 algebraic.Option[security.RiskLevel]
	Approval             algebraic.Option[gate.ApprovalSubmission]
	OperationStream      *events.OperationStream
}

ControlMasterRequest 描述启动或附着 ControlMaster(-M / ControlPersist)的强类型输入(P3-T2 / ADR-019 v2.2 S3-Q1)。 所有多路复用门控严格从 Plan 末跳的 ControlPolicy.EffectiveMaster() / EffectivePersist() 与单实例策略投影求值。

type ControlMasterStatus

type ControlMasterStatus struct {
	// contains filtered or unexported fields
}

ControlMasterStatus 表示受管 ControlMaster 句柄的不可变只读状态快照;零值恒无效并失败关闭。

func (ControlMasterStatus) Active

func (st ControlMasterStatus) Active() bool

func (ControlMasterStatus) EffectiveMaster

func (st ControlMasterStatus) EffectiveMaster() option.ControlMasterMode

func (ControlMasterStatus) EffectivePersist

func (st ControlMasterStatus) EffectivePersist() option.ControlPersistSpec

func (ControlMasterStatus) Err

func (st ControlMasterStatus) Err() error

func (ControlMasterStatus) HandleStatus

func (st ControlMasterStatus) HandleStatus() pool.HandleStatus

func (ControlMasterStatus) IsValid

func (st ControlMasterStatus) IsValid() bool

func (ControlMasterStatus) IsZero

func (st ControlMasterStatus) IsZero() bool

func (ControlMasterStatus) SocketPath

type ExecRequest

type ExecRequest struct {
	Plan                 plan.SealedConnectionPlan
	Command              execution.CommandPlan
	NodeExecution        algebraic.Option[execution.LaunchProfile] // 可选节点默认启动配置(6 级执行继承链 Node 层)
	ExecutionOverride    algebraic.Option[execution.LaunchProfile] // 可选显式 CLI/步骤启动配置覆盖(6 级执行继承链最高层)
	NodeID, Term         string
	Stdin                io.Reader
	Stdout, Stderr       io.Writer
	RequestTTY           RequestTTYMode
	ForwardAgent         algebraic.Option[option.ForwardAgentSpec]
	IdentityAgent        algebraic.Option[option.IdentityAgentSpec]
	ExplicitForwardAgent bool
	Risk                 algebraic.Option[security.RiskLevel]
	Approval             algebraic.Option[gate.ApprovalSubmission]
	OperationStream      *events.OperationStream
}

ExecRequest 描述单次远端命令执行用例的强类型输入。

type ExecutionInheritanceSpec added in v1.3.0

type ExecutionInheritanceSpec = sessplan.ExecutionInheritanceSpec

ExecutionInheritanceSpec 重导出 6 级启动配置继承链规格(CLI > PlaybookStep > PlaybookSettings > Node > Global > server)。

type ExplicitSSHSessionRequest added in v1.3.0

type ExplicitSSHSessionRequest struct {
	ExplicitCLI                 bool
	Plan                        plan.SealedConnectionPlan
	Policy                      option.EffectivePolicy
	ExplicitCommand             algebraic.Option[execution.CommandPlan]
	Subsystem                   string // 可选:SessionType=subsystem 时的显式子系统名称(为空时回退提取命令参数或 RemoteCommand)
	NodeExecution               algebraic.Option[execution.LaunchProfile]
	ExecutionOverride           algebraic.Option[execution.LaunchProfile]
	NodeID, Term                string
	Stdin                       io.Reader
	Stdout, Stderr              io.Writer
	RequestTTY                  RequestTTYMode
	EscapeHelpText              string       // 可选:CLI 边界经 internal/i18n 预渲染的本地化 ~? 帮助文本
	ExplicitForwardAgent        bool         // 可选:调用方是否在 CLI 显式请求开启 ForwardAgent(区分配置继承与显式请求)
	ExecutePostAuthLocalCommand bool         // 可选:在 SSH 认证与建连成功后、打开会话通道/OnStarted 前受控执行 LocalCommand
	OnStarted                   func() error // 可选:远端通道与命令启动成功后、阻塞等待退出前回调(用于脱离时序编排)
	Risk                        algebraic.Option[security.RiskLevel]
	Approval                    algebraic.Option[gate.ApprovalSubmission]
	OperationStream             *events.OperationStream
}

ExplicitSSHSessionRequest 描述显式 CLI ssh 路径下结合 EffectivePolicy 执行远端会话、子系统(-s)或持久化 remote_command 的输入。 必须显式设置 ExplicitCLI=true(零值严格失败关闭),确保 ProbeShell/MCP/SFTP 等非 CLI 路径绝不隐式触发 remote_command。

type ForwardActivationFailure added in v1.3.0

type ForwardActivationFailure struct {
	// contains filtered or unexported fields
}

ForwardActivationFailure 表示 ExitOnForwardFailure==false 模式下单条转发运行期绑定失败的不可变诊断记录;零值恒无效。

func (ForwardActivationFailure) Err added in v1.3.0

Err 返回运行期绑定或监听失败原因;零值返回 nil。

func (ForwardActivationFailure) IsValid added in v1.3.0

func (f ForwardActivationFailure) IsValid() bool

IsValid 报告 ForwardActivationFailure 是否有效。

func (ForwardActivationFailure) IsZero added in v1.3.0

func (f ForwardActivationFailure) IsZero() bool

IsZero 报告 ForwardActivationFailure 是否处于零值无效态。

func (ForwardActivationFailure) Spec added in v1.3.0

Spec 返回失败转发对应的规格快照;零值返回零值 ForwardSpec。

type ForwardInfo

type ForwardInfo struct {
	// contains filtered or unexported fields
}

ForwardInfo 封装成功启动的受管长驻转发句柄与绑定地址元信息;零值恒无效并失败关闭。

func (ForwardInfo) BoundAddr

func (i ForwardInfo) BoundAddr() string

func (ForwardInfo) Done

func (i ForwardInfo) Done() <-chan struct{}

Done 返回只读完成信号通道:受管转发终止并释放本地监听/资源后关闭;零值/无效返回 nil。

func (ForwardInfo) Handle

func (ForwardInfo) IsValid

func (i ForwardInfo) IsValid() bool

ForwardInfo 零值安全只读访问器与响应式停机等待方法(供 entry/cli -N 前台隧道零轮询阻塞等待)。

func (ForwardInfo) IsZero

func (i ForwardInfo) IsZero() bool

func (ForwardInfo) Spec

func (i ForwardInfo) Spec() ports.ForwardSpec

func (ForwardInfo) Wait

func (i ForwardInfo) Wait(ctx context.Context) error

Wait 阻塞等待受管转发终止或 ctx 取消,并在终止后返回终态传输错误(正常 StopForward 停止返回 nil,零值严格失败关闭)。

type ForwardStatus

type ForwardStatus struct {
	// contains filtered or unexported fields
}

ForwardStatus 表示受管隧道转发句柄的不可变只读状态快照;零值恒无效并失败关闭。

func (ForwardStatus) Active

func (st ForwardStatus) Active() bool

func (ForwardStatus) BoundAddr

func (st ForwardStatus) BoundAddr() string

func (ForwardStatus) Err

func (st ForwardStatus) Err() error

func (ForwardStatus) HandleStatus

func (st ForwardStatus) HandleStatus() pool.HandleStatus

func (ForwardStatus) IsValid

func (st ForwardStatus) IsValid() bool

func (ForwardStatus) IsZero

func (st ForwardStatus) IsZero() bool

func (ForwardStatus) Spec

func (st ForwardStatus) Spec() ports.ForwardSpec

type InteractiveRequest

type InteractiveRequest struct {
	Plan                 plan.SealedConnectionPlan
	NodeID, Term         string
	Stdin                io.Reader
	Stdout, Stderr       io.Writer
	RequestTTY           RequestTTYMode
	EscapeChar           algebraic.Option[option.EscapeCharSpec]
	EscapeHelpText       string // 可选:CLI 边界预渲染的本地化 ~? 帮助文本
	ForwardAgent         algebraic.Option[option.ForwardAgentSpec]
	IdentityAgent        algebraic.Option[option.IdentityAgentSpec]
	ExplicitForwardAgent bool
	Risk                 algebraic.Option[security.RiskLevel]
	Approval             algebraic.Option[gate.ApprovalSubmission]
	OperationStream      *events.OperationStream
}

InteractiveRequest 描述交互式远端 Shell 会话用例的强类型输入。

type LocalCommandRequest added in v1.3.0

type LocalCommandRequest struct {
	ExplicitCLI     bool
	Plan            plan.SealedConnectionPlan
	Policy          option.EffectivePolicy
	NodeID          string
	TunnelDevice    string                                        // 可选:已建立的本地 TUN 网卡名;无 TUN 时为空或 "NONE"
	OnAuthorized    func(authCtx context.Context) (string, error) // 可选:在 outer gate 获批后、阶段 2 展开前执行的连建/TUN 回调(如 pool.WithLease),返回实得 TUN 设备名
	ResolveExecPath func(name string) (string, error)             // 可选:当 argv[0] 非绝对路径时用于阶段 1 冻结绝对可执行路径(防 PATH TOCTOU)
	Timeout         algebraic.Option[algebraic.Duration]          // 可选:本机子进程超时
	MaxOutputBytes  algebraic.Option[uint64]                      // 可选:本机子进程输出截断上限(默认 1 MiB)
	Risk            algebraic.Option[security.RiskLevel]
	Approval        algebraic.Option[gate.ApprovalSubmission]
	OperationStream *events.OperationStream
}

LocalCommandRequest 描述显式 CLI ssh 路径下受控零 Shell 执行 LocalCommand 的强类型输入(ADR-019 C2): 必须显式设置 ExplicitCLI=true(零值失败关闭),并满足 Policy.PermitLocalCommand()==true 且 Policy.LocalCommand().IsSome()。

type MuxControlRequest

type MuxControlRequest struct {
	Target               MuxRequest
	Action               ports.MuxControlAction
	Forward              algebraic.Option[ports.ForwardSpec]
	Forwards             []ports.ForwardSpec
	ExitOnForwardFailure bool
}

MuxControlRequest 描述向 ControlMaster 发送 `-O` 控制动作(check/forward/cancel/exit/stop/conninfo/channels)的强类型输入。 渐进兼容:单条转发可经 Forward 传入,批量多条转发经 Forwards 传入(二者互斥,不可同时非空)。

type MuxRequest

type MuxRequest struct {
	Plan            plan.SealedConnectionPlan
	NodeID          string
	SocketPath      algebraic.Option[pathalg.LocalSourcePath]
	ForwardAgent    algebraic.Option[inventory.AgentSpec] // 可选:WithMuxConn 复用兼容性核验所请求的 Agent 转发目标
	Risk            algebraic.Option[security.RiskLevel]
	Approval        algebraic.Option[gate.ApprovalSubmission]
	OperationStream *events.OperationStream
}

MuxRequest 描述面向 ControlMaster 套接字执行探测(ProbeMux)、只读观测(QueryMuxConnInfo/QueryMuxChannels)、 stdio 透传(WithMuxProxy/RunMuxProxy)或共享连接复用(WithMuxConn)的通用强类型输入。

type OpenPTYRequest

type OpenPTYRequest struct {
	Plan            plan.SealedConnectionPlan
	NodeID, Term    string
	Size            algebraic.Option[ports.TerminalSize]
	MaxBufferBytes  int
	Risk            algebraic.Option[security.RiskLevel]
	Approval        algebraic.Option[gate.ApprovalSubmission]
	OperationStream *events.OperationStream
}

OpenPTYRequest 描述在连接池世代 SlotMap 上创建跨请求持久 PTY 会话的强类型输入(ADR-009 / P3-T2)。

type PTYReadRequest

type PTYReadRequest struct {
	Handle   plan.ManagedHandle[plan.KindPTY]
	MaxBytes int  // 0 默认 64 KiB
	Wait     bool // true 时事件驱动等待新输出、EOF 或取消/吊销
}

PTYReadRequest 描述从指定世代 PTY 句柄读取缓冲输出的请求参数。

type PTYReadResult

type PTYReadResult struct {
	// contains filtered or unexported fields
}

PTYReadResult 封装单次 ReadPTY 的不可变输出快照;零值恒无效并失败关闭。

func (PTYReadResult) Data

func (r PTYReadResult) Data() []byte

func (PTYReadResult) DroppedBytes

func (r PTYReadResult) DroppedBytes() uint64

func (PTYReadResult) EOF

func (r PTYReadResult) EOF() bool

func (PTYReadResult) IsValid

func (r PTYReadResult) IsValid() bool

func (PTYReadResult) IsZero

func (r PTYReadResult) IsZero() bool

type PTYStatus

type PTYStatus struct {
	// contains filtered or unexported fields
}

PTYStatus 表示持久 PTY 句柄的不可变只读状态快照;零值恒无效并失败关闭。

func (PTYStatus) Active

func (st PTYStatus) Active() bool

func (PTYStatus) BufferedBytes

func (st PTYStatus) BufferedBytes() int

func (PTYStatus) DroppedBytes

func (st PTYStatus) DroppedBytes() uint64

func (PTYStatus) EOF

func (st PTYStatus) EOF() bool

func (PTYStatus) HandleStatus

func (st PTYStatus) HandleStatus() pool.HandleStatus

func (PTYStatus) IsValid

func (st PTYStatus) IsValid() bool

func (PTYStatus) IsZero

func (st PTYStatus) IsZero() bool

func (PTYStatus) Size

func (st PTYStatus) Size() ports.TerminalSize

func (PTYStatus) Term

func (st PTYStatus) Term() string

type PrivilegeExecRequest

type PrivilegeExecRequest struct {
	Plan                  plan.SealedConnectionPlan
	Privilege             ports.PrivilegeRequest
	Policy                algebraic.Option[inventory.PrivilegePolicy]
	Command               algebraic.Option[execution.CommandPlan]
	TargetUser            algebraic.Option[option.Username]
	Timeout               algebraic.Option[algebraic.Duration]
	NodeExecution         algebraic.Option[execution.LaunchProfile]
	ExecutionOverride     algebraic.Option[execution.LaunchProfile]
	NodeID, Term          string
	PasswordRef           algebraic.Option[secret.Ref]
	PromptPassword        bool
	Paths, RecursivePaths []string
	LexicalScope          algebraic.Option[security.ScopeSnapshot]
	Canonicalize          gate.CanonicalizeFunc
	Stdin                 io.Reader
	Stdout, Stderr        io.Writer
	RequestTTY            RequestTTYMode
	Risk                  algebraic.Option[security.RiskLevel]
	Approval              algebraic.Option[gate.ApprovalSubmission]
	OperationStream       *events.OperationStream
}

PrivilegeExecRequest 描述远端提权执行(sudo/su/doas 及节点持久化 PrivilegePolicy)用例的强类型输入 (ADR-008 / ADR-011 / ADR-018 / M1-T4)。 支持两种入口:

  • 直接传入具体三态 PrivilegeRequest(优先生效);
  • Privilege 留零值并传入 Policy(Node.privilege,支持 none/sudo/su/doas/auto + NonInteractive + su/doas PromptPattern)与 Command。

提权口令严禁以明文字节传递,仅允许经 Vault PasswordRef 或交互 PromptPassword 在同步闭包内借用传递。

type ProbeShellRequest

type ProbeShellRequest struct {
	Plan            plan.SealedConnectionPlan
	NodeID          string
	Timeout         algebraic.Option[algebraic.Duration]
	Risk            algebraic.Option[security.RiskLevel]
	Approval        algebraic.Option[gate.ApprovalSubmission]
	OperationStream *events.OperationStream
}

ProbeShellRequest 描述远端 2 阶段默认 Shell 方言与解释器探测用例的强类型输入(P3-T2)。

type RequestTTYMode

type RequestTTYMode uint8

RequestTTYMode 标识 SSH 伪终端分配策略(对应 OpenSSH RequestTTY auto/yes/no/force 与 -t/-tt/-T); 零值 RequestTTYUnset 失败关闭于文本编解码,运行期按操作类型取确定性默认策略(交互 Shell=auto,单命令=no)。

const (
	RequestTTYUnset RequestTTYMode = RequestTTYMode(sessplan.TTYUnset) // 未显式设置(零值)
	RequestTTYAuto  RequestTTYMode = RequestTTYMode(sessplan.TTYAuto)  // 自动:交互 Shell 且本机为 TTY 时分配 PTY
	RequestTTYYes   RequestTTYMode = RequestTTYMode(sessplan.TTYYes)   // 本机为 TTY 时分配 PTY(对应 -t)
	RequestTTYNo    RequestTTYMode = RequestTTYMode(sessplan.TTYNo)    // 禁止分配 PTY(对应 -T)
	RequestTTYForce RequestTTYMode = RequestTTYMode(sessplan.TTYForce) // 强制分配远端 PTY,即使本机非 TTY(对应 -tt)
)

func ParseRequestTTYMode

func ParseRequestTTYMode(raw string) (RequestTTYMode, error)

ParseRequestTTYMode 严格解析 RequestTTY 文本(auto/yes/no/force)。

func (RequestTTYMode) AppendText

func (m RequestTTYMode) AppendText(b []byte) ([]byte, error)

func (RequestTTYMode) IsValid

func (m RequestTTYMode) IsValid() bool

IsValid / IsZero / String / TextAppender / TextMarshaler / TextUnmarshaler 实现 RequestTTYMode 值语义。

func (RequestTTYMode) IsZero

func (m RequestTTYMode) IsZero() bool

func (RequestTTYMode) MarshalText

func (m RequestTTYMode) MarshalText() ([]byte, error)

func (RequestTTYMode) String

func (m RequestTTYMode) String() string

func (*RequestTTYMode) UnmarshalText

func (m *RequestTTYMode) UnmarshalText(text []byte) error

type SSHForwardsActivationResult added in v1.3.0

type SSHForwardsActivationResult struct {
	// contains filtered or unexported fields
}

SSHForwardsActivationResult 封装显式 CLI ssh 批量激活持久化转发的不可变结果(已启动句柄与运行期失败清单);零值恒无效。

func (SSHForwardsActivationResult) Failed added in v1.3.0

Failed 返回 ExitOnForwardFailure==false 模式下记录的运行期绑定失败明细切片副本。

func (SSHForwardsActivationResult) IsValid added in v1.3.0

func (r SSHForwardsActivationResult) IsValid() bool

IsValid 报告 SSHForwardsActivationResult 是否经 ActivateSSHPolicyForwards 合法返回。

func (SSHForwardsActivationResult) IsZero added in v1.3.0

func (r SSHForwardsActivationResult) IsZero() bool

IsZero 报告 SSHForwardsActivationResult 是否处于零值无效态。

func (SSHForwardsActivationResult) Started added in v1.3.0

Started 返回成功启动的受管转发句柄切片副本。

type SSHPolicyPlan added in v1.3.0

type SSHPolicyPlan struct {
	// contains filtered or unexported fields
}

SSHPolicyPlan 封装从 option.EffectivePolicy 投影得到的不可变显式 CLI ssh 激活规划; 零值恒无效并严格失败关闭。

func PlanSSHPolicyActivation added in v1.3.0

func PlanSSHPolicyActivation(policy option.EffectivePolicy, hasExplicitCommand bool) (SSHPolicyPlan, error)

PlanSSHPolicyActivation 将持久化 EffectivePolicy 投影为显式 CLI ssh 转发/TUN/会话与后台化激活规划; 投影 ForkAfterAuth 与仅限显式 CLI 的 AutoSpawnControlMaster(ADR-019 D1),仅对无效策略失败关闭。

func (SSHPolicyPlan) AutoSpawnControlMaster added in v1.3.0

func (p SSHPolicyPlan) AutoSpawnControlMaster() bool

AutoSpawnControlMaster 报告显式 CLI ssh 路径在无存活主进程时是否应自动拉起持久化后台 ControlMaster (ControlPath 启用、ControlMaster ∈ {auto, autoask, yes, ask} 且 ControlPersist 启用)。

func (SSHPolicyPlan) EscapeChar added in v1.3.0

func (p SSHPolicyPlan) EscapeChar() option.EscapeCharSpec

EscapeChar 返回经四层策略折叠后投影的会话转义字符策略;零值无效规划安全返回零值 EscapeCharSpec。 交互 PTY 会话在直连与 muxstream 模式下经 sessplan.EscapeFilter 解释 5 组序列,在原生 OpenSSH Master 下透传至协议层(ADR-019 C1)。

func (SSHPolicyPlan) ExitOnForwardFailure added in v1.3.0

func (p SSHPolicyPlan) ExitOnForwardFailure() bool

func (SSHPolicyPlan) ForkAfterAuth added in v1.3.0

func (p SSHPolicyPlan) ForkAfterAuth() bool

ForkAfterAuth 报告生效策略是否启用认证后后台脱离(-f / ForkAfterAuthentication=yes,仅限显式 CLI 路径交由后台守护处理)。

func (SSHPolicyPlan) Forwards added in v1.3.0

func (p SSHPolicyPlan) Forwards() []ports.ForwardSpec

func (SSHPolicyPlan) IsValid added in v1.3.0

func (p SSHPolicyPlan) IsValid() bool

SSHPolicyPlan 零值安全只读访问器(切片与映射均返回防御性拷贝)。

func (SSHPolicyPlan) IsZero added in v1.3.0

func (p SSHPolicyPlan) IsZero() bool

func (SSHPolicyPlan) RemoteCommand added in v1.3.0

func (p SSHPolicyPlan) RemoteCommand() algebraic.Option[string]

func (SSHPolicyPlan) RequestTTY added in v1.3.0

func (p SSHPolicyPlan) RequestTTY() RequestTTYMode

func (SSHPolicyPlan) SessionType added in v1.3.0

func (p SSHPolicyPlan) SessionType() option.SessionTypeMode

func (SSHPolicyPlan) SetEnv added in v1.3.0

func (p SSHPolicyPlan) SetEnv() map[string]string

func (SSHPolicyPlan) StdinNull added in v1.3.0

func (p SSHPolicyPlan) StdinNull() bool

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service 是 XOps v2 全量会话、提权、探测、持久 PTY、隧道转发与多路复用控制面用例服务; 零值恒未初始化并严格失败关闭。

func NewService

func NewService(cfg ServiceConfig) (*Service, error)

NewService 校验必填依赖(Gate、Pool、Clock)与可选 DefaultExecution 并构造会话执行 Service。

func (*Service) ActivateSSHPolicyForwards added in v1.3.0

func (s *Service) ActivateSSHPolicyForwards(ctx context.Context, req ActivateSSHForwardsRequest) (SSHForwardsActivationResult, error)

ActivateSSHPolicyForwards 在显式 CLI ssh 边界激活持久化 local_forward/remote_forward(含 -R 反向动态)/dynamic_forward(含 -D Unix)/tunnel:

  • 校验 ExplicitCLI==true,否则零拨号失败关闭;
  • 从 Policy 构造含 AddressFamily 的 ForwardBindOptions 透传至每条 StartForward(强制经 gate.Authorized[security.CapTunnel] 审批防篡改);
  • 安全/门控/审计/取消硬错误或 ExitOnForwardFailure==true 下的任意失败,均立即 LIFO 回滚已启动句柄并返回错误;
  • 仅当 ExitOnForwardFailure==false 且为运行期绑定/监听失败时记录至 Failed 并继续后续转发。

func (*Service) CanSuspendProcessGroup

func (s *Service) CanSuspendProcessGroup() (security.Verdict, error)

CanSuspendProcessGroup 委托 TerminalPort 执行 POSIX 孤儿进程组安全挂起判定(INV-E1); 未初始化、未配置 TerminalPort 或底层异常时严格失败关闭返回 (security.VerdictDeny, error)。

func (*Service) ClosePTY

func (s *Service) ClosePTY(ctx context.Context, handle plan.ManagedHandle[plan.KindPTY]) error

func (*Service) ControlMux

ControlMux 向活跃 ControlMaster 发送 -O 控制命令(check/conninfo/channels/forward/cancel/exit/stop):

  • check/conninfo/channels 走 CapInspect(RiskSafe),conninfo/channels 经 MuxInspectPort 透传 ErrUnsupported;
  • 单条或批量 forward/cancel 将全部规格按确定性顺序纳入单份 CapTunnel 聚合审批信封, 批量模式对每条提交及 ExitOnForwardFailure 触发的 LIFO 回滚独立经 auth.WithSubAudit 记录逐条审计(ADR-019 D2)。

func (*Service) Exec

Exec 执行单条远端命令(严格按 gate.WithAuthorized 包裹 pool.WithLease), 接入 6 级 execution 启动配置继承链、内存期 CommandTexts 黑名单校验、SendEnv 过滤、 按策略决定 PTY/流模式并向可选 OperationStream 发射完整事件序列与确定性 EOF。

func (*Service) ExecPrivileged

ExecPrivileged 执行远端提权命令(支持具体 sudo/su/doas 与节点 PrivilegePolicy 含 method=auto 求解): 经 CommandTexts 黑名单校验与 security.CanonicalScopeEscalated 复核提权作用域, 强制 gate.WithAuthorized[security.CapExecute](恒满足 effRisk >= RiskDangerous)包裹 pool.WithLease, 并在获得授权后将 method=auto 求解为具体三态 ports.PrivilegeMethod,经作用域借用透传提权口令(0 明文消费)。

func (*Service) ExecuteLocalCommand added in v1.3.0

func (s *Service) ExecuteLocalCommand(ctx context.Context, req LocalCommandRequest) (ports.ProcessResult, error)

ExecuteLocalCommand 严格按 ADR-019 C2 两阶段受控执行本机 LocalCommand(零 Shell):

  1. 预授权阶段(Outer Gate):校验 ExplicitCLI/PermitLocalCommand/LocalCommand,解析模板并拒绝 argv[0] 含 %T, 冻结绝对可执行路径(防 PATH TOCTOU),将绑定摘要与预检 CommandTexts 送入 gate.WithAuthorized[CapExecute] (全 Profile 必过 blocked_patterns,strict_* 固定至少 RiskDangerous);
  2. 执行阶段:必要时运行 OnAuthorized(允许 gate 包裹 pool.WithLease/TUN 启动),校验有界 %T 网卡名并完成单遍展开, 固定 argv[0] 为冻结路径后再次复核最终展开命令是否命中 blocked_patterns,通过后经 ProcessPort.Run 同步执行。

func (*Service) InspectControlMaster

func (s *Service) InspectControlMaster(ctx context.Context, handle plan.ManagedHandle[plan.KindMux]) (ControlMasterStatus, error)

InspectControlMaster / TouchControlMaster / StopControlMaster 提供受管 ControlMaster 句柄的状态快照、活跃续期与有序停机。

func (*Service) InspectForward

func (s *Service) InspectForward(ctx context.Context, handle plan.ManagedHandle[plan.KindTunnel]) (ForwardStatus, error)

InspectForward / WithForwardHandle / StopForward 提供受管隧道句柄的状态查询、同步借用与显式释放。

func (*Service) InspectPTY

func (s *Service) InspectPTY(ctx context.Context, handle plan.ManagedHandle[plan.KindPTY]) (PTYStatus, error)

func (*Service) Interactive

Interactive 启动远端交互式 Shell 会话(严格按 gate.WithAuthorized 包裹 pool.WithLease), 按 RequestTTY 策略经 TerminalPort.WithRawTerminal + TerminalHandle.Relay 中继交互流与窗口缩放。

func (*Service) OpenPTY

OpenPTY 在连接池世代 SlotMap 上创建跨请求持久 PTY 会话并返回强类型 ManagedHandle[plan.KindPTY]: 严格遵循 gate.WithAuthorized[security.CapExecute] 包裹 pool.WithLease 与 pool.RegisterLeaseHandleWith。

func (*Service) ProbeMux

func (s *Service) ProbeMux(ctx context.Context, req MuxRequest) (ports.MuxControlResponse, error)

ProbeMux 经 CapInspect 门控探测指定 ControlMaster 套接字存活状态与主进程 PID。

func (*Service) ProbePrivilegeMethod added in v1.3.0

func (s *Service) ProbePrivilegeMethod(ctx context.Context, req ProbeShellRequest) (ports.PrivilegeMethod, error)

ProbePrivilegeMethod 经 CapInspect 鉴权探测远端可用提权工具并解析为具体三态 ports.PrivilegeMethod(sudo > doas > su), 探测不到受支持工具或远端为非 Unix 方言时严格失败关闭。

func (*Service) ProbeShell

ProbeShell 通过冻结的 ports.ShellProbePort 执行规范化 2 阶段远端 Shell 探测(完整支持 posix/fish/csh/tcsh/powershell/cmd): 严格经 gate.WithAuthorized[security.CapInspect] 包裹 pool.WithLease,并对探测快照实施二次失败关闭校验(零盲猜回退), 且绝不隐式激活持久化 OpenSSH 转发/TUN/remote_command。

func (*Service) QueryMuxChannels added in v1.3.0

func (s *Service) QueryMuxChannels(ctx context.Context, req MuxRequest) (ports.ActiveChannelSnapshot, error)

QueryMuxChannels 经 CapInspect(RiskSafe)门控查询活跃 ControlMaster 的活跃会话与转发快照(-O channels / xops mux channels), 对不支持扩展协议的旧版或原生 OpenSSH Master 原样透传 ports.ErrUnsupported(ADR-019 D2)。

func (*Service) QueryMuxConnInfo added in v1.3.0

func (s *Service) QueryMuxConnInfo(ctx context.Context, req MuxRequest) (ports.MuxConnInfo, error)

QueryMuxConnInfo 经 CapInspect(RiskSafe)门控查询活跃 ControlMaster 的只读连接元信息快照(-O conninfo / xops mux info), 对不支持扩展协议的旧版或原生 OpenSSH Master 原样透传 ports.ErrUnsupported(ADR-019 D2)。

func (*Service) ReadPTY

func (s *Service) ReadPTY(ctx context.Context, req PTYReadRequest) (res PTYReadResult, err error)

ReadPTY / WritePTY / ResizePTY / SignalPTY / InspectPTY / ClosePTY 提供跨请求持久 PTY 句柄操作(陈旧世代/吊销/熔断均失败关闭)。

func (*Service) ResizePTY

func (s *Service) ResizePTY(ctx context.Context, handle plan.ManagedHandle[plan.KindPTY], size ports.TerminalSize) error

func (*Service) ResolveExecutionProfile added in v1.3.0

func (s *Service) ResolveExecutionProfile(spec ExecutionInheritanceSpec) (execution.LaunchProfile, error)

ResolveExecutionProfile 按 6 级继承链(CLI > PlaybookStep > PlaybookSettings > Node > Global > server) 求解最终 execution.LaunchProfile;若调用方未显式传入 Global 层,则自动注入 ServiceConfig.DefaultExecution。

func (*Service) RunExplicitSSHSession added in v1.3.0

func (s *Service) RunExplicitSSHSession(ctx context.Context, req ExplicitSSHSessionRequest) (execution.ExecutionOutcome, error)

RunExplicitSSHSession 在显式 CLI ssh 边界结合 EffectivePolicy 执行单命令、子系统(-s)、持久化 remote_command 或交互式 Shell:

  • 强制校验 ExplicitCLI==true,并对 SessionType=none 失败关闭;
  • 持久化 remote_command 仅在无显式 CLI 命令时激活,且强制经 6 级 execution 继承链、gate.Authorized[CapExecute] 与 CommandTexts 黑名单校验;
  • 自动应用 Policy.RequestTTY、Policy.StdinNull、Policy.SetEnv、Policy.EscapeChar 与 Policy.ForwardAgentSpec。

func (*Service) RunMuxProxy

func (s *Service) RunMuxProxy(ctx context.Context, req MuxRequest, stdin io.ReadCloser, stdout io.Writer) error

RunMuxProxy 打开 `-O proxy` 连接并在 conc.RunScoped 监督下完成可关闭 stdin 与 stdout 的双向中继; 在 Nursery 作用域内监听 wCtx 同步中止,确保 stdin 真实读错、远端先达 EOF、背压写阻塞或 ctx 取消 均即时关闭 conn 与 stdin 并忠实传播非关闭故障与取消错误(0 死锁、0 goleak,适配真实 *os.File 的 fs.ErrClosed)。

func (*Service) RunStdioForward added in v1.3.0

func (s *Service) RunStdioForward(ctx context.Context, req StdioForwardRequest) (execution.ExecutionOutcome, error)

RunStdioForward 执行 `-W host:port` 标准输入输出转发(ADR-019 A3):

  • 延迟展开 %h/%p 并经 netaddr.ParseHostPort 校验最终目标;
  • 严格遵循 gate.WithAuthorized[security.CapTunnel] 包裹 pool.WithLease,经 lease.DialTCP 建链;
  • 在 conc.RunScoped 监督下双向桥接 stdin/stdout 并正确传播单向半关闭 CloseWrite(), 正常完成返回退出码 0,前置拒绝或传输中止对应退出码 255(NotStarted/Unknown)。

func (*Service) RunSubsystem added in v1.3.0

RunSubsystem 经 gate.WithAuthorized[security.CapExecute](默认 RiskModerate)包裹 pool.WithLease 启动指定远端 SSH 子系统(通过具名可选接口 ports.SubsystemRemoteSession,不支持时失败关闭返回 ports.ErrUnsupported)。

func (*Service) SignalPTY

func (s *Service) SignalPTY(ctx context.Context, handle plan.ManagedHandle[plan.KindPTY], sig string) error

func (*Service) StartControlMaster

func (s *Service) StartControlMaster(ctx context.Context, req ControlMasterRequest) (ControlMasterInfo, error)

StartControlMaster 启动受管 ControlMaster(-M / ControlPersist)或在 auto/autoask 模式下复用活跃主进程: 严格消费 ControlPolicy.EffectiveMaster() 与 EffectivePersist() 失败关闭投影,绝不绕过 Path 禁用校验。

func (*Service) StartForward

func (s *Service) StartForward(ctx context.Context, req StartForwardRequest) (ForwardInfo, error)

StartForward 启动一条受管长驻 SSH 转发(支持 -L/-R/-D、TCP↔Unix StreamLocal 双向/混合与 TUN): 严格遵循 gate.WithAuthorized[security.CapTunnel] 包裹 pool.WithLease 与 pool.RegisterLeaseHandleWith, 并将 ForwardBindOptions 纳入两步审批绑定参数与风险定级,防 Round-1/Round-2 绑定策略篡改。

func (*Service) StopControlMaster

func (s *Service) StopControlMaster(ctx context.Context, handle plan.ManagedHandle[plan.KindMux]) error

func (*Service) StopForward

func (s *Service) StopForward(ctx context.Context, handle plan.ManagedHandle[plan.KindTunnel]) error

func (*Service) TouchControlMaster

func (s *Service) TouchControlMaster(ctx context.Context, handle plan.ManagedHandle[plan.KindMux]) error

func (*Service) TouchControlMasterActivity

func (s *Service) TouchControlMasterActivity(ctx context.Context, handle plan.ManagedHandle[plan.KindMux], delta int) error

func (*Service) WithForwardHandle

func (s *Service) WithForwardHandle(ctx context.Context, handle plan.ManagedHandle[plan.KindTunnel], fn func(ctx context.Context, fh ports.ForwardHandle) error) error

func (*Service) WithMuxConn

func (s *Service) WithMuxConn(ctx context.Context, req MuxRequest, fn func(ctx context.Context, conn ports.TransportConn) error) error

WithMuxConn 经 MuxSocketPort.DialMux 复用活跃 ControlMaster 并严格核验返回的 (HopDigest, Endpoint) 身份与 ForwardAgent 兼容性策略(不兼容直接返回错误不静默回退),在同步作用域闭包内借出 ports.TransportConn,退出时无条件关闭。

func (*Service) WithMuxProxy

func (s *Service) WithMuxProxy(ctx context.Context, req MuxRequest, fn func(ctx context.Context, conn net.Conn) error) error

WithMuxProxy 以同步作用域闭包打开 ControlMaster `-O proxy`(MuxActionProxy)双向透传连接, 退出回调时无条件关闭底层 net.Conn,确保零命令式泄漏。

func (*Service) WritePTY

func (s *Service) WritePTY(ctx context.Context, handle plan.ManagedHandle[plan.KindPTY], data []byte) (n int, err error)

type ServiceConfig

type ServiceConfig struct {
	Gate                        gate.Authorizer                            // 必填:能力门控授权器(ADR-008:严禁 nil)
	Pool                        *pool.Pool                                 // 必填:双通道纯内存 Actor 连接池(ADR-009)
	Clock                       ports.Clock                                // 必填:时钟端口(事件时间戳、ControlPersist 与耗时统计)
	DefaultExecution            algebraic.Option[execution.LaunchProfile]  // 可选:全局默认执行启动配置(6 级执行继承链 Global 层)
	Env                         ports.EnvPort                              // 可选:只读环境变量与本机身份端口
	Process                     ports.ProcessPort                          // 可选:本机零 Shell 受控子进程端口(ADR-019 C2 LocalCommand)
	Terminal                    ports.TerminalPort                         // 可选:本机原始终端端口
	Escalator                   ports.PrivilegeEscalationPort              // 可选:远端提权(sudo/su/doas)端口
	Vault                       ports.SecretVault                          // 可选:全作用域凭据库端口
	Interaction                 ports.InteractionPort                      // 可选:人工交互端口
	ShellProbe                  ports.ShellProbePort                       // 可选:2 阶段远端 Shell 探测端口
	Forwarder                   ports.ForwarderPort                        // 可选:-L/-R/-D/StreamLocal/TUN 唯一受管转发端口(ADR-019 A1)
	TUNDevice                   ports.TUNDevicePort                        // 渐进兼容保留字段:所有 TUN 隧道已统一经 Forwarder 路由(零直通旁路)
	MuxSocket                   ports.MuxSocketPort                        // 可选:ControlMaster AF_UNIX 控制面端口
	DiagnosticSink              ports.DiagnosticSink                       // 可选:面向 -v/-vv/-vvv 的轻量脱敏诊断通道(严禁持锁调用)
	DisallowForwardAgent        bool                                       // 可选:物理禁止 SSH Agent 转发(零值 false;MCP/受限视图置 true)
	DisallowNativeMux           bool                                       // 可选:禁止经本 Service 启动的 ControlMaster 受理入站原生 OpenSSH Mux 请求(MCP 视图置 true)
	ForcedMuxForwardBindOptions algebraic.Option[ports.ForwardBindOptions] // 可选:强制覆写单实例 ControlMaster 的 ForwardBindOptions 上限(MCP 视图锁 GatewayPortsNo + StreamLocalBindUnlink=false)
}

ServiceConfig 定义会话执行用例服务 Service 的显式出站依赖配置。

type StartForwardRequest

type StartForwardRequest struct {
	Plan            plan.SealedConnectionPlan
	Spec            ports.ForwardSpec
	BindOptions     algebraic.Option[ports.ForwardBindOptions]
	NodeID          string
	Risk            algebraic.Option[security.RiskLevel]
	Approval        algebraic.Option[gate.ApprovalSubmission]
	OperationStream *events.OperationStream
}

StartForwardRequest 描述启动 SSH 端口转发(-L/-R/-D)、StreamLocal(TCP↔Unix 双向/混合)或 TUN 隧道的强类型输入(P3-T2)。

type StdioForwardRequest added in v1.3.0

type StdioForwardRequest struct {
	Plan            plan.SealedConnectionPlan
	TargetTemplate  string
	NodeID          string
	Stdin           io.Reader
	Stdout          io.Writer
	Risk            algebraic.Option[security.RiskLevel]
	Approval        algebraic.Option[gate.ApprovalSubmission]
	OperationStream *events.OperationStream
}

StdioForwardRequest 描述 OpenSSH `-W host:port` 标准输入输出隧道转发用例的强类型输入(ADR-019 A3)。 TargetTemplate 在目标解析完成后按目标跳板展开 %h/%p 并经 netaddr.ParseHostPort 强校验。

type SubsystemRequest added in v1.3.0

type SubsystemRequest struct {
	Plan                 plan.SealedConnectionPlan
	Subsystem            string
	NodeID, Term         string
	ExtraEnv             map[string]string
	Stdin                io.Reader
	Stdout, Stderr       io.Writer
	RequestTTY           RequestTTYMode
	EscapeChar           algebraic.Option[option.EscapeCharSpec]
	EscapeHelpText       string
	ForwardAgent         algebraic.Option[option.ForwardAgentSpec]
	IdentityAgent        algebraic.Option[option.IdentityAgentSpec]
	ExplicitForwardAgent bool
	Risk                 algebraic.Option[security.RiskLevel]
	Approval             algebraic.Option[gate.ApprovalSubmission]
	OperationStream      *events.OperationStream
}

SubsystemRequest 描述经 RFC 4254 subsystem 请求启动远端 SSH 子系统(-s / SessionType=subsystem)的强类型输入(ADR-019 C1)。

Directories

Path Synopsis
internal
sessplan
Package sessplan 提供 core/internal/usecase/session 的无环内部规划、校验与纯辅助组件: 涵盖提权规划与作用域评估、选项/路径展开、转发绑定拼装、门控请求构造、结果分类与流式事件发射。
Package sessplan 提供 core/internal/usecase/session 的无环内部规划、校验与纯辅助组件: 涵盖提权规划与作用域评估、选项/路径展开、转发绑定拼装、门控请求构造、结果分类与流式事件发射。
sessrt
Package sessrt 为 core/internal/usecase/session 提供有状态并发长会话运行时资源驱动:
Package sessrt 为 core/internal/usecase/session 提供有状态并发长会话运行时资源驱动:

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL