From 23b5110101c8b048592dfa6ce8708ea28320fd42 Mon Sep 17 00:00:00 2001 From: reoring Date: Mon, 23 Nov 2026 21:48:50 +0900 Subject: [PATCH] feat(auth): dual-write console sharing and confirm access cutover Write legacy access first, persist synchronization state, and reconcile the fixed app-user binding with caller authority. Map Directory recipients to supplied Groups and organization-person references; keep organization membership disclosure separate and explicitly accepted. Show recipient diffs and require owner confirmation for activation or sealed-version restore; preserve Platform access:manage authority. Cover dual-write failure, approval, drift, cutover guards, organization controls, and generated Console contracts. --- README.md | 47 ++ cmd/server/console.go | 4 + cmd/server/internal/api/access_requests.go | 32 +- cmd/server/internal/api/api.go | 16 +- cmd/server/internal/api/api_test.go | 2 + cmd/server/internal/api/apps.go | 15 +- .../internal/api/console-spa.openapi.json | 642 ++++++++++++++++++ cmd/server/internal/api/share_binding.go | 353 ++++++++++ cmd/server/internal/api/share_binding_test.go | 263 +++++++ cmd/server/internal/api/share_management.go | 228 +++++++ cmd/server/internal/api/share_platform.go | 181 +++++ .../internal/api/testdata/console-wire.json | 32 + cmd/server/internal/api/wire_contract_test.go | 5 + cmd/server/internal/domain/model.go | 4 + cmd/server/internal/store/apps.go | 4 +- .../store/migrations/011_share_sync.sql | 3 + web/src/api/access.ts | 32 +- .../api/contracts/console/operations.test.ts | 3 +- web/src/api/contracts/console/operations.ts | 10 + .../contracts/console/schema/operations.ts | 6 + .../api/contracts/console/schema/schemas.ts | 3 + web/src/api/contracts/console/schema/share.ts | 27 + web/src/api/sharing.ts | 12 + web/src/copy/sharing.en.ts | 23 +- web/src/copy/sharing.ts | 23 +- web/src/features/app/share-dialog.tsx | 18 +- .../features/app/share-management.test.tsx | 110 +++ web/src/features/app/share-management.tsx | 96 +++ web/src/features/build/publish-step.tsx | 10 +- web/src/features/create/access.ts | 28 +- web/src/model/contracts/console.ts | 3 + web/test/dom.ts | 2 +- 32 files changed, 2175 insertions(+), 62 deletions(-) create mode 100644 cmd/server/internal/api/share_binding.go create mode 100644 cmd/server/internal/api/share_binding_test.go create mode 100644 cmd/server/internal/api/share_management.go create mode 100644 cmd/server/internal/api/share_platform.go create mode 100644 cmd/server/internal/store/migrations/011_share_sync.sql create mode 100644 web/src/api/contracts/console/schema/share.ts create mode 100644 web/src/api/sharing.ts create mode 100644 web/src/features/app/share-management.test.tsx create mode 100644 web/src/features/app/share-management.tsx diff --git a/README.md b/README.md index 4c257da..c493717 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,53 @@ creates and cleans an isolated schema per test; without a DSN those tests skip. DOM unit tests use the repository-local `web/test/dom.ts` preload from `web/bunfig.toml`, with no sibling Dashboard package dependency. +### Sharing and access cutover + +All Console sharing writes use the server's `applyAppShare`: app PATCH (including +owner/person changes), access-request approval, and post-bind `POST +/api/console/apps/{id}/share-sync`. Browsers no longer write publish policies. +Before cutover, the legacy policy is applied first and the Console policy plus +`shareRevision`/`shareSync=pending` commit before the fixed binding is replaced. +Binding failure leaves the legacy change intact and records `shareSync=conflict`. +The UI warns instead of reporting completion. The next authorized share change +replaces the fixed binding from the saved legacy policy; it does not union grants, +delete other bindings, or silently approve an access model. Approval remains +pending until both writes are confirmed. No credentials are stored. + +Platform contracts (under `/api/v1/projects/{project}/applications/{app}`): + +- `GET /role-bindings` supplies management authority, the fixed binding ETag, + organization capabilities and source synchronization status. +- `GET /access/share-groups?externalId=...` maps Directory IDs to supplied + `bindingGroupName` and `sourceUID`. `PUT /role-bindings/share` replaces only + `role: app-user`, `subjects`, and optional `organizationPersonRefs`. + It uses `Idempotency-Key` and `If-Match`, or `If-None-Match: *` on creation. +- Company means `Authenticated`; group means supplied `Group` references plus + explicit people; private means owners and invited people; public means an empty + fixed binding. People use `{sourceUID,personID}` even before identity linking: + being added to sharing is not proof that the person can sign in yet. +- Organization membership disclosure is a separate normal binding POST/DELETE. + It requires explicit model acceptance, an eligible role and a ready source. + The dialog distinguishes absent source, first sync pending and unavailable + status, and retains existing assignments for removal during source outages. +- `GET /access-cutover/diff` supplies bounded gaining/losing member samples and + a revision-bound digest. Only an explicit owner confirmation sends `POST + /access-cutover` with `direction`, `candidateDigest`, `expectedApplicationUID`, + `expectedShareRevision`, `expectedBindingETag` and `confirmedDiffDigest`. + The server rereads the diff and rejects stale or unresolved comparisons. + `GET /access-cutover` supplies progress; `AppEnforced` writes bindings only. + Legacy reapplication is rejected after cutover. + After activation, the restore action requires another explicit owner confirmation + and echoes only Platform's sealed `previousDigest` as `candidateDigest` with + `direction: restore`; the Console never accepts a user-chosen previous version. + +Every Platform call uses the current operator's bearer and Platform checks +`access:manage`. Console ownership changes **do not** grant `access-manager`. +Creator bootstrap and explicit Platform assignments remain its only sources; +cutover additionally requires Console ownership. Thus an owner without Platform +management authority cannot share or confirm cutover. No Console admin or +Directory-manager flag substitutes for that authority. + From `web/`, run `bun run mock` and `bun run dev` in separate terminals. The default ports are 54385 for the mock API and 5199 for Vite; set `CONSOLE_MOCK_PORT` and `CONSOLE_PORT` to isolate concurrent work. Neither command requires a live Platform. diff --git a/cmd/server/console.go b/cmd/server/console.go index f1c41b7..8b0d231 100644 --- a/cmd/server/console.go +++ b/cmd/server/console.go @@ -102,6 +102,10 @@ func consoleHandler(upstreamURL, projectID string) (*consoleAPI, func(), error) return nil, err } connected := api.New(database, auth, upstream, links, publicURL) + if err := connected.ConfigureSharing(upstreamURL, auth.HTTPClient().Transport); err != nil { + _ = database.Close() + return nil, err + } connected.ConfigureBuildSessions(conversations, installationID) connected.ConfigureConsoleAuthority(conversationPlatform) console.current.Store(connected) diff --git a/cmd/server/internal/api/access_requests.go b/cmd/server/internal/api/access_requests.go index 6d5cd2f..49b00ec 100644 --- a/cmd/server/internal/api/access_requests.go +++ b/cmd/server/internal/api/access_requests.go @@ -9,6 +9,7 @@ import ( "unicode/utf8" "github.com/appthrust/builder-console/cmd/server/internal/domain" + "github.com/appthrust/builder-console/cmd/server/internal/store" "github.com/google/uuid" ) @@ -175,22 +176,31 @@ func (a *API) approveAccessRequest(s *request) (any, int, error) { } requester := domain.NewActor(r.Requester.ID, domain.Roles{}, effectiveGroups, s.groups) updated := domain.ApproveAccess(app, r.Requester.ID, requester.Visible(app)) - // route runs this handler in one write transaction under the store lock. + // Commit legacy intent first. Approval is final only after binding readback. if err := s.tx.SaveApp(app, updated); err != nil { return nil, 0, err } - if err := s.tx.DecideAccessRequest(r.ID, domain.RequestApproved, s.person.ID, time.Now().UTC()); err != nil { - return nil, 0, err - } - r, err = s.tx.AccessRequest(r.ID) - if err != nil { - return nil, 0, err - } - updated, err = s.tx.App(app.ID) - return struct { + result := struct { Request domain.AppAccessRequest `json:"request"` App domain.App `json:"app"` - }{r, s.appForCaller(updated)}, http.StatusOK, err + }{r, s.appForCaller(updated)} + decide := func(tx *store.Tx) error { + if err := tx.DecideAccessRequest(r.ID, domain.RequestApproved, s.person.ID, time.Now().UTC()); err != nil { + return err + } + tx.HydratePeople = s.directory.People + var err error + result.Request, err = tx.AccessRequest(r.ID) + return err + } + if app.Bound() { + if err := a.applyAppShare(s, &result.App, decide); err != nil { + return nil, 0, err + } + } else if err := decide(s.tx); err != nil { + return nil, 0, err + } + return &result, http.StatusOK, nil } func (a *API) declineAccessRequest(s *request) (any, int, error) { diff --git a/cmd/server/internal/api/api.go b/cmd/server/internal/api/api.go index aa1a187..caed0e7 100644 --- a/cmd/server/internal/api/api.go +++ b/cmd/server/internal/api/api.go @@ -38,6 +38,7 @@ type API struct { builds *buildsession.Service installationID string authorityStacks consoleStackReader + sharing *sharePlatform } type request struct { @@ -55,6 +56,7 @@ type request struct { claims identity.Identity authorityApps map[authorityRoute][]domain.App authorityStackCache map[string]buildsession.ConsoleStack + afterCommit func() error } type endpoint func(*request) (any, int, error) @@ -83,6 +85,12 @@ func New(database *store.Store, auth *identity.Authenticator, upstream *platform // Creation and binding resolve fresh Directory authority before the transaction. a.mux.HandleFunc("POST /api/console/apps", a.routeHandlerMode(true, true, true, true, a.createApp)) a.route("PATCH /api/console/apps/{id}", true, true, a.patchApp) + a.route("POST /api/console/apps/{id}/share-sync", true, true, a.syncAppShare) + a.route("GET /api/console/apps/{id}/share-access", false, true, a.shareAccess) + a.route("POST /api/console/apps/{id}/organization-groups", true, true, a.assignOrganizationGroups) + a.route("DELETE /api/console/apps/{id}/organization-groups/{binding}", true, true, a.removeOrganizationGroups) + a.route("GET /api/console/apps/{id}/share-diff", false, true, a.shareDiff) + a.route("POST /api/console/apps/{id}/access-cutover", true, true, a.startAccessCutover) a.mux.HandleFunc("POST /api/console/apps/{id}/bind", a.routeHandlerMode(true, true, true, true, a.bindApp)) a.route("DELETE /api/console/apps/{id}", true, true, a.deleteApp) a.route("GET /api/console/apps/{id}/comments", false, true, a.comments) @@ -231,12 +239,16 @@ func (a *API) routeHandlerMode(mutation, needsRoles, transactional, fresh bool, // uncached Directory view as build sessions before opening the transaction. func (a *API) withRequest(ctx context.Context, claims identity.Identity, bearer string, mutation, needsRoles, me, fresh bool, handler func(*request) error) error { return a.withResolvedRequest(ctx, claims, bearer, needsRoles, me, fresh, func(state *request) error { - return directoryError(a.store.Do(ctx, mutation, func(tx *store.Tx) error { + err := a.store.Do(ctx, mutation, func(tx *store.Tx) error { state.tx = tx tx.DirectoryGroups = state.groups tx.HydratePeople = state.directory.People return handler(state) - })) + }) + if err == nil && state.afterCommit != nil { + err = state.afterCommit() + } + return directoryError(err) }) } diff --git a/cmd/server/internal/api/api_test.go b/cmd/server/internal/api/api_test.go index 0832871..cc42c25 100644 --- a/cmd/server/internal/api/api_test.go +++ b/cmd/server/internal/api/api_test.go @@ -31,6 +31,7 @@ type harness struct { stackBearer atomic.Value stacks atomic.Value database *store.Store + sharing *shareFixture } func token(subject string) string { @@ -94,6 +95,7 @@ func newHarness(t *testing.T) *harness { } h.server = httptest.NewServer(New(database, auth, platform.New(upstream.URL, "pj-test"), h.directory.client(t), "")) t.Cleanup(h.server.Close) + h.sharing = installShareFixture(t, h) return h } diff --git a/cmd/server/internal/api/apps.go b/cmd/server/internal/api/apps.go index 7f27685..0d1a3ad 100644 --- a/cmd/server/internal/api/apps.go +++ b/cmd/server/internal/api/apps.go @@ -65,6 +65,10 @@ func (a *API) app(s *request) (any, int, error) { if !s.actor.Visible(app) { return nil, 0, httpx.NotFound() } + if app.Bound() && app.AppName != nil && a.sharing != nil { + bindings, err := a.sharing.bindings(s.r.Context(), s.bearer, *app.AppName) + app.CanManageShare = err == nil && bindings.CanManageBindings + } return s.appForCaller(app), 200, nil } @@ -332,7 +336,16 @@ func (a *API) patchApp(s *request) (any, int, error) { return nil, 0, err } updated, err = s.tx.App(app.ID) - return s.appForCaller(updated), 200, err + if err != nil { + return nil, 0, err + } + if input.Share != nil || input.OwnerIDs != nil { + if err := a.applyAppShare(s, &updated, nil); err != nil { + return nil, 0, err + } + } + updated = s.appForCaller(updated) + return &updated, 200, nil } func (a *API) bindApp(s *request) (any, int, error) { diff --git a/cmd/server/internal/api/console-spa.openapi.json b/cmd/server/internal/api/console-spa.openapi.json index 75a843b..23bfc3f 100644 --- a/cmd/server/internal/api/console-spa.openapi.json +++ b/cmd/server/internal/api/console-spa.openapi.json @@ -566,6 +566,242 @@ } } }, + "/apps/{id}/share-sync": { + "post": { + "operationId": "consoleSyncShare", + "x-console-operation-id": "consoleSyncShare", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/App" + } + } + } + }, + "default": { + "description": "HTTP error; never a success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/apps/{id}/share-access": { + "get": { + "operationId": "consoleGetShareAccess", + "x-console-operation-id": "consoleGetShareAccess", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareManagement" + } + } + } + }, + "default": { + "description": "HTTP error; never a success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/apps/{id}/organization-groups": { + "post": { + "operationId": "consoleAssignOrganizationGroups", + "x-console-operation-id": "consoleAssignOrganizationGroups", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareManagement" + } + } + } + }, + "default": { + "description": "HTTP error; never a success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/apps/{id}/organization-groups/{binding}": { + "delete": { + "operationId": "consoleRemoveOrganizationGroups", + "x-console-operation-id": "consoleRemoveOrganizationGroups", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "binding", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareManagement" + } + } + } + }, + "default": { + "description": "HTTP error; never a success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/apps/{id}/share-diff": { + "get": { + "operationId": "consoleGetShareDiff", + "x-console-operation-id": "consoleGetShareDiff", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareDiff" + } + } + } + }, + "default": { + "description": "HTTP error; never a success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/apps/{id}/access-cutover": { + "post": { + "operationId": "consoleStartAccessCutover", + "x-console-operation-id": "consoleStartAccessCutover", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "202": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareCutover" + } + } + } + }, + "default": { + "description": "HTTP error; never a success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/apps/{id}/directory-entry": { "get": { "operationId": "consoleGetDirectoryEntry", @@ -11076,6 +11312,342 @@ ], "additionalProperties": false }, + "ShareManagement": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "bindings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "role": { + "type": "string", + "minLength": 1 + }, + "subjects": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "name": { + "type": "string" + }, + "issuer": { + "type": "string" + }, + "subject": { + "type": "string" + } + }, + "required": [ + "kind" + ] + } + }, + "organizationPersonRefs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "sourceUID": { + "type": "string", + "minLength": 1 + }, + "personID": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "sourceUID", + "personID" + ] + } + }, + "organizationGroupSourceRef": { + "type": "object", + "properties": { + "sourceUID": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "sourceUID" + ] + }, + "managedFor": { + "type": "string" + }, + "etag": { + "type": "string" + } + }, + "required": [ + "name", + "role", + "subjects" + ] + } + }, + "canManageBindings": { + "type": "boolean" + }, + "isOwner": { + "type": "boolean" + }, + "shareSync": { + "type": "string" + }, + "organizationGroups": { + "type": "object", + "properties": { + "declared": { + "type": "boolean" + }, + "accepted": { + "type": "boolean" + }, + "roles": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + }, + "required": [ + "declared", + "accepted", + "roles" + ] + }, + "organizationSource": { + "type": "object", + "properties": { + "sourceUID": { + "type": "string", + "minLength": 1 + }, + "ready": { + "type": "boolean" + }, + "initialSyncComplete": { + "type": "boolean" + }, + "appliedVersion": { + "type": "string" + }, + "consecutiveFailures": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "sourceUID", + "ready", + "initialSyncComplete", + "appliedVersion", + "consecutiveFailures" + ] + }, + "cutover": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "applicationUID": { + "type": "string" + }, + "direction": { + "type": "string" + }, + "phase": { + "type": "string", + "minLength": 1 + }, + "reason": { + "type": "string" + }, + "previousDigest": { + "type": "string" + }, + "cookieIsolationVerified": { + "type": "boolean" + } + }, + "required": [ + "id", + "applicationUID", + "direction", + "phase", + "reason", + "previousDigest", + "cookieIsolationVerified" + ] + } + }, + "required": [ + "bindings", + "canManageBindings", + "isOwner", + "shareSync", + "organizationGroups" + ] + }, + "ShareDiff": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "applicationUID": { + "type": "string", + "minLength": 1 + }, + "candidateDigest": { + "type": "string" + }, + "diffDigest": { + "type": "string", + "minLength": 1 + }, + "shareRevision": { + "type": "string", + "minLength": 1 + }, + "bindingETag": { + "type": "string", + "minLength": 1 + }, + "addedCount": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "removedCount": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "unresolvedCount": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "added": { + "maxItems": 20, + "type": "array", + "items": { + "type": "object", + "properties": { + "principal": { + "type": "string", + "minLength": 1 + }, + "displayName": { + "type": "string" + } + }, + "required": [ + "principal" + ] + } + }, + "removed": { + "maxItems": 20, + "type": "array", + "items": { + "type": "object", + "properties": { + "principal": { + "type": "string", + "minLength": 1 + }, + "displayName": { + "type": "string" + } + }, + "required": [ + "principal" + ] + } + }, + "oldAuthenticated": { + "type": "boolean" + }, + "newAuthenticated": { + "type": "boolean" + } + }, + "required": [ + "applicationUID", + "candidateDigest", + "diffDigest", + "shareRevision", + "bindingETag", + "addedCount", + "removedCount", + "unresolvedCount", + "added", + "removed", + "oldAuthenticated", + "newAuthenticated" + ] + }, + "ShareCutover": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "resource": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "applicationUID": { + "type": "string" + }, + "direction": { + "type": "string" + }, + "phase": { + "type": "string", + "minLength": 1 + }, + "reason": { + "type": "string" + }, + "previousDigest": { + "type": "string" + }, + "cookieIsolationVerified": { + "type": "boolean" + } + }, + "required": [ + "id", + "applicationUID", + "direction", + "phase", + "reason", + "previousDigest", + "cookieIsolationVerified" + ] + } + }, + "required": [ + "resource" + ] + }, "ConversationSetting": { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", @@ -11925,6 +12497,20 @@ "data" ], "additionalProperties": false + }, + "shareRevision": { + "presence": "optionalObservation", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "shareSync": { + "presence": "optionalObservation", + "type": "string" + }, + "canManageShare": { + "presence": "optionalObservation", + "type": "boolean" } }, "required": [ @@ -12280,6 +12866,20 @@ "data" ], "additionalProperties": false + }, + "shareRevision": { + "presence": "optionalObservation", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "shareSync": { + "presence": "optionalObservation", + "type": "string" + }, + "canManageShare": { + "presence": "optionalObservation", + "type": "boolean" } }, "required": [ @@ -12530,6 +13130,20 @@ ], "additionalProperties": false }, + "shareRevision": { + "presence": "optionalObservation", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "shareSync": { + "presence": "optionalObservation", + "type": "string" + }, + "canManageShare": { + "presence": "optionalObservation", + "type": "boolean" + }, "path": { "type": "string" }, @@ -12781,6 +13395,20 @@ ], "additionalProperties": false }, + "shareRevision": { + "presence": "optionalObservation", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "shareSync": { + "presence": "optionalObservation", + "type": "string" + }, + "canManageShare": { + "presence": "optionalObservation", + "type": "boolean" + }, "path": { "type": "string" }, @@ -14469,6 +15097,20 @@ "data" ], "additionalProperties": false + }, + "shareRevision": { + "presence": "optionalObservation", + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "shareSync": { + "presence": "optionalObservation", + "type": "string" + }, + "canManageShare": { + "presence": "optionalObservation", + "type": "boolean" } }, "required": [ diff --git a/cmd/server/internal/api/share_binding.go b/cmd/server/internal/api/share_binding.go new file mode 100644 index 0000000..f56bf46 --- /dev/null +++ b/cmd/server/internal/api/share_binding.go @@ -0,0 +1,353 @@ +package api + +import ( + "cmp" + "encoding/json" + "fmt" + "net/http" + "net/url" + "slices" + "sort" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/builder-console/cmd/server/internal/domain" + "github.com/appthrust/builder-console/cmd/server/internal/store" +) + +// shareRecipients never turns Directory IDs into Platform names or treats an +// unlinked person as a pending invitation. Source validation belongs to Platform. +func shareRecipients(app domain.App, bindings shareBindings, groups []shareGroup) (shareBindingInput, error) { + out := shareBindingInput{Role: "app-user", Subjects: []shareSubject{}} + switch app.Share.Scope { + case "public": + return out, nil + case "company": + out.Subjects = append(out.Subjects, shareSubject{Kind: "Authenticated"}) + return out, nil + case "private", "group": + default: + return out, httpx.Invalid("Unknown share scope") + } + if bindings.OrganizationSource == nil || bindings.OrganizationSource.SourceUID == "" || !bindings.OrganizationSource.InitialSyncComplete { + return out, httpx.Fail(422, "organization_source_unavailable", "The organization source is not installed or has not completed its first sync") + } + if app.Share.Scope == "group" { + for _, id := range app.Share.GroupIDs { + var match string + for _, group := range groups { + if group.ExternalID != id { + continue + } + if match != "" || group.BindingGroupName == "" || group.SourceUID != bindings.OrganizationSource.SourceUID { + return out, httpx.Fail(422, "share_group_unavailable", "A Directory group has no unique supplied Platform Group") + } + match = group.BindingGroupName + } + if match == "" { + return out, httpx.Fail(422, "share_group_unavailable", "A Directory group has no unique supplied Platform Group") + } + out.Subjects = append(out.Subjects, shareSubject{Kind: "Group", Name: match}) + } + } + ids := make([]string, 0, len(app.Owners)+len(app.Share.ExtraPersonIDs)) + for _, owner := range app.Owners { + ids = append(ids, owner.ID) + } + ids = append(ids, app.Share.ExtraPersonIDs...) + sort.Strings(ids) + for _, id := range slices.Compact(ids) { + out.OrganizationPersonRefs = append(out.OrganizationPersonRefs, organizationPersonRef{SourceUID: bindings.OrganizationSource.SourceUID, PersonID: id}) + } + sort.Slice(out.Subjects, func(i, j int) bool { return out.Subjects[i].Name < out.Subjects[j].Name }) + out.Subjects = slices.Compact(out.Subjects) + return out, nil +} + +type legacyAccess struct { + Mode string `json:"mode"` + Pending json.RawMessage `json:"pending"` + Authorization *struct { + External *struct { + AppInstallation string `json:"appInstallation"` + Path string `json:"path"` + } `json:"external"` + } `json:"authorization"` +} +type sharePublish struct { + ID string `json:"id"` + ApplicationID string `json:"applicationId"` + Access legacyAccess `json:"access"` +} + +func legacyMatches(access legacyAccess, scope string) bool { + if len(access.Pending) > 0 && string(access.Pending) != "null" { + return false + } + external := access.Authorization != nil && access.Authorization.External != nil + if scope == "public" { + return access.Mode == "Public" && !external + } + if access.Mode != "Authenticated" { + return false + } + if scope == "company" { + return !external + } + return external && access.Authorization.External.AppInstallation == "builder-console" && access.Authorization.External.Path == "/authz" +} + +func (a *API) sharePublishes(s *request) ([]sharePublish, error) { + var publishes struct { + Data []sharePublish `json:"data"` + Meta struct { + Total int `json:"total"` + NextCursor string `json:"nextCursor"` + } `json:"meta"` + } + if err := a.sharing.call(s.r.Context(), s.bearer, "GET", "/publishes", nil, nil, &publishes); err != nil { + return nil, err + } + if publishes.Data == nil || publishes.Meta.Total > len(publishes.Data) || publishes.Meta.NextCursor != "" { + return nil, upstreamError() + } + return publishes.Data, nil +} + +func (a *API) writeLegacyShare(s *request, app domain.App) error { + publishes, err := a.sharePublishes(s) + if err != nil { + return err + } + p := a.sharing + found := false + for _, publish := range publishes { + if publish.ApplicationID != *app.AppName { + continue + } + found = true + body := map[string]any{"mode": "Authenticated"} + if app.Share.Scope == "public" { + body["mode"] = "Public" + } + if app.Share.Scope == "private" || app.Share.Scope == "group" { + body["externalAuthorization"] = map[string]string{"appInstallation": "builder-console"} + } + var access legacyAccess + headers := http.Header{"Idempotency-Key": {fmt.Sprintf("console-share:%s:%d:%s:%s", app.ID, app.ShareRevision+1, publish.ID, app.Share.Scope)}} + if err := p.call(s.r.Context(), s.bearer, "PUT", "/publishes/"+url.PathEscape(publish.ID)+"/access", body, headers, &access); err != nil { + return err + } + if !legacyMatches(access, app.Share.Scope) { + // An idempotency replay can contain the earlier pending answer. + // Only a fresh observed policy, not that receipt, confirms readiness. + readback, err := a.sharePublishes(s) + if err != nil { + return err + } + if !slices.ContainsFunc(readback, func(observed sharePublish) bool { + return observed.ID == publish.ID && observed.ApplicationID == *app.AppName && legacyMatches(observed.Access, app.Share.Scope) + }) { + return httpx.Fail(409, "share_policy_pending", "The legacy access policy has not been applied; reload before saving") + } + } + } + if !found { + return httpx.Fail(409, "share_publish_pending", "The app URL is not ready for sharing") + } + return nil +} + +// applyAppShare is the only Console sharing writer. The old policy is written +// first. Intent + pending revision commit together before the binding write. +// A failed binding cannot roll back the already-enforced legacy policy. The next +// explicit change replaces only the fixed binding from the current legacy intent; +// it never unions external grants or changes model acceptance. +func (a *API) applyAppShare(s *request, app *domain.App, approved func(*store.Tx) error) error { + if !app.Bound() { + return nil + } + if app.AppName == nil || a.sharing == nil { + return upstreamError() + } + bindings, err := a.sharing.bindings(s.r.Context(), s.bearer, *app.AppName) + if err != nil { + return err + } + app.CanManageShare = bindings.CanManageBindings + cutover, err := a.sharing.cutover(s.r.Context(), s.bearer, *app.AppName) + if err != nil { + return err + } + strict := cutover != nil && cutover.Phase == "AppEnforced" + if cutover != nil && !strict && cutover.Phase != "Prepared" && cutover.Phase != "GuardServing" && cutover.Phase != "Restored" { + return httpx.Conflict("Sharing cannot change during access cutover") + } + if strict { + // After cutover Platform is authoritative. A failed binding write must + // leave the Console projection unchanged, not persist new legacy intent. + app.ShareRevision++ + etag, err := a.replaceShareBinding(s, *app) + if err != nil { + return err + } + app.ShareSync = "applied" + if err := s.tx.Exec(`UPDATE apps SET share_revision=$2,share_sync='applied',share_binding_etag=$3 WHERE id=$1`, app.ID, app.ShareRevision, etag); err != nil { + return err + } + if approved != nil { + return approved(s.tx) + } + return nil + } + if err := a.writeLegacyShare(s, *app); err != nil { + return err + } + app.ShareRevision++ + app.ShareSync = "pending" + if err := s.tx.Exec(`UPDATE apps SET share_revision=$2,share_sync='pending' WHERE id=$1`, app.ID, app.ShareRevision); err != nil { + return err + } + s.afterCommit = func() error { + var bindingError error + err := a.store.Do(s.r.Context(), true, func(tx *store.Tx) error { + var revision int64 + if err := tx.SQL.QueryRowContext(tx.Context, `SELECT share_revision FROM apps WHERE id=$1`, app.ID).Scan(&revision); err != nil { + return err + } + if revision != app.ShareRevision { + return httpx.Conflict("Sharing changed; reload before saving") + } + etag, err := a.replaceShareBinding(s, *app) + bindingError = err + app.ShareSync = "applied" + if err != nil { + app.ShareSync = "conflict" + } + if err := tx.Exec(`UPDATE apps SET share_sync=$2,share_binding_etag=$3 WHERE id=$1`, app.ID, app.ShareSync, etag); err != nil { + return err + } + if bindingError == nil && approved != nil { + return approved(tx) + } + return nil + }) + if err != nil { + return err + } + if approved != nil && bindingError != nil { + return httpx.Fail(409, "share_diverged", "Legacy access was saved, but the binding was not confirmed; retry approval to reconcile") + } + return nil + } + return nil +} + +func (a *API) replaceShareBinding(s *request, app domain.App) (string, error) { + p := a.sharing + bindings, err := p.bindings(s.r.Context(), s.bearer, *app.AppName) + if err != nil { + return "", err + } + var groups struct { + Data []shareGroup `json:"data"` + } + if app.Share.Scope == "group" { + query := url.Values{} + for _, id := range app.Share.GroupIDs { + query.Add("externalId", id) + } + if err := p.call(s.r.Context(), s.bearer, "GET", p.appPath(*app.AppName)+"/access/share-groups?"+query.Encode(), nil, nil, &groups); err != nil { + return "", err + } + } + input, err := shareRecipients(app, bindings, groups.Data) + if err != nil { + return "", err + } + headers := http.Header{"Idempotency-Key": {fmt.Sprintf("console-share:%s:%d", app.ID, app.ShareRevision)}, "If-None-Match": {"*"}} + for _, binding := range bindings.Bindings { + if binding.ManagedFor != "share" { + continue + } + if binding.ETag == "" { + return "", upstreamError() + } + headers.Del("If-None-Match") + headers.Set("If-Match", binding.ETag) + } + var response struct { + Resource shareBinding `json:"resource"` + } + if err := p.call(s.r.Context(), s.bearer, "PUT", p.appPath(*app.AppName)+"/role-bindings/share", input, headers, &response); err != nil { + return "", err + } + if response.Resource.ManagedFor != "share" || response.Resource.ETag == "" { + return "", upstreamError() + } + readback, err := p.bindings(s.r.Context(), s.bearer, *app.AppName) + if err != nil { + return "", err + } + for _, binding := range readback.Bindings { + if binding.ManagedFor == "share" && binding.ETag == response.Resource.ETag && sameShareBinding(binding, input) { + return binding.ETag, nil + } + } + return "", httpx.Conflict("The sharing binding has not been confirmed") +} + +func sameShareBinding(binding shareBinding, input shareBindingInput) bool { + // Platform normalizes sets; compare without depending on server ordering. + subjects := func(v []shareSubject) []shareSubject { + v = slices.Clone(v) + slices.SortFunc(v, func(a, b shareSubject) int { + if n := cmp.Compare(a.Kind, b.Kind); n != 0 { + return n + } + if n := cmp.Compare(a.Name, b.Name); n != 0 { + return n + } + if n := cmp.Compare(a.Issuer, b.Issuer); n != 0 { + return n + } + return cmp.Compare(a.Subject, b.Subject) + }) + return v + } + people := func(v []organizationPersonRef) []organizationPersonRef { + v = slices.Clone(v) + slices.SortFunc(v, func(a, b organizationPersonRef) int { + if n := cmp.Compare(a.SourceUID, b.SourceUID); n != 0 { + return n + } + return cmp.Compare(a.PersonID, b.PersonID) + }) + return v + } + return binding.Role == input.Role && slices.Equal(subjects(binding.Subjects), subjects(input.Subjects)) && slices.Equal(people(binding.OrganizationPersonRefs), people(input.OrganizationPersonRefs)) +} + +func (a *API) syncAppShare(s *request) (any, int, error) { + app, err := s.editableApp() + if err != nil { + return nil, 0, err + } + if !app.Bound() { + return nil, 0, httpx.Conflict("The app is not bound") + } + if app.AppName == nil { + return nil, 0, httpx.NotFound() + } + cutover, err := a.sharing.cutover(s.r.Context(), s.bearer, *app.AppName) + if err != nil { + return nil, 0, err + } + if cutover != nil && cutover.Phase == "AppEnforced" { + return nil, 0, httpx.Conflict("Legacy sharing cannot be reapplied after cutover") + } + if err := a.applyAppShare(s, &app, nil); err != nil { + return nil, 0, err + } + app = s.appForCaller(app) + return &app, 200, nil +} diff --git a/cmd/server/internal/api/share_binding_test.go b/cmd/server/internal/api/share_binding_test.go new file mode 100644 index 0000000..ea42827 --- /dev/null +++ b/cmd/server/internal/api/share_binding_test.go @@ -0,0 +1,263 @@ +package api + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/builder-console/cmd/server/internal/domain" + "github.com/stretchr/testify/require" +) + +func readyShareBindings() shareBindings { + var result shareBindings + _ = json.Unmarshal([]byte(`{"bindings":[],"canManageBindings":true,"organizationGroups":{"declared":false,"accepted":false,"roles":[]},"organizationSource":{"sourceUID":"source","ready":true,"initialSyncComplete":true,"appliedVersion":"1","consecutiveFailures":0}}`), &result) + return result +} + +func TestShareRecipients(t *testing.T) { + app := domain.App{Owners: []domain.Person{{ID: "owner"}}, Share: domain.SharePolicy{GroupIDs: []string{"directory-team"}, ExtraPersonIDs: []string{"unlinked", "owner"}}} + for _, scope := range []string{"company", "group", "private", "public"} { + t.Run(scope, func(t *testing.T) { + app.Share.Scope = scope + got, err := shareRecipients(app, readyShareBindings(), []shareGroup{{ExternalID: "directory-team", BindingGroupName: "supplied-team", SourceUID: "source"}}) + require.NoError(t, err) + require.Equal(t, "app-user", got.Role) + switch scope { + case "company": + require.Equal(t, []shareSubject{{Kind: "Authenticated"}}, got.Subjects) + require.Empty(t, got.OrganizationPersonRefs) + case "public": + require.Empty(t, got.Subjects) + require.Empty(t, got.OrganizationPersonRefs) + default: + require.Equal(t, []organizationPersonRef{{SourceUID: "source", PersonID: "owner"}, {SourceUID: "source", PersonID: "unlinked"}}, got.OrganizationPersonRefs) + if scope == "group" { + require.Equal(t, []shareSubject{{Kind: "Group", Name: "supplied-team"}}, got.Subjects) + } else { + require.Empty(t, got.Subjects) + } + } + }) + } + app.Share.Scope = "group" + _, err := shareRecipients(app, readyShareBindings(), nil) + require.ErrorContains(t, err, "share_group_unavailable") + _, err = shareRecipients(app, readyShareBindings(), []shareGroup{{ExternalID: "directory-team", BindingGroupName: "wrong", SourceUID: "other"}}) + require.ErrorContains(t, err, "share_group_unavailable") + _, err = shareRecipients(app, shareBindings{}, nil) + require.ErrorContains(t, err, "organization_source_unavailable") +} + +type shareFixture struct { + bindings shareBindings + writes []string + bearers []string + failBinding bool + bindingWrites []shareBindingInput + phase string + diff shareDiffResponse + appName string + legacy map[string]any +} + +func installShareFixture(t *testing.T, h *harness) *shareFixture { + t.Helper() + if h.sharing != nil { + return h.sharing + } + f := &shareFixture{bindings: readyShareBindings(), diff: shareDiffResponse{ApplicationUID: "uid", CandidateDigest: "sha256:candidate", DiffDigest: "diff", ShareRevision: "revision", BindingETag: `"etag"`, Added: []shareDiffMember{}, Removed: []shareDiffMember{}}} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + f.writes = append(f.writes, r.Method+" "+r.URL.Path) + f.bearers = append(f.bearers, r.Header.Get("Authorization")) + } + switch { + case strings.HasSuffix(r.URL.Path, "/access/share-groups"): + groups := make([]shareGroup, 0, len(r.URL.Query()["externalId"])) + for _, id := range r.URL.Query()["externalId"] { + groups = append(groups, shareGroup{ExternalID: id, BindingGroupName: "supplied-" + id, SourceUID: "source"}) + } + httpx.WriteJSON(w, 200, map[string]any{"data": groups}) + case strings.HasSuffix(r.URL.Path, "/access-cutover/diff"): + httpx.WriteJSON(w, 200, f.diff) + case strings.HasSuffix(r.URL.Path, "/access-cutover"): + if r.Method == "POST" { + var input map[string]any + require.NoError(t, json.NewDecoder(r.Body).Decode(&input)) + require.NotContains(t, input, "confirmed") + require.Equal(t, f.diff.DiffDigest, input["confirmedDiffDigest"]) + if input["direction"] == "restore" { + require.Equal(t, "sha256:previous", input["candidateDigest"]) + } + f.phase = "Prepared" + } + if f.phase == "" { + w.WriteHeader(404) + } else { + httpx.WriteJSON(w, 200, cutoverResult{Resource: cutoverResource{Phase: f.phase, PreviousDigest: "sha256:previous"}}) + } + case strings.HasSuffix(r.URL.Path, "/role-bindings/share"): + var input shareBindingInput + require.NoError(t, json.NewDecoder(r.Body).Decode(&input)) + f.bindingWrites = append(f.bindingWrites, input) + if f.failBinding { + w.WriteHeader(503) + return + } + if len(f.bindings.Bindings) == 0 { + require.Equal(t, "*", r.Header.Get("If-None-Match")) + } else { + require.Equal(t, `"etag"`, r.Header.Get("If-Match")) + } + binding := shareBinding{Name: "fixed-share", Role: input.Role, Subjects: input.Subjects, OrganizationPersonRefs: input.OrganizationPersonRefs, ETag: `"etag"`, ManagedFor: "share"} + f.bindings.Bindings = []shareBinding{binding} + httpx.WriteJSON(w, 200, map[string]any{"resource": binding}) + case strings.HasSuffix(r.URL.Path, "/role-bindings"): + parts := strings.Split(r.URL.Path, "/") + f.appName = parts[len(parts)-2] + httpx.WriteJSON(w, 200, f.bindings) + case strings.HasSuffix(r.URL.Path, "/publishes"): + httpx.WriteJSON(w, 200, map[string]any{"data": []any{map[string]any{"id": "publish", "applicationId": f.appName, "access": f.legacy}}}) + case strings.HasSuffix(r.URL.Path, "/publishes/publish/access"): + var input struct { + Mode string `json:"mode"` + External any `json:"externalAuthorization"` + } + require.NoError(t, json.NewDecoder(r.Body).Decode(&input)) + access := map[string]any{"mode": input.Mode} + if input.External != nil { + access["authorization"] = map[string]any{"external": map[string]string{"appInstallation": "builder-console", "path": "/authz"}} + } + f.legacy = access + httpx.WriteJSON(w, 200, access) + default: + t.Errorf("unexpected share request %s %s", r.Method, r.URL.Path) + w.WriteHeader(404) + } + })) + t.Cleanup(server.Close) + require.NoError(t, h.server.Config.Handler.(*API).ConfigureSharing(server.URL, nil)) + return f +} + +func boundShareApp(t *testing.T, h *harness) domain.App { + group := createTestGroup(h, "share", nil) + app := createRequestTestApp(h, group, "Shared app") + return call[domain.App](h, "editor", "POST", "/apps/"+app.ID+"/bind", map[string]string{"stackId": "stack", "appName": "bound-app"}, 200) +} + +func TestShareDualWriteIntegration(t *testing.T) { + h := newHarness(t) + f := installShareFixture(t, h) + app := boundShareApp(t, h) + f.failBinding = true + changed := call[domain.App](h, "editor", "PATCH", "/apps/"+app.ID, map[string]any{"share": domain.SharePolicy{Scope: "company"}}, 200) + require.Equal(t, "conflict", changed.ShareSync) + require.Equal(t, []string{"PUT /api/v1/projects/pj-test/publishes/publish/access", "PUT /api/v1/projects/pj-test/applications/bound-app/role-bindings/share"}, f.writes) + readback := call[domain.App](h, "editor", "GET", "/apps/"+app.ID, nil, 200) + require.Equal(t, "company", readback.Share.Scope) + require.Equal(t, "conflict", readback.ShareSync) + f.failBinding = false + changed = call[domain.App](h, "editor", "POST", "/apps/"+app.ID+"/share-sync", nil, 200) + require.Equal(t, "applied", changed.ShareSync) + require.Equal(t, int64(2), changed.ShareRevision) + require.Equal(t, []shareSubject{{Kind: "Authenticated"}}, f.bindingWrites[1].Subjects) + for _, bearer := range f.bearers { + require.Equal(t, "Bearer "+token("editor"), bearer) + } + f.bindings.Bindings[0].ETag = `"external-change"` + management := call[shareManagement](h, "editor", "GET", "/apps/"+app.ID+"/share-access", nil, 200) + require.Equal(t, "conflict", management.ShareSync) + call[httpx.Error](h, "editor", "GET", "/apps/"+app.ID+"/share-diff", nil, 409) + f.bindings.Bindings[0].ETag = `"etag"` + f.phase = "AppEnforced" + f.writes = nil + changed = call[domain.App](h, "editor", "PATCH", "/apps/"+app.ID, map[string]any{"share": domain.SharePolicy{Scope: "private"}}, 200) + require.Equal(t, "applied", changed.ShareSync) + require.Len(t, f.writes, 1) + require.True(t, strings.HasSuffix(f.writes[0], "/role-bindings/share")) + call[httpx.Error](h, "editor", "POST", "/apps/"+app.ID+"/share-sync", nil, 409) +} + +func TestShareApprovalBindingIntegration(t *testing.T) { + h := newHarness(t) + f := installShareFixture(t, h) + app := boundShareApp(t, h) + requestTestAccess(h, "requester", app, "Please share", 201) + requests := call[[]domain.AppAccessRequest](h, "editor", "GET", appRequestPath(app), nil, 200) + path := appRequestPath(app) + "/" + requests[0].ID + "/approve" + f.failBinding = true + call[httpx.Error](h, "editor", "POST", path, nil, 409) + requests = call[[]domain.AppAccessRequest](h, "editor", "GET", appRequestPath(app), nil, 200) + require.Equal(t, domain.RequestPending, requests[0].Status) + f.failBinding = false + result := call[accessRequestDecision](h, "editor", "POST", path, nil, 200) + require.Equal(t, domain.RequestApproved, result.Request.Status) + require.Contains(t, f.bindingWrites[1].OrganizationPersonRefs, organizationPersonRef{SourceUID: "source", PersonID: requests[0].Requester.ID}) + for _, bearer := range f.bearers { + require.Equal(t, "Bearer "+token("editor"), bearer) + } +} + +func TestShareCutoverRequiresCurrentOwnerConfirmationIntegration(t *testing.T) { + h := newHarness(t) + f := installShareFixture(t, h) + app := boundShareApp(t, h) + call[domain.App](h, "editor", "POST", "/apps/"+app.ID+"/share-sync", nil, 200) + diff := call[shareDiffResponse](h, "editor", "GET", "/apps/"+app.ID+"/share-diff", nil, 200) + input := map[string]any{ + "confirmed": false, "direction": "activate", "candidateDigest": diff.CandidateDigest, + "expectedApplicationUID": diff.ApplicationUID, "expectedShareRevision": diff.ShareRevision, + "expectedBindingETag": diff.BindingETag, "confirmedDiffDigest": diff.DiffDigest, + } + path := "/apps/" + app.ID + "/access-cutover" + call[httpx.Error](h, "editor", "POST", path, input, 400) + input["confirmed"] = true + input["confirmedDiffDigest"] = "stale" + call[httpx.Error](h, "editor", "POST", path, input, 409) + input["confirmedDiffDigest"] = diff.DiffDigest + call[httpx.Error](h, "admin", "POST", path, input, 403) + f.diff.UnresolvedCount = 1 + call[httpx.Error](h, "editor", "POST", path, input, 409) + f.diff.UnresolvedCount = 0 + f.bindings.CanManageBindings = false + call[httpx.Error](h, "editor", "POST", path, input, 403) + f.bindings.CanManageBindings = true + require.Len(t, f.writes, 2, "no rejected confirmation may start cutover") + body, err := json.Marshal(input) + require.NoError(t, err) + r := httptest.NewRequest("POST", "/api/console"+path, bytes.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Authorization", "Bearer "+token("editor")) + r.Header.Set("Idempotency-Key", "owner-confirmation") + w := httptest.NewRecorder() + h.server.Config.Handler.ServeHTTP(w, r) + require.Equal(t, 202, w.Code, w.Body.String()) + require.Len(t, f.writes, 3) + require.True(t, strings.HasSuffix(f.writes[2], "/access-cutover")) + f.phase = "AppEnforced" + input["direction"] = "restore" + input["confirmed"] = false + input["candidateDigest"] = "sha256:previous" + call[httpx.Error](h, "editor", "POST", path, input, 400) + input["confirmed"] = true + input["candidateDigest"] = "sha256:unsealed" + call[httpx.Error](h, "editor", "POST", path, input, 409) + require.Len(t, f.writes, 3, "unconfirmed or mismatched restore must not reach Platform") + input["candidateDigest"] = "sha256:previous" + body, err = json.Marshal(input) + require.NoError(t, err) + r = httptest.NewRequest("POST", "/api/console"+path, bytes.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Authorization", "Bearer "+token("editor")) + r.Header.Set("Idempotency-Key", "owner-restore") + w = httptest.NewRecorder() + h.server.Config.Handler.ServeHTTP(w, r) + require.Equal(t, 202, w.Code, w.Body.String()) + require.Len(t, f.writes, 4) +} diff --git a/cmd/server/internal/api/share_management.go b/cmd/server/internal/api/share_management.go new file mode 100644 index 0000000..e93487c --- /dev/null +++ b/cmd/server/internal/api/share_management.go @@ -0,0 +1,228 @@ +package api + +import ( + "net/http" + "net/url" + "slices" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/builder-console/cmd/server/internal/domain" +) + +type shareManagement struct { + shareBindings + Cutover *cutoverResource `json:"cutover,omitempty"` + IsOwner bool `json:"isOwner"` + ShareSync string `json:"shareSync"` +} + +func (a *API) managedShareApp(s *request) (domain.App, shareBindings, error) { + app, err := s.boundApp() + if err != nil { + return app, shareBindings{}, err + } + if app.AppName == nil { + return app, shareBindings{}, httpx.NotFound() + } + bindings, err := a.sharing.bindings(s.r.Context(), s.bearer, *app.AppName) + return app, bindings, err +} + +func shareBindingInSync(app domain.App, bindings shareBindings) bool { + return app.ShareSync == "applied" && app.ShareBindingETag != "" && slices.ContainsFunc(bindings.Bindings, func(binding shareBinding) bool { + return binding.ManagedFor == "share" && binding.ETag == app.ShareBindingETag + }) +} + +func (a *API) shareAccess(s *request) (any, int, error) { + app, bindings, err := a.managedShareApp(s) + if err != nil { + return nil, 0, err + } + cutover, err := a.sharing.cutover(s.r.Context(), s.bearer, *app.AppName) + if err != nil { + return nil, 0, err + } + if (cutover == nil || cutover.Phase != "AppEnforced") && !shareBindingInSync(app, bindings) { + app.ShareSync = "conflict" + } + if cutover == nil || cutover.Phase != "AppEnforced" { + publishes, err := a.sharePublishes(s) + if err != nil { + return nil, 0, err + } + found := false + for _, publish := range publishes { + if publish.ApplicationID != *app.AppName { + continue + } + found = true + if !legacyMatches(publish.Access, app.Share.Scope) { + app.ShareSync = "conflict" + } + } + if !found { + app.ShareSync = "pending" + } + } + return shareManagement{shareBindings: bindings, Cutover: cutover, IsOwner: app.OwnedBy(s.person.ID), ShareSync: app.ShareSync}, 200, nil +} + +func (a *API) assignOrganizationGroups(s *request) (any, int, error) { + app, bindings, err := a.managedShareApp(s) + if err != nil { + return nil, 0, err + } + var input struct { + Role string `json:"role"` + ConfirmDisclosure bool `json:"confirmDisclosure"` + } + if err := decode(s, &input); err != nil { + return nil, 0, err + } + if !input.ConfirmDisclosure { + return nil, 0, httpx.Invalid("Confirm organization membership disclosure before assigning") + } + if !bindings.OrganizationGroups.Declared || !bindings.OrganizationGroups.Accepted || !slices.Contains(bindings.OrganizationGroups.Roles, input.Role) { + return nil, 0, httpx.Conflict("Organization groups require an explicitly accepted role") + } + if bindings.OrganizationSource == nil || !bindings.OrganizationSource.Ready || !bindings.OrganizationSource.InitialSyncComplete { + return nil, 0, httpx.Conflict("The organization source is not ready") + } + for _, binding := range bindings.Bindings { + if binding.OrganizationGroupSourceRef != nil { + return nil, 0, httpx.Conflict("Organization groups are already assigned") + } + } + body := struct { + Role string `json:"role"` + OrganizationGroupSourceRef organizationGroupSourceRef `json:"organizationGroupSourceRef"` + }{input.Role, organizationGroupSourceRef{SourceUID: bindings.OrganizationSource.SourceUID}} + headers := http.Header{"Idempotency-Key": {s.r.Header.Get("Idempotency-Key")}} + if headers.Get("Idempotency-Key") == "" { + return nil, 0, httpx.Invalid("Idempotency-Key is required") + } + if err := a.sharing.call(s.r.Context(), s.bearer, "POST", a.sharing.appPath(*app.AppName)+"/role-bindings", body, headers, nil); err != nil { + return nil, 0, err + } + return a.shareAccess(s) +} + +func (a *API) removeOrganizationGroups(s *request) (any, int, error) { + app, bindings, err := a.managedShareApp(s) + if err != nil { + return nil, 0, err + } + id := s.r.PathValue("binding") + if !slices.ContainsFunc(bindings.Bindings, func(b shareBinding) bool { + return b.Name == id && b.OrganizationGroupSourceRef != nil && b.ManagedFor != "share" + }) { + return nil, 0, httpx.NotFound() + } + if s.r.Header.Get("Idempotency-Key") == "" { + return nil, 0, httpx.Invalid("Idempotency-Key is required") + } + if err := a.sharing.call(s.r.Context(), s.bearer, "DELETE", a.sharing.appPath(*app.AppName)+"/role-bindings/"+url.PathEscape(id), nil, http.Header{"Idempotency-Key": {s.r.Header.Get("Idempotency-Key")}}, nil); err != nil { + return nil, 0, err + } + return a.shareAccess(s) +} + +type shareDiffMember struct { + Principal string `json:"principal"` + DisplayName string `json:"displayName,omitempty"` +} +type shareDiffResponse struct { + ApplicationUID string `json:"applicationUID"` + CandidateDigest string `json:"candidateDigest"` + DiffDigest string `json:"diffDigest"` + ShareRevision string `json:"shareRevision"` + BindingETag string `json:"bindingETag"` + AddedCount int `json:"addedCount"` + RemovedCount int `json:"removedCount"` + UnresolvedCount int `json:"unresolvedCount"` + Added []shareDiffMember `json:"added"` + Removed []shareDiffMember `json:"removed"` + OldAuthenticated bool `json:"oldAuthenticated"` + NewAuthenticated bool `json:"newAuthenticated"` +} + +func (a *API) readShareDiff(s *request, app domain.App) (shareDiffResponse, error) { + var out shareDiffResponse + if app.ShareSync != "applied" { + return out, httpx.Conflict("Reconcile sharing before comparing access") + } + err := a.sharing.call(s.r.Context(), s.bearer, "GET", a.sharing.appPath(*app.AppName)+"/access-cutover/diff", nil, nil, &out) + if err == nil && (out.DiffDigest == "" || out.ApplicationUID == "" || out.ShareRevision == "" || out.BindingETag == "" || out.Added == nil || out.Removed == nil || len(out.Added) > 20 || len(out.Removed) > 20) { + err = upstreamError() + } + return out, err +} + +func (a *API) shareDiff(s *request) (any, int, error) { + app, bindings, err := a.managedShareApp(s) + if err != nil { + return nil, 0, err + } + if !app.OwnedBy(s.person.ID) { + return nil, 0, httpx.Forbidden() + } + if !shareBindingInSync(app, bindings) { + return nil, 0, httpx.Conflict("Reconcile sharing before comparing access") + } + diff, err := a.readShareDiff(s, app) + return diff, 200, err +} + +func (a *API) startAccessCutover(s *request) (any, int, error) { + app, bindings, err := a.managedShareApp(s) + if err != nil { + return nil, 0, err + } + // Console ownership does not grant access:manage. Both checks must pass. + if !app.OwnedBy(s.person.ID) { + return nil, 0, httpx.Forbidden() + } + if !shareBindingInSync(app, bindings) { + return nil, 0, httpx.Conflict("Reconcile sharing before confirming cutover") + } + var input struct { + Confirmed bool `json:"confirmed"` + Direction string `json:"direction"` + CandidateDigest string `json:"candidateDigest"` + ExpectedApplicationUID string `json:"expectedApplicationUID"` + ExpectedShareRevision string `json:"expectedShareRevision"` + ExpectedBindingETag string `json:"expectedBindingETag"` + ConfirmedDiffDigest string `json:"confirmedDiffDigest"` + } + if err := decode(s, &input); err != nil { + return nil, 0, err + } + if !input.Confirmed || (input.Direction != "activate" && input.Direction != "restore") { + return nil, 0, httpx.Invalid("The owner must explicitly confirm the cutover direction") + } + diff, err := a.readShareDiff(s, app) + if err != nil { + return nil, 0, err + } + candidate := diff.CandidateDigest + if input.Direction == "restore" { + previous, err := a.sharing.cutover(s.r.Context(), s.bearer, *app.AppName) + if err != nil { return nil, 0, err } + if previous == nil || previous.Phase != "AppEnforced" || previous.PreviousDigest == "" { + return nil, 0, httpx.Conflict("No sealed previous version is available for restore") + } + candidate = previous.PreviousDigest + } + if diff.UnresolvedCount != 0 || candidate == "" || input.ConfirmedDiffDigest != diff.DiffDigest || input.ExpectedApplicationUID != diff.ApplicationUID || input.ExpectedShareRevision != diff.ShareRevision || input.ExpectedBindingETag != diff.BindingETag || input.CandidateDigest != candidate { + return nil, 0, httpx.Conflict("The access diff changed or is incomplete; review it again") + } + key := s.r.Header.Get("Idempotency-Key") + if key == "" { + return nil, 0, httpx.Invalid("Idempotency-Key is required") + } + body := map[string]string{"direction": input.Direction, "candidateDigest": input.CandidateDigest, "expectedApplicationUID": input.ExpectedApplicationUID, "expectedShareRevision": input.ExpectedShareRevision, "expectedBindingETag": input.ExpectedBindingETag, "confirmedDiffDigest": input.ConfirmedDiffDigest} + var out cutoverResult + err = a.sharing.call(s.r.Context(), s.bearer, "POST", a.sharing.appPath(*app.AppName)+"/access-cutover", body, http.Header{"Idempotency-Key": {key}}, &out) + return out, 202, err +} diff --git a/cmd/server/internal/api/share_platform.go b/cmd/server/internal/api/share_platform.go new file mode 100644 index 0000000..d38b114 --- /dev/null +++ b/cmd/server/internal/api/share_platform.go @@ -0,0 +1,181 @@ +package api + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/url" + "strings" + "time" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/appserver-go/appserver/platformenv" +) + +type shareSubject struct { + Kind string `json:"kind"` + Name string `json:"name,omitempty"` + Issuer string `json:"issuer,omitempty"` + Subject string `json:"subject,omitempty"` +} +type organizationPersonRef struct { + SourceUID string `json:"sourceUID"` + PersonID string `json:"personID"` +} +type organizationGroupSourceRef struct { + SourceUID string `json:"sourceUID"` +} +type shareBindingInput struct { + Role string `json:"role"` + Subjects []shareSubject `json:"subjects"` + OrganizationPersonRefs []organizationPersonRef `json:"organizationPersonRefs,omitempty"` +} +type shareBinding struct { + Name string `json:"name"` + Role string `json:"role"` + Subjects []shareSubject `json:"subjects"` + OrganizationPersonRefs []organizationPersonRef `json:"organizationPersonRefs,omitempty"` + OrganizationGroupSourceRef *organizationGroupSourceRef `json:"organizationGroupSourceRef,omitempty"` + ManagedFor string `json:"managedFor,omitempty"` + ETag string `json:"etag,omitempty"` +} +type shareBindings struct { + Bindings []shareBinding `json:"bindings"` + CanManageBindings bool `json:"canManageBindings"` + OrganizationGroups struct { + Declared bool `json:"declared"` + Accepted bool `json:"accepted"` + Roles []string `json:"roles"` + } `json:"organizationGroups"` + OrganizationSource *struct { + SourceUID string `json:"sourceUID"` + Ready bool `json:"ready"` + InitialSyncComplete bool `json:"initialSyncComplete"` + AppliedVersion string `json:"appliedVersion"` + ConsecutiveFailures int `json:"consecutiveFailures"` + } `json:"organizationSource,omitempty"` +} +type shareGroup struct { + ExternalID string `json:"externalId"` + BindingGroupName string `json:"bindingGroupName"` + SourceUID string `json:"sourceUID"` +} +type cutoverResource struct { + ID string `json:"id"` + ApplicationUID string `json:"applicationUID"` + Direction string `json:"direction"` + Phase string `json:"phase"` + Reason string `json:"reason"` + PreviousDigest string `json:"previousDigest"` + CookieIsolationVerified bool `json:"cookieIsolationVerified"` +} +type cutoverResult struct { + Resource cutoverResource `json:"resource"` +} + +type sharePlatform struct { + origin, prefix string + http *http.Client +} + +// ConfigureSharing uses the same trust roots as the Console's other Platform +// clients. Every operation forwards the current human's bearer, never a service credential. +func (a *API) ConfigureSharing(origin string, transport http.RoundTripper) error { + if _, err := platformenv.Validate(origin, a.platform.ProjectID); err != nil { + return err + } + a.sharing = &sharePlatform{origin: strings.TrimRight(origin, "/"), prefix: "/api/v1/projects/" + url.PathEscape(a.platform.ProjectID), http: &http.Client{ + Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + }} + return nil +} + +func (p *sharePlatform) appPath(app string) string { return "/applications/" + url.PathEscape(app) } + +func (p *sharePlatform) call(ctx context.Context, bearer, method, path string, body any, headers http.Header, out any) error { + if p == nil { + return upstreamError() + } + var payload io.Reader + if body != nil { + data, err := json.Marshal(body) + if err != nil { + return err + } + payload = bytes.NewReader(data) + } + r, err := http.NewRequestWithContext(ctx, method, p.origin+p.prefix+path, payload) + if err != nil { + return err + } + r.Header = headers.Clone() + if r.Header == nil { + r.Header = make(http.Header) + } + r.Header.Set("Authorization", bearer) + r.Header.Set("Accept", "application/json") + if body != nil { + r.Header.Set("Content-Type", "application/json") + } + response, err := p.http.Do(r) + if err != nil { + return upstreamError() + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + if response.StatusCode == 404 { + return httpx.NotFound() + } + if response.StatusCode == 403 { + return httpx.Forbidden() + } + if response.StatusCode == 409 || response.StatusCode == 412 { + return httpx.Fail(response.StatusCode, "share_conflict", "Sharing changed; reload before saving") + } + if response.StatusCode == 422 { + return httpx.Fail(422, "share_unavailable", "A sharing recipient is unavailable or exceeds the limit") + } + return upstreamError() + } + if out == nil || response.StatusCode == 204 { + return nil + } + if err := json.NewDecoder(io.LimitReader(response.Body, 2<<20)).Decode(out); err != nil { + return upstreamError() + } + return nil +} + +func (p *sharePlatform) bindings(ctx context.Context, bearer, app string) (shareBindings, error) { + var out shareBindings + if p == nil { + return out, upstreamError() + } + err := p.call(ctx, bearer, "GET", p.appPath(app)+"/role-bindings", nil, nil, &out) + if err == nil && (out.Bindings == nil || !out.CanManageBindings) { + err = httpx.Forbidden() + } + return out, err +} + +func (p *sharePlatform) cutover(ctx context.Context, bearer, app string) (*cutoverResource, error) { + if p == nil { + return nil, upstreamError() + } + var out cutoverResult + err := p.call(ctx, bearer, "GET", p.appPath(app)+"/access-cutover", nil, nil, &out) + var failure *httpx.Error + if errors.As(err, &failure) && failure.Status == 404 { + return nil, nil + } + if err != nil { + return nil, err + } + if out.Resource.Phase == "" { + return nil, upstreamError() + } + return &out.Resource, nil +} diff --git a/cmd/server/internal/api/testdata/console-wire.json b/cmd/server/internal/api/testdata/console-wire.json index b472817..41c6bbf 100644 --- a/cmd/server/internal/api/testdata/console-wire.json +++ b/cmd/server/internal/api/testdata/console-wire.json @@ -72,6 +72,9 @@ "groupIds": [], "extraPersonIds": [] }, + "shareRevision": 0, + "shareSync": "", + "canManageShare": false, "contribution": {"scope": "group"}, "permissions": {"use": true, "comment": true, "propose": true, "maintain": true, "data": true}, "createdBy": { @@ -128,6 +131,9 @@ "groupIds": [], "extraPersonIds": [] }, + "shareRevision": 0, + "shareSync": "", + "canManageShare": false, "contribution": {"scope": "group"}, "permissions": {"use": true, "comment": true, "propose": true, "maintain": true, "data": true}, "createdBy": { @@ -642,6 +648,9 @@ "groupIds": [], "extraPersonIds": [] }, + "shareRevision": 0, + "shareSync": "", + "canManageShare": false, "contribution": {"scope": "group"}, "permissions": {"use": true, "comment": true, "propose": true, "maintain": true, "data": true}, "createdBy": { @@ -743,5 +752,28 @@ "error": "forbidden", "message": "You do not have permission for this action" } + }, + { + "name": "share-management", + "schema": "ShareManagement", + "body": { + "bindings": [], "canManageBindings": true, + "organizationGroups": {"declared": false, "accepted": false, "roles": []}, + "organizationSource": {"sourceUID": "source", "ready": true, "initialSyncComplete": true, "appliedVersion": "1", "consecutiveFailures": 0}, + "isOwner": true, "shareSync": "applied" + } + }, + { + "name": "share-diff", + "schema": "ShareDiff", + "body": { + "applicationUID": "uid", "candidateDigest": "sha256:candidate", "diffDigest": "diff", "shareRevision": "revision", "bindingETag": "etag", + "addedCount": 0, "removedCount": 0, "unresolvedCount": 0, "added": [], "removed": [], "oldAuthenticated": false, "newAuthenticated": false + } + }, + { + "name": "share-cutover", + "schema": "ShareCutover", + "body": {"resource": {"id": "cutover", "applicationUID": "uid", "direction": "activate", "phase": "Prepared", "reason": "", "previousDigest": "", "cookieIsolationVerified": false}} } ] diff --git a/cmd/server/internal/api/wire_contract_test.go b/cmd/server/internal/api/wire_contract_test.go index 67f12f8..4ae609a 100644 --- a/cmd/server/internal/api/wire_contract_test.go +++ b/cmd/server/internal/api/wire_contract_test.go @@ -101,6 +101,11 @@ func consoleWriterFixtures(t *testing.T) []writerFixture { w := httptest.NewRecorder() httpx.WriteError(w, httpx.Forbidden(), "console") fixtures = append(fixtures, writerFixture{"http-error", "Error", json.RawMessage(w.Body.Bytes())}) + fixtures = append(fixtures, + writerFixture{"share-management", "ShareManagement", shareManagement{shareBindings: readyShareBindings(), IsOwner: true, ShareSync: "applied"}}, + writerFixture{"share-diff", "ShareDiff", shareDiffResponse{ApplicationUID: "uid", CandidateDigest: "sha256:candidate", DiffDigest: "diff", ShareRevision: "revision", BindingETag: "etag", Added: []shareDiffMember{}, Removed: []shareDiffMember{}}}, + writerFixture{"share-cutover", "ShareCutover", cutoverResult{Resource: cutoverResource{ID: "cutover", ApplicationUID: "uid", Direction: "activate", Phase: "Prepared"}}}, + ) return fixtures } diff --git a/cmd/server/internal/domain/model.go b/cmd/server/internal/domain/model.go index b9195e3..9d7a4bb 100644 --- a/cmd/server/internal/domain/model.go +++ b/cmd/server/internal/domain/model.go @@ -129,6 +129,10 @@ type App struct { StackID *string `json:"stackId"` AppName *string `json:"appName"` Share SharePolicy `json:"share"` + ShareRevision int64 `json:"shareRevision"` + ShareSync string `json:"shareSync"` + ShareBindingETag string `json:"-"` + CanManageShare bool `json:"canManageShare"` Contribution ContributionPolicy `json:"contribution"` Permissions Permissions `json:"permissions"` CreatedBy Person `json:"createdBy"` diff --git a/cmd/server/internal/store/apps.go b/cmd/server/internal/store/apps.go index 079905a..236c5da 100644 --- a/cmd/server/internal/store/apps.go +++ b/cmd/server/internal/store/apps.go @@ -18,7 +18,7 @@ const visibleSQL = `$2 OR a.share_scope IN ('company','public') OR $1=ANY(a.shar const appSelect = `SELECT a.id,a.slug,a.display_name,a.description,a.icon,a.tags,a.guide,a.capabilities,a.stack_id,a.app_name, a.share_scope,a.share_group_ids,a.share_extra_person_ids,a.created_at,a.updated_at, - a.group_id,a.created_by,a.contribution_scope, + a.group_id,a.created_by,a.contribution_scope,a.share_revision,a.share_sync,a.share_binding_etag, COALESCE((SELECT jsonb_agg(jsonb_build_object('id',o.person_id) ORDER BY o.person_id) FROM app_owners o WHERE o.app_id=a.id),'[]'::jsonb), COALESCE((SELECT jsonb_agg(jsonb_build_object('id',s.id,'caption',s.caption,'width',s.width,'height',s.height) ORDER BY s.position) @@ -32,7 +32,7 @@ func scanApp(row scanner) (domain.App, error) { var owners, screenshots []byte err := row.Scan(&a.ID, &a.Slug, &a.DisplayName, &a.Description, &a.Icon, pq.Array(&a.Tags), &a.Guide, pq.Array(&a.Capabilities), &a.StackID, &a.AppName, &a.Share.Scope, pq.Array(&a.Share.GroupIDs), pq.Array(&a.Share.ExtraPersonIDs), &a.CreatedAt, &a.UpdatedAt, - &a.Group.ID, &a.CreatedBy.ID, &a.Contribution.Scope, &owners, &screenshots) + &a.Group.ID, &a.CreatedBy.ID, &a.Contribution.Scope, &a.ShareRevision, &a.ShareSync, &a.ShareBindingETag, &owners, &screenshots) if err == nil { err = json.Unmarshal(owners, &a.Owners) } diff --git a/cmd/server/internal/store/migrations/011_share_sync.sql b/cmd/server/internal/store/migrations/011_share_sync.sql new file mode 100644 index 0000000..617e7bf --- /dev/null +++ b/cmd/server/internal/store/migrations/011_share_sync.sql @@ -0,0 +1,3 @@ +ALTER TABLE apps ADD COLUMN share_revision bigint NOT NULL DEFAULT 0; +ALTER TABLE apps ADD COLUMN share_sync text NOT NULL DEFAULT 'pending' CHECK (share_sync IN ('pending', 'applied', 'conflict')); +ALTER TABLE apps ADD COLUMN share_binding_etag text NOT NULL DEFAULT ''; diff --git a/web/src/api/access.ts b/web/src/api/access.ts index 23a7ab0..a756bbb 100644 --- a/web/src/api/access.ts +++ b/web/src/api/access.ts @@ -1,44 +1,38 @@ -import { ORPCError } from '@orpc/client' -import type { ConfirmedPublishAccess, ShareScope } from '../model/contracts/catalog' -import { putPublishAccessContract } from './contracts/platform/catalog' +import type { BusinessApp } from '../model/contracts/console' +import { syncShareContract } from './contracts/console/operations' import { apiGateway } from './gateway' import { platformErrorEnvelope } from './platform-error' import { isPublishPreparationPending, publishPreparationRetryDelay } from './publish-retry' import { sharingCopy } from '../copy/sharing' -import { accessRequest } from '../model/access' +import { isConsoleError } from './console' export class AccessForbiddenError extends Error { constructor() { super(sharingCopy.forbidden) } } export function retryAccess(failureCount: number, error: unknown): boolean { - return failureCount < 20 && platformErrorEnvelope(error)?.details?.reason === 'delivery_pending' + return failureCount < 20 && (isConsoleError(error, 'share_policy_pending') || platformErrorEnvelope(error)?.details?.reason === 'delivery_pending') +} + +export function isCreatedAppSharePending(error: unknown): boolean { + return isConsoleError(error, 'share_publish_pending') || isConsoleError(error, 'share_policy_pending') || isPublishPreparationPending(error) } /** Automatic creation repair waits for rollout prerequisites; manual sharing keeps its existing policy. */ export function retryCreatedAppAccess(failureCount: number, error: unknown): boolean { - return isPublishPreparationPending(error) || retryAccess(failureCount, error) + return (failureCount < 20 && isCreatedAppSharePending(error)) || retryAccess(failureCount, error) } export function createdAppAccessRetryDelay(failureCount: number, error: unknown): number { return isPublishPreparationPending(error) ? publishPreparationRetryDelay(failureCount) : 3_000 } -/** - * Writes the publish's URL access for a share scope, under the caller's - * idempotency key (a retry with the same key is replayed, never applied - * twice). Resolves to the observed access the Platform answered with; an - * unreadable answer rejects with a ResponseContractError (never retried). - */ -export async function putAppAccess(projectId: string, publishId: string, scope: ShareScope, idempotencyKey: string): Promise { +/** The server owns the legacy-policy → fixed-binding write and divergence state. */ +export async function applyAppShare(appId: string, idempotencyKey: string): Promise { try { - return await apiGateway.platform(putPublishAccessContract, { - params: { projectId, publishId }, - headers: { 'Idempotency-Key': idempotencyKey }, - body: accessRequest(scope), - }) + return await apiGateway.console(syncShareContract, { appId, idempotencyKey }) } catch (error) { - if (error instanceof ORPCError && error.status === 403) throw new AccessForbiddenError() + if (isConsoleError(error) && error.status === 403) throw new AccessForbiddenError() throw error } } diff --git a/web/src/api/contracts/console/operations.test.ts b/web/src/api/contracts/console/operations.test.ts index 79c5f79..f0d3e1f 100644 --- a/web/src/api/contracts/console/operations.test.ts +++ b/web/src/api/contracts/console/operations.test.ts @@ -28,7 +28,8 @@ function fixture(schema: keyof typeof schemas): unknown { // embedded artifact fails here; Go validates the same document independently. test('OpenAPI is generated from the canonical Zod schema', () => { const document = JSON.parse(readFileSync(new URL('../../../../../cmd/server/internal/api/console-spa.openapi.json', import.meta.url), 'utf8')) - expect(document).toEqual(openAPIDocument()) + // Compare the published JSON, not Zod's non-enumerable Standard Schema helpers. + expect(document).toEqual(JSON.parse(JSON.stringify(openAPIDocument()))) expect(document.paths['/apps'].get.operationId).toBe('listApps') expect(document.paths['/apps/{id}'].get.operationId).toBe('getApp') }) diff --git a/web/src/api/contracts/console/operations.ts b/web/src/api/contracts/console/operations.ts index e067980..7d5ef0b 100644 --- a/web/src/api/contracts/console/operations.ts +++ b/web/src/api/contracts/console/operations.ts @@ -8,6 +8,7 @@ import { meContract } from './me' import { configContract } from './config' import { groupsContract } from './groups' import { listCommentsContract, markCommentsSeenContract, postCommentContract, removeCommentContract } from './comments' +import { shareManagement, shareDiff, shareSchemas } from './schema/share' export type AppListInput = { scope?: 'mine' | 'company' | 'all'; groupId?: string; q?: string } export type DirectoryAppsInput = { groupId?: string; q?: string; ownerId?: string } @@ -30,6 +31,12 @@ export const appByPathContract = consoleContract({ ...operations.appByPath, read export const createAppContract = consoleContract({ ...operations.createApp, reader: appReader, request: (body: CreateAppInput) => ({ method: 'POST', path: '/api/console/apps', body }) }) export const updateAppContract = consoleContract({ ...operations.updateApp, reader: appReader, request: ({ appId, input }: { appId: string; input: UpdateAppInput }) => ({ method: 'PATCH', path: appPath(appId), body: input }) }) export const bindAppContract = consoleContract({ ...operations.bindApp, reader: appReader, request: ({ appId, stackId, appName }: { appId: string; stackId: string; appName: string }) => ({ method: 'POST', path: `${appPath(appId)}/bind`, body: { stackId, appName } }) }) +export const syncShareContract = consoleContract({ ...operations.syncShare, reader: appReader, request: ({ appId, idempotencyKey }: { appId: string; idempotencyKey: string }) => ({ method: 'POST', path: `${appPath(appId)}/share-sync`, headers: { 'Idempotency-Key': idempotencyKey } }) }) +export const shareAccessContract = consoleContract({ ...operations.shareAccess, reader: shareManagement, request: (appId: string) => ({ method: 'GET', path: `${appPath(appId)}/share-access` }) }) +export const assignOrganizationGroupsContract = consoleContract({ ...operations.assignOrganizationGroups, reader: shareManagement, request: ({ appId, role, idempotencyKey }: { appId: string; role: string; idempotencyKey: string }) => ({ method: 'POST', path: `${appPath(appId)}/organization-groups`, headers: { 'Idempotency-Key': idempotencyKey }, body: { role, confirmDisclosure: true } }) }) +export const removeOrganizationGroupsContract = consoleContract({ ...operations.removeOrganizationGroups, reader: shareManagement, request: ({ appId, binding, idempotencyKey }: { appId: string; binding: string; idempotencyKey: string }) => ({ method: 'DELETE', path: `${appPath(appId)}/organization-groups/${encodeURIComponent(binding)}`, headers: { 'Idempotency-Key': idempotencyKey } }) }) +export const shareDiffContract = consoleContract({ ...operations.shareDiff, reader: shareDiff, request: (appId: string) => ({ method: 'GET', path: `${appPath(appId)}/share-diff` }) }) +export const startAccessCutoverContract = consoleContract({ ...operations.startAccessCutover, reader: shareSchemas.ShareCutover, request: ({ appId, diff, idempotencyKey, previousDigest }: { appId: string; diff: z.output; idempotencyKey: string; previousDigest?: string }) => ({ method: 'POST', path: `${appPath(appId)}/access-cutover`, headers: { 'Idempotency-Key': idempotencyKey }, body: { confirmed: true, direction: previousDigest === undefined ? 'activate' : 'restore', candidateDigest: previousDigest ?? diff.candidateDigest, expectedApplicationUID: diff.applicationUID, expectedShareRevision: diff.shareRevision, expectedBindingETag: diff.bindingETag, confirmedDiffDigest: diff.diffDigest } }) }) export const removeAppContract = consoleEmptyContract({ ...operations.removeApp, request: (appId: string) => ({ method: 'DELETE', path: appPath(appId) }) }) export const directoryAppsContract = consoleContract({ ...operations.directoryApps, reader: items(entryReader), request: (input: DirectoryAppsInput = {}) => ({ method: 'GET', path: `/api/console/apps${query({ scope: 'directory', group: input.groupId, q: input.q, ownerId: input.ownerId })}` }) }) export const directoryEntryContract = consoleContract({ ...operations.directoryEntry, reader: entryReader, request: (appId: string) => ({ method: 'GET', path: `${appPath(appId)}/directory-entry` }) }) @@ -63,6 +70,9 @@ export const consoleContracts = { createPerson: createPersonContract, members: membersContract, directoryUsers: directoryUsersContract, resolve: resolveContract, apps: appsContract, app: appContract, appByPath: appByPathContract, createApp: createAppContract, updateApp: updateAppContract, bindApp: bindAppContract, removeApp: removeAppContract, + syncShare: syncShareContract, shareAccess: shareAccessContract, + assignOrganizationGroups: assignOrganizationGroupsContract, removeOrganizationGroups: removeOrganizationGroupsContract, + shareDiff: shareDiffContract, startAccessCutover: startAccessCutoverContract, directoryApps: directoryAppsContract, directoryEntry: directoryEntryContract, tools: toolsContract, comments: listCommentsContract, postComment: postCommentContract, removeComment: removeCommentContract, markCommentsSeen: markCommentsSeenContract, uploadScreenshot: uploadScreenshotContract, removeScreenshot: removeScreenshotContract, reorderScreenshots: reorderScreenshotsContract, diff --git a/web/src/api/contracts/console/schema/operations.ts b/web/src/api/contracts/console/schema/operations.ts index c1f22a2..0f35e69 100644 --- a/web/src/api/contracts/console/schema/operations.ts +++ b/web/src/api/contracts/console/schema/operations.ts @@ -28,6 +28,12 @@ export const operations = { createApp: op({ operationId: 'consoleCreateApp', method: 'POST', routeTemplate: '/api/console/apps', successStatuses: [201], schema: 'App' }), updateApp: op({ operationId: 'consoleUpdateApp', method: 'PATCH', routeTemplate: '/api/console/apps/{id}', successStatuses: [200], schema: 'App' }), bindApp: op({ operationId: 'consoleBindApp', method: 'POST', routeTemplate: '/api/console/apps/{id}/bind', successStatuses: [200], schema: 'App' }), + syncShare: op({ operationId: 'consoleSyncShare', method: 'POST', routeTemplate: '/api/console/apps/{id}/share-sync', successStatuses: [200], schema: 'App' }), + shareAccess: op({ operationId: 'consoleGetShareAccess', method: 'GET', routeTemplate: '/api/console/apps/{id}/share-access', successStatuses: [200], schema: 'ShareManagement' }), + assignOrganizationGroups: op({ operationId: 'consoleAssignOrganizationGroups', method: 'POST', routeTemplate: '/api/console/apps/{id}/organization-groups', successStatuses: [200], schema: 'ShareManagement' }), + removeOrganizationGroups: op({ operationId: 'consoleRemoveOrganizationGroups', method: 'DELETE', routeTemplate: '/api/console/apps/{id}/organization-groups/{binding}', successStatuses: [200], schema: 'ShareManagement' }), + shareDiff: op({ operationId: 'consoleGetShareDiff', method: 'GET', routeTemplate: '/api/console/apps/{id}/share-diff', successStatuses: [200], schema: 'ShareDiff' }), + startAccessCutover: op({ operationId: 'consoleStartAccessCutover', method: 'POST', routeTemplate: '/api/console/apps/{id}/access-cutover', successStatuses: [202], schema: 'ShareCutover' }), removeApp: op({ operationId: 'consoleDeleteApp', method: 'DELETE', routeTemplate: '/api/console/apps/{id}', successStatuses: [204], schema: null }), directoryApps: op({ operationId: 'consoleListDirectoryApps', method: 'GET', routeTemplate: '/api/console/apps', successStatuses: [200], schema: 'DirectoryEntryList' }), directoryEntry: op({ operationId: 'consoleGetDirectoryEntry', method: 'GET', routeTemplate: '/api/console/apps/{id}/directory-entry', successStatuses: [200], schema: 'DirectoryEntry' }), diff --git a/web/src/api/contracts/console/schema/schemas.ts b/web/src/api/contracts/console/schema/schemas.ts index b281668..f7b0876 100644 --- a/web/src/api/contracts/console/schema/schemas.ts +++ b/web/src/api/contracts/console/schema/schemas.ts @@ -1,5 +1,6 @@ import { z } from 'zod' import { buildSchemas } from './build-sessions' +import { shareSchemas } from './share' // The writer owns total collections. Readers may not turn missing grants into // empty grants. Directory proxy shapes are pinned to appserver-go v0.5.0; @@ -32,6 +33,7 @@ export const app = z.strictObject({ capabilities: total(text), screenshots: total(screenshot), group: appGroup.strict(), owners: total(personRef), stackId: text.nullable(), appName: text.nullable(), share, createdBy: personRef, createdAt: text, updatedAt: text, contribution, permissions: observed(permissions), + shareRevision: observed(count), shareSync: observed(text), canManageShare: observed(z.boolean()), }) export const directoryEntry = app.omit({ slug: true, guide: true, share: true, createdBy: true }).extend({ path: text, canOpen: z.boolean() }) export const group = z.object({ @@ -114,6 +116,7 @@ export const error = z.object({ error: text, message: text, details: observed(z. const list = (item: T) => z.object({ items: total(item) }) export const schemas = { ...buildSchemas, + ...shareSchemas, ConversationSetting: conversationSetting, ConversationSettingRead: conversationSettingRead, ConversationSettingInput: conversationSettingInput, ConversationSettingHeaders: conversationSettingHeaders, ConversationSettingETag: conversationSettingETag, diff --git a/web/src/api/contracts/console/schema/share.ts b/web/src/api/contracts/console/schema/share.ts new file mode 100644 index 0000000..664d757 --- /dev/null +++ b/web/src/api/contracts/console/schema/share.ts @@ -0,0 +1,27 @@ +import { z } from 'zod' + +const id = z.string().min(1) +const personRef = z.object({ sourceUID: id, personID: id }) +const binding = z.object({ + name: id, role: id, subjects: z.array(z.object({ kind: z.string(), name: z.string().optional(), issuer: z.string().optional(), subject: z.string().optional() })), + organizationPersonRefs: z.array(personRef).optional(), organizationGroupSourceRef: z.object({ sourceUID: id }).optional(), + managedFor: z.string().optional(), etag: z.string().optional(), +}) +export const cutoverResource = z.object({ id: z.string(), applicationUID: z.string(), direction: z.string(), phase: id, reason: z.string(), previousDigest: z.string(), cookieIsolationVerified: z.boolean() }) +export const shareManagement = z.object({ + bindings: z.array(binding), canManageBindings: z.boolean(), isOwner: z.boolean(), shareSync: z.string(), + organizationGroups: z.object({ declared: z.boolean(), accepted: z.boolean(), roles: z.array(id) }), + organizationSource: z.object({ sourceUID: id, ready: z.boolean(), initialSyncComplete: z.boolean(), appliedVersion: z.string(), consecutiveFailures: z.number().int().nonnegative() }).optional(), + cutover: cutoverResource.optional(), +}) +export const shareDiff = z.object({ + applicationUID: id, candidateDigest: z.string(), diffDigest: id, shareRevision: id, bindingETag: id, + addedCount: z.number().int().nonnegative(), removedCount: z.number().int().nonnegative(), unresolvedCount: z.number().int().nonnegative(), + added: z.array(z.object({ principal: id, displayName: z.string().optional() })).max(20), + removed: z.array(z.object({ principal: id, displayName: z.string().optional() })).max(20), + oldAuthenticated: z.boolean(), newAuthenticated: z.boolean(), +}) +export const shareSchemas = { ShareManagement: shareManagement, ShareDiff: shareDiff, ShareCutover: z.object({ resource: cutoverResource }) } + +export type ShareAccess = z.output +export type ShareDiff = z.output diff --git a/web/src/api/sharing.ts b/web/src/api/sharing.ts new file mode 100644 index 0000000..a3d7330 --- /dev/null +++ b/web/src/api/sharing.ts @@ -0,0 +1,12 @@ +import { queryOptions } from '@tanstack/react-query' +import { apiGateway } from './gateway' +import { assignOrganizationGroupsContract, removeOrganizationGroupsContract, shareAccessContract, shareDiffContract, startAccessCutoverContract } from './contracts/console/operations' + +import type { ShareDiff } from './contracts/console/schema/share' +export type { ShareAccess, ShareDiff } from './contracts/console/schema/share' +export const readShareAccess = (appId: string) => apiGateway.console(shareAccessContract, appId) +export const readShareDiff = (appId: string) => apiGateway.console(shareDiffContract, appId) +export const shareAccessQuery = (appId: string) => queryOptions({ queryKey: ['console', 'share-access', appId], queryFn: () => readShareAccess(appId), retry: false }) +export const assignOrganizationGroups = (appId: string, role: string, idempotencyKey: string) => apiGateway.console(assignOrganizationGroupsContract, { appId, role, idempotencyKey }) +export const removeOrganizationGroups = (appId: string, binding: string, idempotencyKey: string) => apiGateway.console(removeOrganizationGroupsContract, { appId, binding, idempotencyKey }) +export const startAccessCutover = (appId: string, diff: ShareDiff, idempotencyKey: string, previousDigest?: string) => apiGateway.console(startAccessCutoverContract, { appId, diff, idempotencyKey, previousDigest }) diff --git a/web/src/copy/sharing.en.ts b/web/src/copy/sharing.en.ts index 392544e..514871f 100644 --- a/web/src/copy/sharing.en.ts +++ b/web/src/copy/sharing.en.ts @@ -13,7 +13,7 @@ export const sharingCopyEn: typeof sharingCopyJa = { editor: 'Editor', role: (name: string) => `Role for ${name}`, remove: (name: string) => `Remove ${name}`, - pending: 'Invited (not signed in yet)', + pending: 'Added to sharing; sign-in identity is not linked yet', lastOwner: 'Keep at least one person who can edit.', group: (name: string) => `Members of ${name}`, company: 'Everyone at your company', @@ -27,6 +27,27 @@ export const sharingCopyEn: typeof sharingCopyJa = { invitationEmail: 'Email address for the invitation', forbidden: 'You need Team Editor permissions to change access', unavailable: 'Wait until the URL is ready before saving access settings.', + divergence: 'Legacy sharing was saved, but app bindings differ. The next share save reconciles from legacy settings. Cutover is blocked.', + organization: { + title: 'Memberships shared with the app', all: 'All organization groups', role: 'Role for membership disclosure', + undeclared: 'This app does not request organization memberships', + unaccepted: 'Waiting for Project administrator approval. Check the Access tab in Platform Dashboard.', + applying: 'Applying approval', unavailable: 'This Project has no organization group source', + syncing: 'Waiting for the first complete organization group sync', failed: 'Unable to check status. Reload to try again.', + denied: 'You need this app’s sharing management permission', none: 'Not assigned', + add: 'Start membership disclosure', remove: 'End membership disclosure', + confirm: (role: string, remove: boolean) => `${remove ? 'End' : 'Start'} disclosure of each user’s own departments and teams through ${role}. Individual sharing settings will not change.`, + version: (version: string) => `Last applied version: ${version}`, + }, + cutover: { + title: 'Switch to app-enforced access', compare: 'Review who gains or loses access', + added: 'Gaining access', removed: 'Losing access', + unresolved: 'Some recipients could not be checked. Cutover is blocked.', + authenticated: 'All authenticated users, including future sign-ins', + confirm: 'Confirm the displayed changes and switch', confirmation: 'I have reviewed the recipient changes. Switching causes a brief interruption and requires signing in again.', + applied: 'The app enforces access', running: 'Cutover in progress', + restore: 'Restore the previous version and edge authorization', + }, status: { public: 'Public (anyone)', company: 'Company only', diff --git a/web/src/copy/sharing.ts b/web/src/copy/sharing.ts index ed2a6de..fc3bc3d 100644 --- a/web/src/copy/sharing.ts +++ b/web/src/copy/sharing.ts @@ -14,7 +14,7 @@ export const sharingCopyJa = { editor: '編集', role: (name: string) => `${name} の役割`, remove: (name: string) => `${name} を外す`, - pending: '招待中(まだログインしていません)', + pending: '共有先に追加済み・本人のログイン連携前', lastOwner: '編集できる人を 1 人以上残してください。', group: (name: string) => `${name} のメンバー`, company: '社員全員', @@ -28,6 +28,27 @@ export const sharingCopyJa = { invitationEmail: '招待文に使うメールアドレス', forbidden: '基盤の編集権限(Team Editor)が必要です', unavailable: 'URL の準備ができてから、公開範囲を保存してください。', + divergence: '旧共有設定は保存済みですが、アプリの割り当てと一致していません。次の共有保存で旧設定から再同期します。切替はできません。', + organization: { + title: 'アプリに渡す所属', all: 'すべての組織グループ', role: '所属を渡す役割', + undeclared: 'このアプリは組織の所属を要求していません', + unaccepted: 'Project 管理者の承認待ち。Platform Dashboard の Access タブで確認してください。', + applying: '承認を反映中', unavailable: 'この Project には組織グループの供給元がありません', + syncing: '組織グループの初回同期を待っています', failed: '状態を確認できません。再読み込みしてください。', + denied: 'このアプリの共有管理権限が必要です', none: '割り当てなし', + add: '所属の開示を開始', remove: '所属の開示を終了', + confirm: (role: string, remove: boolean) => `${role} による、利用者本人が属する部署・チームの開示を${remove ? '終了' : '開始'}します。個別の共有設定は変更しません。`, + version: (version: string) => `最終適用版: ${version}`, + }, + cutover: { + title: 'アプリでのアクセス判定へ切替', compare: '切替前の対象者を確認', + added: '利用できるようになる人', removed: '利用できなくなる人', + unresolved: '確認できない対象があります。切替はできません。', + authenticated: '今後ログインする人も含む全認証者', + confirm: '表示した対象者の差を確認して切り替える', confirmation: '対象者の差を確認しました。切替時に一時的な不通と再ログインが発生します。', + applied: 'アプリでアクセスを判定しています', running: '切替処理中', + restore: '以前の版と edge 判定に戻す', + }, status: { public: '公開中(誰でも)', company: '社員のみ', diff --git a/web/src/features/app/share-dialog.tsx b/web/src/features/app/share-dialog.tsx index 366880c..398f686 100644 --- a/web/src/features/app/share-dialog.tsx +++ b/web/src/features/app/share-dialog.tsx @@ -1,9 +1,9 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { useMemo, useRef, useState } from 'react' +import { useMemo, useState } from 'react' import { Building2, Globe, Lock, Users } from 'lucide-react' import { buildGroupTree, flattenGroupTree, isUnknownPerson, type AccessRequest, type BusinessApp, type Me, type Person, type PersonRef } from '../../model/contracts/console' import { isOneOf, knownValue } from '../../model/contracts/build' -import { putAppAccess, retryAccess } from '../../api/access' +import { retryAccess } from '../../api/access' import { appAccessRequestsQuery, consoleKeys, peopleQuery, useGroups } from '../../api/queries/console' import { keys } from '../../api/queries/shared' import { copy } from '../../copy' @@ -18,14 +18,18 @@ import { ensurePerson, useApproveAccessRequest, useDeclineAccessRequest, useUpda import { PersonSearch } from './settings/parts' import { PendingBadge } from './pending-badge' import { UnconfirmedNotice, useWriteConfirmation } from './notices' +import { ShareManagement } from './share-management' +import { shareAccessQuery } from '../../api/sharing' const SCOPES: readonly ShareScope[] = ['private', 'group', 'company', 'public'] const ICONS = { private: Lock, group: Users, company: Building2, public: Globe } -export function ShareDialog({ app, me, canEdit, publishId, url, access, open, onOpenChange, onAccessError }: { +export function ShareDialog({ app, me, canEdit: canEditMetadata, publishId, url, access, open, onOpenChange, onAccessError }: { app: BusinessApp; me: Me; canEdit: boolean; publishId?: string; url?: string; access: AccessDisplay open: boolean; onOpenChange: (open: boolean) => void; onAccessError: (error: unknown) => void }) { + const management = useQuery({ ...shareAccessQuery(app.id), enabled: open && Boolean(app.stackId) }) + const canEdit = canEditMetadata && (!app.stackId || management.data?.canManageBindings === true) const groups = useGroups().data const flatGroups = useMemo(() => flattenGroupTree(buildGroupTree(groups)), [groups]) const extraIds = app.share.extraPersonIds.filter((id) => !app.owners.some((owner) => owner.id === id)) @@ -43,13 +47,10 @@ export function ShareDialog({ app, me, canEdit, publishId, url, access, open, on const [groupIds, setGroupIds] = useState(app.share.groupIds.length ? [...app.share.groupIds] : [app.group.id]) const [confirm, setConfirm] = useState() const [invitationEmail, setInvitationEmail] = useState('') - const requestKey = useRef('') const scopeWrite = useMutation({ mutationFn: async (share: KnownShare) => { if (!canEdit) throw new Error(copy.common.loadFailed) if (!publishId) throw new Error(words.unavailable) - // Never PATCH intent before the user's platform write has succeeded. - await putAppAccess(me.projectId, publishId, share.scope, requestKey.current) await update.mutateAsync({ share }) }, retry: retryAccess, @@ -92,7 +93,6 @@ export function ShareDialog({ app, me, canEdit, publishId, url, access, open, on const saveScope = () => { if (!canEdit || !share || !scope) return const next: KnownShare = { ...share, scope, groupIds: scope === 'group' ? groupIds : [] } - requestKey.current = crypto.randomUUID() if (widensShare(app.share, next)) setConfirm(next) else scopeWrite.mutate(next) } @@ -108,6 +108,7 @@ export function ShareDialog({ app, me, canEdit, publishId, url, access, open, on

