返回 DeepSeek-Reasonix
project_scope.go
根目录 / internal / config / project_scope.go
1 package config
2
3 import (
4 "encoding/json"
5 "fmt"
6 "maps"
7 "os"
8 "path/filepath"
9 "reflect"
10 "slices"
11 "strings"
12
13 "reasonix/internal/permission"
14 "reasonix/internal/permissionpreset"
15 )
16
17 // heldScope is what the user granted, held across the project merge. A
18 // project reasonix.toml arrives with a checkout, so it is untrusted input: it
19 // may narrow these grants and never widen them. The slices are copies because
20 // decoding the project file writes into the arrays the user's decode left.
21 type heldScope struct {
22 sandbox SandboxConfig
23 permissions PermissionsConfig
24 approvalMode string
25 shell ShellConfig
26 rgPath string
27 lsp map[string]LSPServer
28 browser BrowserConfig
29 network NetworkConfig
30 endpoints heldEndpoints
31 bot BotConfig
32 attachments AttachmentsConfig
33 // Regional display preferences: a repository must not alter how spend reads.
34 language, currency, displayCurrency string
35 }
36
37 func holdUserScope(c *Config) heldScope {
38 s, p, b := c.Sandbox, c.Permissions, c.Browser
39 s.AllowWrite, s.ForbidRead = slices.Clone(s.AllowWrite), slices.Clone(s.ForbidRead)
40 b.ChromeArgs = slices.Clone(b.ChromeArgs)
41 p.Allow, p.Ask, p.Deny = slices.Clone(p.Allow), slices.Clone(p.Ask), slices.Clone(p.Deny)
42 attachments := c.Attachments
43 if attachments.MaxStreamBytes != nil {
44 value := *attachments.MaxStreamBytes
45 attachments.MaxStreamBytes = &value
46 }
47 return heldScope{
48 sandbox: s,
49 permissions: p,
50 approvalMode: c.Desktop.DefaultToolApprovalMode,
51 shell: c.Tools.Shell,
52 rgPath: c.Tools.Search.RgPath,
53 lsp: maps.Clone(c.LSP.Servers),
54 browser: b,
55 network: c.Network,
56 endpoints: holdUserEndpoints(c),
57 bot: cloneBotConfig(c.Bot),
58 attachments: attachments,
59 language: c.Desktop.Language,
60 currency: c.Desktop.Currency,
61 displayCurrency: c.Billing.DisplayCurrency,
62 }
63 }
64
65 // IgnoredProjectReason says why a project value was not applied.
66 type IgnoredProjectReason string
67
68 const (
69 // ProjectWidensUser: the value would loosen what the user configured.
70 ProjectWidensUser IgnoredProjectReason = "widens_user_setting"
71 // ProjectOutsideWorkspace: a path that resolves outside the workspace.
72 ProjectOutsideWorkspace IgnoredProjectReason = "outside_workspace"
73 // ProjectUserOnly: a setting only the user config may choose.
74 ProjectUserOnly IgnoredProjectReason = "user_only"
75 // ProjectAwaitingApproval: a program the project names that nobody approved.
76 ProjectAwaitingApproval IgnoredProjectReason = "awaiting_approval"
77 // ProjectApprovalUnavailable: the approval record could not be read.
78 ProjectApprovalUnavailable IgnoredProjectReason = "approval_store_unavailable"
79 // ProjectProgramWritable: a single program where sandboxed commands write.
80 ProjectProgramWritable IgnoredProjectReason = "program_in_writable_location"
81 )
82
83 var ignoredProjectReasonText = map[IgnoredProjectReason]string{
84 ProjectWidensUser: "a project file may only narrow this setting; set it in your user config to change it",
85 ProjectOutsideWorkspace: "the path resolves outside this workspace",
86 ProjectUserOnly: "only your user config sets this",
87 ProjectAwaitingApproval: "it runs only after you approve it; run `reasonix trust` in this workspace",
88 ProjectApprovalUnavailable: "the approval record could not be read, so it stays off",
89 ProjectProgramWritable: "it names a file in this workspace or another place sandboxed commands can write; point it at an installed program",
90 }
91
92 // IgnoredProjectSetting is one value a project file set that the load refused.
93 type IgnoredProjectSetting struct {
94 Key string
95 Value string
96 Reason IgnoredProjectReason
97 }
98
99 type projectScopeReport struct {
100 ignored []IgnoredProjectSetting
101 pending []ProjectProgram
102 admitted []ProjectProgram
103 }
104
105 // IgnoredProjectSettings lists the project values this load refused.
106 func (c *Config) IgnoredProjectSettings() []IgnoredProjectSetting {
107 if c == nil {
108 return nil
109 }
110 return slices.Clone(c.projectScope.ignored)
111 }
112
113 func (c *Config) ignoreProject(key, value string, reason IgnoredProjectReason) {
114 c.projectScope.ignored = append(c.projectScope.ignored, IgnoredProjectSetting{Key: key, Value: value, Reason: reason})
115 // Legacy permission declarations remain inspectable but do not signal a
116 // broken configuration or grant authority merely by being in a checkout.
117 if key != "permissions.allow" && key != "sandbox.allow_write" && key != "sandbox.workspace_root" {
118 c.addLoadWarning(fmt.Sprintf("project config sets %s = %q; ignored: %s", key, value, ignoredProjectReasonText[reason]))
119 }
120 }
121
122 // narrow applies the project-only-narrows rule to everything the project merge
123 // may have written, and gates the programs the project names.
124 func (h heldScope) narrow(c *Config, root string) {
125 ws := workspaceDir(root)
126 // A checkout can only reuse authority held by the user, not create it.
127 grants := NewProjectGrantStore(reasonixHomeDir())
128 grant, err := grants.Grant(ws)
129 if err != nil {
130 c.addLoadWarning(fmt.Sprintf("project grants %s could not be read (%v); access may require approval", grants.Path(), err))
131 }
132 if ws == "" {
133 grant = ProjectGrant{}
134 }
135 h.permissions.Allow = appendMissing(h.permissions.Allow, grant.Allow...)
136 h.sandbox.AllowWrite = appendMissing(h.sandbox.AllowWrite, grant.AllowWrite...)
137 c.Desktop.Language, c.Desktop.Currency, c.Billing.DisplayCurrency = h.language, h.currency, h.displayCurrency
138 h.narrowSandbox(c, ws)
139 h.narrowPermissions(c)
140 if permissionpreset.NormalizeDefault(c.Desktop.DefaultToolApprovalMode) != permissionpreset.NormalizeDefault(h.approvalMode) {
141 c.ignoreProject("desktop.default_tool_approval_mode", c.Desktop.DefaultToolApprovalMode, ProjectUserOnly)
142 }
143 c.Desktop.DefaultToolApprovalMode = h.approvalMode
144 if !reflect.DeepEqual(c.Network, h.network) {
145 c.ignoreProject("network", "proxy_mode="+c.Network.ProxyMode, ProjectUserOnly)
146 }
147 c.Network = h.network
148 // [bot] opens the machine to chat accounts and routes their messages into
149 // sessions; only the user's own config may say which.
150 if !reflect.DeepEqual(c.Bot, h.bot) {
151 c.ignoreProject("bot", "", ProjectUserOnly)
152 }
153 c.Bot = h.bot
154 if !reflect.DeepEqual(c.Attachments, h.attachments) {
155 c.ignoreProject("attachments.max_stream_bytes", "", ProjectUserOnly)
156 }
157 c.Attachments = h.attachments
158 home := reasonixHomeDir()
159 store := NewProjectProgramStore(home)
160 h.gatePrograms(c, store, ws)
161 h.endpoints.gateEndpoints(c, store, ws)
162 }
163
164 func (h heldScope) narrowSandbox(c *Config, ws string) {
165 s, u := &c.Sandbox, h.sandbox
166 if bashJails(u.Bash) && !bashJails(s.Bash) {
167 c.ignoreProject("sandbox.bash", s.Bash, ProjectWidensUser)
168 s.Bash = u.Bash
169 }
170 if s.Network && !u.Network {
171 c.ignoreProject("sandbox.network", "true", ProjectWidensUser)
172 s.Network = false
173 }
174 s.ForbidRead = appendMissing(u.ForbidRead, s.ForbidRead...)
175 if s.WorkspaceRoot != u.WorkspaceRoot && !c.equivalentConfigPath(ws, s.WorkspaceRoot, u.WorkspaceRoot) {
176 if dir, ok := c.workspacePath(ws, s.WorkspaceRoot); ok {
177 s.WorkspaceRoot = dir
178 } else {
179 c.ignoreProject("sandbox.workspace_root", s.WorkspaceRoot, ProjectOutsideWorkspace)
180 s.WorkspaceRoot = u.WorkspaceRoot
181 }
182 } else {
183 s.WorkspaceRoot = u.WorkspaceRoot
184 }
185 allow := slices.Clone(u.AllowWrite)
186 // Only the admitted workspace root counts: a rejected project root cannot
187 // authorize its own extra directories, and a narrowed root stays narrow.
188 coveredRoots := append(slices.Clone(u.AllowWrite), s.WorkspaceRoot)
189 for _, entry := range s.AllowWrite {
190 if slices.Contains(u.AllowWrite, entry) || c.authorizedPath(ws, coveredRoots, entry) {
191 continue
192 }
193 if dir, ok := c.workspacePath(ws, entry); ok {
194 allow = appendMissing(allow, dir)
195 } else {
196 c.ignoreProject("sandbox.allow_write", entry, ProjectOutsideWorkspace)
197 }
198 }
199 s.AllowWrite = allow
200 }
201
202 func (h heldScope) narrowPermissions(c *Config) {
203 p, u := &c.Permissions, h.permissions
204 if normalizedMode(p.Mode) != normalizedMode(u.Mode) {
205 c.ignoreProject("permissions.mode", p.Mode, ProjectUserOnly)
206 }
207 if p.AllowDynamicBash && !u.AllowDynamicBash {
208 c.ignoreProject("permissions.allow_dynamic_bash", "true", ProjectUserOnly)
209 }
210 for _, rule := range p.Allow {
211 if !slices.Contains(u.Allow, rule) && !slices.ContainsFunc(u.Allow, func(allowed string) bool { return permission.RuleCoversString(allowed, rule) }) {
212 c.ignoreProject("permissions.allow", rule, ProjectUserOnly)
213 }
214 }
215 p.Mode, p.AllowDynamicBash, p.Allow = u.Mode, u.AllowDynamicBash, u.Allow
216 p.Ask = appendMissing(u.Ask, p.Ask...)
217 p.Deny = appendMissing(u.Deny, p.Deny...)
218 }
219
220 // bashJails mirrors BashModeForGOOS off Windows: only an explicit "off" runs
221 // bash unconfined, so every other spelling counts as the jail.
222 func bashJails(mode string) bool { return strings.TrimSpace(mode) != "off" }
223
224 func normalizedMode(mode string) string { return strings.ToLower(strings.TrimSpace(mode)) }
225
226 // workspacePath resolves a project-declared path the way the confiner will and
227 // reports whether it stays inside ws. The resolved form is what gets stored, so
228 // a link swapped in after this check cannot move what was approved.
229 func (c *Config) workspacePath(ws, path string) (string, bool) {
230 resolved, ok := c.configPath(ws, path)
231 if !ok {
232 return "", false
233 }
234 return resolved, configDirectoryCovers(ws, resolved)
235 }
236
237 // expandSandboxPath expands ${VAR} from the process environment alone: a
238 // workspace .env must not steer where writes land or which reads are refused,
239 // and a project path still holding "${" is refused rather than expanded again.
240 func (c *Config) expandSandboxPath(path string) string {
241 return ExpandVars(path)
242 }
243
244 // workspaceDir is root absolute and symlink-free, or "" when it cannot be
245 // resolved; an unresolvable workspace contains nothing.
246 func workspaceDir(root string) string {
247 abs, err := filepath.Abs(root)
248 if err != nil {
249 return ""
250 }
251 real, err := filepath.EvalSymlinks(abs)
252 if err != nil {
253 return ""
254 }
255 if info, err := os.Stat(real); err != nil || !info.IsDir() {
256 return ""
257 }
258 return filepath.Clean(real)
259 }
260
261 func appendMissing(base []string, extra ...string) []string {
262 out := slices.Clone(base)
263 for _, v := range extra {
264 if !slices.Contains(out, v) {
265 out = append(out, v)
266 }
267 }
268 return out
269 }
270
271 // cloneBotConfig deep-copies b: the project decode writes into the maps and
272 // slices the user's decode left behind.
273 func cloneBotConfig(b BotConfig) BotConfig {
274 data, err := json.Marshal(b)
275 if err != nil {
276 return BotConfig{}
277 }
278 var out BotConfig
279 if json.Unmarshal(data, &out) != nil {
280 return BotConfig{}
281 }
282 return out
283 }
284
284 lines GO