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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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:<index-digest>`,
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,
Expand All @@ -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:<image-index-digest>
bun hack/publish-entry.ts await --version 0.1.10 --digest sha256:<image-index-digest>
bun hack/publish-entry.ts submit --version 0.1.11 --digest sha256:<image-index-digest>
bun hack/publish-entry.ts await --version 0.1.11 --digest sha256:<image-index-digest>
```

Writers are serialized by `tracker-catalog-publish`; the workflow is guarded to
Expand All @@ -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:
Expand Down
12 changes: 12 additions & 0 deletions catalog/entry.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 34 additions & 14 deletions cmd/server/internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down
5 changes: 3 additions & 2 deletions cmd/server/internal/api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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" {
Expand All @@ -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)
Expand Down
8 changes: 7 additions & 1 deletion cmd/server/internal/api/avatars.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
41 changes: 41 additions & 0 deletions cmd/server/internal/api/keys.go
Original file line number Diff line number Diff line change
@@ -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
}
106 changes: 106 additions & 0 deletions cmd/server/internal/api/keys_test.go
Original file line number Diff line number Diff line change
@@ -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"`)
}
7 changes: 5 additions & 2 deletions cmd/server/internal/api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
{
Expand Down Expand Up @@ -5699,7 +5699,10 @@
"enum": [
"invalid",
"unauthenticated",
"raw_key_not_accepted",
"forbidden",
"insufficient_scope",
"key_subject",
"not_found",
"conflict",
"tracker_store_unavailable",
Expand Down
3 changes: 2 additions & 1 deletion cmd/server/internal/directory/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()}
Expand Down
Loading