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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion mod_api/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,13 +651,14 @@ def get_github_link():
The stored token is never part of this response. The URL carries only
the client id and the scope asked for, both of which are public.
"""
from mod_auth.controllers import github_login_of
from run import config

user = g.api_user
client_id = config.get('GITHUB_CLIENT_ID', '')
return single_response({
'linked': user.github_token is not None,
'github_login': user.github_login,
'github_login': github_login_of(user),
'authorize_url': (
'https://github.com/login/oauth/authorize'
f'?client_id={client_id}&scope=public_repo'),
Expand Down
12 changes: 2 additions & 10 deletions mod_api/routes/runs.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,16 +171,8 @@ def _validate_run_permissions(user, target_repo, main_repo_full):
)
else:
owner = target_repo.split('/')[0]
github_login = getattr(user, 'github_login', None)

if not github_login and getattr(user, 'github_token', None):
from mod_auth.controllers import fetch_username_from_token
github_login = fetch_username_from_token(user)
if github_login:
user.github_login = github_login
g.db.add(user)

github_login = github_login or ''
from mod_auth.controllers import github_login_of
github_login = github_login_of(user) or ''

if not github_login or owner.lower() != github_login.lower():
return make_error_response(
Expand Down
21 changes: 21 additions & 0 deletions mod_auth/controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,27 @@ def fetch_username_from_token(user=None) -> Any:
return None


def github_login_of(user) -> Optional[str]:
"""
Return the GitHub login of a connected account, looking it up if missing.

The login is normally stored by the OAuth callback, but that lookup can
fail, and accounts connected before the column existed never had one.
Asking GitHub again the next time the login is needed repairs them.

:param user: the account to read and, when the lookup succeeds, update
:return: the login, or None when not connected or GitHub did not answer
"""
if user.github_login or user.github_token is None:
return user.github_login
login = fetch_username_from_token(user)
if login:
user.github_login = login
g.db.add(user)
g.db.commit()
return login


@mod_auth.route('/github_callback', methods=['GET', 'POST'])
@template_renderer()
def github_callback():
Expand Down
31 changes: 31 additions & 0 deletions tests/api/test_routes_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,37 @@ def test_github_link_reports_status_without_the_token(self):
res.json['authorize_url'])
self.assertNotIn('client_secret', res.json['authorize_url'])

@patch('mod_auth.controllers.fetch_username_from_token', return_value='found-later')
def test_github_link_looks_up_a_missing_login_and_keeps_it(self, mock_fetch):
user = User.query.filter(User.id == self.user_id).first()
user.github_token = 'gho_secret_value'
user.github_login = None
g.db.commit()

res = self.client.get(
'/api/v1/auth/me/github', headers=self._auth(name='gh3'))

self.assertEqual(res.json['github_login'], 'found-later')
user = User.query.filter(User.id == self.user_id).first()
self.assertEqual(user.github_login, 'found-later')

# Stored now, so the next request does not ask GitHub again.
self.client.get('/api/v1/auth/me/github', headers=self._auth(name='gh4'))
mock_fetch.assert_called_once()

@patch('mod_auth.controllers.fetch_username_from_token', return_value=None)
def test_github_link_without_a_login_when_github_does_not_answer(self, mock_fetch):
user = User.query.filter(User.id == self.user_id).first()
user.github_token = 'gho_secret_value'
user.github_login = None
g.db.commit()

res = self.client.get(
'/api/v1/auth/me/github', headers=self._auth(name='gh5'))

self.assertTrue(res.json['linked'])
self.assertIsNone(res.json['github_login'])

def test_github_unlink_forgets_the_connection(self):
user = User.query.filter(User.id == self.user_id).first()
user.github_token = 'gho_secret_value'
Expand Down
52 changes: 50 additions & 2 deletions web/src/components/DiffDrawer.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";

import { DiffDrawer, type DiffTarget } from "@/components/DiffDrawer";
Expand All @@ -22,6 +23,7 @@ function jsonResponse(status: number, body: unknown): Response {

afterEach(() => {
vi.unstubAllGlobals();
localStorage.clear();
});

describe("DiffDrawer", () => {
Expand All @@ -44,8 +46,13 @@ describe("DiffDrawer", () => {

expect(screen.getByText("Test #7")).toBeInTheDocument();
expect(screen.getByText(/pal\.ts/)).toBeInTheDocument();
expect(await screen.findByText("-old caption")).toBeInTheDocument();
expect(screen.getByText("+new caption")).toBeInTheDocument();
// The pair sits one above the other with only the changed word marked.
const removed = await screen.findByText("old");
expect(removed.tagName).toBe("MARK");
expect(removed.closest("div")?.textContent).toBe("−old caption");
const added = screen.getByText("new");
expect(added.tagName).toBe("MARK");
expect(added.closest("div")?.textContent).toBe("+new caption");
});

it("explains when the output file is missing from storage", async () => {
Expand All @@ -58,4 +65,45 @@ describe("DiffDrawer", () => {
await screen.findByText(/output file for this result isn't present in storage/i),
).toBeInTheDocument();
});

it("offers promotion to admins only, and confirms before posting it", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) =>
String(input).includes("/baseline-approval")
? jsonResponse(200, { status: "approved" })
: jsonResponse(200, { content: "" }),
);
vi.stubGlobal("fetch", fetchMock);

const { wrapper } = createWrapper();
const view = render(<DiffDrawer target={target} onClose={vi.fn()} />, { wrapper });
expect(screen.queryByText(/promote to baseline/i)).toBeNull();
view.unmount();

signIn("admin");
render(<DiffDrawer target={target} onClose={vi.fn()} />, { wrapper });
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: /promote to baseline/i }));
expect(fetchMock.mock.calls.some(([u]) => String(u).includes("baseline-approval"))).toBe(false);

await user.click(await screen.findByRole("button", { name: "Replace baseline" }));
expect(await screen.findByText("Baseline promoted.")).toBeInTheDocument();
const [url, init] = fetchMock.mock.calls.find(([u]) => String(u).includes("baseline-approval"))!;
expect(String(url)).toContain("/runs/21/samples/14/baseline-approval");
expect(JSON.parse(String(init?.body))).toMatchObject({
regression_id: 7,
output_id: 3,
});
});
});

function signIn(role: string) {
localStorage.setItem(
"sp-session",
JSON.stringify({
token: "t",
email: "[email protected]",
role,
expires_at: new Date(Date.now() + 60_000).toISOString(),
}),
);
}
Loading
Loading