Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ jobs:
ARTEX_PG_DSN: postgres://artex:testpass@localhost:5432/artextest_race?sslmode=disable

run: >-
go test -race -p 1 ./agent ./archivestore ./cmd/artex ./config ./db ./evidence ./guard
go test -race -p 1 ./accessaudit ./agent ./archivestore ./cmd/artex ./config ./db ./egress ./evidence ./guard
./intercept ./llmpool ./llmrec ./mcphttp ./notify ./server ./sidequestion
./traffic ./traffic/rewrite

Expand Down Expand Up @@ -220,6 +220,7 @@ jobs:
- run: npm run test:traffic-stream
- run: npm run test:sse
- run: npm run test:auth
- run: npm run test:access-audit
- run: npm run test:tamper-hooks
- run: npm run test:i18n
- run: npm run test:navigation
Expand Down
1 change: 1 addition & 0 deletions Dockerfile.egress-proxy
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:ea47ee45f1284d60f9
WORKDIR /src
COPY go.mod go.sum ./
COPY sandbox/ ./sandbox/
COPY accessaudit/ ./accessaudit/
COPY cmd/artex-egress-proxy/ ./cmd/artex-egress-proxy/
ARG TARGETOS=linux
ARG TARGETARCH
Expand Down
1 change: 1 addition & 0 deletions Dockerfile.runner
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:ea47ee45f1284d60f9
WORKDIR /src
COPY go.mod go.sum ./
COPY sandbox/ ./sandbox/
COPY accessaudit/ ./accessaudit/
COPY cmd/artex-runner/ ./cmd/artex-runner/
ARG ARTEX_VERSION=dev
ARG TARGETOS=linux
Expand Down
4 changes: 2 additions & 2 deletions Dockerfile.worker
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# ARTEX isolated per-task worker image (CONTRACT.md §4).
# Runs as uid/gid 10001, read-only rootfs, cap_drop ALL, no-new-privileges,
# mounted ONLY with /app/data/tasks/<id>:/workspace:rw and connected ONLY to
# the per-task internal network artex-task-<id>.
# mounted with its task workspace (rw) and public audit CA bundle (ro),
# and connected ONLY to the per-task internal network artex-task-<id>.
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:ea47ee45f1284d60f9cc09cb2c3bb4f508c256b640bd8bb30342ff13d1adcb52 AS wrap-build
WORKDIR /src
COPY go.mod go.sum ./
Expand Down
24 changes: 24 additions & 0 deletions accessaudit/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package accessaudit

import "context"

type storeKey struct{}
type identityKey struct{}

func WithStore(ctx context.Context, s *Store) context.Context {
return context.WithValue(ctx, storeKey{}, s)
}
func WithIdentity(ctx context.Context, f func(*Identity)) context.Context {
i := IdentityFrom(ctx)
f(&i)
return context.WithValue(ctx, identityKey{}, i)
}
func IdentityFrom(ctx context.Context) Identity {
i, _ := ctx.Value(identityKey{}).(Identity)
return i
}
func Record(ctx context.Context, e Event) {
s, _ := ctx.Value(storeKey{}).(*Store)
e.Identity = IdentityFrom(ctx)
s.Record(e)
}
76 changes: 76 additions & 0 deletions accessaudit/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package accessaudit

import (
"context"
"crypto/rand"
"net/http"
"net/http/httptrace"
"net/url"
"sync"
)

type transport struct {
base http.RoundTripper
tool string
}

// Transport goes INSIDE the governor so cache hits are not network evidence.
func Transport(base http.RoundTripper, tool string) http.RoundTripper {
if base == nil {
base = http.DefaultTransport
}
return transport{base, tool}
}
func (t transport) RoundTrip(req *http.Request) (*http.Response, error) {
id := rand.Text()
e := Event{Source: "native_http", Outcome: "transport_attempt", Tool: t.tool, Method: req.Method, URL: req.URL.String(), RequestID: id}
Record(req.Context(), e)
resp, err := t.base.RoundTrip(req)
e.Outcome = "transport_error"
if err == nil && resp != nil {
e.Outcome = "response_headers"
e.Status = resp.StatusCode
}
Record(req.Context(), e)
return resp, err
}

type fetchKey struct{}
type fetchTrace struct {
mu sync.Mutex
raw, id string
}

// TraceFetch observes Norma's real network callbacks without replacing its
// client, TLS, redirect or pinned-dial policy. Tool output is never evidence.
func TraceFetch(ctx context.Context, u *url.URL) context.Context {
st := &fetchTrace{raw: u.String(), id: rand.Text()}
ctx = context.WithValue(ctx, fetchKey{}, st)
emit := func(outcome string) {
st.mu.Lock()
e := Event{Source: "webfetch_trace", Outcome: outcome, Tool: "WebFetch", Method: "GET", URL: st.raw, RequestID: st.id}
st.mu.Unlock()
Record(ctx, e)
}
Record(ctx, Event{Source: "webfetch_trace", Outcome: "tool_attempt", Tool: "WebFetch", Method: "GET", URL: u.String()})
return httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
GetConn: func(string) { st.mu.Lock(); st.id = rand.Text(); st.mu.Unlock() },
WroteRequest: func(i httptrace.WroteRequestInfo) {
if i.Err != nil {
emit("write_error")
} else {
emit("request_written")
}
},
GotFirstResponseByte: func() { emit("response_started") },
})
}

