- libraryagent:0700 目录内 0600 unix socket + SO_PEERCRED 同 uid, 固定 binary/归档/日志/项目/写入者声明,请求只能选范围与作业号 - API:POST/GET /api/v1/library/captures(入队 library.capture + 读队列状态) - worker:library.capture handler 走 socket;启动先 recover;不挂 Docker socket、 不持有来源凭据 - web:整库版本页显示真实作业状态并可发起封存(未接线/无权限给出原因) - scripts/library-agent-install.sh:构建、安装 systemd user 服务并读回权限
This commit is contained in:
@@ -0,0 +1,224 @@
|
||||
// Package libraryagent is the least-privilege execution boundary for
|
||||
// whole-library capture on the target host.
|
||||
//
|
||||
// Why it exists: capturing a library has to stop the source writer for a few
|
||||
// seconds and read source credentials. Handing the governance containers the
|
||||
// Docker socket (a full write API) or the source credentials would be a much
|
||||
// larger privilege than that operation needs. Instead this agent runs as the
|
||||
// ordinary operator account on the host, listens on one unix socket which only
|
||||
// that account can connect to, and executes one fixed command with a fixed
|
||||
// writer declaration. A caller can choose the scope and (optionally) a job id —
|
||||
// nothing else.
|
||||
package libraryagent
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config is fixed at start-up by the operator (systemd unit / CLI flags). It is
|
||||
// never taken from a request.
|
||||
type Config struct {
|
||||
Socket string
|
||||
Binary string
|
||||
ArchiveRoot string
|
||||
JournalRoot string
|
||||
// Writer declaration passed to the binary, exactly as reviewed in
|
||||
// scripts/library-capture.sh. Clients cannot influence it.
|
||||
SourceApp string
|
||||
SourcePG string
|
||||
SourceES string
|
||||
GovernancePG string
|
||||
Project string
|
||||
Writers string
|
||||
NonWriters string
|
||||
MaxDuration time.Duration
|
||||
// Run executes the binary; replaced in tests.
|
||||
Run func(ctx context.Context, name string, args ...string) ([]byte, error)
|
||||
}
|
||||
|
||||
type request struct {
|
||||
Action string `json:"action"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
Job string `json:"job,omitempty"`
|
||||
}
|
||||
|
||||
type response struct {
|
||||
OK bool `json:"ok"`
|
||||
Action string `json:"action"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
Job string `json:"job,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Payload json.RawMessage `json:"payload,omitempty"`
|
||||
}
|
||||
|
||||
var jobPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
|
||||
|
||||
// Agent serves capture requests. Only one operation runs at a time: a library
|
||||
// capture owns the writer group, so overlapping requests would race the window.
|
||||
type Agent struct {
|
||||
config Config
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func New(config Config) (*Agent, error) {
|
||||
if !filepath.IsAbs(config.Socket) || !filepath.IsAbs(config.ArchiveRoot) || !filepath.IsAbs(config.JournalRoot) {
|
||||
return nil, errors.New("library agent paths must be absolute")
|
||||
}
|
||||
if config.Binary == "" || config.Project == "" || config.Writers == "" || !strings.Contains(config.NonWriters, "=") {
|
||||
return nil, errors.New("library agent needs a binary, project, writers and a non-writer declaration")
|
||||
}
|
||||
if config.MaxDuration <= 0 || config.MaxDuration > 30*time.Minute {
|
||||
return nil, errors.New("library agent duration bound is invalid")
|
||||
}
|
||||
return &Agent{config: config}, nil
|
||||
}
|
||||
|
||||
// Serve listens until ctx is cancelled. The socket is created 0600 inside a
|
||||
// 0700 directory and removed on shutdown.
|
||||
func (a *Agent) Serve(ctx context.Context) error {
|
||||
if err := os.MkdirAll(filepath.Dir(a.config.Socket), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(filepath.Dir(a.config.Socket), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
_ = os.Remove(a.config.Socket)
|
||||
listener, err := net.Listen("unix", a.config.Socket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
listener.Close()
|
||||
_ = os.Remove(a.config.Socket)
|
||||
}()
|
||||
if err := os.Chmod(a.config.Socket, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
_ = listener.Close()
|
||||
}()
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
go a.handle(ctx, conn)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Agent) handle(ctx context.Context, conn net.Conn) {
|
||||
defer conn.Close()
|
||||
if err := peerAllowed(conn); err != nil {
|
||||
_ = json.NewEncoder(conn).Encode(response{OK: false, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
_ = conn.SetDeadline(time.Now().Add(a.config.MaxDuration + 30*time.Second))
|
||||
decoder := json.NewDecoder(bufio.NewReader(conn))
|
||||
var req request
|
||||
if err := decoder.Decode(&req); err != nil {
|
||||
_ = json.NewEncoder(conn).Encode(response{OK: false, Error: "invalid request"})
|
||||
return
|
||||
}
|
||||
result := a.execute(ctx, req)
|
||||
_ = json.NewEncoder(conn).Encode(result)
|
||||
}
|
||||
|
||||
// execute serialises operations and maps a request onto the one fixed command.
|
||||
func (a *Agent) execute(ctx context.Context, req request) response {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
out := response{Action: req.Action, Scope: req.Scope, Job: req.Job}
|
||||
var args []string
|
||||
switch req.Action {
|
||||
case "status":
|
||||
args = []string{"status"}
|
||||
case "recover":
|
||||
args = []string{"recover"}
|
||||
case "capture":
|
||||
if req.Scope != "internal" && req.Scope != "external" {
|
||||
out.Error = "scope must be internal or external"
|
||||
return out
|
||||
}
|
||||
if req.Job != "" && !jobPattern.MatchString(req.Job) {
|
||||
out.Error = "invalid job id"
|
||||
return out
|
||||
}
|
||||
args = []string{"capture", "-scope", req.Scope}
|
||||
if req.Job != "" {
|
||||
args = append(args, "-job", req.Job)
|
||||
}
|
||||
default:
|
||||
out.Error = "unsupported action"
|
||||
return out
|
||||
}
|
||||
args = append(args, a.config.declaration()...)
|
||||
bounded, cancel := context.WithTimeout(ctx, a.config.MaxDuration)
|
||||
defer cancel()
|
||||
payload, err := a.config.run(bounded, a.config.Binary, args...)
|
||||
if err != nil {
|
||||
out.Error = "operation failed"
|
||||
if message := strings.TrimSpace(string(payload)); message != "" && len(message) <= 2000 {
|
||||
out.Error = message
|
||||
}
|
||||
return out
|
||||
}
|
||||
out.OK = true
|
||||
if json.Valid(payload) {
|
||||
out.Payload = json.RawMessage(payload)
|
||||
} else {
|
||||
out.Payload = json.RawMessage(`{}`)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// declaration pins every path and the writer group so a request cannot redirect
|
||||
// the operation to another stack, archive or journal.
|
||||
func (c Config) declaration() []string {
|
||||
return []string{
|
||||
"-source-app", c.SourceApp,
|
||||
"-source-pg", c.SourcePG,
|
||||
"-source-es", c.SourceES,
|
||||
"-governance-pg", c.GovernancePG,
|
||||
"-project", c.Project,
|
||||
"-writers", c.Writers,
|
||||
"-non-writers", c.NonWriters,
|
||||
"-archive", c.ArchiveRoot,
|
||||
"-journal", c.JournalRoot,
|
||||
}
|
||||
}
|
||||
|
||||
func (c Config) run(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
if c.Run != nil {
|
||||
return c.Run(ctx, name, args...)
|
||||
}
|
||||
command := exec.CommandContext(ctx, name, args...)
|
||||
command.Env = append(os.Environ(), "LIBRARYCTL_AGENT=1")
|
||||
return command.CombinedOutput()
|
||||
}
|
||||
|
||||
// Describe returns a redacted view for logs and health checks.
|
||||
func (a *Agent) Describe() map[string]any {
|
||||
return map[string]any{
|
||||
"socket": a.config.Socket,
|
||||
"archive_root": a.config.ArchiveRoot,
|
||||
"journal_root": a.config.JournalRoot,
|
||||
"project": a.config.Project,
|
||||
"writers": a.config.Writers,
|
||||
"scope_choice": "request may select internal or external only",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package libraryagent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testAgent(t *testing.T) (*Agent, string, func() []string) {
|
||||
t.Helper()
|
||||
root, err := os.MkdirTemp(os.TempDir(), "kgag-")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(root) })
|
||||
if err = os.Chmod(root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var calls []string
|
||||
config := Config{
|
||||
Socket: filepath.Join(root, "agent.sock"),
|
||||
Binary: "/bin/echo",
|
||||
ArchiveRoot: filepath.Join(root, "library"),
|
||||
JournalRoot: filepath.Join(root, "freeze"),
|
||||
SourceApp: "WKNFull-app",
|
||||
SourcePG: "WKNFull-postgres",
|
||||
SourceES: "WKNFull-elasticsearch",
|
||||
GovernancePG: "knowledge-governance-p1-postgres-1",
|
||||
Project: "weknora071full",
|
||||
Writers: "app",
|
||||
NonWriters: "frontend=UI only; no knowledge writes",
|
||||
MaxDuration: time.Minute,
|
||||
Run: func(_ context.Context, name string, args ...string) ([]byte, error) {
|
||||
mu.Lock()
|
||||
calls = append(calls, name+" "+strings.Join(args, " "))
|
||||
mu.Unlock()
|
||||
return []byte(`{"snapshot_id":"abc","state":"succeeded"}`), nil
|
||||
},
|
||||
}
|
||||
agent, err := New(config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return agent, config.Socket, func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), calls...)
|
||||
}
|
||||
}
|
||||
|
||||
func roundTrip(t *testing.T, socket string, payload string) response {
|
||||
t.Helper()
|
||||
conn, err := net.Dial("unix", socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
if _, err = conn.Write([]byte(payload + "\n")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out response
|
||||
if err = json.NewDecoder(conn).Decode(&out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The socket is the whole security boundary: 0600 in a 0700 directory, and the
|
||||
// declaration (archive, journal, project, writers) comes from the agent's own
|
||||
// configuration, never from the request.
|
||||
func TestAgentSocketIsPrivateAndPinsTheDeclaration(t *testing.T) {
|
||||
agent, socket, calls := testAgent(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() { _ = agent.Serve(ctx) }()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
if _, err := os.Stat(socket); err == nil {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("agent socket never appeared")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
info, err := os.Stat(socket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0600 {
|
||||
t.Fatalf("socket mode %v", info.Mode().Perm())
|
||||
}
|
||||
dir, err := os.Stat(filepath.Dir(socket))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dir.Mode().Perm() != 0700 {
|
||||
t.Fatalf("socket directory mode %v", dir.Mode().Perm())
|
||||
}
|
||||
out := roundTrip(t, socket, `{"action":"capture","scope":"internal","job":"lib-internal-test"}`)
|
||||
if !out.OK || out.Job != "lib-internal-test" {
|
||||
t.Fatalf("capture rejected: %+v", out)
|
||||
}
|
||||
recorded := calls()
|
||||
if len(recorded) != 1 {
|
||||
t.Fatalf("expected one execution, got %v", recorded)
|
||||
}
|
||||
for _, want := range []string{"capture -scope internal -job lib-internal-test",
|
||||
"-archive " + filepath.Join(filepath.Dir(socket), "library"),
|
||||
"-journal " + filepath.Join(filepath.Dir(socket), "freeze"),
|
||||
"-project weknora071full", "-writers app"} {
|
||||
if !strings.Contains(recorded[0], want) {
|
||||
t.Fatalf("execution %q missing %q", recorded[0], want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(recorded[0], "..") {
|
||||
t.Fatal("unexpected path traversal in declaration")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentRejectsUnsupportedRequestsWithoutExecuting(t *testing.T) {
|
||||
agent, socket, calls := testAgent(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() { _ = agent.Serve(ctx) }()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
if _, err := os.Stat(socket); err == nil {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("agent socket never appeared")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
for _, payload := range []string{
|
||||
`{"action":"shell","command":"docker ps"}`,
|
||||
`{"action":"capture","scope":"production"}`,
|
||||
`{"action":"capture","scope":"internal","job":"bad job; rm -rf /"}`,
|
||||
`not json`,
|
||||
} {
|
||||
out := roundTrip(t, socket, payload)
|
||||
if out.OK || out.Error == "" {
|
||||
t.Fatalf("accepted %q: %+v", payload, out)
|
||||
}
|
||||
}
|
||||
if got := calls(); len(got) != 0 {
|
||||
t.Fatalf("rejected requests still executed: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRejectsIncompleteConfiguration(t *testing.T) {
|
||||
if _, err := New(Config{}); err == nil {
|
||||
t.Fatal("empty configuration accepted")
|
||||
}
|
||||
if _, err := New(Config{Socket: "relative.sock", ArchiveRoot: "/tmp/a", JournalRoot: "/tmp/j",
|
||||
Binary: "/bin/true", Project: "p", Writers: "app", NonWriters: "frontend=ui", MaxDuration: time.Minute}); err == nil {
|
||||
t.Fatal("relative socket path accepted")
|
||||
}
|
||||
if _, err := New(Config{Socket: "/tmp/a.sock", ArchiveRoot: "/tmp/a", JournalRoot: "/tmp/j",
|
||||
Binary: "/bin/true", Project: "p", Writers: "app", NonWriters: "frontend", MaxDuration: time.Minute}); err == nil {
|
||||
t.Fatal("non-writer declaration without a reason accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package libraryagent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ClientConfig is what a governance process needs: one socket path. It never
|
||||
// carries source credentials or Docker access — those stay with the agent.
|
||||
type ClientConfig struct {
|
||||
Socket string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Result is the agent's answer to one capture/status/recover request.
|
||||
type Result struct {
|
||||
OK bool
|
||||
Scope string
|
||||
Job string
|
||||
SnapshotID string
|
||||
Replay bool
|
||||
Error string
|
||||
Payload json.RawMessage
|
||||
}
|
||||
|
||||
// Capture asks the agent to seal one library scope. The job id makes the call
|
||||
// idempotent: repeating it returns the already sealed candidate.
|
||||
func Capture(ctx context.Context, config ClientConfig, scope, job string) (Result, error) {
|
||||
return call(ctx, config, map[string]string{"action": "capture", "scope": scope, "job": job})
|
||||
}
|
||||
|
||||
// Status probes the agent (source wiring, writer group, archive usage).
|
||||
func Status(ctx context.Context, config ClientConfig) (Result, error) {
|
||||
return call(ctx, config, map[string]string{"action": "status"})
|
||||
}
|
||||
|
||||
// Recover restores writers from an interrupted freeze journal.
|
||||
func Recover(ctx context.Context, config ClientConfig) (Result, error) {
|
||||
return call(ctx, config, map[string]string{"action": "recover"})
|
||||
}
|
||||
|
||||
func call(ctx context.Context, config ClientConfig, request map[string]string) (Result, error) {
|
||||
if config.Socket == "" {
|
||||
return Result{}, errors.New("library agent socket is not configured")
|
||||
}
|
||||
timeout := config.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 2 * time.Minute
|
||||
}
|
||||
bounded, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
var dialer net.Dialer
|
||||
conn, err := dialer.DialContext(bounded, "unix", config.Socket)
|
||||
if err != nil {
|
||||
return Result{}, errors.New("library agent is unreachable")
|
||||
}
|
||||
defer conn.Close()
|
||||
if deadline, ok := bounded.Deadline(); ok {
|
||||
_ = conn.SetDeadline(deadline)
|
||||
}
|
||||
if err = json.NewEncoder(conn).Encode(request); err != nil {
|
||||
return Result{}, errors.New("library agent request failed")
|
||||
}
|
||||
var response struct {
|
||||
OK bool `json:"ok"`
|
||||
Scope string `json:"scope"`
|
||||
Job string `json:"job"`
|
||||
Error string `json:"error"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
}
|
||||
if err = json.NewDecoder(conn).Decode(&response); err != nil {
|
||||
return Result{}, errors.New("library agent returned an invalid response")
|
||||
}
|
||||
result := Result{OK: response.OK, Scope: response.Scope, Job: response.Job, Error: response.Error, Payload: response.Payload}
|
||||
var payload struct {
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Replay bool `json:"replay"`
|
||||
}
|
||||
if len(response.Payload) > 0 && json.Unmarshal(response.Payload, &payload) == nil {
|
||||
result.SnapshotID, result.Replay = payload.SnapshotID, payload.Replay
|
||||
}
|
||||
if !result.OK {
|
||||
if result.Error == "" {
|
||||
result.Error = "library agent refused the request"
|
||||
}
|
||||
return result, errors.New(result.Error)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package libraryagent
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// peerAllowed enforces that the connecting process runs as the same uid as the
|
||||
// agent. File mode 0600 already limits connect() to that uid; the credential
|
||||
// check makes the boundary explicit and fails closed if the socket is ever
|
||||
// reached another way (bind mount into a container with a different uid).
|
||||
func peerAllowed(conn net.Conn) error {
|
||||
unixConn, ok := conn.(*net.UnixConn)
|
||||
if !ok {
|
||||
return errors.New("unsupported transport")
|
||||
}
|
||||
raw, err := unixConn.SyscallConn()
|
||||
if err != nil {
|
||||
return errors.New("peer credentials unavailable")
|
||||
}
|
||||
var credential *syscall.Ucred
|
||||
var controlErr error
|
||||
if err = raw.Control(func(fd uintptr) {
|
||||
credential, controlErr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
|
||||
}); err != nil {
|
||||
return errors.New("peer credentials unavailable")
|
||||
}
|
||||
if controlErr != nil || credential == nil {
|
||||
return errors.New("peer credentials unavailable")
|
||||
}
|
||||
if credential.Uid != uint32(os.Geteuid()) {
|
||||
return errors.New("peer uid is not allowed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build !linux
|
||||
|
||||
package libraryagent
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
// The capture host is Linux (Docker + unix socket); other platforms refuse
|
||||
// rather than guess at peer credentials.
|
||||
func peerAllowed(net.Conn) error {
|
||||
return errors.New("library agent requires Linux peer credentials")
|
||||
}
|
||||
Reference in New Issue
Block a user