oficina / agent-access Public
Run connection service under Rastrillo platform activation
7 files changed,
+664
−13
README.md+26 −3cmd/oficina-connect/main.go+100 −10cmd/oficina-connect/main_test.go+348 −0cmd/oficina-connect/testdata/synthetic-config.json+38 −0docs/platform-runtime.md+13 −0scripts/build-release.sh+33 −0scripts/vet-release.py+106 −0
CI passed — run details
diff --git a/README.md b/README.md| index 2224686..0810502 100644 |
| --- a/README.md |
| +++ b/README.md |
| @@ -8,8 +8,9 @@ Status: implementation in progress. Shared operations, HTTP/MCP adapters, the |
| CLI, browser consent with PKCE, rotating refresh tokens and revocation are |
| implemented. Tests exercise browser authorization through an HTTPS fixture, |
| including real loopback callbacks and the signed Home identity handoff. A runnable |
| -connection service and the first Memoria adapter are on feature branches. Other |
| -app adapters and deployment remain in progress. No production endpoint is deployed. |
| +connection service and reviewed adapters for Docs, Sheets, Memoria, Calendar, |
| +Calls and Slides are on feature branches, exposing 20 operations. Live four-client |
| +acceptance and deployment remain outstanding. No production endpoint is deployed. |
| Each request supplies a verified person, client, grant, selected teams and |
| scopes. The registry rejects unauthorized team/scope combinations before calling |
| @@ -47,7 +48,7 @@ team IDs; ordinary commands never open a browser implicitly. |
| ## Running the connection service |
| -Build `go build ./cmd/oficina-connect` and `go build ./cmd/oficina`. |
| +For local development, build `go build ./cmd/oficina-connect` and `go build ./cmd/oficina`. |
| `oficina-connect -config connection.json -db /persistent/connect.db` listens on |
| 127.0.0.1:8080 behind an HTTPS reverse proxy preserving the public Host. Configure |
| an independent origin such as `https://connect.example.test`; this is separate |
| @@ -144,3 +145,25 @@ configured Home issuer to `NewRemoteVerifier`; subjects are released only after |
| an exact match. A grant database binds that Home issuer persistently and refuses |
| a changed issuer or an unbound database already containing grants. Changing the |
| Home authority requires an explicit migration, not a configuration-only restart. |
| + |
| +## Platform deployment |
| + |
| +`OFICINA_CONNECT_CONFIG_BASE64` selects the Rastrillo/CARLOS runtime before |
| +standalone flag parsing. It contains the same strict public JSON as `-config`, |
| +limited to 64 KiB decoded. Secrets remain separate. This mode accepts `serve`, |
| +`-socket`, `-addr`, and `-db`; relative database paths resolve beneath |
| +`STATE_DIRECTORY`. It provides framework health/version probes and graceful |
| +shutdown. `-config` and `-listen` belong to standalone mode and are refused here. |
| +See [the runtime contract](docs/platform-runtime.md) for limits and tests. |
| + |
| +Build committed release artifacts with `scripts/build-release.sh /absolute/output`. |
| +The output includes Linux/arm64 service and CLI binaries, native equivalents, |
| +`VERSION` (the full source SHA), and `SHA256SUMS`. Use exactly that `VERSION` as |
| +`carlos deploy --version`; the service reports it from `/api/version`. |
| + |
| +Before publishing, run `scripts/vet-release.py /absolute/output --carlos /path/to/carlos`. |
| +This uses a temporary local CARLOS store and a synthetic configuration; no upload |
| +or infrastructure change occurs. It checks the native artifact through the real |
| +`carlos vet --boot` contract. Repeat on Linux/arm64 with `--target linux-arm64` |
| +for the deployment artifact. The generated fixture is only for boot verification, |
| +never a production secret or a valid live app registration. |
diff --git a/cmd/oficina-connect/main.go b/cmd/oficina-connect/main.go| index 71c2f3f..85f6bcd 100644 |
| --- a/cmd/oficina-connect/main.go |
| +++ b/cmd/oficina-connect/main.go |
| @@ -17,6 +17,7 @@ import ( |
| access "amadan.net/oficina/agent-access.git" |
| "amadan.net/oficina/agent-access.git/connection" |
| + "amadan.net/rastrillo/rastrillo" |
| "amadan.net/rastrillo/rastrillo/db" |
| ) |
| @@ -29,6 +30,9 @@ func main() { |
| } |
| func run(logger *slog.Logger) error { |
| + if encoded := os.Getenv("OFICINA_CONNECT_CONFIG_BASE64"); encoded != "" { |
| + return runPlatform(logger, encoded) |
| + } |
| configPath := flag.String("config", "", "connection configuration JSON file") |
| dbPath := flag.String("db", "oficina-connect.db", "persistent SQLite database path") |
| listen := flag.String("listen", "127.0.0.1:8080", "HTTP listener behind the HTTPS proxy") |
| @@ -45,17 +49,10 @@ func run(logger *slog.Logger) error { |
| if err != nil || len(raw) > 2<<20 || access.UniqueJSON(raw) != nil { |
| return errors.New("invalid connection configuration JSON") |
| } |
| - var cfg connection.Config |
| - decoder := json.NewDecoder(bytes.NewReader(raw)) |
| - decoder.DisallowUnknownFields() |
| - if decoder.Decode(&cfg) != nil { |
| - return errors.New("invalid connection configuration") |
| - } |
| - cfg.DEK, err = base64.StdEncoding.DecodeString(os.Getenv("OFICINA_CONNECT_DEK")) |
| - if err != nil || len(cfg.DEK) != 32 { |
| - return errors.New("OFICINA_CONNECT_DEK must encode 32 bytes") |
| + cfg, err := loadConfig(raw) |
| + if err != nil { |
| + return err |
| } |
| - cfg.DirectoryToken = os.Getenv("OFICINA_DIRECTORY_TOKEN") |
| d, err := db.Open(*dbPath, logger) |
| if err != nil { |
| return errors.New("could not open connection database") |
| @@ -82,3 +79,96 @@ func run(logger *slog.Logger) error { |
| return server.Shutdown(shutdown) |
| } |
| } |
| + |
| +const platformConfigLimit = 64 << 10 |
| +const appHeaderLimit = 16 << 10 |
| + |
| +func loadConfig(raw []byte) (connection.Config, error) { |
| + var cfg connection.Config |
| + if access.UniqueJSON(raw) != nil { |
| + return cfg, errors.New("invalid connection configuration JSON") |
| + } |
| + decoder := json.NewDecoder(bytes.NewReader(raw)) |
| + decoder.DisallowUnknownFields() |
| + if decoder.Decode(&cfg) != nil { |
| + return cfg, errors.New("invalid connection configuration") |
| + } |
| + var err error |
| + cfg.DEK, err = base64.StdEncoding.DecodeString(os.Getenv("OFICINA_CONNECT_DEK")) |
| + if err != nil || len(cfg.DEK) != 32 { |
| + return cfg, errors.New("OFICINA_CONNECT_DEK must encode 32 bytes") |
| + } |
| + cfg.DirectoryToken = os.Getenv("OFICINA_DIRECTORY_TOKEN") |
| + return cfg, nil |
| +} |
| + |
| +func runPlatform(logger *slog.Logger, encoded string) error { |
| + if len(encoded) > base64.StdEncoding.EncodedLen(platformConfigLimit) { |
| + return errors.New("invalid deployment configuration size") |
| + } |
| + raw, err := base64.StdEncoding.Strict().DecodeString(encoded) |
| + if err != nil || len(raw) > platformConfigLimit { |
| + return errors.New("invalid deployment configuration encoding or size") |
| + } |
| + cfg, err := loadConfig(raw) |
| + if err != nil { |
| + return err |
| + } |
| + opts, err := rastrillo.Resolve(rastrillo.Options{DBPath: "oficina-connect.db", Logger: logger}) |
| + if err != nil { |
| + return errors.New("invalid platform activation arguments") |
| + } |
| + d, err := db.Open(opts.DBPath, logger) |
| + if err != nil { |
| + return errors.New("could not open connection database") |
| + } |
| + defer d.Close() |
| + app, err := connection.New(context.Background(), cfg, d, logger) |
| + if err != nil { |
| + return errors.New("connection service configuration or storage is unavailable") |
| + } |
| + opts = servingOptions(opts, app.Handler) |
| + if err := rastrillo.Serve(opts); err != nil { |
| + return errors.New("connection platform runtime failed") |
| + } |
| + return nil |
| +} |
| + |
| +// servingOptions relinquishes framework database ownership while preserving the |
| +// resolved listener coordinates and logger. The caller closes its handle only |
| +// after Serve has drained the HTTP server. |
| +func servingOptions(opts rastrillo.Options, handler http.Handler) rastrillo.Options { |
| + opts.DBPath = "" |
| + opts.NoSpeculationRules = true |
| + opts.ReadHeaderTimeout = 10 * time.Second |
| + opts.ReadTimeout = 30 * time.Second |
| + opts.WriteTimeout = 60 * time.Second |
| + opts.IdleTimeout = 60 * time.Second |
| + opts.Mux = http.NewServeMux() |
| + opts.Mux.Handle("/", handler) |
| + opts.Wrap = limitAppHeaders |
| + return opts |
| +} |
| + |
| +// This application budget is additional to the framework's 1 MiB parser limit. |
| +// Probes bypass app middleware. Count Host separately: net/http removes it from |
| +// Header. Repeated values each pay for their header name. |
| +func limitAppHeaders(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + size := len(r.RequestURI) + len("Host") + len(r.Host) |
| + for name, values := range r.Header { |
| + for _, value := range values { |
| + size += len(name) + len(value) |
| + if size > appHeaderLimit { |
| + http.Error(w, "Request headers too large", http.StatusRequestHeaderFieldsTooLarge) |
| + return |
| + } |
| + } |
| + } |
| + if size > appHeaderLimit { |
| + http.Error(w, "Request headers too large", http.StatusRequestHeaderFieldsTooLarge) |
| + return |
| + } |
| + next.ServeHTTP(w, r) |
| + }) |
| +} |
diff --git a/cmd/oficina-connect/main_test.go b/cmd/oficina-connect/main_test.go| new file mode 100644 |
| index 0000000..de6aced |
| --- /dev/null |
| +++ b/cmd/oficina-connect/main_test.go |
| @@ -0,0 +1,348 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/base64" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo" |
| +) |
| + |
| +func syntheticConfig(t *testing.T) []byte { |
| + t.Helper() |
| + raw, err := os.ReadFile("testdata/synthetic-config.json") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return raw |
| +} |
| + |
| +func TestApplicationHeaderBudget(t *testing.T) { |
| + for _, kind := range []string{"target", "host", "repeated"} { |
| + t.Run(kind, func(t *testing.T) { |
| + r := httptest.NewRequest("GET", "/", nil) |
| + r.Host = "h" |
| + r.Header = make(http.Header) |
| + switch kind { |
| + case "target": |
| + r.RequestURI = strings.Repeat("a", appHeaderLimit-len("Host")-len(r.Host)) |
| + case "host": |
| + r.Host = strings.Repeat("a", appHeaderLimit-len("Host")-len(r.RequestURI)) |
| + case "repeated": |
| + r.Header["Long-Header-Name"] = []string{strings.Repeat("a", appHeaderLimit-2*len("Long-Header-Name")-len("Host")-len(r.Host)-len(r.RequestURI)), ""} |
| + } |
| + calls := 0 |
| + h := limitAppHeaders(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(204) })) |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(w, r) |
| + if w.Code != 204 || calls != 1 { |
| + t.Fatalf("boundary rejected: %d", w.Code) |
| + } |
| + switch kind { |
| + case "target": |
| + r.RequestURI += "a" |
| + case "host": |
| + r.Host += "a" |
| + case "repeated": |
| + r.Header["Long-Header-Name"][1] = "a" |
| + } |
| + w = httptest.NewRecorder() |
| + h.ServeHTTP(w, r) |
| + if w.Code != 431 || calls != 1 || w.Header().Get("Set-Cookie") != "" { |
| + t.Fatalf("over budget reached app: %d calls %d", w.Code, calls) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRuntimeExecutable(t *testing.T) { |
| + // Build the real entry point, including the link-time platform version probe. |
| + dir, err := os.MkdirTemp("", "connect-runtime-") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(dir) }) |
| + binary := filepath.Join(dir, "oficina-connect") |
| + build := exec.Command("go", "build", "-ldflags=-X amadan.net/rastrillo/rastrillo.BuildVersion=runtime-test-1234", "-o", binary, ".") |
| + if out, err := build.CombinedOutput(); err != nil { |
| + t.Fatalf("build: %v: %s", err, out) |
| + } |
| + raw := syntheticConfig(t) |
| + baseEnv := []string{} |
| + for _, v := range os.Environ() { |
| + if !strings.HasPrefix(v, "OFICINA_") && !strings.HasPrefix(v, "STATE_DIRECTORY=") && !strings.HasPrefix(v, "LISTEN_") { |
| + baseEnv = append(baseEnv, v) |
| + } |
| + } |
| + secret := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{5}, 32)) |
| + token := "synthetic-directory-secret-must-not-appear" |
| + newCommand := func(t *testing.T, config []byte, args ...string) (*exec.Cmd, string) { |
| + t.Helper() |
| + work := filepath.Join(dir, strings.ReplaceAll(t.Name(), "/", "-")) |
| + state := filepath.Join(work, "state") |
| + if err := os.MkdirAll(state, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := exec.Command(binary, args...) |
| + cmd.Dir = work |
| + cmd.Env = append(append([]string{}, baseEnv...), "STATE_DIRECTORY="+state, "OFICINA_CONNECT_CONFIG_BASE64="+base64.StdEncoding.EncodeToString(config), "OFICINA_CONNECT_DEK="+secret, "OFICINA_DIRECTORY_TOKEN="+token) |
| + return cmd, state |
| + } |
| + for _, mode := range []string{"platform", "platform-db", "bare-socket", "standalone", "config-limit"} { |
| + t.Run(mode, func(t *testing.T) { |
| + socket := filepath.Join(dir, mode+".sock") |
| + args := []string{"serve", "-socket", socket} |
| + data := raw |
| + if mode == "config-limit" { |
| + data = append(append([]byte{}, raw...), bytes.Repeat([]byte(" "), platformConfigLimit-len(raw))...) |
| + } |
| + if mode == "bare-socket" { |
| + args = args[1:] |
| + } |
| + if mode == "platform-db" { |
| + args = append(args, "-db", "override.db") |
| + } |
| + cmd, state := newCommand(t, data, args...) |
| + var client *http.Client |
| + baseURL := "http://connect.example.test" |
| + if mode == "standalone" { |
| + listener, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + addr := listener.Addr().String() |
| + listener.Close() |
| + configPath := filepath.Join(state, "config.json") |
| + if err := os.WriteFile(configPath, raw, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd.Args = []string{binary, "-config", configPath, "-listen", addr, "-db", filepath.Join(state, "oficina-connect.db")} |
| + for i, v := range cmd.Env { |
| + if strings.HasPrefix(v, "OFICINA_CONNECT_CONFIG_BASE64=") { |
| + cmd.Env[i] = "OFICINA_CONNECT_CONFIG_BASE64=" |
| + } |
| + } |
| + transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "tcp", addr) |
| + }} |
| + client = &http.Client{Transport: transport, Timeout: time.Second} |
| + defer transport.CloseIdleConnections() |
| + } else { |
| + transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "unix", socket) |
| + }} |
| + client = &http.Client{Transport: transport, Timeout: time.Second} |
| + defer transport.CloseIdleConnections() |
| + } |
| + var output bytes.Buffer |
| + cmd.Stdout = &output |
| + cmd.Stderr = &output |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + finished := false |
| + t.Cleanup(func() { |
| + if !finished { |
| + cmd.Process.Kill() |
| + cmd.Wait() |
| + } |
| + }) |
| + deadline := time.Now().Add(10 * time.Second) |
| + for { |
| + resp, err := client.Get(baseURL + "/healthz") |
| + if err == nil { |
| + resp.Body.Close() |
| + if resp.StatusCode == 200 { |
| + break |
| + } |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("startup timeout") |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + check := func(path, host string, status int, contains string) { |
| + t.Helper() |
| + req, _ := http.NewRequest("GET", baseURL+path, nil) |
| + req.Host = host |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode != status || (!strings.Contains(string(body), contains) || (path == "/api/version" && string(body) != contains)) { |
| + t.Fatalf("%s host %s: %d %s", path, host, resp.StatusCode, body) |
| + } |
| + } |
| + check("/.well-known/oauth-authorization-server", "connect.example.test", 200, "https://connect.example.test") |
| + check("/.well-known/oauth-authorization-server", "wrong.example.test", 404, "") |
| + if mode != "standalone" { |
| + check("/api/version", "probe.invalid", 200, "runtime-test-1234") |
| + check("/healthz", "probe.invalid", 200, "") |
| + } |
| + req, _ := http.NewRequest("GET", baseURL+"/.well-known/oauth-authorization-server", nil) |
| + headerSize := appHeaderLimit + 1 |
| + if mode == "standalone" { |
| + headerSize += 8192 |
| + } // net/http reserves an extra read buffer |
| + req.Header.Set("X-Large", strings.Repeat("a", headerSize)) |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != 431 { |
| + t.Fatalf("large headers status %d", resp.StatusCode) |
| + } |
| + // The framework parser still caps headers independently of app middleware. |
| + if mode != "standalone" { |
| + req, _ = http.NewRequest("GET", baseURL+"/healthz", nil) |
| + req.Header.Set("X-Large", strings.Repeat("a", 32<<10)) |
| + resp, err = client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != 200 { |
| + t.Fatalf("probe incorrectly subject to app budget: %d", resp.StatusCode) |
| + } |
| + req, _ = http.NewRequest("GET", baseURL+"/healthz", nil) |
| + req.Header.Set("X-Large", strings.Repeat("a", (1<<20)+8192)) |
| + resp, err = client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != 431 { |
| + t.Fatalf("parser limit: %d", resp.StatusCode) |
| + } |
| + } |
| + if err := cmd.Process.Signal(syscall.SIGTERM); err != nil { |
| + t.Fatal(err) |
| + } |
| + done := make(chan error, 1) |
| + go func() { done <- cmd.Wait() }() |
| + select { |
| + case err := <-done: |
| + finished = true |
| + if err != nil { |
| + t.Fatalf("shutdown %v: %s", err, output.String()) |
| + } |
| + case <-time.After(15 * time.Second): |
| + t.Fatal("shutdown timeout") |
| + } |
| + database := "oficina-connect.db" |
| + if mode == "platform-db" { |
| + database = "override.db" |
| + } |
| + if _, err := os.Stat(filepath.Join(state, database)); err != nil { |
| + t.Fatalf("persistent database missing: %v", err) |
| + } |
| + if _, err := os.Stat(filepath.Join(cmd.Dir, database)); !os.IsNotExist(err) { |
| + t.Fatal("database escaped STATE_DIRECTORY") |
| + } |
| + if strings.Contains(output.String(), secret) || strings.Contains(output.String(), token) { |
| + t.Fatal("secret in logs") |
| + } |
| + }) |
| + } |
| + for _, kind := range []string{"oversize", "malformed", "unknown", "duplicate", "missing-dek", "missing-directory", "mixed-config", "mixed-listen", "noncanonical-base64"} { |
| + t.Run(kind, func(t *testing.T) { |
| + data := raw |
| + args := []string{"serve", "-socket", filepath.Join(dir, "refuse.sock")} |
| + switch kind { |
| + case "oversize": |
| + data = append(append([]byte{}, raw...), bytes.Repeat([]byte(" "), platformConfigLimit+1-len(raw))...) |
| + case "malformed": |
| + data = []byte(`{"canary":"DO_NOT_LOG_CONFIG"`) |
| + case "unknown": |
| + data = append([]byte(`{"DO_NOT_LOG_CONFIG":true,`), raw[1:]...) |
| + case "duplicate": |
| + data = append([]byte(`{"origin":"DO_NOT_LOG_CONFIG",`), raw[1:]...) |
| + case "mixed-config": |
| + args = append(args, "-config", "unused") |
| + case "mixed-listen": |
| + args = append(args, "-listen", "127.0.0.1:0") |
| + } |
| + if kind == "noncanonical-base64" { |
| + data = append([]byte{}, data...) |
| + for len(data)%3 != 1 { |
| + data = append(data, ' ') |
| + } |
| + } |
| + cmd, state := newCommand(t, data, args...) |
| + if kind == "noncanonical-base64" { |
| + encoded := []byte(base64.StdEncoding.EncodeToString(data)) |
| + alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" |
| + index := strings.IndexByte(alphabet, encoded[len(encoded)-3]) |
| + encoded[len(encoded)-3] = alphabet[index+1] // same decoded bytes, nonzero unused bits |
| + if decoded, err := base64.StdEncoding.DecodeString(string(encoded)); err != nil || !bytes.Equal(decoded, data) { |
| + t.Fatal("bad mutation fixture") |
| + } |
| + for i, v := range cmd.Env { |
| + if strings.HasPrefix(v, "OFICINA_CONNECT_CONFIG_BASE64=") { |
| + cmd.Env[i] = "OFICINA_CONNECT_CONFIG_BASE64=" + string(encoded) |
| + } |
| + } |
| + } |
| + if kind == "missing-dek" || kind == "missing-directory" { |
| + prefix := "OFICINA_CONNECT_DEK=" |
| + if kind == "missing-directory" { |
| + prefix = "OFICINA_DIRECTORY_TOKEN=" |
| + } |
| + for i, v := range cmd.Env { |
| + if strings.HasPrefix(v, prefix) { |
| + cmd.Env[i] = prefix |
| + } |
| + } |
| + } |
| + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) |
| + defer cancel() |
| + bounded := exec.CommandContext(ctx, binary, cmd.Args[1:]...) |
| + bounded.Env = cmd.Env |
| + bounded.Dir = cmd.Dir |
| + out, err := bounded.CombinedOutput() |
| + if err == nil || ctx.Err() != nil { |
| + t.Fatalf("expected prompt startup refusal: %v", err) |
| + } |
| + for _, s := range []string{secret, token, "DO_NOT_LOG_CONFIG"} { |
| + if bytes.Contains(out, []byte(s)) { |
| + t.Fatal("sensitive diagnostic") |
| + } |
| + } |
| + if kind == "mixed-config" || kind == "mixed-listen" || kind == "noncanonical-base64" { |
| + if _, err := os.Stat(filepath.Join(state, "oficina-connect.db")); !os.IsNotExist(err) { |
| + t.Fatal("mixed arguments opened database") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestServingOptionsOwnershipAndDeadlines(t *testing.T) { |
| + opts := servingOptions(rastrillo.Options{DBPath: "already-open.db", Socket: "activation.sock", Addr: "127.0.0.1:9876"}, http.NotFoundHandler()) |
| + if opts.DBPath != "" { |
| + t.Fatal("framework must not open a second database") |
| + } |
| + if opts.Socket != "activation.sock" || opts.Addr != "127.0.0.1:9876" { |
| + t.Fatal("activation coordinates lost") |
| + } |
| + if opts.ReadHeaderTimeout != 10*time.Second || opts.ReadTimeout != 30*time.Second || opts.WriteTimeout != 60*time.Second || opts.IdleTimeout != 60*time.Second { |
| + t.Fatalf("unexpected HTTP deadlines: %+v", opts) |
| + } |
| + if !opts.NoSpeculationRules { |
| + t.Fatal("consent endpoints must not enable speculative loads") |
| + } |
| +} |
diff --git a/cmd/oficina-connect/testdata/synthetic-config.json b/cmd/oficina-connect/testdata/synthetic-config.json| new file mode 100644 |
| index 0000000..4d95ab0 |
| --- /dev/null |
| +++ b/cmd/oficina-connect/testdata/synthetic-config.json |
| @@ -0,0 +1,38 @@ |
| +{ |
| + "origin": "https://connect.example.test", |
| + "home_issuer": "https://id.example.test", |
| + "consumer_id": "agent-access", |
| + "home_keys": { |
| + "synthetic": "BFhO/ANh3vKaaPC3dyDpO7UbqOMzU5eWPUZ2hswxDRFCstPE/30UfUh9AteRLVV6YOPk7oXdV1PhN8EipRgxdwo=" |
| + }, |
| + "directory": "https://home.example.test", |
| + "routes": [ |
| + { |
| + "team": "test", |
| + "resource": "https://notes.example.test/api/v1", |
| + "operations": [ |
| + { |
| + "name": "notes_list", |
| + "description": "List notes", |
| + "scope": "notes:read", |
| + "read_only": true, |
| + "input_schema": { |
| + "type": "object", |
| + "required": [ |
| + "team" |
| + ], |
| + "properties": { |
| + "team": { |
| + "type": "string" |
| + } |
| + }, |
| + "additionalProperties": false |
| + }, |
| + "output_schema": { |
| + "type": "object" |
| + } |
| + } |
| + ] |
| + } |
| + ] |
| +} |
diff --git a/docs/platform-runtime.md b/docs/platform-runtime.md| new file mode 100644 |
| index 0000000..7ece427 |
| --- /dev/null |
| +++ b/docs/platform-runtime.md |
| @@ -0,0 +1,13 @@ |
| +# Connection service platform runtime |
| + |
| +Bounded deployment prerequisite: the current standalone flags cannot satisfy CARLOS socket activation, `serve` argv, persistent state directory, health/version probes or config delivery. Keep the existing standalone `-config/-listen/-db` mode. Add an explicit deployment mode selected by nonempty `OFICINA_CONNECT_CONFIG_BASE64`, decoded as the same strict public configuration JSON, with a deployment-only 64 KiB decoded cap (at most 87384 base64 bytes, below Linux per-environment-string limits). Standalone file input retains its 2 MiB cap; larger deployment catalogs must be split/reduced until file delivery is explicitly implemented. Secrets remain only `OFICINA_CONNECT_DEK` and `OFICINA_DIRECTORY_TOKEN`; reject malformed or ambiguous configuration without logging payloads. |
| + |
| +Deployment mode uses the already pinned Rastrillo Resolve/Serve contract, default DB `oficina-connect.db` under STATE_DIRECTORY, optional socket/addr/db activation arguments, health/version probes, graceful signal handling and existing request timeouts. Open the database exactly once, run the same connection.New service, then clear Options.DBPath before Serve. Mount the existing host-checked service handler under the framework mux. App consent/handoff headers retain their existing behavior. No Home claims or permission rules change. |
| + |
| +Test the actual subprocess via a Unix socket using CARLOS-style argv, verify metadata/health/version, DB location and graceful termination; exercise malformed public config and missing secret startup refusal without sensitive diagnostic output. Retain standalone compatibility tests and full module vet/race checks. Independent source/evidence review precedes a canary deployment. Live infrastructure work requires a separate concrete scoped approval under the CARLOS platform AGENTS rule. |
| + |
| +Release builds must stamp the exact release version token (the full git SHA in this release recipe) into `amadan.net/rastrillo/rastrillo.BuildVersion` via -X, record artifact SHA256, and verify that non-dev value from `/api/version`. Tests build an executable with a fixed non-dev stamp. The env branch runs before any standalone flag parsing; mixed env with standalone `-config` or `-listen` flags fails; shared platform `-db` remains valid. |
| + |
| +The pinned framework has no MaxHeaderBytes option. Platform mode intentionally uses its bounded net/http default network parser limit (1 MiB, as the existing Oficina apps do), plus the retained ten-second header deadline. A wrapper additionally refuses application requests with more than 16 KiB of header names/values and request target before app/session/OAuth handling. This application budget does not claim to reduce the framework parser's allocation bound. Probe routes use the framework's parser limit. Standalone remains 16 KiB at the network parser. Tests distinguish these bounds. This avoids upgrading all app dependencies solely to add a transport option; converge on an upstream explicit MaxHeaderBytes option later. |
| + |
| +The release recipe passes the same full SHA to both the BuildVersion linker stamp and `carlos deploy --version`; CARLOS compares those byte-for-byte. For `carlos vet --boot`, supply a synthetic valid public configuration, synthetic DEK and synthetic directory token through inherited environment. Never add a configless healthy mode. The synthetic configuration performs no upstream calls on boot and uses reserved test origins. |
diff --git a/scripts/build-release.sh b/scripts/build-release.sh| new file mode 100755 |
| index 0000000..b4a4da2 |
| --- /dev/null |
| +++ b/scripts/build-release.sh |
| @@ -0,0 +1,33 @@ |
| +#!/usr/bin/env bash |
| +# Build committed source only. No upload, promotion or infrastructure changes. |
| +set -euo pipefail |
| +test "$#" -ge 1 && test "$#" -le 2 |
| +mkdir -p "$1" |
| +release_output=$(cd "$1" && pwd) |
| +cd "$(dirname "$0")/.." |
| +release_commit=$(git rev-parse --verify "${2:-HEAD}^{commit}") |
| +release_source=$(mktemp -d) |
| +trap 'rm -rf -- "$release_source"' EXIT |
| +git archive "$release_commit" | tar -x -C "$release_source" |
| +cd "$release_source" |
| +export GOWORK=off |
| +export GOTOOLCHAIN=go1.26.5 |
| +export CGO_ENABLED=0 |
| +for release_command in oficina-connect oficina; do |
| + GOOS=linux GOARCH=arm64 go build -mod=readonly -trimpath -buildvcs=false \ |
| + -ldflags "-s -w -X amadan.net/rastrillo/rastrillo.BuildVersion=$release_commit" \ |
| + -o "$release_output/$release_command-linux-arm64" "./cmd/$release_command" |
| + GOOS=$(go env GOHOSTOS) GOARCH=$(go env GOHOSTARCH) go build -mod=readonly -trimpath -buildvcs=false \ |
| + -ldflags "-s -w -X amadan.net/rastrillo/rastrillo.BuildVersion=$release_commit" \ |
| + -o "$release_output/$release_command-native" "./cmd/$release_command" |
| +done |
| +cp cmd/oficina-connect/testdata/synthetic-config.json "$release_output/synthetic-config.json" |
| +printf '%s\n' "$release_commit" > "$release_output/VERSION" |
| +cd "$release_output" |
| +python3 - <<'HASHES' |
| +import hashlib |
| +from pathlib import Path |
| +names = ("oficina-connect-linux-arm64", "oficina-linux-arm64", "oficina-connect-native", "oficina-native") |
| +Path("SHA256SUMS").write_text("".join(hashlib.sha256(Path(name).read_bytes()).hexdigest() + " " + name + "\n" for name in names)) |
| +HASHES |
| +printf 'Built %s; pass that exact value to carlos deploy --version.\n' "$release_commit" |
diff --git a/scripts/vet-release.py b/scripts/vet-release.py| new file mode 100755 |
| index 0000000..dcbe4cd |
| --- /dev/null |
| +++ b/scripts/vet-release.py |
| @@ -0,0 +1,106 @@ |
| +#!/usr/bin/env python3 |
| +"""Vet a local native artifact through CARLOS' real local-store boot check. |
| + |
| +Never uploads or contacts CARLOS. The synthetic fixture grants no live access. |
| +Run on Linux/arm64 with --target linux-arm64 to vet the deployment artifact. |
| +""" |
| +import argparse |
| +import base64 |
| +import hashlib |
| +import http.client |
| +import json |
| +import os |
| +import pathlib |
| +import platform |
| +import shutil |
| +import socket |
| +import time |
| +import subprocess |
| +import tempfile |
| + |
| +parser = argparse.ArgumentParser() |
| +parser.add_argument("bundle", type=pathlib.Path) |
| +parser.add_argument("--carlos", required=True) |
| +parser.add_argument("--target", choices=("native", "linux-arm64"), default="native") |
| +args = parser.parse_args() |
| +args.bundle = args.bundle.resolve(strict=True) |
| +carlos = pathlib.Path(args.carlos).resolve(strict=True) |
| +if not carlos.is_file() or not os.access(carlos, os.X_OK): |
| + parser.error("--carlos must name an executable file") |
| +if args.target == "linux-arm64" and (platform.system() != "Linux" or platform.machine() not in ("aarch64", "arm64")): |
| + parser.error("linux-arm64 boot vet requires Linux/arm64") |
| +version = (args.bundle / "VERSION").read_text().strip() |
| +if len(version) != 40 or any(c not in "0123456789abcdef" for c in version): |
| + parser.error("VERSION must be a full git SHA") |
| +expected_names = {"oficina-connect-linux-arm64", "oficina-linux-arm64", "oficina-connect-native", "oficina-native"} |
| +recorded = {} |
| +for line in (args.bundle / "SHA256SUMS").read_text().splitlines(): |
| + digest, name = line.split(" ") |
| + if name not in expected_names or name in recorded or len(digest) != 64: |
| + parser.error("invalid SHA256SUMS") |
| + recorded[name] = digest |
| +if set(recorded) != expected_names: |
| + parser.error("incomplete SHA256SUMS") |
| +for name, digest in recorded.items(): |
| + if hashlib.sha256((args.bundle / name).read_bytes()).hexdigest() != digest: |
| + parser.error("artifact differs from recorded SHA256SUMS: " + name) |
| +artifact = args.bundle / ("oficina-connect-" + args.target) |
| +raw = artifact.read_bytes() |
| +config = (args.bundle / "synthetic-config.json").read_bytes() |
| +with tempfile.TemporaryDirectory(prefix="oficina-local-vet-") as scratch: |
| + work = pathlib.Path(scratch) |
| + release = work / "store" / "apps" / "bds" / "oficina-connect" / "releases" / version |
| + release.mkdir(parents=True) |
| + shutil.copyfile(artifact, release / "oficina-connect") |
| + target = "linux-arm64" if args.target == "linux-arm64" else platform.system().lower() + "-" + {"arm64": "arm64", "aarch64": "arm64", "x86_64": "amd64"}[platform.machine()] |
| + manifest = {"schema": 1, "app": "oficina-connect", "version": version, "kind": "binary", "artifacts": {target: {"file": "oficina-connect", "sha256": hashlib.sha256(raw).hexdigest(), "size": len(raw)}}} |
| + (release / "manifest.json").write_text(json.dumps(manifest)) |
| + state = work / "state" |
| + state.mkdir() |
| + # No production deployment variables, credentials, or inherited activation FDs. |
| + env = {k: v for k, v in os.environ.items() if not k.startswith(("CARLOS_", "OFICINA_", "AWS_", "LISTEN_")) and k != "STATE_DIRECTORY"} |
| + env.update(CARLOS_DEPLOYMENT_DIR=str(work / "store"), CARLOS_CREDENTIALS=str(work / "no-credentials"), |
| + STATE_DIRECTORY=str(state), OFICINA_CONNECT_CONFIG_BASE64=base64.b64encode(config).decode(), |
| + OFICINA_CONNECT_DEK=base64.b64encode(bytes([5]) * 32).decode(), |
| + OFICINA_DIRECTORY_TOKEN="synthetic-directory-secret-must-not-appear") |
| + subprocess.run([str(carlos), "vet", "--account", "bds", "--app", "oficina-connect", "--version", version, "--boot"], cwd=work, env=env, check=True) |
| + if not (state / "oficina-connect.db").is_file(): |
| + raise SystemExit("boot vet did not create persistent state; a skipped boot is not success") |
| + |
| + # CARLOS boot vet checks health only; independently prove the exact release |
| + # stamp from these verified bytes, not just from the manifest we supplied. |
| + sock = work / "version.sock" |
| + class UnixHTTP(http.client.HTTPConnection): |
| + def connect(self): |
| + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| + self.sock.settimeout(1) |
| + self.sock.connect(str(sock)) |
| + |
| + with tempfile.TemporaryFile() as diagnostics: |
| + process = subprocess.Popen([str(artifact), "serve", "-socket", str(sock)], cwd=work, env=env, |
| + stdout=diagnostics, stderr=diagnostics) |
| + try: |
| + deadline = time.monotonic() + 10 |
| + while True: |
| + request = UnixHTTP("probe.invalid", timeout=1) |
| + try: |
| + request.request("GET", "/api/version") |
| + response = request.getresponse() |
| + body = response.read(256) |
| + if response.status != 200 or body != version.encode(): |
| + raise SystemExit("artifact /api/version does not exactly match VERSION") |
| + break |
| + except (OSError, http.client.HTTPException): |
| + if process.poll() is not None or time.monotonic() >= deadline: |
| + raise SystemExit("artifact version probe failed") |
| + time.sleep(0.05) |
| + finally: |
| + request.close() |
| + process.terminate() |
| + if process.wait(timeout=15) != 0: |
| + raise SystemExit("artifact failed graceful SIGTERM shutdown") |
| + finally: |
| + if process.poll() is None: |
| + process.kill() |
| + process.wait() |
| + print("Artifact checksum, exact version and graceful shutdown verified: " + version) |