// FetchRedirect runs only after the existing redirect gate allows the hop.
func FetchRedirect(req *http.Request) {
if st, ok := req.Context().Value(fetchKey{}).(*fetchTrace); ok {
st.mu.Lock()
st.raw = req.URL.String()
st.mu.Unlock()
}
}
50 changes: 50 additions & 0 deletions accessaudit/http_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package accessaudit

import (
"errors"
"net/http"
"net/http/httptest"
"testing"
)

type failTransport struct{}

func (failTransport) RoundTrip(*http.Request) (*http.Response, error) {
return nil, errors.New("secret URL must not be recorded")
}
func TestHTTPRedirectAttributionAndFailure(t *testing.T) {
s := testStore(t)
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/first" {
http.Redirect(w, r, "/last?token=hidden", 302)
return
}
w.WriteHeader(204)
}))
defer target.Close()
ctx := WithIdentity(WithStore(t.Context(), s), func(i *Identity) { i.TaskID = "7"; i.RunID = "run-1" })
req, _ := http.NewRequestWithContext(ctx, "GET", target.URL+"/first", nil)
resp, err := (&http.Client{Transport: Transport(nil, "test")}).Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
_, err = Transport(failTransport{}, "failed").RoundTrip(req)
if err == nil {
t.Fatal("error swallowed")
}
p, err := s.Search(t.Context(), window())
if err != nil || len(p.Events) != 6 {
t.Fatal(p, err)
}
counts := map[string]int{}
for _, e := range p.Events {
counts[e.Outcome]++
if e.TaskID != "7" || e.RunID != "run-1" {
t.Fatal(e)
}
}
if counts["transport_attempt"] != 3 || counts["response_headers"] != 2 || counts["transport_error"] != 1 {
t.Fatal(counts)
}
}
113 changes: 113 additions & 0 deletions accessaudit/import.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package accessaudit

import (
"context"
"database/sql"
"errors"
"time"
)

// ImportedEvent comes from a trusted producer, not the operator ingest API.
// Key identifies one observation across retries; Event.ID is producer-local.
type ImportedEvent struct {
Key string `json:"key"`
Event Event `json:"event"`
}

func (s *Store) initImports() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS access_imports (
key TEXT PRIMARY KEY, event_id INTEGER NOT NULL REFERENCES access_events(id) ON DELETE CASCADE);
CREATE INDEX IF NOT EXISTS access_import_event ON access_imports(event_id);
CREATE TABLE IF NOT EXISTS access_sources (
source TEXT PRIMARY KEY, cursor TEXT NOT NULL, gaps INTEGER NOT NULL DEFAULT 0);`)
return err
}

func (s *Store) ImportCursor(ctx context.Context, source string) (string, error) {
var cursor string
err := s.db.QueryRowContext(ctx, `SELECT cursor FROM access_sources WHERE source=?`, source).Scan(&cursor)
if errors.Is(err, sql.ErrNoRows) {
err = nil
}
return cursor, err
}

func (s *Store) ImportGaps(ctx context.Context) (int64, error) {
var gaps int64
err := s.db.QueryRowContext(ctx, `SELECT COALESCE(SUM(gaps),0) FROM access_sources`).Scan(&gaps)
return gaps, err
}

// Import commits observations and the producer cursor together. A failed import
// is retried without loss, and a repeated page cannot duplicate observations.
// It preserves the producer's observation time instead of inventing access at
// collection time. Only trusted runner collection calls this method.
func (s *Store) Import(ctx context.Context, source, previous, next string, records []ImportedEvent, gap bool) error {
if source == "" || len(source) > 128 || len(previous) > 256 || len(next) > 256 || len(records) > 200 {
return errors.New("invalid audit import")
}
s.mu.RLock()
defer s.mu.RUnlock()
if s.closed {
return errors.New("access audit closed")
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var cursor string
err = tx.QueryRowContext(ctx, `SELECT cursor FROM access_sources WHERE source=?`, source).Scan(&cursor)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
if cursor != previous {
return errors.New("audit cursor changed")
}
for _, record := range records {
e := record.Event
if record.Key == "" || len(record.Key) > 256 || e.ObservedAt.IsZero() || e.ObservedAt.After(time.Now().Add(time.Minute)) {
return errors.New("invalid audit producer record")
}
safe, host, err := RedactURL(e.URL)
if err != nil {
return err
}
for _, value := range []string{e.TaskID, e.Agent, e.RunID, e.ToolUseID, e.Source, e.Outcome, e.Tool, e.Method, e.RequestID} {
if len(value) > 256 {
return errors.New("oversized audit producer field")
}
}
key := source + ":" + record.Key
var exists int
err = tx.QueryRowContext(ctx, `SELECT 1 FROM access_imports WHERE key=?`, key).Scan(&exists)
if err == nil {
continue
}
if !errors.Is(err, sql.ErrNoRows) {
return err
}
res, err := tx.ExecContext(ctx, `INSERT INTO access_events(ts,task_id,conversation_id,agent,run_id,tool_use_id,source,outcome,tool,method,url,host,status,request_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, e.ObservedAt.UnixMilli(), e.TaskID, e.ConversationID, e.Agent, e.RunID, e.ToolUseID, e.Source, e.Outcome, e.Tool, e.Method, safe, host, e.Status, e.RequestID)
if err != nil {
return err
}
id, err := res.LastInsertId()
if err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `INSERT INTO access_imports(key,event_id) VALUES(?,?)`, key, id); err != nil {
return err
}
}
var gaps int
if gap {
gaps = 1
}
if _, err := tx.ExecContext(ctx, `INSERT INTO access_sources(source,cursor,gaps) VALUES(?,?,?) ON CONFLICT(source) DO UPDATE SET cursor=excluded.cursor,gaps=access_sources.gaps+excluded.gaps`, source, next, gaps); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `DELETE FROM access_events WHERE ts < ? OR id <= (SELECT COALESCE(MAX(id),0)-? FROM access_events)`, time.Now().Add(-RetentionDays*24*time.Hour).UnixMilli(), MaxEvents); err != nil {
return err
}
return tx.Commit()
}
59 changes: 59 additions & 0 deletions accessaudit/import_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package accessaudit

