diff --git a/README.md b/README.md index 3de0366..bfe76b2 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,12 @@ The same 401 expires the edge's session cookies for this host real sign-in and receives a newly minted token instead of replaying the refused one. The SSO session and other apps' sessions are not touched. +Scripts and agents use an Access Key instead of a browser session: create a key +in the `tracker` space (`tracker:read`, `tracker:write`), exchange it with +`apth access-keys exchange`, and send the assertion as the bearer. The key acts +as its user with the Viewer role. The rules are in +[`design/API.md`](design/API.md#access-keys-v0111). + PostgreSQL integration tests are opt-in: they skip when both `BUILTIN_APPSERVER_TEST_DATABASE_URL` and `BUILDER_CONSOLE_TEST_DATABASE_URL` are unset. An explicitly configured test database must permit isolated schema creation. @@ -113,14 +119,14 @@ a required BuildKit secret, never through build arguments or committed files. ## Catalog and release -The next app release is **0.1.10**, also recorded in `web/package.json`. +The next app release is **0.1.11**, also recorded in `web/package.json`. `catalog/entry.yaml` carries no committed version: the first tag (`v0.1.0`) created `versions[]` with `ghcr.io/appthrust/tracker@sha256:`, stream `0.1`; later tags append at publication time. Do not add a version with an unbuilt or placeholder image digest. OpenAPI's `info.version` describes the API schema, not the app release. This repository has no hand-maintained changelog. -After the release prerequisites are available, push the SemVer tag `v0.1.10`. +After the release prerequisites are available, push the SemVer tag `v0.1.11`. The tag workflow: 1. Performs one multi-platform build on `ubuntu-24.04` for Linux amd64 and arm64, @@ -140,8 +146,8 @@ The tag workflow: Publication commands used by the workflow: ```sh -bun hack/publish-entry.ts submit --version 0.1.10 --digest sha256: -bun hack/publish-entry.ts await --version 0.1.10 --digest sha256: +bun hack/publish-entry.ts submit --version 0.1.11 --digest sha256: +bun hack/publish-entry.ts await --version 0.1.11 --digest sha256: ``` Writers are serialized by `tracker-catalog-publish`; the workflow is guarded to @@ -162,8 +168,8 @@ After publication, each estate's `AppCatalogSource` syncs the signed catalog. Install Issues from the Project Marketplace (Directory is an automatic dependency). Existing `follow` installations on stream `0.1` roll to the new version; `pinned` installations show `UpdateAvailable` and require an explicit -version update. Confirm the installation is Ready, `/releasez` reports `0.1.10`, -and a signed-in Tracker page lists the Sprints page in the navigation. These are release steps, +version update. Confirm the installation is Ready, `/releasez` reports `0.1.11`, +the Project lists the `tracker` Access Key space as Ready, and an exchanged key reads `/api/tracker/v1/me`. These are release steps, not actions performed by a source-only version bump. Migration authority: diff --git a/catalog/entry.yaml b/catalog/entry.yaml index 8441113..ef621e9 100644 --- a/catalog/entry.yaml +++ b/catalog/entry.yaml @@ -12,6 +12,18 @@ spec: - email tokenClaims: - groups + bearerPassThrough: true + accessKeys: + audience: tracker + audienceEnv: TRACKER_ACCESS_AUDIENCE + keyPrefix: trk + scopes: + - name: tracker:read + description: Read issues, epics, comments, projects, sprints and views + - name: tracker:write + description: Create and edit issues, epics, comments, projects and sprints as the key's user + defaultTTL: 720h0m0s + maxTTL: 8760h0m0s components: - defaultValues: livenessProbePath: /healthz diff --git a/cmd/server/internal/api/api.go b/cmd/server/internal/api/api.go index 6bad088..60b5ccc 100644 --- a/cmd/server/internal/api/api.go +++ b/cmd/server/internal/api/api.go @@ -110,22 +110,38 @@ func (a *API) route(pattern string, mutation, roles bool, fn endpoint) { if !ok { return } - s := &request{r: r, w: w, bearer: r.Header.Get("Authorization"), actor: domain.Actor{Person: domain.Person{Sub: claims.Principal.Subject, Name: claims.Name, Email: claims.Email}, Role: "Viewer"}} - if s.actor.Name == "" { - s.actor.Name = s.actor.Sub - } - if roles { - access, err := a.platform.Access(ctx, s.actor.Sub, s.bearer) + s := &request{r: r, w: w} + if claims.Principal.Kind == "key" { + actor, err := keyActor(claims.Principal, a.workspace, mutation) if err != nil { - httpx.WriteError(w, httpx.Fail(503, "identity_unavailable", "The platform role is temporarily unavailable"), "tracker") + httpx.WriteError(w, err, "tracker") return } - if !access.NotMember { - s.actor.Role = access.Role + // The assertion is addressed to Tracker only: it is never forwarded + // to Directory, so people stay the stored snapshots. + s.actor = actor + if mutation { + log.Printf("tracker access key mutation: %s %s key=%q subject=%q request_id=%q", r.Method, r.URL.Path, claims.Principal.KeyName, actor.Sub, r.Header.Get("X-Request-Id")) + } + } else { + s.bearer = r.Header.Get("Authorization") + s.actor = domain.Actor{Person: domain.Person{Sub: claims.Principal.Subject, Name: claims.Name, Email: claims.Email}, Role: "Viewer"} + if s.actor.Name == "" { + s.actor.Name = s.actor.Sub + } + if roles { + access, err := a.platform.Access(ctx, s.actor.Sub, s.bearer) + if err != nil { + httpx.WriteError(w, httpx.Fail(503, "identity_unavailable", "The platform role is temporarily unavailable"), "tracker") + return + } + if !access.NotMember { + s.actor.Role = access.Role + } + } + if mutation { + s.actor.Person = a.directory.Enrich(ctx, s.bearer, s.actor.Person) } - } - if mutation { - s.actor.Person = a.directory.Enrich(ctx, s.bearer, s.actor.Person) } if err := a.store.EnsureWorkspace(ctx, a.workspace); err != nil { writeStoreError(w, err) @@ -176,10 +192,14 @@ func (a *API) authenticate(w http.ResponseWriter, r *http.Request) (identity.Ide if errors.Is(err, identity.ErrUnavailable) { httpx.WriteError(w, httpx.Fail(503, "identity_unavailable", "The identity provider is temporarily unavailable"), "tracker") } else { - // The edge has already accepted this session, so a 401 here is the app + // The edge has already accepted this request, so a 401 here is the app // disagreeing with the edge about the token; record why. log.Printf("tracker auth rejected: %s %s request_id=%q %s edge_cookies_expired=%d", r.Method, r.URL.Path, r.Header.Get("X-Request-Id"), describeRejection(r.Header.Get("Authorization"), err), expireEdgeSession(w, r)) - httpx.WriteError(w, httpx.Fail(401, "unauthenticated", "A valid bearer token is required"), "tracker") + failure := httpx.Fail(401, "unauthenticated", "A valid bearer token is required") + if errors.Is(err, identity.ErrRawKeyNotAccepted) { + failure = httpx.Fail(401, "raw_key_not_accepted", "Exchange the access key for an assertion before calling this API") + } + httpx.WriteError(w, failure, "tracker") } return identity.Identity{}, "", false } diff --git a/cmd/server/internal/api/api_test.go b/cmd/server/internal/api/api_test.go index d0391ab..59b55c2 100644 --- a/cmd/server/internal/api/api_test.go +++ b/cmd/server/internal/api/api_test.go @@ -33,7 +33,8 @@ func token(subject string) string { claims, _ := json.Marshal(map[string]string{"sub": subject, "email": subject + "@example.test", "name": subject}) return base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none"}`)) + "." + base64.RawURLEncoding.EncodeToString(claims) + "." } -func newHarness(t *testing.T) *harness { +func newHarness(t *testing.T) *harness { return newHarnessTrusting(t, identity.Trust{}) } +func newHarnessTrusting(t *testing.T, trust identity.Trust) *harness { database, _ := testutil.Database(t, store.Open) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/api/v1/projects/pj-test/access" { @@ -52,7 +53,7 @@ func newHarness(t *testing.T) *harness { require.NoError(t, err) _, _, err = auth.Authenticate(t.Context(), issuer.Bearer(t)) require.NoError(t, err) - auth, err = identity.New(identity.Trust{}) + auth, err = identity.New(trust) require.NoError(t, err) server := httptest.NewServer(New(database, auth, platformclient.New(upstream.URL, "pj-test"), directory.New(nil, ""), "pj-test")) t.Cleanup(server.Close) diff --git a/cmd/server/internal/api/avatars.go b/cmd/server/internal/api/avatars.go index a184e89..d7074e1 100644 --- a/cmd/server/internal/api/avatars.go +++ b/cmd/server/internal/api/avatars.go @@ -20,7 +20,13 @@ func (a *API) avatar(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() r = r.WithContext(ctx) - if _, _, ok := a.authenticate(w, r); !ok { + claims, _, ok := a.authenticate(w, r) + if !ok { + return + } + if claims.Principal.Kind == "key" { + // Directory owns avatars and does not accept Tracker's assertion. + httpx.WriteError(w, httpx.Fail(403, "key_subject", "Access keys cannot read Directory avatars"), "tracker") return } id := r.PathValue("id") diff --git a/cmd/server/internal/api/keys.go b/cmd/server/internal/api/keys.go new file mode 100644 index 0000000..33fed5c --- /dev/null +++ b/cmd/server/internal/api/keys.go @@ -0,0 +1,41 @@ +package api + +import ( + "slices" + + "github.com/appthrust/appserver-go/accesskey" + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/tracker/cmd/server/internal/domain" +) + +// Access Key scopes declared by catalog/entry.yaml (access.accessKeys.scopes). +const ( + scopeRead = "tracker:read" + scopeWrite = "tracker:write" +) + +// keyActor maps an Access Key assertion to the actor it may act as. +// +// The assertion audience is the same in every Project, so the Project claim is +// the tenant boundary. A key acts as the person it was issued to with the +// Viewer role: it never reaches the Platform role lookup, so Admin-only +// operations stay with signed-in users. Keys without a person behind them +// (component, external, cluster) are refused because every Tracker write +// records a person. +func keyActor(principal accesskey.Principal, project string, mutation bool) (domain.Actor, error) { + if principal.Project != project { + return domain.Actor{}, httpx.Fail(401, "unauthenticated", "A valid bearer token is required") + } + subject, err := accesskey.ParseSubject(principal.Subject) + if err != nil || subject.Kind != accesskey.SubjectUser { + return domain.Actor{}, httpx.Fail(403, "key_subject", "Only access keys issued to a user can call this API") + } + required := scopeRead + if mutation { + required = scopeWrite + } + if !slices.Contains(principal.Scopes, required) { + return domain.Actor{}, httpx.Fail(403, "insufficient_scope", "The access key does not permit this operation") + } + return domain.Actor{Person: domain.Person{Sub: subject.ID, Name: subject.ID}, Role: "Viewer"}, nil +} diff --git a/cmd/server/internal/api/keys_test.go b/cmd/server/internal/api/keys_test.go new file mode 100644 index 0000000..cfa0532 --- /dev/null +++ b/cmd/server/internal/api/keys_test.go @@ -0,0 +1,106 @@ +package api + +import ( + "bytes" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "testing" + "time" + + "github.com/appthrust/appserver-go/accesskey" + "github.com/appthrust/appserver-go/appserver/identity" + "github.com/appthrust/tracker/cmd/server/internal/domain" + "github.com/appthrust/tracker/cmd/server/internal/store" + "github.com/stretchr/testify/require" +) + +func TestAccessKeyActsAsItsUserWithinScopeAndProject(t *testing.T) { + private, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + signer := accesskey.NewES256Signer("test-key", private) + jwks := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/access/jwks.json" { + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(signer.JWKS()) + })) + t.Cleanup(jwks.Close) + issuer := accesskey.IssuerURL(jwks.URL) + assertion := func(project string, subject accesskey.Subject, scopes ...string) string { + token, err := signer.Sign(accesskey.Claims{ + Issuer: issuer, Audience: "tracker", Project: project, KeyName: "ak-test", Subject: subject, + Scopes: scopes, JTI: "test", IssuedAt: time.Now(), ExpiresAt: time.Now().Add(time.Minute), + }) + require.NoError(t, err) + return "Bearer " + token + } + user := func(id string) accesskey.Subject { return accesskey.Subject{Kind: accesskey.SubjectUser, ID: id} } + h := newHarnessTrusting(t, identity.Trust{AccessIssuer: issuer, AccessAudience: "tracker"}) + do := func(bearer, method, path string, body any) (int, []byte) { + t.Helper() + var reader io.Reader + if body != nil { + data, err := json.Marshal(body) + require.NoError(t, err) + reader = bytes.NewReader(data) + } + r, err := http.NewRequest(method, h.server.URL+"/api/tracker/v1"+path, reader) + require.NoError(t, err) + r.Header.Set("Authorization", bearer) + r.Header.Set("Content-Type", "application/json") + response, err := h.server.Client().Do(r) + require.NoError(t, err) + defer response.Body.Close() + data, err := io.ReadAll(response.Body) + require.NoError(t, err) + return response.StatusCode, data + } + + // The harness grants Admin to the signed-in user "admin"; a key issued to + // that user must still be a Viewer. + both := assertion("pj-test", user("admin"), scopeRead, scopeWrite) + status, data := do(both, "POST", "/issues", map[string]string{"title": "From an agent", "type": "task"}) + require.Equal(t, 201, status, string(data)) + var issue domain.Issue + require.NoError(t, json.Unmarshal(data, &issue)) + require.Equal(t, "admin", issue.Reporter.Sub) + + page := call[store.Page](h, "admin", "GET", "/issues?filter="+url.QueryEscape(`{"reporter":["me"]}`), nil, 200) + require.Len(t, page.Items, 1, "the signed-in user owns what their key reported") + + issue2 := map[string]string{"title": "Refused", "type": "task"} + for _, test := range []struct { + name, bearer, method, path string + body any + status int + code string + }{ + {"read", assertion("pj-test", user("admin"), scopeRead), "GET", "/issues/" + issue.ID, nil, 200, ""}, + {"read scope cannot write", assertion("pj-test", user("admin"), scopeRead), "POST", "/issues", issue2, 403, "insufficient_scope"}, + {"write scope cannot read", assertion("pj-test", user("admin"), scopeWrite), "GET", "/issues", nil, 403, "insufficient_scope"}, + {"other project", assertion("pj-other", user("admin"), scopeRead, scopeWrite), "GET", "/issues", nil, 401, "unauthenticated"}, + {"component subject", assertion("pj-test", accesskey.Subject{Kind: accesskey.SubjectComponent, ID: "web"}, scopeRead, scopeWrite), "GET", "/issues", nil, 403, "key_subject"}, + {"admin issue delete", both, "DELETE", "/issues/" + issue.ID, nil, 403, "forbidden"}, + {"admin workspace settings", both, "PATCH", "/workspace", map[string]string{"key": "NEW"}, 403, "forbidden"}, + {"directory avatar", both, "GET", "/people/01JABCDEFGHJKMNPQRSTVWXYZ0/avatar", nil, 403, "key_subject"}, + } { + status, data := do(test.bearer, test.method, test.path, test.body) + require.Equal(t, test.status, status, "%s: %s", test.name, data) + if test.code != "" { + require.Contains(t, string(data), `"error":"`+test.code+`"`, test.name) + } + } + + secret, err := accesskey.Generate("trk", rand.Reader) + require.NoError(t, err) + status, data = do("Bearer "+secret.String(), "GET", "/issues", nil) + require.Equal(t, 401, status) + require.Contains(t, string(data), `"error":"raw_key_not_accepted"`) +} diff --git a/cmd/server/internal/api/openapi.json b/cmd/server/internal/api/openapi.json index dcde732..2e59788 100644 --- a/cmd/server/internal/api/openapi.json +++ b/cmd/server/internal/api/openapi.json @@ -2,8 +2,8 @@ "openapi": "3.1.0", "info": { "title": "Tracker API", - "version": "0.1.10", - "description": "Contract: design/API.md. One workspace per PLATFORM_PROJECT_ID." + "version": "0.1.11", + "description": "Contract: design/API.md. One workspace per PLATFORM_PROJECT_ID. The bearer is the signed-in user's token or an Access Key assertion (audience tracker; scope tracker:read for GET, tracker:write otherwise)." }, "servers": [ { @@ -5699,7 +5699,10 @@ "enum": [ "invalid", "unauthenticated", + "raw_key_not_accepted", "forbidden", + "insufficient_scope", + "key_subject", "not_found", "conflict", "tracker_store_unavailable", diff --git a/cmd/server/internal/directory/client.go b/cmd/server/internal/directory/client.go index c21903f..065999b 100644 --- a/cmd/server/internal/directory/client.go +++ b/cmd/server/internal/directory/client.go @@ -52,7 +52,8 @@ func (c *Client) Enrich(ctx context.Context, bearer string, snapshot domain.Pers return snapshot } func (c *Client) list(ctx context.Context, bearer string, query url.Values) ([]domain.Person, error) { - if c == nil || c.links == nil { + // Without a caller bearer there is no authority to ask Directory with. + if c == nil || c.links == nil || bearer == "" { return nil, link.ErrAbsent } key := cacheKey{sha256.Sum256([]byte(bearer)), query.Encode()} diff --git a/design/API.md b/design/API.md index f8240b6..3c371b2 100644 --- a/design/API.md +++ b/design/API.md @@ -7,11 +7,13 @@ emits `openapi.json` from these shapes) and the SPA mock Conventions (SDK `httpx`): success bodies are the resource or `{ "items": [...], "nextCursor": string|null }`; errors are `{ "error": "", "message": "...", "issues"?: [{path, message}] }` with -codes `invalid` (400), `unauthenticated` (401), `forbidden` (403), +codes `invalid` (400), `unauthenticated` (401), `raw_key_not_accepted` (401), +`forbidden` (403), `insufficient_scope` (403), `key_subject` (403), `not_found` (404), `conflict` (409), `directory_avatar_unavailable` (502), `tracker_store_unavailable` (503), `identity_unavailable` (503). Timestamps -RFC 3339 UTC. IDs are ULIDs unless noted. All routes require the edge bearer; -`GET /openapi.json` does not. +RFC 3339 UTC. IDs are ULIDs unless noted. All routes require a bearer: the +signed-in user's token forwarded by the edge, or an Access Key assertion +([Access Keys](#access-keys-v0111)); `GET /openapi.json` does not. ## Shapes @@ -427,3 +429,42 @@ with ledgers that yield velocities 18, 21, 24 points, one active two-week sprint on its fourth day with a scope increase and one cancellation, one planned sprint; about half of the seeded work items carry a size, spread over all five. + +## Access Keys (v0.1.11) + +Scripts, CLIs and coding agents call this API without a browser session. The +mechanism is the platform's Access Keys +(`appthrust/platform` `design/platform/access-keys/README.md`); Tracker adds no +credential of its own. + +`catalog/entry.yaml` declares the space: audience `tracker`, key prefix `trk`, +scopes `tracker:read` and `tracker:write`, and `bearerPassThrough` so the edge +verifies a bearer instead of starting a sign-in. The platform projects +`TRACKER_ACCESS_AUDIENCE` and `PLATFORM_ACCESS_ISSUER`. + +```sh +apth access-keys create --project --space tracker --scope tracker:read --scope tracker:write +printf %s "$KEY" | apth access-keys exchange --project # assertion, valid ≤ 5 min +curl -H "Authorization: Bearer " https://tracker./api/tracker/v1/issues +``` + +Rules (`cmd/server/internal/api/keys.go`, `keyActor`): + +| Rule | Result when violated | +| --- | --- | +| The raw key is exchanged first; only the assertion is a bearer | 401 `raw_key_not_accepted` | +| The assertion's Project equals `PLATFORM_PROJECT_ID`. The audience is the same in every Project, so this claim is the tenant boundary | 401 `unauthenticated` | +| The key's subject is a user. Every write records a person; component, external and cluster keys have none | 403 `key_subject` | +| `GET` routes need `tracker:read`; every other method needs `tracker:write`. Neither implies the other | 403 `insufficient_scope` | +| The key acts as its user (`sub` = the subject id) with role `Viewer`. The Platform role is not looked up, so Admin-only routes stay with signed-in users | 403 `forbidden` | +| `GET /people/{id}/avatar` is Directory's data under Directory's authority | 403 `key_subject` | + +What the user's key creates belongs to that user: `reporter: ['me']` in the +SPA lists it. The assertion carries no name or email and is never forwarded to +Directory, so a key write stores `name = sub` as the person snapshot and +`GET /people` answers `source: 'unavailable'`; a signed-in reader still sees +the Directory name. `GET /me` returns `{ sub, name: sub, role: 'Viewer', isAdmin: false }`. + +Each mutation request made with a key writes one `tracker access key mutation:` +log line (method, path, key name, subject, edge `X-Request-Id`) before +authorization. The timeline does not distinguish key writes from the user's own. diff --git a/web/package.json b/web/package.json index daeea42..8c35c41 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "@appthrust/tracker", - "version": "0.1.10", + "version": "0.1.11", "private": true, "type": "module", "scripts": {