Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8899: feat(qoder): issue short-lived single-repo tokens from workspace GitHub App (#10236)
AstralSolipsisme1411d222c3b
diff --git a/server/cmd/qoder-runtime/README.md b/server/cmd/qoder-runtime/README.mdindex 99cd53245b..5145997ff3 100644--- a/server/cmd/qoder-runtime/README.md+++ b/server/cmd/qoder-runtime/README.md@@ -84,6 +84,22 @@ wide fallback credential is used. This is the standalone bridge's configuration;managed connections set repository tokens in the web and desktop apps instead(see below).++Managed connections fall back to the workspace's GitHub App integration when a+repository has no hand-entered token: the server mints a 1-hour installation+token scoped to that single repository (`contents` and `pull_requests` write,+`metadata` read) and injects it the same way. This needs the GitHub App (and+each existing installation) to carry those write permissions; an installation+that never approved them fails the run with a message naming the missing+permissions instead of a generic missing-credential error. Repositories under a+connected GitHub account then need no manual token, while anything outside the+installation (and any workspace without one) still requires an explicit token.+The rotating token never breaks session reuse — follow-ups fingerprint the+installation binding (`github_app:<installation_id>`) — and losing coverage+fails the next run's credential re-check before a session is reused. Runs+longer than the token's lifetime get a fresh token pushed into the live+session about 45 minutes after each issuance.+A project may bind one HTTPS GitHub repository and an optional branch ref.Without one, the agent's default repository (`runtime_config.repository`) ismounted, and failing that the workspace's only repository when a credential isdiff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex 210e57afcd..5556179769 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -1,6 +1,7 @@package handlerimport (+ "bytes""context""crypto/hmac""crypto/rand"@@ -27,6 +28,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/qoderruntime"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -938,6 +940,131 @@ func revokeGitHubInstallationToken(client *http.Client, token string) {_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, githubAPIResponseLimit))}+// ── Qoder repository credentials from the workspace GitHub App ─────────────++// issueQoderRepositoryToken mints a short-lived installation token bound to+// one repository through a GitHub App installation the workspace connected.+// It backs the Qoder bridge's credential fallback: repositories covered by+// the installation need no hand-entered PAT. The caller must supply lowercase+// owner/repo of the canonical repository URL; a token that comes back scoped+// to anything else is refused. qoderruntime.ErrGitHubAppNotCovered reports+// that no bound installation authorizes the repository.+func (h *Handler) issueQoderRepositoryToken(ctx context.Context, workspaceID, owner, repo string) (string, int64, error) {+ ws, err := parseStrictUUID(workspaceID)+ if err != nil {+ return "", 0, qoderruntime.ErrGitHubAppNotCovered+ }+ appJWT, err := signGitHubAppJWT(time.Now())+ if err != nil {+ return "", 0, fmt.Errorf("sign GitHub App JWT: %w", err)+ }+ if appJWT == "" {+ return "", 0, qoderruntime.ErrGitHubAppNotCovered+ }+ installations, err := h.Queries.ListGitHubInstallationsByWorkspace(ctx, ws)+ if err != nil {+ return "", 0, fmt.Errorf("list workspace GitHub installations: %w", err)+ }+ for _, installation := range installations {+ if !strings.EqualFold(installation.AccountLogin, owner) {+ continue+ }+ token, err := createRepositoryInstallationToken(ctx, appJWT, installation.InstallationID, owner, repo)+ if err == nil {+ return token, installation.InstallationID, nil+ }+ if errors.Is(err, errGitHubRepositoryNotCovered) {+ continue+ }+ if errors.Is(err, errGitHubAppPermissionsNotGranted) {+ return "", 0, qoderruntime.ErrGitHubAppPermissions+ }+ return "", 0, err+ }+ return "", 0, qoderruntime.ErrGitHubAppNotCovered+}++// errGitHubRepositoryNotCovered marks a 4xx refusal from the access-token+// endpoint: the installation exists but does not include the repository (for+// example a selected-repositories installation or a revoked grant).+var errGitHubRepositoryNotCovered = errors.New("github app installation does not include the repository")++// errGitHubAppPermissionsNotGranted marks GitHub's 422 reply when the token+// request asks for permissions the installation never granted. That is an+// operator-actionable configuration gap, not a missing repository.+var errGitHubAppPermissionsNotGranted = errors.New("github app installation has not granted the requested permissions")++// createRepositoryInstallationToken creates a 1-hour installation access+// token locked to a single repository with the minimum permissions remote+// work needs (clone, push branches, open pull requests). The request names+// the repository explicitly, and the response must confirm exactly that+// repository; anything wider is discarded.+func createRepositoryInstallationToken(ctx context.Context, appJWT string, installationID int64, owner, repo string) (string, error) {+ client := &http.Client{Timeout: 15 * time.Second}+ endpoint := fmt.Sprintf("%s/app/installations/%d/access_tokens", strings.TrimRight(githubAPIBase, "/"), installationID)+ // The repository list is explicit and singular: GitHub refuses a name the+ // installation cannot access, so the grant can never widen past one repo.+ body, err := json.Marshal(map[string]any{+ "repositories": []string{repo},+ "permissions": map[string]string{"contents": "write", "pull_requests": "write", "metadata": "read"},+ })+ if err != nil {+ return "", err+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))+ if err != nil {+ return "", err+ }+ setGitHubAPIHeaders(req, appJWT)+ req.Header.Set("Content-Type", "application/json")+ res, err := client.Do(req)+ if err != nil {+ // The wrapped *url.Error embeds the endpoint (and with it the+ // admin-only installation id); keep that out of member-visible+ // task failures and log it instead.+ slog.WarnContext(ctx, "github: create repository installation token request failed", "error", err)+ return "", errors.New("cannot reach GitHub to create a repository installation token")+ }+ defer res.Body.Close()+ if res.StatusCode != http.StatusCreated {+ raw, _ := io.ReadAll(io.LimitReader(res.Body, 16<<10))+ if res.StatusCode >= 400 && res.StatusCode < 500 && res.StatusCode != 408 && res.StatusCode != 429 {+ // A 422 naming ungranted permissions is a configuration gap the+ // workspace admin can fix; anything else means the installation+ // does not cover this repository.+ var refusal struct {+ Message string `json:"message"`+ }+ if json.Unmarshal(raw, &refusal) == nil && strings.Contains(strings.ToLower(refusal.Message), "permissions requested are not granted") {+ return "", errGitHubAppPermissionsNotGranted+ }+ return "", errGitHubRepositoryNotCovered+ }+ return "", fmt.Errorf("create repository installation token: github status %d", res.StatusCode)+ }+ var payload struct {+ Token string `json:"token"`+ Repositories []struct {+ Name string `json:"name"`+ Owner struct {+ Login string `json:"login"`+ } `json:"owner"`+ } `json:"repositories"`+ }+ if err := json.NewDecoder(io.LimitReader(res.Body, githubAPIResponseLimit)).Decode(&payload); err != nil {+ return "", fmt.Errorf("decode repository installation token: %w", err)+ }+ if payload.Token == "" {+ return "", errors.New("github returned an empty repository installation token")+ }+ // The token must be scoped to exactly the requested repository; a wider+ // or different scope is a boundary violation and is never handed out.+ if len(payload.Repositories) != 1 || !strings.EqualFold(payload.Repositories[0].Name, repo) || !strings.EqualFold(payload.Repositories[0].Owner.Login, owner) {+ return "", fmt.Errorf("repository installation token scope mismatch for %s/%s", owner, repo)+ }+ return payload.Token, nil+}+func (h *Handler) DeleteGitHubInstallation(w http.ResponseWriter, r *http.Request) {workspaceID := chi.URLParam(r, "id")wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")diff --git a/server/internal/handler/qoder_connection.go b/server/internal/handler/qoder_connection.goindex 9d2332cd3a..ad47771605 100644--- a/server/internal/handler/qoder_connection.go+++ b/server/internal/handler/qoder_connection.go@@ -510,6 +510,9 @@ func (h *Handler) runQoderSupervisor(ctx context.Context, conn *pgxpool.Conn, se},BeforeStep: func(stepCtx context.Context) (func(), error) {return h.acquireQoderStep(stepCtx, ws, rev)+ },+ GitHubAppToken: func(tokenCtx context.Context, owner, repo string) (string, int64, error) {+ return h.issueQoderRepositoryToken(tokenCtx, ws, owner, repo)}}, nil)if err != nil {_, _ = conn.Exec(ctx, `UPDATE cloud_agent_connection SET status='error',last_error='invalid execution configuration' WHERE provider='qoder_cloud' AND workspace_id=$1`, ws)diff --git a/server/internal/handler/qoder_github_app_test.go b/server/internal/handler/qoder_github_app_test.gonew file mode 100644index 0000000000..5eb7f32278--- /dev/null+++ b/server/internal/handler/qoder_github_app_test.go@@ -0,0 +1,151 @@+package handler++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/qoderruntime"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// withQoderGitHubApp wires the App identity and a stubbed GitHub API for+// repository-token issuance tests. It returns the installation ID bound to+// the test workspace.+func withQoderGitHubApp(t *testing.T, handler http.HandlerFunc) int64 {+ t.Helper()+ pemBytes, _ := generateTestRSAKeyPEM(t)+ t.Setenv("GITHUB_APP_ID", "11111")+ t.Setenv("GITHUB_APP_PRIVATE_KEY", string(pemBytes))+ srv := httptest.NewServer(handler)+ t.Cleanup(srv.Close)+ oldBase := githubAPIBase+ githubAPIBase = srv.URL+ t.Cleanup(func() { githubAPIBase = oldBase })++ const installationID int64 = 909090+ _, err := testHandler.Queries.CreateGitHubInstallation(context.Background(), db.CreateGitHubInstallationParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ InstallationID: installationID,+ AccountLogin: "acme",+ AccountType: "Organization",+ })+ if err != nil {+ t.Fatalf("CreateGitHubInstallation: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM github_installation WHERE installation_id = $1`, installationID)+ })+ return installationID+}++// The issued installation token request must name exactly one repository and+// the minimal permission set, and the response must confirm that repository;+// the returned token never reaches anything wider.+func TestIssueQoderRepositoryTokenSingleRepositoryScope(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ var requestBodies []map[string]any+ installationID := withQoderGitHubApp(t, func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/app/installations/909090/access_tokens" || r.Method != http.MethodPost {+ http.NotFound(w, r)+ return+ }+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Errorf("decode request: %v", err)+ }+ requestBodies = append(requestBodies, body)+ if auth := r.Header.Get("Authorization"); !strings.HasPrefix(auth, "Bearer ") {+ t.Errorf("missing App JWT: %q", auth)+ }+ writeJSON(w, http.StatusCreated, map[string]any{+ "token": "ghs_one_repo",+ "expires_at": "2026-11-09T12:00:00Z",+ "repositories": []map[string]any{{"name": "app", "owner": map[string]any{"login": "acme"}}},+ })+ })++ token, gotInstallation, err := testHandler.issueQoderRepositoryToken(context.Background(), testWorkspaceID, "acme", "app")+ if err != nil {+ t.Fatalf("issueQoderRepositoryToken: %v", err)+ }+ if token != "ghs_one_repo" || gotInstallation != installationID {+ t.Fatalf("token=%q installation=%d", token, gotInstallation)+ }+ if len(requestBodies) != 1 {+ t.Fatalf("expected one token request, got %d", len(requestBodies))+ }+ want := map[string]any{"repositories": []any{"app"}, "permissions": map[string]any{"contents": "write", "pull_requests": "write", "metadata": "read"}}+ raw, _ := json.Marshal(requestBodies[0])+ rawWant, _ := json.Marshal(want)+ if string(raw) != string(rawWant) {+ t.Fatalf("token request scope: got %s want %s", raw, rawWant)+ }+}++// A workspace installation that does not cover the repository — wrong owner,+// or GitHub refusing the single-repository grant — must surface+// ErrGitHubAppNotCovered so the bridge falls back to a clear rejection.+func TestIssueQoderRepositoryTokenNotCovered(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ withQoderGitHubApp(t, func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusNotFound)+ })+ if _, _, err := testHandler.issueQoderRepositoryToken(context.Background(), testWorkspaceID, "someone-else", "app"); !errors.Is(err, qoderruntime.ErrGitHubAppNotCovered) {+ t.Fatalf("wrong owner: err=%v", err)+ }+ if _, _, err := testHandler.issueQoderRepositoryToken(context.Background(), testWorkspaceID, "acme", "not-granted"); !errors.Is(err, qoderruntime.ErrGitHubAppNotCovered) {+ t.Fatalf("revoked repository: err=%v", err)+ }+}++// GitHub's two 422 refusals mean different things: ungranted permissions are+// an operator-actionable configuration gap, while a repository the+// installation cannot see is plain "not covered". Conflating them sends the+// admin hunting for a missing repository when the App needs permissions.+func TestIssueQoderRepositoryTokenPermissionRefusal(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ message := "The repository acme/app was not found in the installation."+ withQoderGitHubApp(t, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"message": message})+ })+ _, _, err := testHandler.issueQoderRepositoryToken(context.Background(), testWorkspaceID, "acme", "app")+ if !errors.Is(err, qoderruntime.ErrGitHubAppNotCovered) {+ t.Fatalf("repository refusal: err=%v", err)+ }+ message = "The permissions requested are not granted to this installation."+ _, _, err = testHandler.issueQoderRepositoryToken(context.Background(), testWorkspaceID, "acme", "app")+ if !errors.Is(err, qoderruntime.ErrGitHubAppPermissions) {+ t.Fatalf("permission refusal: err=%v", err)+ }+ if !strings.Contains(err.Error(), "approve Contents and Pull requests write access") {+ t.Fatalf("permission refusal is not actionable: %v", err)+ }+}++// A GitHub response whose repositories do not confirm the requested single+// repository is a boundary violation; no token is handed out.+func TestIssueQoderRepositoryTokenRejectsWiderScope(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ withQoderGitHubApp(t, func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, http.StatusCreated, map[string]any{+ "token": "ghs_wide",+ "repositories": []map[string]any{},+ })+ })+ if token, _, err := testHandler.issueQoderRepositoryToken(context.Background(), testWorkspaceID, "acme", "app"); err == nil || token != "" {+ t.Fatalf("wide-scope token accepted: token=%q err=%v", token, err)+ }+}diff --git a/server/internal/qoderruntime/bridge.go b/server/internal/qoderruntime/bridge.goindex 86d317b3b7..39e306c75d 100644--- a/server/internal/qoderruntime/bridge.go+++ b/server/internal/qoderruntime/bridge.go@@ -21,24 +21,29 @@ import (const Provider = "qoder_cloud"type Config struct {- DaemonID string `json:"daemon_id,omitempty"`- LoadState func(context.Context) ([]byte, error) `json:"-"`- SaveState func(context.Context, []byte) error `json:"-"`- BeforeStep func(context.Context) (func(), error) `json:"-"`- OnReady func(context.Context, string) error `json:"-"`- GitHubTokens map[string]string `json:"-"`- GitHubTokenFiles map[string]string `json:"github_token_files,omitempty"`- MulticaURL string `json:"multica_url"`- MulticaToken string `json:"multica_token"`- WorkspaceID string `json:"workspace_id"`- QoderURL string `json:"qoder_url"`- QoderToken string `json:"qoder_token"`- EnvironmentID string `json:"environment_id"`- StateDir string `json:"state_dir"`- Name string `json:"name,omitempty"`- RunTimeout time.Duration `json:"-"`- SubmissionTimeout time.Duration `json:"-"`- PollInterval time.Duration `json:"-"`+ DaemonID string `json:"daemon_id,omitempty"`+ LoadState func(context.Context) ([]byte, error) `json:"-"`+ SaveState func(context.Context, []byte) error `json:"-"`+ BeforeStep func(context.Context) (func(), error) `json:"-"`+ OnReady func(context.Context, string) error `json:"-"`+ GitHubTokens map[string]string `json:"-"`+ GitHubTokenFiles map[string]string `json:"github_token_files,omitempty"`+ // GitHubAppToken issues a short-lived installation token restricted to one+ // repository through the workspace's GitHub App integration. It returns+ // ErrGitHubAppNotCovered when no bound installation authorizes the+ // repository. The token stays in the transient request copy only.+ GitHubAppToken func(ctx context.Context, owner, repo string) (string, int64, error) `json:"-"`+ MulticaURL string `json:"multica_url"`+ MulticaToken string `json:"multica_token"`+ WorkspaceID string `json:"workspace_id"`+ QoderURL string `json:"qoder_url"`+ QoderToken string `json:"qoder_token"`+ EnvironmentID string `json:"environment_id"`+ StateDir string `json:"state_dir"`+ Name string `json:"name,omitempty"`+ RunTimeout time.Duration `json:"-"`+ SubmissionTimeout time.Duration `json:"-"`+ PollInterval time.Duration `json:"-"`// MaxConcurrency bounds simultaneous remote sessions; extra tasks stay queued in Multica.MaxConcurrency int `json:"max_concurrency,omitempty"`}@@ -403,6 +408,11 @@ func (b *Bridge) stepRun(ctx context.Context, r *run) error {if time.Now().Before(r.RetryAt) {return nil}+ if r.Phase == "running" {+ if err := b.refreshRunningCredentials(ctx, r); err != nil {+ return err+ }+ }if r.Phase == "creating" {// The provider may have created a session before the response was lost.// Never create a second session automatically for the same run.@@ -418,11 +428,18 @@ func (b *Bridge) stepRun(ctx context.Context, r *run) error {if r.Phase == "prepared" {// Resolve credentials before reusing a session too, so a revoked or// changed repository credential is never carried into a follow-up.- resources, err := b.sessionResources(r.Resources)+ resources, fingerprint, rotating, err := b.sessionResources(ctx, r.Resources)if err != nil {return b.reject(ctx, r, err.Error())}- fingerprint := resourceFingerprint(resources)+ // A rotating credential is timestamped for the live refresh; only the+ // timestamp is journaled, never the token.+ if rotating {+ r.CredentialIssuedAt = time.Now()+ } else {+ r.CredentialIssuedAt = time.Time{}+ }+ repositoryCopies := resourcesresources = append(resources, r.Files...)if r.PriorSessionID != "" && (len(r.Files) == 0 || r.MountFiles) {continued, err := b.continueSession(ctx, r, fingerprint)@@ -432,13 +449,47 @@ func (b *Bridge) stepRun(ctx context.Context, r *run) error {if continued {r.SessionID = r.PriorSessionIDr.Continued = true- r.Phase = "created"- if err := b.persist(); err != nil {- return err+ // A GitHub App credential rotates on every resolution; push the+ // fresh token into the reused session before any message goes+ // out. The run stays "prepared" until the refresh completed, so+ // a rate-limited or failed refresh retries the whole continue+ // path next tick instead of sending with a stale credential.+ if rotating {+ switch err := b.refreshRepositoryCredentials(ctx, r.SessionID, repositoryCopies); {+ case err == nil:+ case errors.Is(err, errRefreshDeferred):+ r.RetryAt = time.Now().Add(30 * time.Second)+ return b.persist()+ case errors.Is(err, errRefreshRefused):+ // The session cannot take the update (for example the+ // repository is no longer mounted there); start a fresh+ // session below.+ r.SessionID, r.PriorSessionID, r.Continued = "", "", false+ r.Credits = runCredits{}+ r.MountedFiles = 0+ default:+ return err+ }+ }+ if r.Continued {+ // One journal write covers both the completed refresh and+ // the phase flip.+ r.Phase = "created"+ if err := b.persist(); err != nil {+ return err+ }}}}if r.Phase == "prepared" {+ if r.Continued {+ // A deferred refresh left the run bound to a prior session+ // that is no longer continuable; start clean so the fresh+ // session is not treated as continued (no history cursor, no+ // remounted files, no stale credit base).+ r.SessionID, r.PriorSessionID, r.Continued = "", "", false+ r.Credits = runCredits{}+ }if err := b.createSession(ctx, r, resources, fingerprint); err != nil || r.Phase != "created" {return err}@@ -562,16 +613,21 @@ func (b *Bridge) createSession(ctx context.Context, r *run, resources []map[stri// resourcesMetadataKey stores resourceFingerprint on each session Multica creates.const resourcesMetadataKey = "multica_resources"+// fingerprintEntry is one repository's stable credential identity: a manual+// token hashes as itself (rotation must invalidate session reuse), a GitHub+// App token hashes as its installation binding so rotating short-lived tokens+// keep the fingerprint stable.+type fingerprintEntry struct {+ key, branch, credential string+}+// resourceFingerprint identifies the repositories, branches and credentials a// session was created with. Only this digest leaves the bridge.-func resourceFingerprint(resources []map[string]any) string {+func resourceFingerprint(entries []fingerprintEntry) string {h := sha256.New()h.Write([]byte("multica-qoder-resources-v1\n"))- for _, res := range resources {- raw, _ := res["url"].(string)- key, _ := repositoryKey(raw)- token, _ := res["authorization_token"].(string)- fmt.Fprintf(h, "%s\x00%s\x00%s\n", key, checkoutBranch(res["checkout"]), token)+ for _, entry := range entries {+ fmt.Fprintf(h, "%s\x00%s\x00%s\n", entry.key, entry.branch, entry.credential)}return hex.EncodeToString(h.Sum(nil))}@@ -620,6 +676,7 @@ func (b *Bridge) continueSession(ctx context.Context, r *run, fingerprint stringif id := sessionAgentID(s.Agent); (id != "" && id != r.AgentID) || (s.EnvironmentID != "" && s.EnvironmentID != b.cfg.EnvironmentID) {return false, nil}+if s.Metadata[resourcesMetadataKey] != fingerprint {return false, nil}@@ -631,6 +688,131 @@ func (b *Bridge) continueSession(ctx context.Context, r *run, fingerprint stringreturn true, nil}+// errRefreshDeferred and errRefreshRefused classify a repository credential+// refresh: the session's provider asked us to retry later, or refused the+// update (including a repository that is no longer mounted), respectively.+var (+ errRefreshDeferred = errors.New("session resource update rate limited")+ errRefreshRefused = errors.New("session refused the repository credential update")+)++// sessionRepositoryResourceID finds the mounted-resource ID of one GitHub+// repository in a session, following the resource list's pagination.+func (b *Bridge) sessionRepositoryResourceID(ctx context.Context, sessionID, key string) (string, error) {+ page := ""+ for range 100 {+ path := "/sessions/" + url.PathEscape(sessionID) + "/resources"+ if page != "" {+ path += "?page=" + url.QueryEscape(page)+ }+ var response struct {+ Data []struct {+ ID string `json:"id"`+ Type string `json:"type"`+ URL string `json:"url"`+ } `json:"data"`+ NextPage string `json:"next_page"`+ }+ if err := b.qoder.call(ctx, http.MethodGet, path, nil, &response); err != nil {+ return "", err+ }+ for _, resource := range response.Data {+ if resource.Type != "github_repository" {+ continue+ }+ if candidate, err := repositoryKey(resource.URL); err == nil && candidate == key {+ return resource.ID, nil+ }+ }+ if response.NextPage == "" {+ return "", nil+ }+ page = response.NextPage+ }+ return "", fmt.Errorf("session resource list did not settle")+}++// refreshRepositoryCredentials pushes fresh tokens into a session's mounted+// repositories. The add-resource endpoint only accepts files, so an existing+// repository is updated through its per-resource credential endpoint, matched+// by canonical repository URL so a token never lands on another resource.+func (b *Bridge) refreshRepositoryCredentials(ctx context.Context, sessionID string, resources []map[string]any) error {+ for i := range resources {+ raw, _ := resources[i]["url"].(string)+ key, err := repositoryKey(raw)+ if err != nil {+ return fmt.Errorf("refresh session repository credential: %w", err)+ }+ token, _ := resources[i]["authorization_token"].(string)+ resourceID, err := b.sessionRepositoryResourceID(ctx, sessionID, key)+ if err != nil {+ if rateLimited(err) {+ return errRefreshDeferred+ }+ if definitelyRejected(err) {+ return errRefreshRefused+ }+ return err+ }+ if resourceID == "" {+ return errRefreshRefused+ }+ err = b.qoder.call(ctx, http.MethodPost, "/sessions/"+url.PathEscape(sessionID)+"/resources/"+url.PathEscape(resourceID), map[string]string{"authorization_token": token}, nil)+ if err != nil {+ if rateLimited(err) {+ return errRefreshDeferred+ }+ if definitelyRejected(err) {+ return errRefreshRefused+ }+ return err+ }+ }+ return nil+}++// credentialRefreshInterval is how long a run waits before re-issuing a+// rotating GitHub App credential into its live session; GitHub installation+// tokens expire after one hour, so the refresh lands with margin to spare.+const credentialRefreshInterval = 45 * time.Minute++// refreshRunningCredentials keeps a live session's short-lived GitHub token+// usable for runs longer than the token's lifetime: about 45 minutes after+// the last issuance it re-resolves the credentials and pushes them into the+// session. Only the issuance timestamp is journaled, never the token; its+// zero value disables the refresh (static credentials, or a session that+// refused the update for good). Transient failures back off and retry.+func (b *Bridge) refreshRunningCredentials(ctx context.Context, r *run) error {+ if r.CredentialIssuedAt.IsZero() || time.Now().Before(r.CredentialIssuedAt.Add(credentialRefreshInterval)) {+ return nil+ }+ resources, _, rotating, err := b.sessionResources(ctx, r.Resources)+ if err != nil {+ // The run is already executing; a failed refresh (for example a+ // just-revoked installation) must not kill it. Retry next tick.+ b.log.WarnContext(ctx, "Qoder credential refresh failed", "task_id", r.TaskID, "error", err)+ r.CredentialIssuedAt = time.Now().Add(-credentialRefreshInterval + time.Minute)+ return b.persist()+ }+ if !rotating {+ // Credentials became manual mid-flight (for example an operator bound+ // a PAT); nothing expires anymore.+ r.CredentialIssuedAt = time.Time{}+ return b.persist()+ }+ if err := b.refreshRepositoryCredentials(ctx, r.SessionID, resources); err != nil {+ b.log.WarnContext(ctx, "Qoder credential refresh push failed", "task_id", r.TaskID, "error", err)+ if errors.Is(err, errRefreshRefused) {+ r.CredentialIssuedAt = time.Time{}+ } else {+ r.CredentialIssuedAt = time.Now().Add(-credentialRefreshInterval + time.Minute)+ }+ return b.persist()+ }+ r.CredentialIssuedAt = time.Now()+ return b.persist()+}+// sessionAgentID accepts the agent as a bare ID or as an object with an id.func sessionAgentID(raw json.RawMessage) string {var id stringdiff --git a/server/internal/qoderruntime/concurrency_test.go b/server/internal/qoderruntime/concurrency_test.goindex 86d81bbd08..0623457eb8 100644--- a/server/internal/qoderruntime/concurrency_test.go+++ b/server/internal/qoderruntime/concurrency_test.go@@ -10,6 +10,7 @@ import ("strings""sync""testing"+ "time""github.com/multica-ai/multica/server/internal/daemon")@@ -30,22 +31,50 @@ type multiHarness struct {prompts map[string]stringmetadata map[string]map[string]stringresources map[string][]map[string]any- issue string- downloads map[string]string- uploads int- mounts map[string][]map[string]any- mountStatus int- // calls records attachment mounts and message sends in order.+ // mounted models each session's mounted resources like the official API:+ // repositories registered at creation with sesr_… ids, files appended by+ // the add-resource endpoint, tokens updated by the per-resource endpoint.+ mounted map[string][]mountedResource+ tokenLog []tokenUpdate+ // resourcePageSize bounds GET /sessions/{id}/resources pages (default 100).+ resourcePageSize int+ issue string+ downloads map[string]string+ uploads int+ mounts map[string][]map[string]any+ mountStatus int+ // resourceStatus queues one-time HTTP statuses for credential-update+ // POSTs; once empty, updates are recorded normally.+ resourceStatus []int+ // calls records credential updates, attachment mounts and message sends in order.calls []string}+type mountedResource struct {+ id, typ, url, fileID string+}++type tokenUpdate struct {+ session, resourceID, token string+}++// mountResource registers a created or added resource and hands out the next+// sesr_ id.+func (h *multiHarness) mountResource(session string, res map[string]any) {+ id := fmt.Sprintf("sesr_%d", len(h.mounted[session])+1)+ typ, _ := res["type"].(string)+ url, _ := res["url"].(string)+ fileID, _ := res["file_id"].(string)+ h.mounted[session] = append(h.mounted[session], mountedResource{id: id, typ: typ, url: url, fileID: fileID})+}+func newTask(id, prior string) *daemon.Task {return &daemon.Task{ID: id, RuntimeID: "runtime-1", WorkspaceID: workspaceID, IssueID: "issue-" + id, IssueIdentifier: "MUL-42", AuthToken: "mat_task", PriorSessionID: prior, Agent: &daemon.AgentData{Instructions: "Run tests", RuntimeConfig: json.RawMessage(`{"qoder_agent_id":"agent_1"}`)}}}func setupMulti(t *testing.T, limit int, tasks ...*daemon.Task) *multiHarness {t.Helper()- h := &multiHarness{queue: tasks, status: map[string]string{}, completed: map[string]map[string]any{}, failed: map[string]map[string]any{}, sessions: map[string][]map[string]any{}, sessionStatus: map[string]string{}, prompts: map[string]string{}, metadata: map[string]map[string]string{}, resources: map[string][]map[string]any{}, downloads: map[string]string{}, mounts: map[string][]map[string]any{}}+ h := &multiHarness{queue: tasks, status: map[string]string{}, completed: map[string]map[string]any{}, failed: map[string]map[string]any{}, sessions: map[string][]map[string]any{}, sessionStatus: map[string]string{}, prompts: map[string]string{}, metadata: map[string]map[string]string{}, resources: map[string][]map[string]any{}, downloads: map[string]string{}, mounts: map[string][]map[string]any{}, mounted: map[string][]mountedResource{}}taskID := func(path string) string {rest := strings.TrimPrefix(path, "/api/daemon/tasks/")return rest[:strings.Index(rest, "/")]@@ -118,20 +147,85 @@ func setupMulti(t *testing.T, limit int, tasks ...*daemon.Task) *multiHarness {json.NewDecoder(r.Body).Decode(&req)h.metadata[id] = req.Metadatah.resources[id] = req.Resources+ for _, res := range req.Resources {+ if typ, _ := res["type"].(string); typ == "github_repository" {+ h.mountResource(id, res)+ }+ }fmt.Fprintf(w, `{"id":%q}`, id)case r.URL.Path == "/files" && r.Method == http.MethodPost:h.uploads++fmt.Fprintf(w, `{"id":"file_%d"}`, h.uploads)case len(parts) == 3 && parts[2] == "resources" && r.Method == http.MethodPost:+ // The official add-resource endpoint only accepts file resources.+ var res map[string]any+ json.NewDecoder(r.Body).Decode(&res)+ if typ, _ := res["type"].(string); typ != "file" {+ w.WriteHeader(http.StatusBadRequest)+ io.WriteString(w, `{"error":{"message":"only file resources can be added"}}`)+ return+ }if h.mountStatus != 0 {w.WriteHeader(h.mountStatus)return}- var res map[string]any- json.NewDecoder(r.Body).Decode(&res)h.mounts[parts[1]] = append(h.mounts[parts[1]], res)+ h.mountResource(parts[1], res)h.calls = append(h.calls, "mount "+parts[1])io.WriteString(w, `{}`)+ case len(parts) == 3 && parts[2] == "resources" && r.Method == http.MethodGet:+ // The resource list pages like the event list, with opaque cursors.+ mounted := h.mounted[parts[1]]+ after := strings.TrimPrefix(r.URL.Query().Get("page"), "next:")+ if after != "" {+ for i, res := range mounted {+ if res.id == after {+ mounted = mounted[i+1:]+ break+ }+ }+ }+ size := h.resourcePageSize+ if size <= 0 {+ size = 100+ }+ data := make([]map[string]string, 0, len(mounted))+ for _, res := range mounted {+ data = append(data, map[string]string{"id": res.id, "type": res.typ, "url": res.url})+ }+ page := map[string]any{"data": data, "has_more": false}+ if len(mounted) > size {+ page["data"] = data[:size]+ page["has_more"] = true+ page["next_page"] = "next:" + mounted[size-1].id+ }+ json.NewEncoder(w).Encode(page)+ case len(parts) == 4 && parts[2] == "resources" && r.Method == http.MethodPost:+ // The per-resource credential update endpoint.+ if len(h.resourceStatus) > 0 {+ status := h.resourceStatus[0]+ h.resourceStatus = h.resourceStatus[1:]+ w.WriteHeader(status)+ return+ }+ var res *mountedResource+ for i := range h.mounted[parts[1]] {+ if h.mounted[parts[1]][i].id == parts[3] {+ res = &h.mounted[parts[1]][i]+ break+ }+ }+ if res == nil || res.typ != "github_repository" {+ http.NotFound(w, r)+ return+ }+ var body struct {+ AuthorizationToken string `json:"authorization_token"`+ }+ json.NewDecoder(r.Body).Decode(&body)+ h.tokenLog = append(h.tokenLog, tokenUpdate{session: parts[1], resourceID: parts[3], token: body.AuthorizationToken})+ h.calls = append(h.calls, "credential "+parts[1])+ io.WriteString(w, `{}`)case len(parts) == 3 && parts[2] == "events" && r.Method == http.MethodPost:h.calls = append(h.calls, "send "+parts[1])var req struct {@@ -444,10 +538,304 @@ func TestResourceFingerprintSurvivesJournalRoundTrip(t *testing.T) {if err := json.Unmarshal(raw, &restored); err != nil {t.Fatal(err)}- if got, want := resourceFingerprint(restored.Resources), resourceFingerprint([]map[string]any{release}); got != want {+ entries := func(resources ...map[string]any) []fingerprintEntry {+ out := make([]fingerprintEntry, 0, len(resources))+ for _, res := range resources {+ key, err := repositoryKey(res["url"].(string))+ if err != nil {+ t.Fatal(err)+ }+ out = append(out, fingerprintEntry{key: key, branch: checkoutBranch(res["checkout"]), credential: "credential"})+ }+ return out+ }+ if got, want := resourceFingerprint(entries(restored.Resources...)), resourceFingerprint(entries(release)); got != want {t.Fatal("restored resources fingerprint differently")}- if resourceFingerprint(restored.Resources) == resourceFingerprint([]map[string]any{defaultBranch}) {+ if resourceFingerprint(entries(restored.Resources...)) == resourceFingerprint(entries(defaultBranch)) {t.Fatal("restored branch dropped from fingerprint")}}++// A follow-up whose repository credential comes from the GitHub App+// integration keeps reusing the idle session — the fingerprint hashes the+// installation binding, not the rotating token — and pushes the fresh token+// into the session before the follow-up message.+func TestFollowUpRefreshesRotatingGitHubAppCredential(t *testing.T) {+ task := newTask("task-1", "sess_prev")+ task.Agent.RuntimeConfig = json.RawMessage(`{"qoder_agent_id":"agent_1","repository":{"url":"https://github.com/acme/app","ref":"main"}}`)+ h := setupMulti(t, 1, task)+ h.sessionStatus["sess_prev"] = "idle"+ h.metadata["sess_prev"] = map[string]string{resourcesMetadataKey: resourceFingerprint([]fingerprintEntry{{key: "https://github.com/acme/app", branch: "main", credential: "github_app:424242"}})}+ h.sessions["sess_prev"] = []map[string]any{+ {"id": "evt_old_0", "type": "user.message", "content": []map[string]string{{"type": "text", "text": "earlier run"}}},+ {"id": "evt_old_1", "type": "session.status_idle", "stop_reason": map[string]string{"type": "end_turn"}},+ }+ // The prior session already carries the mounted repository; only its+ // credential may be updated, and only through the per-resource endpoint.+ h.mountResource("sess_prev", map[string]any{"type": "github_repository", "url": "https://github.com/acme/app"})+ h.b.cfg.GitHubAppToken = func(context.Context, string, string) (string, int64, error) {+ return "ghs_fresh", 424242, nil+ }+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ if h.creates != 0 || len(h.sentTo) != 1 || h.sentTo[0] != "sess_prev" {+ t.Fatalf("follow-up did not continue: creates=%d sentTo=%v", h.creates, h.sentTo)+ }+ if len(h.tokenLog) != 1 || h.tokenLog[0].session != "sess_prev" || h.tokenLog[0].resourceID != "sesr_1" || h.tokenLog[0].token != "ghs_fresh" {+ t.Fatalf("rotating credential not updated on the mounted resource: %+v", h.tokenLog)+ }+ if fmt.Sprint(h.calls) != "[credential sess_prev send sess_prev]" {+ t.Fatalf("calls: %v", h.calls)+ }+}++// A rotating credential refresh that is rate limited or fails transiently+// must defer the follow-up message, not send it with the stale session+// credential: the run stays "prepared" until the refresh completed, and the+// retry re-resolves, refreshes and only then sends.+func TestFollowUpRefreshRetriesAfterDeferral(t *testing.T) {+ task := newTask("task-1", "sess_prev")+ task.Agent.RuntimeConfig = json.RawMessage(`{"qoder_agent_id":"agent_1","repository":{"url":"https://github.com/acme/app","ref":"main"}}`)+ h := setupMulti(t, 1, task)+ h.sessionStatus["sess_prev"] = "idle"+ h.metadata["sess_prev"] = map[string]string{resourcesMetadataKey: resourceFingerprint([]fingerprintEntry{{key: "https://github.com/acme/app", branch: "main", credential: "github_app:424242"}})}+ h.sessions["sess_prev"] = []map[string]any{+ {"id": "evt_old_0", "type": "user.message", "content": []map[string]string{{"type": "text", "text": "earlier run"}}},+ {"id": "evt_old_1", "type": "session.status_idle", "stop_reason": map[string]string{"type": "end_turn"}},+ }+ h.mountResource("sess_prev", map[string]any{"type": "github_repository", "url": "https://github.com/acme/app"})+ h.b.cfg.GitHubAppToken = func(context.Context, string, string) (string, int64, error) {+ return "ghs_fresh", 424242, nil+ }+ refresh := func() *run {+ t.Helper()+ run := h.b.state.first()+ if run == nil {+ t.Fatal("run dropped while refresh deferred")+ }+ return run+ }+ // First resource POST is rate limited: the tick defers with the run still+ // "prepared" and no message sent.+ h.resourceStatus = []int{http.StatusTooManyRequests}+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ run := refresh()+ if run.Phase != "prepared" || run.Continued != true {+ t.Fatalf("rate limit did not defer inside prepared: %#v", run)+ }+ if len(h.sentTo) != 0 || len(h.mounts["sess_prev"]) != 0 {+ t.Fatalf("message or mount escaped the deferral: sentTo=%v mounts=%v", h.sentTo, h.mounts["sess_prev"])+ }+ // The backoff holds the run; a tick inside it changes nothing.+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ if len(h.sentTo) != 0 || len(h.mounts["sess_prev"]) != 0 {+ t.Fatalf("backoff ignored: sentTo=%v mounts=%v", h.sentTo, h.mounts["sess_prev"])+ }+ // After the backoff, a transient server error also leaves the run+ // prepared with nothing sent.+ run = refresh()+ run.RetryAt = time.Now().Add(-time.Second)+ h.resourceStatus = []int{http.StatusInternalServerError}+ if err := h.b.step(context.Background()); err == nil {+ t.Fatal("transient refresh failure swallowed")+ }+ run = refresh()+ if run.Phase != "prepared" {+ t.Fatalf("transient error changed state: %#v", run)+ }+ if len(h.sentTo) != 0 {+ t.Fatalf("message sent despite failed refresh: %v", h.sentTo)+ }+ // A clean retry refreshes the credential and only then sends.+ run = refresh()+ run.RetryAt = time.Now().Add(-time.Second)+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ run = refresh()+ if run.Phase != "running" {+ t.Fatalf("retry did not complete the refresh: phase=%s", run.Phase)+ }+ if len(h.sentTo) != 1 || h.sentTo[0] != "sess_prev" || h.creates != 0 {+ t.Fatalf("follow-up did not continue after retry: creates=%d sentTo=%v", h.creates, h.sentTo)+ }+ if len(h.tokenLog) != 1 || h.tokenLog[0].session != "sess_prev" || h.tokenLog[0].resourceID != "sesr_1" || h.tokenLog[0].token != "ghs_fresh" {+ t.Fatalf("credential not refreshed on retry: %+v", h.tokenLog)+ }+ if fmt.Sprint(h.calls) != "[credential sess_prev send sess_prev]" {+ t.Fatalf("calls: %v", h.calls)+ }+}++// A run whose rotating GitHub App credential ages past the refresh interval+// re-issues it and pushes the fresh token into the live session, so git work+// after the token's one-hour lifetime still succeeds.+func TestRunningSessionRefreshesRotatingCredential(t *testing.T) {+ task := newTask("task-1", "")+ task.Agent.RuntimeConfig = json.RawMessage(`{"qoder_agent_id":"agent_1","repository":{"url":"https://github.com/acme/app","ref":"main"}}`)+ h := setupMulti(t, 1, task)+ issued := 0+ tokens := []string{"ghs_first", "ghs_second"}+ h.b.cfg.GitHubAppToken = func(context.Context, string, string) (string, int64, error) {+ token := tokens[issued]+ issued+++ return token, 424242, nil+ }+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ run := h.b.state.first()+ if run == nil || run.Phase != "running" || run.CredentialIssuedAt.IsZero() {+ t.Fatalf("run did not start with a rotating credential: %#v", run)+ }+ if h.resources["sess_new_1"][0]["authorization_token"] != "ghs_first" {+ t.Fatalf("creation credential: %v", h.resources["sess_new_1"])+ }+ // A fresh issuance is not due yet: no refresh, no extra issuance.+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ if issued != 1 || len(h.tokenLog) != 0 {+ t.Fatalf("premature refresh: issued=%d updates=%v", issued, h.tokenLog)+ }+ // Past the interval the live session receives a fresh token on its+ // mounted repository, without a new session or message.+ run.CredentialIssuedAt = time.Now().Add(-credentialRefreshInterval - time.Minute)+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ if issued != 2 || h.creates != 1 || len(h.sentTo) != 1 {+ t.Fatalf("refresh spawned work: issued=%d creates=%d sentTo=%v", issued, h.creates, h.sentTo)+ }+ if len(h.tokenLog) != 1 || h.tokenLog[0].session != "sess_new_1" || h.tokenLog[0].resourceID != "sesr_1" || h.tokenLog[0].token != "ghs_second" {+ t.Fatalf("live session not refreshed: %+v", h.tokenLog)+ }+}++// When a deferred credential refresh outlives the prior session (it stopped+// being idle), the follow-up starts a clean fresh session: the new session is+// not treated as continued, so its files are mounted exactly once and the+// stale credit base of the dead session is dropped.+func TestDeferredRefreshFallsBackToFreshSession(t *testing.T) {+ task := newTask("task-1", "sess_prev")+ task.Agent.RuntimeConfig = json.RawMessage(`{"qoder_agent_id":"agent_1","repository":{"url":"https://github.com/acme/app","ref":"main"}}`)+ h := setupMulti(t, 1, task)+ chatFollowUp(h, [3]string{"notes.md", "text/markdown", "hello"})+ h.metadata["sess_prev"] = map[string]string{resourcesMetadataKey: resourceFingerprint([]fingerprintEntry{{key: "https://github.com/acme/app", branch: "main", credential: "github_app:424242"}})}+ h.mountResource("sess_prev", map[string]any{"type": "github_repository", "url": "https://github.com/acme/app"})+ h.b.cfg.GitHubAppToken = func(context.Context, string, string) (string, int64, error) {+ return "ghs_fresh", 424242, nil+ }+ h.resourceStatus = []int{http.StatusTooManyRequests}+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ run := h.b.state.first()+ if run == nil || run.Phase != "prepared" || !run.Continued || len(h.sentTo) != 0 || len(h.calls) != 0 {+ t.Fatalf("refresh was not deferred: %#v calls=%v", run, h.calls)+ }+ // The prior session becomes busy during the backoff window.+ h.sessionStatus["sess_prev"] = "running"+ run.RetryAt = time.Now().Add(-time.Second)+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ run = h.b.state.first()+ if run == nil || run.Continued || run.SessionID != "sess_new_1" || run.Credits.Base != nil {+ t.Fatalf("fresh session carries continued state: %#v", run)+ }+ if h.creates != 1 || fmt.Sprint(h.calls) != "[send sess_new_1]" {+ t.Fatalf("fresh session not clean: creates=%d calls=%v", h.creates, h.calls)+ }+ // The attachment came with the created session, not remounted.+ if len(h.mounts["sess_new_1"]) != 0 || len(h.resources["sess_new_1"]) != 2 {+ t.Fatalf("files mounted twice: mounts=%v resources=%v", h.mounts["sess_new_1"], h.resources["sess_new_1"])+ }+}++// The repository can sit beyond the first page of the session's resource+// list; the refresh must follow the cursor instead of missing it.+func TestFollowUpRefreshFindsRepositoryBeyondFirstPage(t *testing.T) {+ task := newTask("task-1", "sess_prev")+ task.Agent.RuntimeConfig = json.RawMessage(`{"qoder_agent_id":"agent_1","repository":{"url":"https://github.com/acme/app","ref":"main"}}`)+ h := setupMulti(t, 1, task)+ h.sessionStatus["sess_prev"] = "idle"+ h.metadata["sess_prev"] = map[string]string{resourcesMetadataKey: resourceFingerprint([]fingerprintEntry{{key: "https://github.com/acme/app", branch: "main", credential: "github_app:424242"}})}+ h.sessions["sess_prev"] = []map[string]any{+ {"id": "evt_old_0", "type": "user.message", "content": []map[string]string{{"type": "text", "text": "earlier run"}}},+ {"id": "evt_old_1", "type": "session.status_idle", "stop_reason": map[string]string{"type": "end_turn"}},+ }+ h.mountResource("sess_prev", map[string]any{"type": "file", "file_id": "file_earlier"})+ h.mountResource("sess_prev", map[string]any{"type": "github_repository", "url": "https://github.com/acme/app"})+ h.resourcePageSize = 1+ h.b.cfg.GitHubAppToken = func(context.Context, string, string) (string, int64, error) {+ return "ghs_fresh", 424242, nil+ }+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ if h.creates != 0 || len(h.sentTo) != 1 || h.sentTo[0] != "sess_prev" {+ t.Fatalf("follow-up did not continue: creates=%d sentTo=%v", h.creates, h.sentTo)+ }+ if len(h.tokenLog) != 1 || h.tokenLog[0].resourceID != "sesr_2" || h.tokenLog[0].token != "ghs_fresh" {+ t.Fatalf("paged repository not refreshed: %+v", h.tokenLog)+ }+}++// A prior session that no longer carries the mounted repository cannot take+// the credential update; the follow-up starts a fresh session instead of+// reusing it with a stale credential.+func TestFollowUpStartsFreshWhenRepositoryUnmounted(t *testing.T) {+ task := newTask("task-1", "sess_prev")+ task.Agent.RuntimeConfig = json.RawMessage(`{"qoder_agent_id":"agent_1","repository":{"url":"https://github.com/acme/app","ref":"main"}}`)+ h := setupMulti(t, 1, task)+ h.sessionStatus["sess_prev"] = "idle"+ h.metadata["sess_prev"] = map[string]string{resourcesMetadataKey: resourceFingerprint([]fingerprintEntry{{key: "https://github.com/acme/app", branch: "main", credential: "github_app:424242"}})}+ h.sessions["sess_prev"] = []map[string]any{+ {"id": "evt_old_0", "type": "user.message", "content": []map[string]string{{"type": "text", "text": "earlier run"}}},+ {"id": "evt_old_1", "type": "session.status_idle", "stop_reason": map[string]string{"type": "end_turn"}},+ }+ // No github_repository mounted on the prior session.+ h.b.cfg.GitHubAppToken = func(context.Context, string, string) (string, int64, error) {+ return "ghs_fresh", 424242, nil+ }+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ run := h.b.state.first()+ if h.creates != 1 || run.Continued || len(h.tokenLog) != 0 {+ t.Fatalf("unmounted repository not refused: creates=%d continued=%v updates=%v", h.creates, run.Continued, h.tokenLog)+ }+ if len(h.sentTo) != 1 || h.sentTo[0] != "sess_new_1" {+ t.Fatalf("fresh session did not take over: %v", h.sentTo)+ }+}++// Once the workspace installation no longer covers the repository, the+// pre-run credential re-resolution rejects the follow-up instead of reusing+// the idle session with a stale credential.+func TestFollowUpBlockedWhenInstallationRevoked(t *testing.T) {+ task := newTask("task-1", "sess_prev")+ task.Agent.RuntimeConfig = json.RawMessage(`{"qoder_agent_id":"agent_1","repository":{"url":"https://github.com/acme/app","ref":"main"}}`)+ h := setupMulti(t, 1, task)+ h.sessionStatus["sess_prev"] = "idle"+ h.metadata["sess_prev"] = map[string]string{resourcesMetadataKey: resourceFingerprint([]fingerprintEntry{{key: "https://github.com/acme/app", branch: "main", credential: "github_app:424242"}})}+ h.b.cfg.GitHubAppToken = func(context.Context, string, string) (string, int64, error) {+ return "", 0, ErrGitHubAppNotCovered+ }+ if err := h.b.step(context.Background()); err != nil {+ t.Fatal(err)+ }+ if h.failed["task-1"] == nil || h.failed["task-1"]["error"] != "no GitHub credential configured for project repository" {+ t.Fatalf("revoked installation not blocked: %#v", h.failed["task-1"])+ }+ if h.creates != 0 || len(h.sentTo) != 0 {+ t.Fatalf("revoked installation still ran: creates=%d sentTo=%v", h.creates, h.sentTo)+ }+}diff --git a/server/internal/qoderruntime/credentials.go b/server/internal/qoderruntime/credentials.goindex ac1a2ebea8..418c4fb0ed 100644--- a/server/internal/qoderruntime/credentials.go+++ b/server/internal/qoderruntime/credentials.go@@ -1,6 +1,8 @@package qoderruntimeimport (+ "context"+ "errors""fmt""io""net/url"@@ -22,46 +24,96 @@ func repositoryKey(raw string) (string, error) {return "https://github.com/" + strings.ToLower(strings.Join(parts, "/")), nil}-// sessionResources creates an ephemeral request copy; never put secrets in the journal.-func (b *Bridge) sessionResources(resources []map[string]any) ([]map[string]any, error) {+// ErrGitHubAppNotCovered reports that the workspace's GitHub App integration+// cannot authorize a repository; callers fall back to other credentials or+// reject the run.+var ErrGitHubAppNotCovered = errors.New("GitHub App installation does not cover the repository")++// ErrGitHubAppPermissions reports that the workspace's GitHub App is+// installed without the repository write permissions automatic authorization+// needs. Unlike ErrGitHubAppNotCovered this is operator-actionable: approve+// the added permissions on GitHub or fall back to a manual repository token.+var ErrGitHubAppPermissions = errors.New("workspace GitHub App has not granted repository write permissions; approve Contents and Pull requests write access on GitHub, or add a manual repository token")++// sessionResources creates an ephemeral request copy; never put secrets in the+// journal. A repository resolves its credential in priority order: an explicit+// manual token binding first, then a short-lived single-repository token from+// the workspace's GitHub App integration. GitHub App tokens rotate on every+// request, so the fingerprint hashes the stable authorization identity+// (installation + repository + branch) instead of the token, letting+// follow-ups reuse an idle session while the pre-run re-resolution still+// blocks a revoked installation.+func (b *Bridge) sessionResources(ctx context.Context, resources []map[string]any) ([]map[string]any, string, bool, error) {out := make([]map[string]any, 0, len(resources))+ entries := make([]fingerprintEntry, 0, len(resources))+ rotating := falsefor _, resource := range resources {raw, _ := resource["url"].(string)key, err := repositoryKey(raw)if err != nil {- return nil, err+ return nil, "", false, err}token := b.cfg.GitHubTokens[key]path := ""for configured, file := range b.cfg.GitHubTokenFiles {candidate, err := repositoryKey(configured)if err != nil {- return nil, fmt.Errorf("invalid GitHub credential repository binding")+ return nil, "", false, fmt.Errorf("invalid GitHub credential repository binding")}if candidate == key {if path != "" {- return nil, fmt.Errorf("duplicate GitHub credential repository binding")+ return nil, "", false, fmt.Errorf("duplicate GitHub credential repository binding")}path = file}}- if path == "" && token == "" {- return nil, fmt.Errorf("no GitHub credential configured for project repository")+ credential := token+ if credential == "" && path != "" {+ if credential, err = readRepositoryToken(path); err != nil {+ return nil, "", false, err+ }}- if token == "" {- token, err = readRepositoryToken(path)+ identity := credential+ if credential == "" {+ if b.cfg.GitHubAppToken == nil {+ return nil, "", false, fmt.Errorf("no GitHub credential configured for project repository")+ }+ owner, repo, ok := repositoryParts(key)+ if !ok {+ return nil, "", false, fmt.Errorf("no GitHub credential configured for project repository")+ }+ issued, installation, err := b.cfg.GitHubAppToken(ctx, owner, repo)+ if errors.Is(err, ErrGitHubAppNotCovered) {+ return nil, "", false, fmt.Errorf("no GitHub credential configured for project repository")+ }if err != nil {- return nil, err+ return nil, "", false, err+ }+ if issued == "" || installation == 0 {+ return nil, "", false, fmt.Errorf("GitHub App token issuer returned no credential")}+ credential = issued+ identity = fmt.Sprintf("github_app:%d", installation)+ rotating = true}copy := make(map[string]any, len(resource)+1)for k, v := range resource {copy[k] = v}- copy["authorization_token"] = token+ copy["authorization_token"] = credentialout = append(out, copy)+ entries = append(entries, fingerprintEntry{key: key, branch: checkoutBranch(resource["checkout"]), credential: identity})+ }+ return out, resourceFingerprint(entries), rotating, nil+}++// repositoryParts splits a canonical repository key into owner and name.+func repositoryParts(key string) (owner, repo string, ok bool) {+ parts := strings.Split(strings.TrimPrefix(key, "https://github.com/"), "/")+ if len(parts) != 2 || parts[0] == "" || parts[1] == "" {+ return "", "", false}- return out, nil+ return parts[0], parts[1], true}func readRepositoryToken(path string) (string, error) {diff --git a/server/internal/qoderruntime/credentials_test.go b/server/internal/qoderruntime/credentials_test.goindex a9fe47436d..5c989de22f 100644--- a/server/internal/qoderruntime/credentials_test.go+++ b/server/internal/qoderruntime/credentials_test.go@@ -1,6 +1,9 @@package qoderruntimeimport (+ "context"+ "errors"+ "fmt""os""path/filepath""strings"@@ -15,13 +18,16 @@ func TestRepositoryCredentialRequestOnly(t *testing.T) {}b := &Bridge{cfg: Config{GitHubTokenFiles: map[string]string{"https://github.com/Owner/Repo.git": file}}}r := &run{Resources: []map[string]any{{"type": "github_repository", "url": "https://github.com/owner/repo", "checkout": map[string]string{"type": "branch", "name": "main"}}}}- request, err := b.sessionResources(r.Resources)+ request, _, rotating, err := b.sessionResources(context.Background(), r.Resources)if err != nil {t.Fatal(err)}if request[0]["authorization_token"] != "test-secret" {t.Fatal("missing request credential")}+ if rotating {+ t.Fatal("manual credential marked rotating")+ }state := filepath.Join(dir, "state.json")if err := save(state, &journal{Runs: []*run{r}}); err != nil {t.Fatal(err)@@ -36,16 +42,102 @@ func TestRepositoryCredentialRequestOnly(t *testing.T) {if err := os.WriteFile(file, []byte("rotated-secret"), 0600); err != nil {t.Fatal(err)}- request, err = b.sessionResources(r.Resources)+ request, _, _, err = b.sessionResources(context.Background(), r.Resources)if err != nil || request[0]["authorization_token"] != "rotated-secret" {t.Fatal("credential rotation not picked up")}r.Resources[0]["url"] = "https://github.com/owner/another"- if _, err := b.sessionResources(r.Resources); err == nil {+ if _, _, _, err := b.sessionResources(context.Background(), r.Resources); err == nil {t.Fatal("credential crossed repository boundary")}}+// A GitHub App credential backs the same boundary guarantees: single+// repository scope, a stable fingerprint across token rotation, and a hard+// block once the workspace installation no longer covers the repository.+func TestGitHubAppCredentialRotationAndFingerprint(t *testing.T) {+ resource := func(url string) map[string]any {+ return map[string]any{"type": "github_repository", "url": url, "checkout": map[string]string{"type": "branch", "name": "main"}}+ }+ var issued []string+ var requested [][2]string+ b := &Bridge{cfg: Config{GitHubAppToken: func(ctx context.Context, owner, repo string) (string, int64, error) {+ requested = append(requested, [2]string{owner, repo})+ issued = append(issued, fmt.Sprintf("ghs_%d", len(issued)))+ return issued[len(issued)-1], 424242, nil+ }}}+ resources := []map[string]any{resource("https://github.com/acme/app")}+ first, fingerprint, rotating, err := b.sessionResources(context.Background(), resources)+ if err != nil {+ t.Fatal(err)+ }+ if !rotating || first[0]["authorization_token"] != "ghs_0" {+ t.Fatalf("app credential not issued: rotating=%v", rotating)+ }+ if len(requested) != 1 || requested[0] != [2]string{"acme", "app"} {+ t.Fatalf("issuer scoped to wrong repository: %v", requested)+ }+ second, repeat, _, err := b.sessionResources(context.Background(), resources)+ if err != nil {+ t.Fatal(err)+ }+ if second[0]["authorization_token"] != "ghs_1" {+ t.Fatal("short-lived token not rotated between resolutions")+ }+ if repeat != fingerprint {+ t.Fatal("rotating credential changed the session fingerprint")+ }+ // A manual token outranks the App integration and restores the static+ // fingerprint behaviour.+ manual := &Bridge{cfg: Config{GitHubTokens: map[string]string{"https://github.com/acme/app": "pat"}, GitHubAppToken: func(context.Context, string, string) (string, int64, error) {+ t.Fatal("manual token must outrank the GitHub App")+ return "", 0, nil+ }}}+ request, manualPrint, rotating, err := manual.sessionResources(context.Background(), resources)+ if err != nil || request[0]["authorization_token"] != "pat" || rotating {+ t.Fatalf("manual priority broken: %v %v", request, err)+ }+ if manualPrint == fingerprint {+ t.Fatal("manual credential shares the app credential fingerprint")+ }+ // Losing coverage — an unbound installation — must block the run.+ revoked := &Bridge{cfg: Config{GitHubAppToken: func(context.Context, string, string) (string, int64, error) {+ return "", 0, ErrGitHubAppNotCovered+ }}}+ if _, _, _, err := revoked.sessionResources(context.Background(), resources); err == nil || err.Error() != "no GitHub credential configured for project repository" {+ t.Fatalf("revoked installation not blocked: %v", err)+ }+}++func TestGitHubAppCredentialIssuerScope(t *testing.T) {+ var requested [][2]string+ b := &Bridge{cfg: Config{GitHubAppToken: func(ctx context.Context, owner, repo string) (string, int64, error) {+ requested = append(requested, [2]string{owner, repo})+ return "ghs_x", 7, nil+ }}}+ if _, _, _, err := b.sessionResources(context.Background(), []map[string]any{{"url": "https://github.com/Acme/App"}}); err != nil {+ t.Fatal(err)+ }+ if len(requested) != 1 || requested[0] != [2]string{"acme", "app"} {+ t.Fatalf("issuer not scoped to the target repository: %v", requested)+ }+}++// An App that is installed without the repository write permissions surfaces+// the operator-actionable message, not the generic "no credential" one.+func TestGitHubAppPermissionErrorIsActionable(t *testing.T) {+ b := &Bridge{cfg: Config{GitHubAppToken: func(context.Context, string, string) (string, int64, error) {+ return "", 0, fmt.Errorf("issue token: %w", ErrGitHubAppPermissions)+ }}}+ _, _, _, err := b.sessionResources(context.Background(), []map[string]any{{"url": "https://github.com/acme/app"}})+ if !errors.Is(err, ErrGitHubAppPermissions) {+ t.Fatalf("sentinel lost: %v", err)+ }+ if !strings.Contains(err.Error(), "approve Contents and Pull requests write access") || strings.Contains(err.Error(), "no GitHub credential configured") {+ t.Fatalf("not actionable or misclassified: %v", err)+ }+}+func TestRepositoryCredentialValidation(t *testing.T) {for _, raw := range []string{"https://github.com/owner", "https://github.com:443/a/b", "https://github.com/a/b?token=x", "https://[email protected]/a/b", "https://github.com/a/b/extra", "https://github.com/a/%62", "https://github.com/a/.."} {if _, err := repositoryKey(raw); err == nil {diff --git a/server/internal/qoderruntime/prompt.go b/server/internal/qoderruntime/prompt.goindex f70634186b..7b482b993c 100644--- a/server/internal/qoderruntime/prompt.go+++ b/server/internal/qoderruntime/prompt.go@@ -116,7 +116,7 @@ func (b *Bridge) prepare(ctx context.Context, t *claimedTask) (*run, error) {}if len(r.Resources) == 0 && len(t.Repos) == 1 {if resource, err := repositoryResource(Repository{URL: t.Repos[0].URL}); err == nil {- if _, err := b.sessionResources([]map[string]any{resource}); err == nil {+ if _, _, _, err := b.sessionResources(ctx, []map[string]any{resource}); err == nil {r.Resources = append(r.Resources, resource)}}diff --git a/server/internal/qoderruntime/state.go b/server/internal/qoderruntime/state.goindex 8094fe7a2e..e2cfb90776 100644--- a/server/internal/qoderruntime/state.go+++ b/server/internal/qoderruntime/state.go@@ -40,21 +40,27 @@ type run struct {// chat run carries only its message's files (MountFiles), mounted one by// one into a continued session; MountedFiles counts those already mounted.// Images go into the task message.- Files []map[string]any `json:"files,omitempty"`- MountFiles bool `json:"mount_files,omitempty"`- MountedFiles int `json:"mounted_files,omitempty"`- Images []map[string]string `json:"images,omitempty"`- Phase string `json:"phase"`- Cursor string `json:"cursor,omitempty"`- Seq int `json:"seq"`- Started bool `json:"started"`- Output string `json:"output,omitempty"`- Failure string `json:"failure,omitempty"`- Outcome string `json:"outcome,omitempty"`- QuickCreate *quickCreate `json:"quick_create,omitempty"`- Reply *replyFiles `json:"reply,omitempty"`- Credits runCredits `json:"credits"`- Leader *squadLeader `json:"leader,omitempty"`+ Files []map[string]any `json:"files,omitempty"`+ MountFiles bool `json:"mount_files,omitempty"`+ MountedFiles int `json:"mounted_files,omitempty"`+ // CredentialIssuedAt timestamps the last GitHub App token issuance for+ // this run. Non-zero means the repository credential rotates and the live+ // session gets a fresh token before the one-hour expiry; the zero value+ // covers static credentials and refreshes that were refused for good.+ // Only the timestamp is journaled, never the token.+ CredentialIssuedAt time.Time `json:"credential_issued_at,omitempty"`+ Images []map[string]string `json:"images,omitempty"`+ Phase string `json:"phase"`+ Cursor string `json:"cursor,omitempty"`+ Seq int `json:"seq"`+ Started bool `json:"started"`+ Output string `json:"output,omitempty"`+ Failure string `json:"failure,omitempty"`+ Outcome string `json:"outcome,omitempty"`+ QuickCreate *quickCreate `json:"quick_create,omitempty"`+ Reply *replyFiles `json:"reply,omitempty"`+ Credits runCredits `json:"credits"`+ Leader *squadLeader `json:"leader,omitempty"`}func save(path string, j *journal) error {