From c2fa234df42b51f9cbe39f1c7d899688590ec5ce Mon Sep 17 00:00:00 2001 From: Yuval Yeret <6516902+yyeret@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:53:34 -0500 Subject: [PATCH] Improve GitHub App access UX, 404 guidance, and accessible repo listing --- cloudflare_app.py | 166 ++++++++++++++++++-- index.html | 62 +++++++- mcp_server.py | 46 +++++- public/index.html | 62 +++++++- tests/frontend/api-response.test.cjs | 29 ++++ tests/integration/test_mcp_app.py | 29 ++++ tests/integration/test_private_issue_api.py | 65 ++++++++ 7 files changed, 444 insertions(+), 15 deletions(-) diff --git a/cloudflare_app.py b/cloudflare_app.py index aabd731..39342ad 100644 --- a/cloudflare_app.py +++ b/cloudflare_app.py @@ -145,6 +145,15 @@ def repository_preference_key(provider: str, account_id: str | int) -> str: return f'{provider}:{digest}' +def github_app_install_url(env) -> str: + if not env: + return "" + slug = getattr(env, "GITHUB_APP_SLUG", "") or getattr(env, "MCP_GITHUB_APP_SLUG", "") + if isinstance(slug, str) and re.fullmatch(r"[A-Za-z0-9-]{1,100}", slug): + return f"https://github.com/apps/{slug}/installations/new" + return "" + + @app.get("/api/auth/config") async def auth_config(request: Request): env = environment(request) @@ -153,6 +162,7 @@ async def auth_config(request: Request): "required": auth_required(request), "github_enabled": bool(env and getattr(env, 'GITHUB_OAUTH_CLIENT_ID', '') and getattr(env, 'GITHUB_OAUTH_CLIENT_SECRET', '') and getattr(env, 'GITHUB_OAUTH_REDIRECT_URI', '')), + "github_app_install_url": github_app_install_url(env), } @@ -259,7 +269,13 @@ async def delete_account(request: Request): return response -async def public_repo_exists(repo: str, token: str | None, *, allow_private=False) -> dict: +async def public_repo_exists( + repo: str, + token: str | None, + *, + allow_private: bool = False, + github_login: str | None = None, +) -> dict: headers = {"Accept": "application/vnd.github+json", "User-Agent": "github-flow-analytics/0.1"} if token: headers["Authorization"] = f"Bearer {token}" @@ -269,7 +285,17 @@ async def public_repo_exists(repo: str, token: str | None, *, allow_private=Fals except (TimeoutError, httpx.HTTPError) as exc: raise HTTPException(502, 'GitHub could not be reached. Please try again.') from exc if status == 404: - raise HTTPException(status_code=404, detail="Repository not found or unavailable to the connected GitHub identity.") + if github_login: + detail = ( + f"Repository not found or the GitHub App is not installed on this repository for @{github_login}. " + "Grant repository access in GitHub App settings and try again." + ) + else: + detail = ( + "Repository not found. If it is private, connect GitHub, install the GitHub App on the repository, " + "and allow private analysis." + ) + raise HTTPException(status_code=404, detail=detail) if status == 403: raise HTTPException(status_code=429, detail="GitHub is currently refusing analysis requests from this service. Please try again later.") @@ -282,6 +308,105 @@ async def public_repo_exists(repo: str, token: str | None, *, allow_private=Fals return data +async def list_accessible_repositories(identity, *, include_private: bool = True) -> dict[str, Any]: + headers = { + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {identity.token}", + "User-Agent": "github-flow-analytics/0.1", + "X-GitHub-Api-Version": "2022-11-28", + } + try: + status, _, payload = await asyncio.wait_for( + request_json("https://api.github.com/user/installations?per_page=100", headers=headers, timeout=10), 10 + ) + except (TimeoutError, httpx.HTTPError) as exc: + raise HTTPException(502, "GitHub could not be reached. Please try again.") from exc + if status == 401: + raise HTTPException(401, "Your GitHub credential expired or was revoked. Sign in again.") + + repos_by_key: dict[str, dict[str, Any]] = {} + truncated = False + installation_count = 0 + source = "github_app" + + def collect(items: list[Any]) -> None: + for item in items: + if not isinstance(item, dict): + continue + full_name = item.get("full_name") + if not isinstance(full_name, str) or "/" not in full_name: + continue + is_private = bool(item.get("private")) + if is_private and not include_private: + continue + repos_by_key[full_name.lower()] = { + "full_name": full_name, + "private": is_private, + "pushed_at": item.get("pushed_at") if isinstance(item.get("pushed_at"), str) else "", + } + + if status == 200 and isinstance(payload, dict) and isinstance(payload.get("installations"), list): + installations = payload["installations"] + installation_count = len(installations) + if installation_count > 10: + truncated = True + for inst in installations[:10]: + inst_id = inst.get("id") if isinstance(inst, dict) else None + if type(inst_id) is not int or inst_id <= 0: + continue + try: + r_status, _, r_payload = await asyncio.wait_for( + request_json( + f"https://api.github.com/user/installations/{inst_id}/repositories?per_page=100", + headers=headers, + timeout=10, + ), + 10, + ) + except (TimeoutError, httpx.HTTPError) as exc: + raise HTTPException(502, "GitHub could not be reached. Please try again.") from exc + if r_status == 200 and isinstance(r_payload, dict) and isinstance(r_payload.get("repositories"), list): + items = r_payload["repositories"] + collect(items) + total = r_payload.get("total_count") + if isinstance(total, int) and total > len(items): + truncated = True + elif status == 403: + source = "oauth_or_pat" + try: + r_status, _, r_payload = await asyncio.wait_for( + request_json("https://api.github.com/user/repos?per_page=100&sort=pushed", headers=headers, timeout=10), + 10, + ) + except (TimeoutError, httpx.HTTPError) as exc: + raise HTTPException(502, "GitHub could not be reached. Please try again.") from exc + if r_status == 401: + raise HTTPException(401, "Your GitHub credential expired or was revoked. Sign in again.") + if r_status != 200 or not isinstance(r_payload, list): + raise HTTPException(502, "GitHub could not list accessible repositories. Please try again.") + collect(r_payload) + if len(r_payload) >= 100: + truncated = True + else: + raise HTTPException(502, "GitHub could not list accessible repositories. Please try again.") + + repositories = sorted( + repos_by_key.values(), + key=lambda item: (item["pushed_at"], item["full_name"].lower()), + reverse=True, + ) + if len(repositories) > 200: + repositories = repositories[:200] + truncated = True + return { + "login": identity.login, + "source": source, + "installation_count": installation_count, + "repositories": repositories, + "truncated": truncated, + } + + async def caller_github(request): if request.headers.get('authorization') is not None or getattr(request, 'cookies', {}).get(github_auth.GITHUB_SESSION_COOKIE): try: @@ -307,15 +432,17 @@ async def authorize_analysis(request, *, expected_account=None): async def repository_access(repo, request, identity, allow_private): token = identity.token if identity else getattr(environment(request), 'GITHUB_TOKEN', None) - metadata = await public_repo_exists(repo, token, allow_private=allow_private) + metadata = await public_repo_exists( + repo, token, allow_private=allow_private, github_login=identity.login if identity else None + ) if metadata['private'] and not identity: raise HTTPException(401, 'Connect your GitHub identity or supply its bearer credential for private analysis.') # Anonymous content reads cannot cross a later public-to-private transition. return token if metadata['private'] else None, metadata['private'] -async def mcp_repository_access(repo, token, allow_private): - metadata = await public_repo_exists(repo, token, allow_private=allow_private) +async def mcp_repository_access(repo, token, allow_private, *, github_login=None): + metadata = await public_repo_exists(repo, token, allow_private=allow_private, github_login=github_login) repository_id = metadata.get('id') if type(repository_id) is not int or repository_id < 1: raise HTTPException(502, 'GitHub returned unreadable repository access information.') @@ -342,6 +469,16 @@ async def health(): return {"ok": True} +@app.get("/api/github/repos") +async def github_repos(request: Request): + identity = await caller_github(request) + if not identity: + raise HTTPException(401, "Connect your GitHub identity to list accessible repositories.") + result = await list_accessible_repositories(identity, include_private=True) + result["install_url"] = github_app_install_url(environment(request)) + return result + + @app.post("/api/analyze") async def analyze_repo(req: AnalyzeRequest, request: Request): identity = await authorize_analysis(request, expected_account=request.headers.get('X-Analysis-Account')) @@ -353,7 +490,9 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False): repo = parse_repo(req.repo_url) env = request.scope.get("env") if full_dashboard: - repo, private, repository_id = await mcp_repository_access(repo, identity.token, req.allow_private) + repo, private, repository_id = await mcp_repository_access( + repo, identity.token, req.allow_private, github_login=identity.login + ) token = identity.token if private else None else: token, private = await repository_access(repo, request, identity, req.allow_private) @@ -446,7 +585,9 @@ async def issue_value_for_identity(req, request, identity, *, mcp=False): await enforce_limit(request, 'analyze', 10, identity=identity if mcp else None) repo = parse_repo(req.repo_url) if mcp: - repo, private, repository_id = await mcp_repository_access(repo, identity.token, req.allow_private) + repo, private, repository_id = await mcp_repository_access( + repo, identity.token, req.allow_private, github_login=identity.login + ) token = identity.token if private else None else: token, private = await repository_access(repo, request, identity, req.allow_private) @@ -581,7 +722,7 @@ async def chat_for_identity(req, request, identity, *, full_dashboard=False): if full_dashboard: if private and not req.allow_private: raise HTTPException(403, 'Allow private analysis to coach against this snapshot.') - metadata = await public_repo_exists(repo, identity.token, allow_private=private) + metadata = await public_repo_exists(repo, identity.token, allow_private=private, github_login=identity.login) if metadata['private'] != private or metadata.get('id') != metrics.get('repository_id'): raise HTTPException(403, 'Repository access changed. Analyze it again.') if private: @@ -618,7 +759,14 @@ async def chat_for_identity(req, request, identity, *, full_dashboard=False): raise HTTPException(status_code=502, detail="AI service is temporarily unavailable.") from exc -install_mcp(app, analyze_for_identity, issue_value_for_identity, chat_for_identity) +install_mcp( + app, + analyze_for_identity, + issue_value_for_identity, + chat_for_identity, + list_repos=list_accessible_repositories, + install_url_for_env=github_app_install_url, +) @app.api_route("/{path:path}", methods=["GET", "HEAD"]) diff --git a/index.html b/index.html index f6633f3..6d48610 100644 --- a/index.html +++ b/index.html @@ -120,6 +120,9 @@ } .btn-ghost:hover{border-color:var(--violet);color:var(--text);} #repo-setup a{color:#c4b5fd;} + .github-access-bar:not([hidden]){display:flex;flex-wrap:wrap;align-items:center;gap:.4rem 1rem;font-size:.875rem;color:var(--text-dim);} + #github-status{color:#6ee7b7;font-weight:500;} + #github-repos-summary{color:var(--text-dim);} #repo-setup details{color:var(--text-dim);font-size:.875rem;} #repo-setup summary{cursor:pointer;} .provider-keys{display:grid;gap:.5rem;margin-top:.75rem;} @@ -512,17 +515,24 @@

⚡ GitHub Flow Analytics

+ - +
AI assessment API keys (optional) @@ -741,6 +751,52 @@

Flowy AI Coach

let repositoryPreferenceKey; let restoredPrivateRepository; + function updateGitHubAccessUI(session) { + const bar = document.getElementById('github-access-bar'); + const status = document.getElementById('github-status'); + const connect = document.getElementById('github-connect'); + const install = document.getElementById('github-app-install'); + const enabled = Boolean(authConfig.github_enabled); + bar.hidden = !enabled; + if (!enabled) return; + const isGitHub = session?.provider === 'github' && Boolean(session.login); + status.hidden = !isGitHub; + status.textContent = isGitHub ? `Connected to GitHub as @${session.login}` : ''; + connect.hidden = isGitHub; + const installUrl = typeof authConfig.github_app_install_url === 'string' ? authConfig.github_app_install_url : ''; + install.hidden = !installUrl; + if (installUrl) install.href = installUrl; + } + + async function loadAccessibleRepositories() { + const summaryEl = document.getElementById('github-repos-summary'); + const datalist = document.getElementById('accessible-repos'); + if (!summaryEl || !datalist) return; + try { + const response = await fetch('/api/github/repos', {credentials:'same-origin', signal: AbortSignal.timeout(12000)}); + if (!response.ok) return; + const data = await response.json(); + const repos = Array.isArray(data?.repositories) ? data.repositories : []; + datalist.replaceChildren(...repos.map(repo => { + const option = document.createElement('option'); + option.value = repo.full_name; + option.label = repo.private ? `${repo.full_name} (private)` : repo.full_name; + return option; + })); + const privateCount = repos.filter(repo => repo.private).length; + if (repos.length === 0) { + summaryEl.textContent = '0 repositories granted to GitHub App'; + } else { + const suffix = data.truncated ? '+' : ''; + summaryEl.textContent = `${repos.length}${suffix} accessible ${repos.length === 1 ? 'repo' : 'repos'}` + + (privateCount ? ` (${privateCount} private)` : ''); + } + summaryEl.hidden = false; + } catch { + // Non-fatal: manual repository entry still works. + } + } + async function configureAuthentication() { try { const signal = AbortSignal.timeout(12000); @@ -751,7 +807,7 @@

Flowy AI Coach

} authConfig = await readApiResponse(response); document.getElementById('github-signin').hidden = !authConfig.github_enabled; - document.getElementById('github-connect').hidden = !authConfig.github_enabled; + updateGitHubAccessUI(null); document.getElementById('chat-github-help').hidden = !authConfig.github_enabled; document.getElementById('chat-github-unavailable').hidden = authConfig.github_enabled !== false; if (authConfig.required) document.getElementById('login-gate').classList.add('visible'); @@ -804,8 +860,10 @@

Flowy AI Coach

document.getElementById('login-gate').classList.remove('visible'); document.getElementById('account-actions').hidden = false; document.getElementById('account-email').textContent = session.login || session.email; + updateGitHubAccessUI(session); repositoryPreferenceKey = session.account_key; document.getElementById('analyze-btn').disabled = false; + if (session?.provider === 'github') loadAccessibleRepositories(); if (repositoryPreferenceKey) restoreLastRepository(); } diff --git a/mcp_server.py b/mcp_server.py index 27cc98b..1536e03 100644 --- a/mcp_server.py +++ b/mcp_server.py @@ -65,6 +65,11 @@ class CoachArgs(BaseModel): history: list[Message] = Field(default_factory=list, max_length=10) +class ListReposArgs(BaseModel): + model_config = ConfigDict(extra='forbid') + query: str | None = Field(default=None, min_length=1, max_length=100) + + def definition(name, description, model, *, ui=True, app_only=False): security = [{'type': 'oauth2', 'scopes': [SCOPE]}] meta = {'securitySchemes': security, 'openai/widgetAccessible': True} @@ -94,6 +99,10 @@ def definition(name, description, model, *, ui=True, app_only=False): RefreshArgs, ui=False, app_only=True), definition('assess_dashboard_issues', 'Assess the selected issues in the dashboard.', IssueArgs, ui=False, app_only=True), + definition('list_accessible_repositories', + 'List repositories accessible to the connected GitHub App identity. ' + 'Only includes private repositories when private analysis was enabled during MCP sign-in.', + ListReposArgs, ui=False), ] @@ -139,7 +148,7 @@ def routing_name(header): return header -def install_mcp(app, analyze, issue_value, coach): +def install_mcp(app, analyze, issue_value, coach, *, list_repos=None, install_url_for_env=None): async def call_tool(params, request, grant): name = params.get('name') args = params.get('arguments', {}) @@ -153,14 +162,47 @@ async def call_tool(params, request, grant): inputs = IssueArgs.model_validate(args) elif name == 'ask_flow_coach': inputs = CoachArgs.model_validate(args) + elif name == 'list_accessible_repositories': + inputs = ListReposArgs.model_validate(args) else: raise HTTPException(400, 'Unknown GitHub Analytics tool.') - if inputs.allow_private and not grant['private_consent']: + if not isinstance(inputs, ListReposArgs) and inputs.allow_private and not grant['private_consent']: raise HTTPException(403, 'Reconnect GitHub Flow Analytics and enable private repositories during sign-in.') identity = await identify_token(grant['github_token']) if str(identity.github_id) != str(grant['github_id']): raise HTTPException(401, 'The GitHub identity changed. Reconnect GitHub Flow Analytics.') + if isinstance(inputs, ListReposArgs): + if list_repos is None: + raise HTTPException(503, 'Repository listing is unavailable.') + private_enabled = bool(grant['private_consent']) + result = await list_repos(identity, include_private=private_enabled) + repos = result.get('repositories', []) + if inputs.query: + needle = inputs.query.strip().lower() + repos = [item for item in repos if needle in item['full_name'].lower()] + install_url = install_url_for_env(request.scope.get('env')) if install_url_for_env else '' + data = { + 'login': result.get('login', identity.login), + 'source': result.get('source', 'github_app'), + 'installation_count': result.get('installation_count', 0), + 'private_consent_enabled': private_enabled, + 'repositories': repos, + 'truncated': bool(result.get('truncated', False)), + **({'install_url': install_url} if install_url else {}), + } + names = [item['full_name'] for item in repos] + if names: + preview = ', '.join(names[:25]) + extra = f' (+{len(names) - 25} more)' if len(names) > 25 else '' + text = f'@{data["login"]} can access {len(names)} repositories: {preview}{extra}.' + else: + text = f'No accessible repositories found for @{data["login"]}.' + if install_url: + text += f' Install or configure the GitHub App: {install_url}' + if not private_enabled: + text += ' Private repositories are hidden because private analysis was not enabled during sign-in.' + return tool_result(text, data) if isinstance(inputs, CoachArgs): answer = await coach(inputs, request, identity, full_dashboard=True) return tool_result(answer['reply'], answer) diff --git a/public/index.html b/public/index.html index f6633f3..6d48610 100644 --- a/public/index.html +++ b/public/index.html @@ -120,6 +120,9 @@ } .btn-ghost:hover{border-color:var(--violet);color:var(--text);} #repo-setup a{color:#c4b5fd;} + .github-access-bar:not([hidden]){display:flex;flex-wrap:wrap;align-items:center;gap:.4rem 1rem;font-size:.875rem;color:var(--text-dim);} + #github-status{color:#6ee7b7;font-weight:500;} + #github-repos-summary{color:var(--text-dim);} #repo-setup details{color:var(--text-dim);font-size:.875rem;} #repo-setup summary{cursor:pointer;} .provider-keys{display:grid;gap:.5rem;margin-top:.75rem;} @@ -512,17 +515,24 @@