import (
"path/filepath"
"testing"
"time"
)

func TestImportAtomicRetryAndRestart(t *testing.T) {
path := filepath.Join(t.TempDir(), "audit.sqlite")
s, err := Open(path)
if err != nil {
t.Fatal(err)
}
at := time.Now().Add(-time.Minute).Truncate(time.Millisecond)
records := []ImportedEvent{{Key: "segment:1", Event: Event{URL: "https://example.com/path?secret=hidden", Source: "docker_egress", ObservedAt: at, Identity: Identity{TaskID: "a"}}}}
if err := s.Import(t.Context(), "docker:a", "", "one", records, false); err != nil {
t.Fatal(err)
}
if err := s.Import(t.Context(), "docker:a", "", "two", records, false); err == nil {
t.Fatal("stale cursor accepted")
}
// Same observation at a later cursor is idempotent.
if err := s.Import(t.Context(), "docker:a", "one", "two", records, true); err != nil {
t.Fatal(err)
}
bad := append(append([]ImportedEvent{}, records...), ImportedEvent{Key: "bad", Event: Event{URL: "invalid"}})
if err := s.Import(t.Context(), "docker:a", "two", "three", bad, false); err == nil {
t.Fatal("invalid page committed")
}
s.Close()
s, err = Open(path)
if err != nil {
t.Fatal(err)
}
defer s.Close()
cursor, err := s.ImportCursor(t.Context(), "docker:a")
if err != nil || cursor != "two" {
t.Fatal(cursor, err)
}
page, err := s.Search(t.Context(), window())
if err != nil || len(page.Events) != 1 {
t.Fatal(page, err)
}
if !page.Events[0].ObservedAt.Equal(at) || page.Events[0].URL != "https://example.com/path" {
t.Fatal(page.Events[0])
}
if gaps, err := s.ImportGaps(t.Context()); err != nil || gaps != 1 {
t.Fatal(gaps, err)
}
// Pruning observations also prunes their deduplication keys.
if _, err := s.db.Exec("DELETE FROM access_events"); err != nil {
t.Fatal(err)
}
var count int
if err := s.db.QueryRow("SELECT COUNT(*) FROM access_imports").Scan(&count); err != nil || count != 0 {
t.Fatal(count, err)
}
}
18 changes: 18 additions & 0 deletions accessaudit/proxy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package accessaudit

import "context"

// ProxyFactory issues an opaque, revocable capability for this execution. The
// proxy resolves it server-side; client-supplied task headers are never trusted.
type ProxyFactory func(Identity) (string, string, func())
type proxyFactoryKey struct{}

func WithProxyFactory(ctx context.Context, f ProxyFactory) context.Context {
return context.WithValue(ctx, proxyFactoryKey{}, f)
}
func ExecutionProxy(ctx context.Context, fallback, caCert string) (string, string, func()) {
if f, ok := ctx.Value(proxyFactoryKey{}).(ProxyFactory); ok && f != nil {
return f(IdentityFrom(ctx))
}
return fallback, caCert, func() {}
}
Loading
Loading