oficina / docs Public

Add scoped read-only Oficina dashboard feed

Paul Campbell pushed by paul@keymail.dev fd6a0381bea0c3083df9a53f5830fe536c256d04 parent c660212
8 files changed, +252 −3
  • go.mod +1 −0
  • go.sum +4 −0
  • internal/docs/app.go +11 −1
  • internal/docs/dashboard.go +83 −0
  • internal/docs/dashboard_test.go +131 −0
  • internal/docs/grants.go +11 −1
  • internal/docs/home_router_integration_test.go +4 −1
  • internal/docs/team_router_test.go +7 −0

CI cancelled — superseded by a newer push — run details

diff --git a/go.mod b/go.mod
index f57eaff..fefb942 100644
--- a/go.mod
+++ b/go.mod
@@ -4,6 +4,7 @@ go 1.26.5
require (
amadan.net/oficina/estilo.git v0.0.0-20261024225350-d53b8e9533a1
+ amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf
amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3
diff --git a/go.sum b/go.sum
index 3d27146..6251ecb 100644
--- a/go.sum
+++ b/go.sum
@@ -1,5 +1,9 @@
amadan.net/oficina/estilo.git v0.0.0-20261024225350-d53b8e9533a1 h1:Xaidrm9rzFyne6PujFYXiY7nGRy+/KzH7kGBM2+D5LQ=
amadan.net/oficina/estilo.git v0.0.0-20261024225350-d53b8e9533a1/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816 h1:AFDuOio0MxNxN9ZWVc3lul1QHkNjNUCO56kXpe/Fw3I=
+amadan.net/oficina/home/dashboard v0.0.0-20261024234842-3774eb68f816/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0=
+amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064 h1:2YbDksZDxpY9khlhXmTeiM89yze7w2XfYSumtrzH4tc=
+amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064/go.mod h1:+7xsX+QyVFrKy5gDAGh+FZ5+75z4CibWTL0wl9DWAw0=
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM=
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
amadan.net/oficina/home/roster v0.0.0-20260908123429-74dda570e0cf h1:SRKjCUgtk42WwR7VSn+V0eLNk20mfiY8dQmzdw13Sbo=
diff --git a/internal/docs/app.go b/internal/docs/app.go
index 6af0fbc..9f5bd31 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -24,6 +24,7 @@ import (
"amadan.net/oficina/estilo.git/brand"
"amadan.net/oficina/estilo.git/chrome"
"amadan.net/oficina/estilo.git/theme"
+ "amadan.net/oficina/home/dashboard"
"amadan.net/oficina/home/handoff"
nativeauth "amadan.net/rastrillo/native/server"
"amadan.net/rastrillo/rastrillo"
@@ -290,7 +291,7 @@ type App struct {
// §2): sessions.Schema before auth.Schema — auth's own backfill
// migration reads the sessions table — before this app's own Schema
// (models.go).
-var BootSchema = migrate.Merge(sessions.Schema, authSchema, Schema, linkstore.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"))
+var BootSchema = migrate.Merge(migrate.MustFromFS(dashboard.Migrations, "oficina_dashboard"), sessions.Schema, authSchema, Schema, linkstore.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"))
// New opens the database, applies migrations and wires the router. It
// is rastrillo SKILL.md's app.go shape: db.Open for the SQLite handle,
@@ -637,6 +638,15 @@ func New(cfg Config) (*App, error) {
// both live under this one URL prefix, so one composed handler,
// not two competing route registrations. Still unauthenticated,
// still mounted above the RequireSession group below.
+ if home != nil {
+ provider, e := h.dashboardProvider(home, homeSettings, list, d.Writer())
+ if e != nil {
+ return nil, e
+ }
+ if provider != nil {
+ r.Handle(dashboard.Path, provider)
+ }
+ }
r.Handle("/static/*", staticHandler(render.assets.Handler()))
// The suite's app icons, served from estilo (the bar's brand, and the
// switcher's tiles once they render).
diff --git a/internal/docs/dashboard.go b/internal/docs/dashboard.go
new file mode 100644
index 0000000..ad66574
--- /dev/null
+++ b/internal/docs/dashboard.go
@@ -0,0 +1,83 @@
+package docs
+
+import (
+ "context"
+ "database/sql"
+ "net/http"
+ "os"
+ "time"
+
+ "amadan.net/oficina/home/dashboard"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+type dashboardAccessKey struct{}
+type dashboardAccess struct{ access *requestAccess }
+
+func (h *handlers) dashboardProvider(home *homeRoutes, c *homeSettings, list allowlist, db *sql.DB) (http.Handler, error) {
+ team := os.Getenv("OFICINA_DASHBOARD_TEAM")
+ if team == "" {
+ return nil, nil
+ }
+ // Resolve the same existing principal as the browser, without creating a
+ // local account or calling EnsureHome. The token itself confers no access.
+ resolve := func(ctx context.Context, subject string) (requestIdentity, error) {
+ r, _ := http.NewRequestWithContext(ctx, http.MethodGet, h.origin+"/", nil)
+ id, e := home.bridge.resolver.resolve(sessions.WithSession(r, sessions.Session{Subject: subject, Method: homeAssertionMethod}))
+ if e != nil {
+ return requestIdentity{}, e
+ }
+ if h.store.team == nil {
+ ok, e := list.allows(actorAddress(id.Actor))
+ if e != nil {
+ return requestIdentity{}, dashboard.ErrUnavailable
+ }
+ if !ok {
+ return requestIdentity{}, dashboard.ErrRefused
+ }
+ }
+ return id, nil
+ }
+ provider, err := dashboard.NewProvider(dashboard.ProviderConfig{DB: db, Origin: h.origin, Issuer: c.issuer, Directory: h.directory, Keys: c.keys, Team: team, Kind: "documents", Resolve: func(ctx context.Context, subject string) (int64, error) {
+ id, e := resolve(ctx, subject)
+ return id.Actor.PersonID, e
+ }, Read: func(ctx context.Context, person int64, subject string, _ time.Time) (dashboard.Response, error) {
+ id, e := resolve(ctx, subject)
+ if e != nil || id.Actor.PersonID != person {
+ return dashboard.Response{}, dashboard.ErrRefused
+ }
+ if h.store.team != nil {
+ access := h.store.team.resolveAccess(ctx, id)
+ ctx = context.WithValue(ctx, accessContextKey{}, access)
+ ctx.Value(dashboardAccessKey{}).(*dashboardAccess).access = access
+ }
+ rows, e := h.store.listForLimited(ctx, id.Actor, dashboard.MaxItems+1)
+ if e != nil {
+ return dashboard.Response{}, e
+ }
+ out := dashboard.Response{Truncated: len(rows) > dashboard.MaxItems}
+ if out.Truncated {
+ rows = rows[:dashboard.MaxItems]
+ }
+ for _, d := range rows {
+ out.Items = append(out.Items, dashboard.Item{ID: d.Sqid, Title: d.Title, URL: h.origin + "/d/" + d.Sqid, Updated: d.UpdatedAt})
+ }
+ return out, nil
+ }, Write: func(w http.ResponseWriter, r *http.Request, body []byte) {
+ if h.store.team != nil {
+ access := r.Context().Value(dashboardAccessKey{}).(*dashboardAccess).access
+ if access == nil {
+ http.Error(w, "Dashboard unavailable", 503)
+ return
+ }
+ r = r.WithContext(context.WithValue(r.Context(), accessContextKey{}, access))
+ }
+ _ = writeGuardedBody(w, r, 200, body)
+ }})
+ if err != nil {
+ return nil, err
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ provider.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), dashboardAccessKey{}, &dashboardAccess{})))
+ }), nil
+}
diff --git a/internal/docs/dashboard_test.go b/internal/docs/dashboard_test.go
new file mode 100644
index 0000000..5c486b0
--- /dev/null
+++ b/internal/docs/dashboard_test.go
@@ -0,0 +1,131 @@
+package docs
+
+import (
+ "amadan.net/oficina/home/dashboard"
+ "github.com/go-json-experiment/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestDashboardUsesExistingAccountAndDocumentGrants(t *testing.T) {
+ t.Setenv("OFICINA_DASHBOARD_TEAM", "blue")
+ f := newRouterHomeFixtureDirectory(t, "https://oficina.example.test")
+ s := f.app.store
+ ctx := t.Context()
+ alice, e := s.EnsurePerson(ctx, "alice@example.com")
+ if e != nil {
+ t.Fatal(e)
+ }
+ bob, e := s.EnsurePerson(ctx, "bob@example.com")
+ if e != nil {
+ t.Fatal(e)
+ }
+ own, e := s.Create(ctx, alice, "Own")
+ if e != nil {
+ t.Fatal(e)
+ }
+ shared, e := s.Create(ctx, bob, "Shared")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = s.Create(ctx, bob, "Private"); e != nil {
+ t.Fatal(e)
+ }
+ if e = s.Grant(ctx, bob, shared.Sqid, "alice@example.com", RoleWriter); e != nil {
+ t.Fatal(e)
+ }
+ subject := "pr_abcdefghijklmnopqrstuvwxyz"
+ b := f.browser()
+ b.localSignin(t, "alice@example.com")
+ start := routerRedirect(t, b.do("POST", "/account/home", ""), "")
+ nonce := b.start(t, start, "300")
+ routerRedirect(t, b.exchange(t, nonce, subject, time.Now().Add(-time.Minute)), "/account/home/confirm")
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), "")
+ call := func(sub string) *httptest.ResponseRecorder {
+ jti, _ := dashboard.ID()
+ nonce, _ := dashboard.ID()
+ now := time.Now().Unix()
+ token, e := dashboard.Sign(f.key, dashboard.Claims{Version: 1, Issuer: bridgeIssuer, Audience: bridgeOrigin, Directory: "https://oficina.example.test", Subject: sub, Team: "blue", Purpose: "dashboard-read", KeyID: f.keyID, ID: jti, Nonce: nonce, Issued: now, Expires: now + 120})
+ if e != nil {
+ t.Fatal(e)
+ }
+ r := httptest.NewRequest("GET", bridgeOrigin+dashboard.Path, nil)
+ r.Header.Set("Authorization", "Bearer "+token)
+ w := httptest.NewRecorder()
+ f.app.Handler().ServeHTTP(w, r)
+ return w
+ }
+ w := call(subject)
+ var data dashboard.Response
+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &data) != nil || len(data.Items) != 2 {
+ t.Fatal("feed", w.Code, w.Body.String())
+ }
+ for _, item := range data.Items {
+ if item.ID != own.Sqid && item.ID != shared.Sqid {
+ t.Fatal("private document exposed")
+ }
+ }
+ if w := call("pr_bbbbbbbbbbbbbbbbbbbbbbbbbb"); w.Code != 403 {
+ t.Fatal("unknown link", w.Code)
+ }
+ if routerRows(t, f, "people") != 2 {
+ t.Fatal("dashboard created account")
+ }
+}
+
+// Expire the exact membership lease between response preparation and emission.
+type dashboardDeadlineRecorder struct {
+ *teamDeadlineRecorder
+ clock *teamTestClock
+}
+
+func (w *dashboardDeadlineRecorder) SetWriteDeadline(time.Time) error {
+ if w.clock != nil {
+ w.clock.step(60 * time.Second)
+ w.clock = nil
+ }
+ return nil
+}
+func TestDashboardTeamResponseUsesEmissionGuard(t *testing.T) {
+ f := newTeamRouterFixtureWithDashboard(t, true)
+ b := f.browser()
+ b.localSignin(t, "alice@example.com")
+ b.linkProof(t, teamSubject('a'), "alice@example.com")
+ routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
+ request := func() *http.Request {
+ jti, _ := dashboard.ID()
+ nonce, _ := dashboard.ID()
+ now := time.Now().Unix()
+ token, e := dashboard.Sign(f.key, dashboard.Claims{Version: 1, Issuer: bridgeIssuer, Audience: bridgeOrigin, Directory: f.cfg.Directory, Subject: teamSubject('a'), Team: "TeamA", Purpose: "dashboard-read", KeyID: f.keyID, ID: jti, Nonce: nonce, Issued: now, Expires: now + 120})
+ if e != nil {
+ t.Fatal(e)
+ }
+ r := httptest.NewRequest("GET", bridgeOrigin+dashboard.Path, nil)
+ r.Header.Set("Authorization", "Bearer "+token)
+ return r
+ }
+ good := &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
+ f.app.Handler().ServeHTTP(good, request())
+ if good.Code != 200 || !strings.Contains(good.Body.String(), "Alice original") || strings.Contains(good.Body.String(), "Bob private") {
+ t.Fatal("team scope", good.Code, good.Body.String())
+ }
+ late := &dashboardDeadlineRecorder{teamDeadlineRecorder: &teamDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}, clock: f.clock}
+ aborted := false
+ func() {
+ defer func() {
+ if v := recover(); v != nil {
+ if v != http.ErrAbortHandler {
+ panic(v)
+ }
+ aborted = true
+ }
+ }()
+ f.app.Handler().ServeHTTP(late, request())
+ }()
+ if !aborted || late.Body.Len() != 0 {
+ t.Fatal("expired lease emitted data", late.Code, late.Body.String())
+ }
+}
diff --git a/internal/docs/grants.go b/internal/docs/grants.go
index a91518f..fd7e3e8 100644
--- a/internal/docs/grants.go
+++ b/internal/docs/grants.go
@@ -337,10 +337,13 @@ func (s *Store) CanWrite(ctx context.Context, a Actor, docID int64) bool {
// opened since spring. Which are yours the row answers itself, through
// docRow.SharedNote, without reordering the list.
func (s *Store) ListFor(ctx context.Context, a Actor) ([]*Document, error) {
+ return s.listForLimited(ctx, a, 0)
+}
+func (s *Store) listForLimited(ctx context.Context, a Actor, limit int) ([]*Document, error) {
var docs []*Document
err := s.permissionScope(ctx, s.db.WithContext(ctx), a, permissionRead).
Where("documents.deleted_at IS NULL").
- Order("documents.updated_at DESC, documents.id DESC").
+ Order("documents.updated_at DESC, documents.id DESC").Limit(limitOrUnlimited(limit)).
Find(&docs).Error
if err != nil {
return nil, s.permissionError(ctx, a, fmt.Errorf("docs: list readable documents: %w", err))
@@ -354,3 +357,10 @@ func (s *Store) ListFor(ctx context.Context, a Actor) ([]*Document, error) {
s.rememberResponse(ctx, permissionRead, docs...)
return docs, nil
}
+
+func limitOrUnlimited(n int) int {
+ if n <= 0 {
+ return -1
+ }
+ return n
+}
diff --git a/internal/docs/home_router_integration_test.go b/internal/docs/home_router_integration_test.go
index a86421c..4cfc169 100644
--- a/internal/docs/home_router_integration_test.go
+++ b/internal/docs/home_router_integration_test.go
@@ -31,6 +31,9 @@ type routerBrowser struct {
}
func newRouterHomeFixture(t *testing.T) *routerHomeFixture {
+ return newRouterHomeFixtureDirectory(t, "")
+}
+func newRouterHomeFixtureDirectory(t *testing.T, directory string) *routerHomeFixture {
t.Helper()
key, err := assertioncrypto.Generate()
if err != nil {
@@ -43,7 +46,7 @@ func newRouterHomeFixture(t *testing.T) *routerHomeFixture {
t.Fatal(err)
}
cfg := HomeConfig{Issuer: bridgeIssuer, ConsumerID: "router-docs", KeysBase64: base64.StdEncoding.EncodeToString(manifest), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{83}, 32))}
- app, err := NewForTestWith(t, Config{Origin: bridgeOrigin, Home: &cfg, AllowedAddresses: "alice@example.com,bob@example.com", SampleDocuments: "0", Mailer: navigationMail{}})
+ app, err := NewForTestWith(t, Config{Origin: bridgeOrigin, Directory: directory, Home: &cfg, AllowedAddresses: "alice@example.com,bob@example.com", SampleDocuments: "0", Mailer: navigationMail{}})
if err != nil {
t.Fatal(err)
}
diff --git a/internal/docs/team_router_test.go b/internal/docs/team_router_test.go
index 9b031f7..d28f683 100644
--- a/internal/docs/team_router_test.go
+++ b/internal/docs/team_router_test.go
@@ -71,6 +71,9 @@ type teamRouterFixture struct {
}
func newTeamRouterFixture(t *testing.T) *teamRouterFixture {
+ return newTeamRouterFixtureWithDashboard(t, false)
+}
+func newTeamRouterFixtureWithDashboard(t *testing.T, dashboard bool) *teamRouterFixture {
t.Helper()
ctx := t.Context()
credential, e := family.Generate()
@@ -140,6 +143,10 @@ func newTeamRouterFixture(t *testing.T) *teamRouterFixture {
}
keys, _ := json.Marshal([]roster.Key{{ID: "operator1", Public: base64.RawURLEncoding.EncodeToString(operator.SignPub())}})
cfg.Team = &TeamConfig{TeamID: binding.Team, DirectoryOrigin: binding.Directory, ProvisioningBase64: base64.StdEncoding.EncodeToString(wire), OperatorKeysBase64: base64.StdEncoding.EncodeToString(keys), RosterToken: fixed(7), clock: f.clock, transport: directory}
+ if dashboard {
+ t.Setenv("OFICINA_DASHBOARD_TEAM", binding.Team)
+ cfg.Directory = binding.Directory
+ }
app, e = New(cfg)
if e != nil {
t.Fatal(e)