⚡ GitHub Flow Analytics

+ - +
AI assessment API keys (optional) @@ -741,6 +751,52 @@

Flowy AI Coach

let repositoryPreferenceKey; let restoredPrivateRepository; + function updateGitHubAccessUI(session) { + const bar = document.getElementById('github-access-bar'); + const status = document.getElementById('github-status'); + const connect = document.getElementById('github-connect'); + const install = document.getElementById('github-app-install'); + const enabled = Boolean(authConfig.github_enabled); + bar.hidden = !enabled; + if (!enabled) return; + const isGitHub = session?.provider === 'github' && Boolean(session.login); + status.hidden = !isGitHub; + status.textContent = isGitHub ? `Connected to GitHub as @${session.login}` : ''; + connect.hidden = isGitHub; + const installUrl = typeof authConfig.github_app_install_url === 'string' ? authConfig.github_app_install_url : ''; + install.hidden = !installUrl; + if (installUrl) install.href = installUrl; + } + + async function loadAccessibleRepositories() { + const summaryEl = document.getElementById('github-repos-summary'); + const datalist = document.getElementById('accessible-repos'); + if (!summaryEl || !datalist) return; + try { + const response = await fetch('/api/github/repos', {credentials:'same-origin', signal: AbortSignal.timeout(12000)}); + if (!response.ok) return; + const data = await response.json(); + const repos = Array.isArray(data?.repositories) ? data.repositories : []; + datalist.replaceChildren(...repos.map(repo => { + const option = document.createElement('option'); + option.value = repo.full_name; + option.label = repo.private ? `${repo.full_name} (private)` : repo.full_name; + return option; + })); + const privateCount = repos.filter(repo => repo.private).length; + if (repos.length === 0) { + summaryEl.textContent = '0 repositories granted to GitHub App'; + } else { + const suffix = data.truncated ? '+' : ''; + summaryEl.textContent = `${repos.length}${suffix} accessible ${repos.length === 1 ? 'repo' : 'repos'}` + + (privateCount ? ` (${privateCount} private)` : ''); + } + summaryEl.hidden = false; + } catch { + // Non-fatal: manual repository entry still works. + } + } + async function configureAuthentication() { try { const signal = AbortSignal.timeout(12000); @@ -751,7 +807,7 @@

Flowy AI Coach

} authConfig = await readApiResponse(response); document.getElementById('github-signin').hidden = !authConfig.github_enabled; - document.getElementById('github-connect').hidden = !authConfig.github_enabled; + updateGitHubAccessUI(null); document.getElementById('chat-github-help').hidden = !authConfig.github_enabled; document.getElementById('chat-github-unavailable').hidden = authConfig.github_enabled !== false; if (authConfig.required) document.getElementById('login-gate').classList.add('visible'); @@ -804,8 +860,10 @@

Flowy AI Coach

document.getElementById('login-gate').classList.remove('visible'); document.getElementById('account-actions').hidden = false; document.getElementById('account-email').textContent = session.login || session.email; + updateGitHubAccessUI(session); repositoryPreferenceKey = session.account_key; document.getElementById('analyze-btn').disabled = false; + if (session?.provider === 'github') loadAccessibleRepositories(); if (repositoryPreferenceKey) restoreLastRepository(); } diff --git a/tests/frontend/api-response.test.cjs b/tests/frontend/api-response.test.cjs index c6cdfcf..335245b 100644 --- a/tests/frontend/api-response.test.cjs +++ b/tests/frontend/api-response.test.cjs @@ -70,3 +70,32 @@ test('an empty-description PR displays its reason without a score beside assesse assert.match(unscored, /Not scored: The PR description is empty/); assert.doesNotMatch(unscored, /|null|NaN/); }); + +test('GitHub access bar shows connected login and app install link when signed in with GitHub', () => { + const elements = Object.fromEntries( + ['github-access-bar', 'github-status', 'github-connect', 'github-app-install'] + .map(id => [id, {hidden: true, textContent: '', href: ''}]) + ); + const authStart = html.indexOf(' function updateGitHubAccessUI('); + const authEnd = html.indexOf(' async function loadAccessibleRepositories(', authStart); + assert.ok(authStart > -1 && authEnd > authStart, 'updateGitHubAccessUI helper should exist'); + const context = vm.createContext({ + authConfig: {github_enabled: true, github_app_install_url: 'https://github.com/apps/flowy/installations/new'}, + document: {getElementById: id => elements[id]}, + }); + vm.runInContext(html.slice(authStart, authEnd), context); + + context.updateGitHubAccessUI({signed_in: true, email: 'user@example.test'}); + assert.equal(elements['github-access-bar'].hidden, false); + assert.equal(elements['github-connect'].hidden, false); + assert.equal(elements['github-status'].hidden, true); + assert.equal(elements['github-app-install'].hidden, false); + assert.equal(elements['github-app-install'].href, 'https://github.com/apps/flowy/installations/new'); + + context.updateGitHubAccessUI({signed_in: true, provider: 'github', login: 'yyeret'}); + assert.equal(elements['github-access-bar'].hidden, false); + assert.equal(elements['github-connect'].hidden, true); + assert.equal(elements['github-status'].hidden, false); + assert.equal(elements['github-status'].textContent, 'Connected to GitHub as @yyeret'); + assert.equal(elements['github-app-install'].hidden, false); +}); diff --git a/tests/integration/test_mcp_app.py b/tests/integration/test_mcp_app.py index ccdf878..f5b761d 100644 --- a/tests/integration/test_mcp_app.py +++ b/tests/integration/test_mcp_app.py @@ -364,3 +364,32 @@ async def anonymous_issue(*args, **kwargs): assert record['assessed'] == 1 assert record['items'][0]['cost_of_delay'] == 29 assert record['sources']['readme'] + + +def test_mcp_list_accessible_repositories_respects_private_consent_and_query(client, monkeypatch): + async def installations(url, **kwargs): + assert kwargs['headers']['Authorization'] == 'Bearer ghu_provider-secret' + if url.endswith('/user/installations?per_page=100'): + return 200, {}, {'installations': [{'id': 42}]} + if url.endswith('/user/installations/42/repositories?per_page=100'): + return 200, {}, { + 'total_count': 2, + 'repositories': [ + {'full_name': 'o/public-flow', 'private': False, 'pushed_at': '2026-11-18T00:00:00Z'}, + {'full_name': 'o/secret-flow', 'private': True, 'pushed_at': '2026-11-19T00:00:00Z'}, + ], + } + raise AssertionError(f'Unexpected URL: {url}') + + monkeypatch.setattr(hosted, 'request_json', installations) + + public_token = connect(client, private=False) + public_result = tool(client, 'list_accessible_repositories', {}, public_token) + assert [r['full_name'] for r in public_result['structuredContent']['repositories']] == ['o/public-flow'] + assert public_result['structuredContent']['private_consent_enabled'] is False + assert 'o/secret-flow' not in str(public_result) + + private_token = connect(client, private=True) + private_result = tool(client, 'list_accessible_repositories', {'query': 'secret'}, private_token) + assert [r['full_name'] for r in private_result['structuredContent']['repositories']] == ['o/secret-flow'] + assert private_result['structuredContent']['private_consent_enabled'] is True diff --git a/tests/integration/test_private_issue_api.py b/tests/integration/test_private_issue_api.py index a3b5088..889ecd2 100644 --- a/tests/integration/test_private_issue_api.py +++ b/tests/integration/test_private_issue_api.py @@ -236,3 +236,68 @@ async def __aenter__(self): return FakeAIClient() 'repo': 'o/r', 'analysis_id': 'original', 'message': 'Next?'}) assert response.status_code == 200 assert response.json()['reply'] == 'Throughput rose.' + + +def test_auth_config_exposes_valid_github_app_install_url(monkeypatch): + client, env, _, _ = setup(monkeypatch) + assert client.get('/api/auth/config').json()['github_app_install_url'] == '' + + env.MCP_GITHUB_APP_SLUG = 'flowy-analytics' + assert client.get('/api/auth/config').json()['github_app_install_url'] == ( + 'https://github.com/apps/flowy-analytics/installations/new' + ) + + env.GITHUB_APP_SLUG = 'browser-app' + assert client.get('/api/auth/config').json()['github_app_install_url'] == ( + 'https://github.com/apps/browser-app/installations/new' + ) + + env.GITHUB_APP_SLUG = 'bad/slug' + assert client.get('/api/auth/config').json()['github_app_install_url'] == '' + + +def test_repo_404_distinguishes_missing_github_identity_from_app_installation(monkeypatch): + client, _, _, _ = setup(monkeypatch) + async def missing(*_, **__): return 404, {}, {'message': 'Not Found'} + monkeypatch.setattr(hosted, 'request_json', missing) + + unauthenticated = client.post('/api/analyze', json={'repo_url': 'o/private-repo', 'allow_private': True}) + assert unauthenticated.status_code == 404 + assert 'connect GitHub' in unauthenticated.json()['detail'] + assert 'connected GitHub identity' not in unauthenticated.json()['detail'] + + authenticated = client.post('/api/analyze', headers={'Authorization': 'Bearer caller-a'}, + json={'repo_url': 'o/private-repo', 'allow_private': True}) + assert authenticated.status_code == 404 + assert '@owner' in authenticated.json()['detail'] + assert 'GitHub App' in authenticated.json()['detail'] + + +def test_github_repos_endpoint_lists_installed_repositories_for_connected_identity(monkeypatch): + client, env, _, _ = setup(monkeypatch) + env.MCP_GITHUB_APP_SLUG = 'flowy-analytics' + + async def github_installations(url, **kwargs): + assert kwargs['headers']['Authorization'] == 'Bearer caller-a' + if url.endswith('/user/installations?per_page=100'): + return 200, {}, {'installations': [{'id': 99}]} + if url.endswith('/user/installations/99/repositories?per_page=100'): + return 200, {}, { + 'total_count': 2, + 'repositories': [ + {'full_name': 'owner/public-repo', 'private': False, 'pushed_at': '2026-11-10T00:00:00Z'}, + {'full_name': 'owner/private-repo', 'private': True, 'pushed_at': '2026-11-19T00:00:00Z'}, + ], + } + raise AssertionError(f'Unexpected URL: {url}') + + monkeypatch.setattr(hosted, 'request_json', github_installations) + assert client.get('/api/github/repos').status_code == 401 + response = client.get('/api/github/repos', headers={'Authorization': 'Bearer caller-a'}) + assert response.status_code == 200 + body = response.json() + assert body['login'] == 'owner' + assert body['source'] == 'github_app' + assert body['installation_count'] == 1 + assert body['install_url'] == 'https://github.com/apps/flowy-analytics/installations/new' + assert [r['full_name'] for r in body['repositories']] == ['owner/private-repo', 'owner/public-repo']