{access.label}

{!share ? {text.unsupported.share} : null} + {app.shareSync && app.shareSync !== 'applied' ? {words.divergence} : null} {confirmation.unconfirmed ? void confirmation.confirm()} confirming={confirmation.confirming} /> : null} {canEdit && requests.isLoadingError ? void requests.refetch()} /> : null} {canEdit && pending.length > 0 ? ( @@ -186,10 +187,11 @@ export function ShareDialog({ app, me, canEdit, publishId, url, access, open, on return { value, title: value === 'private' ? words.limited : copy.create.share[value].title, description: value === 'private' ? words.limitedHint : copy.create.share[value].body, icon: , disabled: value === 'public' && !me.isConsoleAdmin, children: value === 'group' && scope === 'group' ? : undefined } })} /> - {canEdit ? : null} + {canEdit ? : null} {!publishId ?

{words.unavailable}

: null} {scopeWrite.error && !confirmation.unconfirmed ?
: null} +

{words.noMail}

{url ? <> diff --git a/web/src/features/app/share-management.test.tsx b/web/src/features/app/share-management.test.tsx new file mode 100644 index 0000000..ccf30fd --- /dev/null +++ b/web/src/features/app/share-management.test.tsx @@ -0,0 +1,110 @@ +import { afterEach, expect, spyOn, test } from 'bun:test' +import { notifyManager, QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { shareAccessQuery, type ShareAccess } from '../../api/sharing' +import { sharingCopy as words } from '../../copy/sharing' +import { ShareManagement, organizationGroupsDisabledReason } from './share-management' +import { appReader } from '../../api/contracts/console/readers' +import { readFileSync } from 'node:fs' + +const fixtures: { schema: string; body: unknown }[] = JSON.parse(readFileSync(new URL('../../../../cmd/server/internal/api/testdata/console-wire.json', import.meta.url), 'utf8')) +const app = { ...appReader.parse(fixtures.find((item) => item.schema === 'App')!.body), stackId: 'stack', shareSync: 'applied' } +const ready: ShareAccess = { + bindings: [], canManageBindings: true, isOwner: true, shareSync: 'applied', + organizationGroups: { declared: true, accepted: true, roles: ['member'] }, + organizationSource: { sourceUID: 'source', ready: true, initialSyncComplete: true, appliedVersion: 'v1', consecutiveFailures: 0 }, +} +let root: Root | undefined +let container: HTMLDivElement +let client: QueryClient +const restores: (() => void)[] = [] +afterEach(async () => { + await act(async () => root?.unmount()) + root = undefined + container?.remove() + client?.clear() + for (const restore of restores.splice(0)) restore() +}) +async function mount(value: ShareAccess) { + client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } }) + client.setQueryData(shareAccessQuery(app.id).queryKey, value) + container = document.createElement('div') + document.body.append(container) + root = createRoot(container) + await act(async () => root!.render()) +} + +const disabledCases: { name: string; data: ShareAccess; reason: string }[] = [ + { name: 'undeclared', data: { ...ready, organizationGroups: { declared: false, accepted: false, roles: [] } }, reason: words.organization.undeclared }, + { name: 'offered only', data: { ...ready, organizationGroups: { ...ready.organizationGroups, accepted: false } }, reason: words.organization.unaccepted }, + { name: 'acceptance applying', data: { ...ready, organizationGroups: { ...ready.organizationGroups, roles: [] } }, reason: words.organization.applying }, + { name: 'source absent', data: { ...ready, organizationSource: undefined }, reason: words.organization.unavailable }, + { name: 'initial sync pending', data: { ...ready, organizationSource: { ...ready.organizationSource!, initialSyncComplete: false } }, reason: words.organization.syncing }, + { name: 'authority absent', data: { ...ready, canManageBindings: false }, reason: words.organization.denied }, +] +test.each(disabledCases)('organization groups control is disabled: $name', async ({ data, reason }) => { + const requests: string[] = [] + const fetch = spyOn(globalThis, 'fetch').mockImplementation((async (input) => { requests.push(String(input)); return new Response(null, { status: 403 }) }) as typeof globalThis.fetch) + restores.push(() => fetch.mockRestore()) + await mount(data) + const control = container.querySelector('input[type="checkbox"]')! + expect(control.disabled).toBe(true) + await act(async () => control.click()) + expect(container.textContent).toContain(reason) + expect(requests).toEqual([]) +}) + +test('accepted organization groups still require disclosure confirmation', async () => { + expect(organizationGroupsDisabledReason(ready)).toBeUndefined() + const requests: string[] = [] + const fetch = spyOn(globalThis, 'fetch').mockImplementation((async (input) => { requests.push(String(input)); return new Response(null, { status: 403 }) }) as typeof globalThis.fetch) + restores.push(() => fetch.mockRestore()) + await mount(ready) + const control = container.querySelector('input[type="checkbox"]')! + expect(control.disabled).toBe(false) + await act(async () => control.click()) + expect(document.body.textContent).toContain(words.organization.confirm('member', false)) + expect(requests).toEqual([]) +}) + +test('cutover cannot start merely by reading the recipient diff', async () => { + const requests: string[] = [] + const fetch = spyOn(globalThis, 'fetch').mockImplementation((async (input, init) => { + requests.push(`${init?.method ?? 'GET'} ${input}`) + return Response.json({ applicationUID: 'uid', candidateDigest: 'sha256:version', diffDigest: 'diff', shareRevision: 'revision', bindingETag: 'etag', addedCount: 1, removedCount: 1, unresolvedCount: 0, added: [{ principal: 'u_added', displayName: 'Added Person' }], removed: [{ principal: 'u_removed', displayName: 'Removed Person' }], oldAuthenticated: false, newAuthenticated: false }) + }) as typeof globalThis.fetch) + restores.push(() => fetch.mockRestore()) + await mount(ready) + const compare = [...container.querySelectorAll('button')].find((button) => button.textContent === words.cutover.compare)! + const rendered = Promise.withResolvers() + const observer = new MutationObserver(() => { if (container.textContent?.includes('Added Person')) rendered.resolve() }) + observer.observe(container, { childList: true, subtree: true }) + try { + await act(async () => { compare.click() }) + await rendered.promise + } finally { observer.disconnect() } + expect(container.textContent).toContain('Added Person') + expect(container.textContent).toContain('Removed Person') + expect(requests).toEqual([`GET /api/console/apps/${app.id}/share-diff`]) + const confirm = [...container.querySelectorAll('button')].find((button) => button.textContent === words.cutover.confirm)! + await act(async () => confirm.click()) + expect(document.body.textContent).toContain(words.cutover.confirmation) + expect(requests).toHaveLength(1) +}) + +test('restore is offered only after cutover and requires a sealed previous digest', async () => { + notifyManager.setScheduler((callback) => callback()) + restores.push(() => notifyManager.setScheduler((callback) => setTimeout(callback, 0))) + const requests: string[] = [] + const fetch = spyOn(globalThis, 'fetch').mockImplementation((async (input) => { requests.push(String(input)); return new Response(null, { status: 403 }) }) as typeof globalThis.fetch) + restores.push(() => fetch.mockRestore()) + await mount(ready) + const restoreButton = () => [...container.querySelectorAll('button')].find((button) => button.textContent === words.cutover.restore) + expect(restoreButton()).toBeUndefined() + const state: ShareAccess = { ...ready, cutover: { id: 'cutover', applicationUID: 'uid', direction: 'activate', phase: 'AppEnforced', reason: '', previousDigest: '', cookieIsolationVerified: true } } + await act(async () => { client.setQueryData(shareAccessQuery(app.id).queryKey, state) }) + expect(restoreButton()?.disabled).toBe(true) + await act(async () => restoreButton()!.click()) + expect(requests).toEqual([]) +}) diff --git a/web/src/features/app/share-management.tsx b/web/src/features/app/share-management.tsx new file mode 100644 index 0000000..df30898 --- /dev/null +++ b/web/src/features/app/share-management.tsx @@ -0,0 +1,96 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useState } from 'react' +import { assignOrganizationGroups, readShareDiff, removeOrganizationGroups, shareAccessQuery, startAccessCutover, type ShareAccess, type ShareDiff } from '../../api/sharing' +import type { BusinessApp } from '../../model/contracts/console' +import { sharingCopy as words } from '../../copy/sharing' +import { ActionError, Button, ConfirmDialog, LoadFailed, Notice, Select } from '../../ui' + +export function organizationGroupsDisabledReason(access: ShareAccess | undefined): string | undefined { + if (!access) return words.organization.failed + if (!access.canManageBindings) return words.organization.denied + if (!access.organizationGroups.declared) return words.organization.undeclared + if (!access.organizationGroups.accepted) return words.organization.unaccepted + if (!access.organizationGroups.roles.length) return words.organization.applying + if (!access.organizationSource) return words.organization.unavailable + if (!access.organizationSource.initialSyncComplete) return words.organization.syncing + if (!access.organizationSource.ready) return words.organization.failed + return undefined +} + +/** Membership disclosure is independent of the four URL-sharing scopes. */ +export function ShareManagement({ app, open }: { app: BusinessApp; open: boolean }) { + const queryClient = useQueryClient() + const query = shareAccessQuery(app.id) + const access = useQuery({ ...query, enabled: open && Boolean(app.stackId), refetchInterval: (state) => { + const phase = state.state.data?.cutover?.phase + return open && phase && !['AppEnforced', 'Restored'].includes(phase) ? 3_000 : false + } }) + const [role, setRole] = useState('') + const [disclosure, setDisclosure] = useState<{ role: string; binding?: string }>() + const [confirmCutover, setConfirmCutover] = useState<{ diff: ShareDiff; previousDigest?: string }>() + const selectedRole = access.data?.organizationGroups.roles.includes(role) ? role : access.data?.organizationGroups.roles[0] ?? '' + const reason = organizationGroupsDisabledReason(access.data) + const existing = access.data?.bindings.filter((binding) => binding.organizationGroupSourceRef) ?? [] + const save = useMutation({ + mutationFn: async (change: { role: string; binding?: string }) => change.binding + ? removeOrganizationGroups(app.id, change.binding, crypto.randomUUID()) + : assignOrganizationGroups(app.id, change.role, crypto.randomUUID()), + onSuccess: (data) => { queryClient.setQueryData(query.queryKey, data); setDisclosure(undefined) }, + onSettled: () => queryClient.invalidateQueries({ queryKey: query.queryKey }), + }) + const diff = useMutation({ mutationFn: () => readShareDiff(app.id) }) + const cutover = useMutation({ + mutationFn: (snapshot: { diff: ShareDiff; previousDigest?: string }) => startAccessCutover(app.id, snapshot.diff, crypto.randomUUID(), snapshot.previousDigest), + onSuccess: () => { setConfirmCutover(undefined); diff.reset() }, + onSettled: () => queryClient.invalidateQueries({ queryKey: query.queryKey }), + }) + const restore = useMutation({ + mutationFn: () => readShareDiff(app.id), + onSuccess: (diff) => { + const previousDigest = access.data?.cutover?.previousDigest + if (previousDigest && diff.unresolvedCount === 0) setConfirmCutover({ diff, previousDigest }) + }, + }) + const snapshot = diff.data + const source = access.data?.organizationSource + const phase = access.data?.cutover?.phase + const applied = phase === 'AppEnforced' + const running = Boolean(phase && !['AppEnforced', 'Restored'].includes(phase)) + return <> +
+

{words.organization.title}

+ {access.data?.shareSync === 'conflict' ? {words.divergence} : null} + +