From 46c185d928156c894a8fcb5e44630bd8db184307 Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Mon, 30 Nov 2026 22:57:05 +0900 Subject: [PATCH] feat(inspection): add policy and plugin execution foundation --- docs/design/ja/file-inspection.md | 122 ++++++++++ docs/design/ja/implementation-backlog.md | 7 + docs/design/ja/operations.md | 4 + internal/inspection/policy.go | 295 +++++++++++++++++++++++ internal/inspection/policy_test.go | 135 +++++++++++ internal/inspection/runner.go | 268 ++++++++++++++++++++ internal/inspection/runner_test.go | 233 ++++++++++++++++++ 7 files changed, 1064 insertions(+) create mode 100644 docs/design/ja/file-inspection.md create mode 100644 internal/inspection/policy.go create mode 100644 internal/inspection/policy_test.go create mode 100644 internal/inspection/runner.go create mode 100644 internal/inspection/runner_test.go diff --git a/docs/design/ja/file-inspection.md b/docs/design/ja/file-inspection.md new file mode 100644 index 0000000..5d1efff --- /dev/null +++ b/docs/design/ja/file-inspection.md @@ -0,0 +1,122 @@ +# ファイル検査と配信制御 + +2026-11-30。アップロード受入、ファイル検査、Webへの配信許可を分離する。 +**現段階は共通評価器・プラグイン契約・実行器のみ実装済み。HTTP配信制限、DB保存、 +イベント登録、管理画面、実検査エンジンは未接続。現在のアップロードに検査が追加されたわけではない。** + +利用者合意により、今回の実装範囲はSCAN-01/02の骨子までで一旦区切る。 +SCAN-03以降は設計上の残件として保持し、このコミットを契機に自動で着手・有効化しない。 + +## 公開範囲・権限との関係 + +公開範囲は既存のDomain → Quartier → Street → Spotと、それらのPath境界に従う。 +下位の既定値はinherit。上位の制約を下位が緩和できない。 +公開可能な上限、Revisionの明示/自動公開、認証後のread/writeは別の判定として維持する。 +検査結果は追加の配信条件であり、cleanになっても非公開文書を公開したり、権限を付与したりしない。 + +検査設定も同様に継承する。初期状態はdisabled。下位で明示したdisabledでも、上位の +monitor/requiredを解除しない。上位で要求したエンジンを下位で削除・別版へ置換しない。 +下位で別エンジンを追加する場合は、すべての必要な検査を通す。 +エンジン更新・検査解除は、その上位設定を変更できる管理者が明示的に行う。 + +| モード | 配信判定 | +| --- | --- | +| inherit | この範囲で追加の指定をせず上位に従う | +| disabled | 上位に制約がなければ既存の配信判定を維持 | +| monitor | 検査結果を記録・表示するが、検査だけを理由に配信を止めない | +| required | 必須エンジンすべてについて、有効なclean結果が必要 | + +monitorはmaliciousでも配信を止めない明示的な観測モード。設定画面でこの性質を説明する。 +requiredでエンジンが無効・不在・異常・期限切れなら拒否する。プラグイン停止を検査免除と解釈しない。 + +## 保存と非同期処理 + +1. 認証、create/write権限、条件付き保存、サイズ、MIME等を既存の保存境界で検証する。 +2. 不変Documentを永続化する。Path・Revision・検査要求outboxは対応するDB transactionで公開する。 +3. outboxをイベントキューへ転送し、重複を抑止して検査を実行する。 +4. 現在のポリシー、送信同意、ジョブ所有権を再確認し、結果を条件付きで保存する。 +5. 配信要求ごとに既存のアクセス権・公開状態と、有効な検査結果を確認する。 + +アップロードHTTP要求中にスキャナーの完了を待たない。配信要求から同期スキャンもしない。 +保存成功と配信可能は別。検査待ちであっても保存済みなら保存APIは失敗扱いにしない。 +CLIの新規作成PUT契約の201・identityヘッダーを維持し、検査状態は別メタデータとして追加する。 +CLIは独自サニタイズや自動再送を行わない。スキャナーは保存本文を書き換えない。 +無害化/CDRを将来追加する場合は、別Document/Revisionと由来を記録し、黙って置換しない。 + +## 結果と識別子 + +結果キーはDomain UUID、ポリシー世代、保存内容のSHA-256、エンジンID・版・定義版。 +Path名やUUID単独、ファイル名、アップロード側が申告した検査結果を根拠にしない。 +エンジンはclean/suspicious/maliciousを返す。本体はpending/error/expiredも管理する。 +cleanは当該検査で検出なしを意味し、安全性の絶対保証ではない。 + +ポリシー世代は設定・関係するtopology・エンジン有効状態の変更時にサーバーが更新する。 +初版はDomain世代の変更で保守的に無効化する。大規模Domainの再検査負荷は後続でscope単位へ分割する。 +別Domainの同じhashには結果を流用しない。別エンジン版・定義版・世代や期限切れの結果も使わない。 +検査開始・終了時刻、期限、監査用ジョブID、worker lease、試行番号、判定を保存する。 +プラグインの生の例外・ファイル本文・資格情報を通常ログや通知へ出さない。 + +DB保存案は`inspection_policies`、`inspection_reports`と既存outbox/queueを使用する。 +reportsは上記キーをuniqueとし、古い試行や失効leaseによる上書きを拒否する。 +SQLはSQLite/PostgreSQL/MySQLのnative migrationと共通契約試験で追加する。 +CHECKや索引を含むschema検査、既存版のchecksum保持を実施し、SQLite専用SQLを共通処理へ増やさない。 + +## プラグインと実行制約 + +検査はビューア/エディタではなくシステム拡張。拡張カタログへ公開するのは配信ゲート接続後。 +現段階の`internal/inspection.Registry`はアプリ所有の信頼済み実装のみ登録でき、登録直後は無効。 +任意コマンド実行、アップロードされたコードのロード、URLからのプラグイン取得は行わない。 +実際のスキャナーはまだ登録していない。合成テストの模擬スキャナーを製品へ有効化しない。 + +実行器はGeduldhの不変Storeから読み、サイズとSHA-256をストリーム検証してからプラグインへ渡す。 +プラグインには読み取りストリームのみ渡し、Path・Bearer・DB接続や保存変更権限は渡さない。 +外部送信するプラグインは、Domain管理者の別の同意がないと読み取り開始前に拒否する。 +送信URL、TLS、SSRF対策、応答上限、送信先サービスの保持・第三者再送方針は実アダプタ接続の受入条件。 + +実行枠は1〜4、入力上限は最大256 MiB、協調的timeoutは最大1分、結果TTLは最大24時間に制限する。 +満杯時は待ち行列をメモリ上に増やさずErrBusyを返し、既存スケジューラで再配置する。 +実行数、完了・失敗数、検証byte数、累積実行時間を取得可能。現状は実行器単位の値であり、 +エンジン別永続集計、CPU/メモリ監視、設定画面への接続は後続。 + +実行直前・検証後・結果返却前に、呼出元のRecheckで世代・ジョブ・同意を再確認する。 +結果DBへのcommitでは別途lease/世代CASが必須。コールバックだけでtransactionの代用にしない。 +実行中のエンジン停止→再有効化も、旧実行結果を採用しない。 + +Go内プラグインはプロセス隔離ではない。contextを無視する実装を強制停止する保証はなく、 +終了までは実行枠を保持する。実際の重い/外部エンジンはsidecarとCPU/メモリ/timeout制限を検討する。 +恒久停止への対応・lease回収・再試行上限をイベントキュー側で担保してから有効化する。 + +## 配信・処理経路の受入ゲート + +検査対象のバイト列を処理する前に共通ゲートを通す。HTTPであればETag/304・Range/206・ +HEAD・identityヘッダー等を返す前に判定する。拒否応答はprivate,no-storeとする。 +既にダウンロードされたデータやブラウザに残ったコピーの回収は保証できない。 + +| 経路 | 必要な確認 | +| --- | --- | +| 通常/匿名/ブログ等のビューア、履歴 | 対象Revisionと依存Document、公開・ACL判定を維持 | +| RAW、UUID、Revision、Asset、共有リンク | 名前空間やURL種別を変えて迂回しない | +| サムネイル、PDF/画像/アーカイブ解析、全文索引 | 未検査データを先にパーサーへ渡さない | +| エディタ、連携アダプタ、export、CLI get | バイト列引渡しを同じ条件で制御 | +| 生成済みpreview/cache/CDN | 元Documentとpolicy世代を保持し、旧キャッシュからの配信を防ぐ | + +別名Pathを持つObjectは現在の関連範囲すべてを検査する。公開側の別名だけを選んで制約を外さない。 +`DecidePaths`は渡された全Pathを評価し、空・上限超過・不正snapshotは拒否する。 +ただし全Pathを列挙できたかは呼出元の責務。省略した配列を完全なsnapshotとして渡してはならない。 +UUID/Asset/依存Documentの所属を解決できない場合も、ルートのdisabled設定に置き換えてはならない。 +跨Domainでは各Domainの設定・権限を独立に評価する。 +隔離ファイルを管理者が取得する操作を設ける場合は、通常RAWを例外化せず、専用監査経路とする。 + +## 段階と残件 + +| ID | 状態 | 内容 | +| --- | --- | --- | +| SCAN-01 | 実装済み | Path継承、世代・hash付き結果判定、別名の全件評価、認可と分離した追加ゲート | +| SCAN-02 | 実装済み | 無効開始の信頼済みプラグインregistry、制限付き実行器、合成試験 | +| SCAN-03 | 未実装 | 3DBの設定・結果保存、CAS/監査、outboxとqueue接続、lease/retry、プラグイン別計測 | +| SCAN-04 | 未実装 | 上表の全配信/解析経路への接続、依存物・別名・キャッシュ・HEAD/Range/304の結合試験 | +| SCAN-05 | 未実装 | 管理UI/CLI、継承元と実効値表示、監視モードの警告、権限制御、手動再検査 | +| SCAN-06 | 未実装 | MWDB/Karton等の実プラグイン、外部同意、隔離、資源制限、実機受入 | + +SCAN-03/04完了まで必須モードをユーザーへ公開しない。本番データのスキャン・外部送信は別途明示的に開始する。 +合成試験: `go test -race ./internal/inspection ./internal/schutzaria ./internal/geduldh -count=3`。 diff --git a/docs/design/ja/implementation-backlog.md b/docs/design/ja/implementation-backlog.md index 0a03863..23e4b75 100644 --- a/docs/design/ja/implementation-backlog.md +++ b/docs/design/ja/implementation-backlog.md @@ -42,6 +42,13 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性 ## 次の実施順 +2026-11-30追記:利用者合意により[ファイル検査レイヤ](file-inspection.md)のSCAN-01/02を先行実装。 +公開範囲は既存の上位Path継承を維持し、検査を追加の配信条件とする。 +DB非依存のポリシー評価と無効開始のプラグイン実行基盤のみ。SCAN-03(3DB保存・queue)、 +SCAN-04(全配信/解析経路)、SCAN-05/06(設定・実検査)を残件とし、未接続の必須モードは公開しない。 +並行するpages-cliとの新規作成PUT契約は維持。検査待ちと保存失敗を混同しない。 +利用者合意により検査レイヤはこの骨子で一旦区切り、SCAN-03以降への接続は保留する。 + 2026-11-08、利用者指定により、大きな機能を提供するサブプロジェクトを以下の順で進める。 前案の小規模な回復・基盤改善を先に一巡する順序は、この順序へ置き換える。 diff --git a/docs/design/ja/operations.md b/docs/design/ja/operations.md index a1c3856..674c998 100644 --- a/docs/design/ja/operations.md +++ b/docs/design/ja/operations.md @@ -33,6 +33,10 @@ WebDAV/SSHFSの可変ファイルとimmutable CASは別です。最初はread-on MWDB/Karton等の接続はpending/clean/suspicious/malicious/error/expiredの状態と、engine・版・hash・時刻・由来を持つ非同期処理を案とします。監査必須の範囲ではcleanがない間のviewer/download/adapterを閉じます。scannerへ機密本文を送る操作には別の送信方針が必要です。 +2026-11-30:[ファイル検査と配信制御](file-inspection.md)へ詳細化。Path継承と追加判定、 +プラグイン契約・制限付き実行器を実装。DB・queue・配信ゲート・実エンジンは未接続で、 +現行アップロードを自動検査する状態ではありません。 + ## DRとHAの順序 次段階の詳細設計DR-D1は [役割・再参加](dr-authority-and-rejoin.md)、 diff --git a/internal/inspection/policy.go b/internal/inspection/policy.go new file mode 100644 index 0000000..24fe688 --- /dev/null +++ b/internal/inspection/policy.go @@ -0,0 +1,295 @@ +// Package inspection implements file inspection contracts, not authorization +// or a malware scanner. No HTTP route, worker or external service is enabled +// by importing it. Callers must load complete, trusted policy snapshots. +package inspection + +import ( + "encoding/hex" + "errors" + "path" + "sort" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/google/uuid" +) + +var ErrPolicy = errors.New("invalid inspection policy") + +type Mode string + +const ( + Inherit Mode = "inherit" + Disabled Mode = "disabled" + Monitor Mode = "monitor" + Required Mode = "required" +) + +type State string + +const ( + Pending State = "pending" + Clean State = "clean" + Suspicious State = "suspicious" + Malicious State = "malicious" + Error State = "error" + Expired State = "expired" +) + +// Engine identifies both the executable and its signature/model definitions. +// Definitions must change when the engine's detection data changes. +type Engine struct { + ID string `json:"id"` + Version string `json:"version"` + Definitions string `json:"definitions"` +} + +func (e Engine) valid() bool { + return label(e.ID) && label(e.Version) && label(e.Definitions) +} +func label(s string) bool { + return s != "" && len(s) <= 128 && utf8.ValidString(s) && strings.TrimSpace(s) == s && strings.IndexFunc(s, unicode.IsControl) < 0 +} +func validUUID(s string) bool { + id, err := uuid.Parse(s) + return err == nil && id.String() == s && id != uuid.Nil +} +func validHash(s string) bool { + if len(s) != 64 || strings.ToLower(s) != s { + return false + } + _, err := hex.DecodeString(s) + return err == nil +} + +// Paths are already-decoded semantic Paths. Literal '%' and '+' are valid; +// never percent-decode a second time. Scope tests use segment boundaries. +func canonical(p string) bool { + return utf8.ValidString(p) && len(p) <= 4096 && strings.HasPrefix(p, "/") && path.Clean(p) == p && !strings.Contains(p, "\\") && strings.IndexFunc(p, unicode.IsControl) < 0 +} +func under(p, root string) bool { + return root == "/" || p == root || strings.HasPrefix(p, root+"/") +} + +type Rule struct { + Path string `json:"path"` + Mode Mode `json:"mode"` + Engines []Engine `json:"engines"` +} + +// Policy is a Domain-local snapshot. Generation must change on policy OR +// relevant topology/engine-enable changes. Rules come from authorized locality settings, +// not from uploader-controlled data. External consent is Domain-admin owned. +type Policy struct { + Domain string `json:"domain"` + Generation string `json:"generation"` + AllowExternal bool `json:"allow_external"` + Rules []Rule `json:"rules"` +} + +type Effective struct { + Domain string + Generation string + Mode Mode + AllowExternal bool + Engines []Engine +} + +func rank(m Mode) int { + switch m { + case Inherit, Disabled: + return 0 + case Monitor: + return 1 + case Required: + return 2 + default: + return -1 + } +} + +// Resolve never weakens an ancestor's mode or drops ancestor engines. A lower +// rule can add engines but cannot replace an inherited engine's version. +func (p Policy) Resolve(logicalPath string) (Effective, error) { + out := Effective{Domain: p.Domain, Generation: p.Generation, Mode: Disabled, AllowExternal: p.AllowExternal} + if !validUUID(p.Domain) || !validUUID(p.Generation) || !canonical(logicalPath) || len(p.Rules) > 128 { + return Effective{}, ErrPolicy + } + rules := append([]Rule(nil), p.Rules...) + sort.Slice(rules, func(i, j int) bool { return len(rules[i].Path) < len(rules[j].Path) }) + seen := map[string]bool{} + engines := map[string]Engine{} + for _, r := range rules { + if !canonical(r.Path) || seen[r.Path] || rank(r.Mode) < 0 || len(r.Engines) > 16 || ((r.Mode == Inherit || r.Mode == Disabled) && len(r.Engines) > 0) { + return Effective{}, ErrPolicy + } + seen[r.Path] = true + local := map[string]bool{} + for _, e := range r.Engines { + if !e.valid() || local[e.ID] { + return Effective{}, ErrPolicy + } + local[e.ID] = true + } + if !under(logicalPath, r.Path) { + continue + } + if rank(r.Mode) > rank(out.Mode) { + out.Mode = r.Mode + } + for _, e := range r.Engines { + if old, ok := engines[e.ID]; ok && old != e { + return Effective{}, ErrPolicy + } + engines[e.ID] = e + } + } + if len(engines) > 16 || (out.Mode != Disabled && len(engines) == 0) { + return Effective{}, ErrPolicy + } + for _, e := range engines { + out.Engines = append(out.Engines, e) + } + sort.Slice(out.Engines, func(i, j int) bool { return out.Engines[i].ID < out.Engines[j].ID }) + return out, nil +} + +// Key is the minimum cache/job identity. Never reuse a result across Domains, +// policy generations, content hashes, or engine/definition versions. +type Key struct { + Domain string `json:"domain"` + Generation string `json:"generation"` + Hash string `json:"sha256"` + Engine Engine `json:"engine"` +} + +func (k Key) valid() bool { + return validUUID(k.Domain) && validUUID(k.Generation) && validHash(k.Hash) && k.Engine.valid() +} + +// Report is trusted worker output, never supplied by an uploader. Publication +// must additionally CAS the job lease/generation when persisting this record. +type Report struct { + Key Key + State State + Finished time.Time + Expires time.Time +} +type Decision struct { + Allowed bool + State State + Reason string +} + +// Decide is an ADDITIONAL gate. accessAllowed is the application's existing +// ACL/publication decision; an inspection result can never grant that access. +// active is a fresh snapshot of enabled engines, not the queued job's snapshot. +func Decide(accessAllowed bool, p Effective, hash string, reports []Report, active []Engine, now time.Time) Decision { + if !accessAllowed { + return Decision{Reason: "access_denied"} + } + if !validUUID(p.Domain) || !validUUID(p.Generation) || !validHash(hash) || now.IsZero() || rank(p.Mode) < 0 || p.Mode == Inherit || len(p.Engines) > 16 || len(reports) > 64 || len(active) > 64 { + return Decision{State: Error, Reason: "invalid_policy"} + } + if p.Mode == Disabled { + return Decision{Allowed: true, Reason: "inspection_disabled"} + } + if len(p.Engines) == 0 { + return Decision{State: Error, Reason: "missing_engine"} + } + status, reason := Clean, "inspection_clean" + seen := map[string]bool{} + for _, e := range p.Engines { + if !e.valid() || seen[e.ID] { + return Decision{State: Error, Reason: "invalid_policy"} + } + seen[e.ID] = true + key := Key{p.Domain, p.Generation, hash, e} + state, why := Pending, "inspection_pending" + enabled := false + for _, a := range active { + if a == e { + enabled = true + } + } + var matches []Report + for _, r := range reports { + if r.Key == key { + matches = append(matches, r) + } + } + if !enabled { + state, why = Error, "engine_unavailable" + } else if len(matches) > 1 { + state, why = Error, "ambiguous_result" + } else if len(matches) == 1 { + r := matches[0] + switch r.State { + case Pending, Error, Expired: + state, why = r.State, "inspection_"+string(r.State) + case Clean, Suspicious, Malicious: + if r.Finished.IsZero() || r.Finished.After(now) || !r.Expires.After(r.Finished) { + state, why = Error, "invalid_result" + } else if !r.Expires.After(now) { + state, why = Expired, "inspection_expired" + } else { + state, why = r.State, "inspection_"+string(r.State) + } + default: + state, why = Error, "invalid_result" + } + } + if severity(state) > severity(status) { + status, reason = state, why + } + } + return Decision{Allowed: p.Mode == Monitor || status == Clean, State: status, Reason: reason} +} +func severity(s State) int { + switch s { + case Clean: + return 0 + case Pending: + return 1 + case Expired: + return 2 + case Error: + return 3 + case Suspicious: + return 4 + case Malicious: + return 5 + } + return 3 +} + +// DecidePaths evaluates all supplied current bindings, not just the requested +// alias. The caller must load a complete Domain-local binding snapshot, including +// source/dependency policy when appropriate. An empty/truncated set cannot stand +// for an unrestricted UUID/Asset. Cross-Domain bindings need a separate decision +// per Domain. This method performs no lookup and is not a routing middleware. +func DecidePaths(accessAllowed bool, p Policy, bindings []string, hash string, reports []Report, active []Engine, now time.Time) Decision { + if !accessAllowed { + return Decision{Reason: "access_denied"} + } + if len(bindings) == 0 || len(bindings) > 128 { + return Decision{State: Error, Reason: "incomplete_bindings"} + } + decision := Decision{Allowed: true, Reason: "inspection_disabled"} + for _, binding := range bindings { + effective, err := p.Resolve(binding) + if err != nil { + return Decision{State: Error, Reason: "invalid_policy"} + } + next := Decide(true, effective, hash, reports, active, now) + if !next.Allowed { + return next + } + if next.State != "" && (decision.State == "" || severity(next.State) > severity(decision.State)) { + decision = next + } + } + return decision +} diff --git a/internal/inspection/policy_test.go b/internal/inspection/policy_test.go new file mode 100644 index 0000000..a7f785f --- /dev/null +++ b/internal/inspection/policy_test.go @@ -0,0 +1,135 @@ +package inspection + +import ( + "strings" + "testing" + "time" +) + +const domain = "00000000-0000-4000-8000-000000000001" +const generation = "00000000-0000-4000-8000-000000000002" + +var engine = Engine{"test.local", "1", "definitions-1"} + +func TestPolicyInheritance(t *testing.T) { + p := Policy{Domain: domain, Generation: generation, Rules: []Rule{ + {Path: "/private", Mode: Required, Engines: []Engine{engine}}, + {Path: "/private/child", Mode: Disabled}, + {Path: "/private/child/deep", Mode: Inherit}, + }} + for _, path := range []string{"/private", "/private/child", "/private/child/deep/page"} { + e, err := p.Resolve(path) + if err != nil || e.Mode != Required || len(e.Engines) != 1 || e.Engines[0] != engine { + t.Fatalf("inherit %q: %+v %v", path, e, err) + } + } + for _, path := range []string{"/", "/private2/page", "/private_%/page"} { + e, err := p.Resolve(path) + if err != nil || e.Mode != Disabled { + t.Fatalf("scope %q: %+v %v", path, e, err) + } + } + p.Rules = append(p.Rules, Rule{Path: "/private/child/deep/page", Mode: Required, Engines: []Engine{{"test.second", "1", "defs"}}}) + e, err := p.Resolve("/private/child/deep/page") + if err != nil || len(e.Engines) != 2 { + t.Fatal("child dropped ancestor engine", e, err) + } + p.Rules[3].Engines = []Engine{{engine.ID, "2", engine.Definitions}} + if _, err := p.Resolve("/private/child/deep/page"); err == nil { + t.Fatal("child replaced required engine") + } +} + +func TestPolicyValidationAndExactPaths(t *testing.T) { + for _, path := range []string{"/日本語/100%+完了", "/a/%2e%2e/b", "/a_b/page"} { + p := Policy{Domain: domain, Generation: generation, Rules: []Rule{{Path: path, Mode: Required, Engines: []Engine{engine}}}} + if e, err := p.Resolve(path + "/child"); err != nil || e.Mode != Required { + t.Fatal(path, e, err) + } + } + for _, path := range []string{"", "relative", "/a/../b", "/a//b", "/a/", "/a\\b", "/a\x00b", "/\xff", "/" + strings.Repeat("a", 4096)} { + if _, err := (Policy{Domain: domain, Generation: generation}).Resolve(path); err == nil { + t.Fatalf("invalid path %q", path) + } + } + for _, rules := range [][]Rule{ + {{Path: "/", Mode: "unknown"}}, + {{Path: "/", Mode: Required}}, + {{Path: "/", Mode: Inherit, Engines: []Engine{engine}}}, + {{Path: "/", Mode: Monitor, Engines: []Engine{engine, engine}}}, + {{Path: "/", Mode: Disabled}, {Path: "/", Mode: Disabled}}, + } { + if _, err := (Policy{Domain: domain, Generation: generation, Rules: rules}).Resolve("/p"); err == nil { + t.Fatal("invalid policy accepted", rules) + } + } + if _, err := (Policy{}).Resolve("/"); err == nil { + t.Fatal("missing snapshot accepted") + } +} + +func TestDecisionCannotGrantAccess(t *testing.T) { + p := Effective{Domain: domain, Generation: generation, Mode: Required, Engines: []Engine{engine}} + hash := strings.Repeat("a", 64) + now := time.Unix(1000, 0) + good := Report{Key: Key{domain, generation, hash, engine}, State: Clean, Finished: now.Add(-time.Second), Expires: now.Add(time.Hour)} + for _, mode := range []Mode{Disabled, Monitor, Required} { + p.Mode = mode + if d := Decide(false, p, hash, []Report{good}, []Engine{engine}, now); d.Allowed || d.Reason != "access_denied" { + t.Fatal(d) + } + } + p.Mode = Required + if d := Decide(true, p, hash, []Report{good}, []Engine{engine}, now); !d.Allowed || d.State != Clean { + t.Fatal(d) + } + for _, state := range []State{Pending, Suspicious, Malicious, Error, Expired, "unknown"} { + r := good + r.State = state + if d := Decide(true, p, hash, []Report{r}, []Engine{engine}, now); d.Allowed { + t.Fatal(state, d) + } + } + for _, mutate := range []func(*Report){ + func(r *Report) { r.Key.Domain = generation }, + func(r *Report) { r.Key.Generation = domain }, + func(r *Report) { r.Key.Hash = strings.Repeat("b", 64) }, + func(r *Report) { r.Key.Engine.Definitions = "new" }, + func(r *Report) { r.Expires = now }, + func(r *Report) { r.Finished = now.Add(time.Hour) }, + } { + r := good + mutate(&r) + if d := Decide(true, p, hash, []Report{r}, []Engine{engine}, now); d.Allowed { + t.Fatal("stale/wrong evidence accepted", d) + } + } + if d := Decide(true, p, hash, []Report{good}, nil, now); d.Allowed || d.Reason != "engine_unavailable" { + t.Fatal(d) + } + if d := Decide(true, p, hash, []Report{good, good}, []Engine{engine}, now); d.Allowed { + t.Fatal("ambiguous evidence", d) + } + p.Mode = Monitor + bad := good + bad.State = Malicious + if d := Decide(true, p, hash, []Report{bad}, []Engine{engine}, now); !d.Allowed || d.State != Malicious { + t.Fatal("monitor changed access or hid verdict", d) + } +} + +func TestEveryRequiredEngineMustPass(t *testing.T) { + second := Engine{"test.second", "1", "defs"} + now := time.Now() + hash := strings.Repeat("b", 64) + p := Effective{Domain: domain, Generation: generation, Mode: Required, Engines: []Engine{engine, second}} + r := Report{Key: Key{domain, generation, hash, engine}, State: Clean, Finished: now.Add(-time.Second), Expires: now.Add(time.Minute)} + if d := Decide(true, p, hash, []Report{r}, []Engine{engine, second}, now); d.Allowed { + t.Fatal(d) + } + r2 := r + r2.Key.Engine = second + if d := Decide(true, p, hash, []Report{r, r2}, []Engine{engine, second}, now); !d.Allowed { + t.Fatal(d) + } +} diff --git a/internal/inspection/runner.go b/internal/inspection/runner.go new file mode 100644 index 0000000..caa8c69 --- /dev/null +++ b/internal/inspection/runner.go @@ -0,0 +1,268 @@ +package inspection + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "sort" + "sync" + "sync/atomic" + "time" + + "pageswiki/internal/geduldh" +) + +var ( + ErrUnavailable = errors.New("inspection engine unavailable or changed") + ErrExternal = errors.New("external inspection is not permitted") + ErrBusy = errors.New("inspection capacity exhausted") + ErrInput = errors.New("inspection input invalid or too large") + ErrEngine = errors.New("inspection engine failed") +) + +type Manifest struct { + Engine Engine + External bool +} + +// Scanner implementations are trusted, registered by application code. A +// manifest is not permission to run a command, import code or connect a URL. +// Inspect must honor ctx; in-process plugins are NOT a process sandbox. +// The reader is valid only during Inspect and contains no Path or credential. +type Scanner interface { + Inspect(context.Context, io.Reader) (State, error) +} +type registration struct { + manifest Manifest + scanner Scanner + enabled bool + epoch uint64 +} +type Registry struct { + mu sync.RWMutex + entries map[string]registration +} + +func NewRegistry() *Registry { return &Registry{entries: map[string]registration{}} } + +// Register always starts disabled. Changing a definition version requires a +// new registry registration/application lifecycle, never an in-place mutation. +func (r *Registry) Register(m Manifest, scanner Scanner) error { + if !m.Engine.valid() || scanner == nil { + return ErrPolicy + } + r.mu.Lock() + defer r.mu.Unlock() + if _, ok := r.entries[m.Engine.ID]; ok { + return ErrPolicy + } + if len(r.entries) >= 64 { + return ErrPolicy + } + if r.entries == nil { + r.entries = map[string]registration{} + } + r.entries[m.Engine.ID] = registration{manifest: m, scanner: scanner} + return nil +} +func (r *Registry) SetEnabled(id string, enabled bool) error { + r.mu.Lock() + defer r.mu.Unlock() + e, ok := r.entries[id] + if !ok { + return ErrUnavailable + } + if e.enabled != enabled { + e.epoch++ + e.enabled = enabled + r.entries[id] = e + } + return nil +} +func (r *Registry) Active() []Engine { + r.mu.RLock() + defer r.mu.RUnlock() + var out []Engine + for _, e := range r.entries { + if e.enabled { + out = append(out, e.manifest.Engine) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) + return out +} +func (r *Registry) acquire(engine Engine) (registration, error) { + r.mu.RLock() + defer r.mu.RUnlock() + e, ok := r.entries[engine.ID] + if !ok || !e.enabled || e.manifest.Engine != engine { + return registration{}, ErrUnavailable + } + return e, nil +} + +type Limits struct { + Workers int + MaxBytes int64 + Timeout time.Duration + ResultTTL time.Duration +} +type Metrics struct { + Running int64 + Completed uint64 + Failed uint64 + BytesVerified uint64 + DurationNS uint64 +} +type Runner struct { + registry *Registry + limits Limits + slots chan struct{} + running atomic.Int64 + completed atomic.Uint64 + failed atomic.Uint64 + bytes atomic.Uint64 + duration atomic.Uint64 +} + +func NewRunner(registry *Registry, limits Limits) (*Runner, error) { + if registry == nil || limits.Workers < 1 || limits.Workers > 4 || limits.MaxBytes < 1 || limits.MaxBytes > 256<<20 || limits.Timeout <= 0 || limits.Timeout > time.Minute || limits.ResultTTL <= 0 || limits.ResultTTL > 24*time.Hour { + return nil, ErrPolicy + } + return &Runner{registry: registry, limits: limits, slots: make(chan struct{}, limits.Workers)}, nil +} +func (r *Runner) Metrics() Metrics { + return Metrics{r.running.Load(), r.completed.Load(), r.failed.Load(), r.bytes.Load(), r.duration.Load()} +} + +// Recheck reloads current job ownership, policy generation, topology and +// external-transmission consent. It runs before opening bytes and again before +// returning a report. The persistence layer must still CAS the lease/generation +// on commit; this callback is not an atomic database transaction. +type Recheck func(context.Context, Key) error + +// Run is for a background worker, never a synchronous HTTP request. Capacity +// exhaustion returns immediately so the existing scheduler can defer the job. +// Documents must satisfy Geduldh's immutable Store contract. Verify before +// handing bytes to a scanner (especially an external service). +func (r *Runner) Run(ctx context.Context, documents geduldh.Store, key Key, allowExternal bool, recheck Recheck) (report Report, err error) { + if !key.valid() || documents == nil || recheck == nil { + return Report{}, ErrInput + } + if err = ctx.Err(); err != nil { + return Report{}, err + } + entry, err := r.registry.acquire(key.Engine) + if err != nil { + return Report{}, err + } + if entry.manifest.External && !allowExternal { + return Report{}, ErrExternal + } + select { + case r.slots <- struct{}{}: + default: + return Report{}, ErrBusy + } + start := time.Now() + r.running.Add(1) + defer func() { + // Never leak a plugin panic or diagnostic (which may contain payloads). + if recover() != nil { + report = Report{} + err = ErrEngine + } + r.running.Add(-1) + <-r.slots + r.duration.Add(uint64(time.Since(start))) + if err != nil { + report = Report{} + r.failed.Add(1) + } else { + r.completed.Add(1) + } + }() + ctx, cancel := context.WithTimeout(ctx, r.limits.Timeout) + defer cancel() + check := func() error { + if err := ctx.Err(); err != nil { + return err + } + current, err := r.registry.acquire(key.Engine) + if err != nil || current.epoch != entry.epoch { + return ErrUnavailable + } + if recheck(ctx, key) != nil { + if err := ctx.Err(); err != nil { + return err + } + return ErrUnavailable + } + return nil + } + if err = check(); err != nil { + return Report{}, err + } + info, err := documents.Stat(ctx, key.Hash) + if ctx.Err() != nil { + return Report{}, ctx.Err() + } + if err != nil || info.Hash != key.Hash || info.Size < 0 || info.Size > r.limits.MaxBytes { + return Report{}, ErrInput + } + reader, err := documents.Open(ctx, key.Hash) + if err != nil { + if ctx.Err() != nil { + return Report{}, ctx.Err() + } + return Report{}, ErrInput + } + defer reader.Close() + hash := sha256.New() + n, err := io.Copy(hash, io.LimitReader(contextReader{ctx, reader}, info.Size+1)) + if err != nil { + if ctx.Err() != nil { + return Report{}, ctx.Err() + } + return Report{}, ErrInput + } + if n != info.Size || hex.EncodeToString(hash.Sum(nil)) != key.Hash { + return Report{}, ErrInput + } + r.bytes.Add(uint64(n)) + if _, err = reader.Seek(0, io.SeekStart); err != nil { + return Report{}, ErrInput + } + if err = check(); err != nil { + return Report{}, err + } + state, err := entry.scanner.Inspect(ctx, io.LimitReader(contextReader{ctx, reader}, info.Size)) + if ctx.Err() != nil { + return Report{}, ctx.Err() + } + if err != nil { + return Report{}, ErrEngine + } + if state != Clean && state != Suspicious && state != Malicious { + return Report{}, ErrEngine + } + if err = check(); err != nil { + return Report{}, err + } + now := time.Now() + return Report{Key: key, State: state, Finished: now, Expires: now.Add(r.limits.ResultTTL)}, nil +} + +type contextReader struct { + ctx context.Context + reader io.Reader +} + +func (r contextReader) Read(b []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + return r.reader.Read(b) +} diff --git a/internal/inspection/runner_test.go b/internal/inspection/runner_test.go new file mode 100644 index 0000000..8b1a449 --- /dev/null +++ b/internal/inspection/runner_test.go @@ -0,0 +1,233 @@ +package inspection + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "strings" + "sync/atomic" + "testing" + "time" + + "pageswiki/internal/geduldh" +) + +type scanFunc func(context.Context, io.Reader) (State, error) + +func (f scanFunc) Inspect(ctx context.Context, r io.Reader) (State, error) { return f(ctx, r) } + +type testReader struct{ *bytes.Reader } + +func (*testReader) Close() error { return nil } + +type testDocuments struct { + payload []byte + size int64 + opens atomic.Int64 +} + +func (d *testDocuments) Stat(_ context.Context, h string) (geduldh.Info, error) { + return geduldh.Info{Hash: h, Size: d.size}, nil +} +func (d *testDocuments) Open(context.Context, string) (geduldh.Reader, error) { + d.opens.Add(1) + return &testReader{bytes.NewReader(d.payload)}, nil +} +func (*testDocuments) Verify(context.Context, string) error { + panic("runner must verify the bytes itself") +} +func (*testDocuments) PutIfAbsent(context.Context, string, int64, io.Reader) error { + panic("runner must never modify documents") +} +func fixture(t *testing.T, external bool, fn scanFunc) (*Runner, *Registry, *testDocuments, Key) { + t.Helper() + reg := NewRegistry() + if err := reg.Register(Manifest{engine, external}, fn); err != nil { + t.Fatal(err) + } + r, err := NewRunner(reg, Limits{Workers: 1, MaxBytes: 1024, Timeout: time.Second, ResultTTL: time.Hour}) + if err != nil { + t.Fatal(err) + } + body := []byte("synthetic input, not a real user document") + sum := sha256.Sum256(body) + return r, reg, &testDocuments{payload: body, size: int64(len(body))}, Key{domain, generation, hex.EncodeToString(sum[:]), engine} +} +func current(context.Context, Key) error { return nil } + +func TestRunnerDisabledExternalAndHashGates(t *testing.T) { + var calls atomic.Int64 + r, reg, docs, key := fixture(t, true, func(ctx context.Context, reader io.Reader) (State, error) { + calls.Add(1) + _, err := io.Copy(io.Discard, reader) + return Clean, err + }) + if _, err := r.Run(context.Background(), docs, key, true, current); !errors.Is(err, ErrUnavailable) { + t.Fatal(err) + } + if err := reg.SetEnabled(engine.ID, true); err != nil { + t.Fatal(err) + } + if _, err := r.Run(context.Background(), docs, key, false, current); !errors.Is(err, ErrExternal) { + t.Fatal(err) + } + if docs.opens.Load() != 0 || calls.Load() != 0 { + t.Fatal("read before consent") + } + bad := key + bad.Hash = strings.Repeat("a", 64) + if _, err := r.Run(context.Background(), docs, bad, true, current); !errors.Is(err, ErrInput) { + t.Fatal(err) + } + if calls.Load() != 0 { + t.Fatal("corrupt content sent to plugin") + } + report, err := r.Run(context.Background(), docs, key, true, current) + if err != nil || report.State != Clean || report.Key != key || calls.Load() != 1 || !report.Expires.After(report.Finished) { + t.Fatal(report, err) + } + m := r.Metrics() + if m.Completed != 1 || m.Failed != 1 || m.Running != 0 || m.BytesVerified != uint64(docs.size) { + t.Fatal(m) + } +} + +func TestRunnerCapacityAndDisableDuringScan(t *testing.T) { + started, release := make(chan struct{}), make(chan struct{}) + r, reg, docs, key := fixture(t, false, func(ctx context.Context, reader io.Reader) (State, error) { + close(started) + <-release + return Clean, nil + }) + if err := reg.SetEnabled(engine.ID, true); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { _, err := r.Run(context.Background(), docs, key, false, current); done <- err }() + <-started + _, busy := r.Run(context.Background(), docs, key, false, current) + _ = reg.SetEnabled(engine.ID, false) + _ = reg.SetEnabled(engine.ID, true) // Even an immediate toggle invalidates this run. + close(release) + err := <-done + if !errors.Is(busy, ErrBusy) || !errors.Is(err, ErrUnavailable) { + t.Fatal(busy, err) + } + if m := r.Metrics(); m.Running != 0 || m.Completed != 0 || m.Failed != 1 { + t.Fatal(m) + } +} + +func TestRunnerBoundedFailureAndRecheck(t *testing.T) { + for _, kind := range []string{"panic", "error", "invalid", "timeout", "stale", "oversize", "wrong-size"} { + t.Run(kind, func(t *testing.T) { + var calls atomic.Int64 + r, reg, docs, key := fixture(t, false, func(ctx context.Context, _ io.Reader) (State, error) { + calls.Add(1) + switch kind { + case "panic": + panic("private document text") + case "error": + return Clean, errors.New("private text") + case "invalid": + return Pending, nil + case "timeout": + <-ctx.Done() + return Clean, nil + } + return Clean, nil + }) + _ = reg.SetEnabled(engine.ID, true) + if kind == "oversize" { + docs.size = 1025 + } + if kind == "wrong-size" { + docs.size-- + } + if kind == "timeout" { + r.limits.Timeout = 10 * time.Millisecond + } + checks := 0 + recheck := func(context.Context, Key) error { + checks++ + if kind == "stale" && checks == 3 { + return errors.New("private policy") + } + return nil + } + report, err := r.Run(context.Background(), docs, key, false, recheck) + if err == nil || strings.Contains(err.Error(), "private") || report != (Report{}) { + t.Fatal(report, err) + } + if (kind == "oversize" || kind == "wrong-size") && calls.Load() != 0 { + t.Fatal("invalid data reached plugin") + } + if kind == "timeout" && !errors.Is(err, context.DeadlineExceeded) { + t.Fatal(err) + } + if r.Metrics().Running != 0 { + t.Fatal("worker slot leaked") + } + }) + } +} + +func TestRunnerRequiresFreshSnapshot(t *testing.T) { + r, reg, docs, key := fixture(t, false, func(context.Context, io.Reader) (State, error) { t.Fatal("plugin called"); return Clean, nil }) + _ = reg.SetEnabled(engine.ID, true) + if _, err := r.Run(context.Background(), docs, key, false, nil); !errors.Is(err, ErrInput) { + t.Fatal(err) + } + if _, err := r.Run(context.Background(), docs, key, false, func(context.Context, Key) error { return ErrPolicy }); !errors.Is(err, ErrUnavailable) { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := r.Run(ctx, docs, key, false, current); !errors.Is(err, context.Canceled) { + t.Fatal(err) + } + if docs.opens.Load() != 0 { + t.Fatal("stale job opened payload") + } +} + +func TestInspectionLifecycleDoesNotPublishOrBypassAliases(t *testing.T) { + r, registry, docs, key := fixture(t, false, func(_ context.Context, reader io.Reader) (State, error) { + _, err := io.Copy(io.Discard, reader) + return Clean, err + }) + p := Policy{Domain: domain, Generation: generation, Rules: []Rule{{Path: "/private", Mode: Required, Engines: []Engine{engine}}}} + bindings := []string{"/open/alias", "/private/source"} + gate := func(acl bool, reports []Report) Decision { + return DecidePaths(acl, p, bindings, key.Hash, reports, registry.Active(), time.Now()) + } + _ = registry.SetEnabled(engine.ID, true) + if d := gate(true, nil); d.Allowed || d.State != Pending { + t.Fatal("unscanned alias allowed", d) + } + report, err := r.Run(context.Background(), docs, key, false, current) + if err != nil { + t.Fatal(err) + } + if d := gate(true, []Report{report}); !d.Allowed { + t.Fatal(d) + } + if d := gate(false, []Report{report}); d.Allowed { + t.Fatal("scan published private file", d) + } + _ = registry.SetEnabled(engine.ID, false) + if d := gate(true, []Report{report}); d.Allowed { + t.Fatal("disabled plugin bypass", d) + } + _ = registry.SetEnabled(engine.ID, true) + p.Generation = "00000000-0000-4000-8000-000000000003" + if d := gate(true, []Report{report}); d.Allowed { + t.Fatal("stale policy result", d) + } + if d := DecidePaths(true, p, nil, key.Hash, nil, registry.Active(), time.Now()); d.Allowed { + t.Fatal("missing bindings accepted", d) + } +}