pygitweb 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pygitweb/__init__.py +22 -0
- pygitweb/__meta__.py +9 -0
- pygitweb/actions.py +1303 -0
- pygitweb/addproject_permissions_test.py +114 -0
- pygitweb/api/__init__.py +0 -0
- pygitweb/api/action.py +20 -0
- pygitweb/api/plugins/__init__.py +0 -0
- pygitweb/api/plugins/project_zip.py +71 -0
- pygitweb/api/project.py +67 -0
- pygitweb/api/subpage.py +22 -0
- pygitweb/auth.py +387 -0
- pygitweb/auth.schema.json +106 -0
- pygitweb/auth_config.py +243 -0
- pygitweb/auth_oauth.py +343 -0
- pygitweb/auth_test.py +390 -0
- pygitweb/boards_permissions_test.py +113 -0
- pygitweb/change_queue.py +110 -0
- pygitweb/change_queue_routes_test.py +146 -0
- pygitweb/change_queue_test.py +91 -0
- pygitweb/comments_permissions_test.py +140 -0
- pygitweb/config.py +185 -0
- pygitweb/conftest.py +43 -0
- pygitweb/dependencies.py +87 -0
- pygitweb/formatting.py +182 -0
- pygitweb/formatting_test.py +68 -0
- pygitweb/git_helpers.py +454 -0
- pygitweb/git_helpers_test.py +223 -0
- pygitweb/gravatar.py +16 -0
- pygitweb/gravatar_test.py +10 -0
- pygitweb/hooks_install.py +278 -0
- pygitweb/hooks_install_test.py +363 -0
- pygitweb/hooks_permissions_test.py +116 -0
- pygitweb/main.py +887 -0
- pygitweb/merge_requests.py +230 -0
- pygitweb/merge_requests_test.py +85 -0
- pygitweb/mr_permissions_test.py +148 -0
- pygitweb/password_hash.py +74 -0
- pygitweb/password_hash_test.py +20 -0
- pygitweb/permissions.py +209 -0
- pygitweb/permissions_test.py +86 -0
- pygitweb/plugin_loader.py +83 -0
- pygitweb/projects.py +213 -0
- pygitweb/projects_test.py +186 -0
- pygitweb/sessions.py +73 -0
- pygitweb/settings.py +412 -0
- pygitweb/settings.schema.json +73 -0
- pygitweb/settings_config.py +122 -0
- pygitweb/settings_config_test.py +101 -0
- pygitweb/settings_permissions_test.py +76 -0
- pygitweb/static/blob-view.js +133 -0
- pygitweb/static/board.js +839 -0
- pygitweb/static/hook-install.js +53 -0
- pygitweb/static/icons/cloud-down.svg +1 -0
- pygitweb/static/icons/cloud-exclamation.svg +1 -0
- pygitweb/static/icons/cloud-filled.svg +1 -0
- pygitweb/static/icons/cloud-storm.svg +1 -0
- pygitweb/static/icons/cloud-up.svg +1 -0
- pygitweb/static/icons/cloud.svg +1 -0
- pygitweb/static/logo.svg +44 -0
- pygitweb/static/main.css +1210 -0
- pygitweb/static/navbar-auth.js +82 -0
- pygitweb/static/readme-render.js +174 -0
- pygitweb/static/search-page.js +139 -0
- pygitweb/static/summary-ref-switcher.js +130 -0
- pygitweb/static/themes/solarized.css +34 -0
- pygitweb/tasks.py +595 -0
- pygitweb/tasks_permissions_test.py +137 -0
- pygitweb/tasks_routes_test.py +430 -0
- pygitweb/templates/addproject.html +174 -0
- pygitweb/templates/blobdiff.html +57 -0
- pygitweb/templates/board.html +31 -0
- pygitweb/templates/board_card.html +44 -0
- pygitweb/templates/commitdiff.html +57 -0
- pygitweb/templates/hooks_summary_cell.html +37 -0
- pygitweb/templates/login.html +37 -0
- pygitweb/templates/merge_request_summary_cell.html +18 -0
- pygitweb/templates/merge_request_tag.html +90 -0
- pygitweb/templates/pagination.html +44 -0
- pygitweb/templates/preamble.html +89 -0
- pygitweb/templates/project_settings.html +13 -0
- pygitweb/templates/pygit2_settings.html +12 -0
- pygitweb/templates/pygitweb_settings.html +12 -0
- pygitweb/templates/search.html +77 -0
- pygitweb/templates/settings_form_field.html +27 -0
- pygitweb/templates/table.html +15 -0
- pygitweb/templates/user_profile.html +10 -0
- pygitweb/templates_env.py +21 -0
- pygitweb/timeline_cache.py +243 -0
- pygitweb/validation.py +75 -0
- pygitweb/validation_test.py +167 -0
- pygitweb-0.1.0.dist-info/METADATA +165 -0
- pygitweb-0.1.0.dist-info/RECORD +95 -0
- pygitweb-0.1.0.dist-info/WHEEL +5 -0
- pygitweb-0.1.0.dist-info/licenses/LICENSE +21 -0
- pygitweb-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
from collections.abc import Generator
|
|
2
|
+
from unittest.mock import patch
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
from fastapi.testclient import TestClient
|
|
6
|
+
|
|
7
|
+
from pygitweb.auth_config import AuthConfig, LocalUser
|
|
8
|
+
from pygitweb.main import app
|
|
9
|
+
from pygitweb.permissions import PERMISSION_ADD_PROJECTS, PermissionsMap
|
|
10
|
+
|
|
11
|
+
_ADDPROJECTS_AUTH = AuthConfig(
|
|
12
|
+
auth_mode="local",
|
|
13
|
+
local_users=[LocalUser(user="admin", password="secret"), LocalUser(user="viewer", password="secret")],
|
|
14
|
+
oauth_permissions=PermissionsMap.model_validate({
|
|
15
|
+
"*": [],
|
|
16
|
+
PERMISSION_ADD_PROJECTS: ["admin"],
|
|
17
|
+
}),
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.fixture
|
|
22
|
+
def client() -> Generator[TestClient, None, None]:
|
|
23
|
+
with TestClient(app) as c:
|
|
24
|
+
yield c
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@pytest.fixture
|
|
28
|
+
def addprojects_auth() -> Generator[AuthConfig, None, None]:
|
|
29
|
+
with (
|
|
30
|
+
patch("pygitweb.auth_config.auth_config", _ADDPROJECTS_AUTH),
|
|
31
|
+
patch("pygitweb.auth.auth_config", _ADDPROJECTS_AUTH),
|
|
32
|
+
patch("pygitweb.main.auth_config", _ADDPROJECTS_AUTH),
|
|
33
|
+
):
|
|
34
|
+
yield _ADDPROJECTS_AUTH
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _login(client: TestClient, username: str) -> None:
|
|
38
|
+
client.post(
|
|
39
|
+
"/login",
|
|
40
|
+
data={"username": username, "password": "secret", "next": "/"},
|
|
41
|
+
follow_redirects=False,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_projectnamevalid_open_when_auth_disabled(client: TestClient) -> None:
|
|
46
|
+
from pygitweb.config import settings
|
|
47
|
+
|
|
48
|
+
with (
|
|
49
|
+
patch.object(settings, "AUTH", False),
|
|
50
|
+
patch("pygitweb.main.project_visible_in_list", return_value=False),
|
|
51
|
+
):
|
|
52
|
+
r = client.get("/projectnamevalid", params={"name": "newproj"})
|
|
53
|
+
assert r.status_code == 200
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_addproject_page_open_when_auth_disabled(client: TestClient) -> None:
|
|
57
|
+
from pygitweb.config import settings
|
|
58
|
+
|
|
59
|
+
with patch.object(settings, "AUTH", False):
|
|
60
|
+
r = client.get("/addproject")
|
|
61
|
+
assert r.status_code == 200
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_projectnamevalid_401_without_login(client: TestClient, addprojects_auth: AuthConfig) -> None:
|
|
65
|
+
from pygitweb.config import settings
|
|
66
|
+
|
|
67
|
+
with patch.object(settings, "AUTH", True):
|
|
68
|
+
r = client.get("/projectnamevalid", params={"name": "newproj"})
|
|
69
|
+
assert r.status_code == 401
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_projectnamevalid_allowed_with_grant(client: TestClient, addprojects_auth: AuthConfig) -> None:
|
|
73
|
+
from pygitweb.config import settings
|
|
74
|
+
|
|
75
|
+
with (
|
|
76
|
+
patch.object(settings, "AUTH", True),
|
|
77
|
+
patch("pygitweb.main.project_visible_in_list", return_value=False),
|
|
78
|
+
):
|
|
79
|
+
_login(client, "admin")
|
|
80
|
+
r = client.get("/projectnamevalid", params={"name": "newproj"})
|
|
81
|
+
assert r.status_code == 200
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_projectnamevalid_forbidden_without_grant(client: TestClient, addprojects_auth: AuthConfig) -> None:
|
|
85
|
+
from pygitweb.config import settings
|
|
86
|
+
|
|
87
|
+
with (
|
|
88
|
+
patch.object(settings, "AUTH", True),
|
|
89
|
+
patch("pygitweb.main.project_visible_in_list", return_value=False),
|
|
90
|
+
):
|
|
91
|
+
_login(client, "viewer")
|
|
92
|
+
r = client.get("/projectnamevalid", params={"name": "newproj"})
|
|
93
|
+
assert r.status_code == 403
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_addproject_page_readable_without_grant(client: TestClient, addprojects_auth: AuthConfig) -> None:
|
|
97
|
+
from pygitweb.config import settings
|
|
98
|
+
|
|
99
|
+
with patch.object(settings, "AUTH", True):
|
|
100
|
+
_login(client, "viewer")
|
|
101
|
+
r = client.get("/addproject")
|
|
102
|
+
assert r.status_code == 200
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_addproject_post_forbidden_without_grant(client: TestClient, addprojects_auth: AuthConfig) -> None:
|
|
106
|
+
from pygitweb.config import settings
|
|
107
|
+
|
|
108
|
+
with (
|
|
109
|
+
patch.object(settings, "AUTH", True),
|
|
110
|
+
patch("pygitweb.main.project_visible_in_list", return_value=False),
|
|
111
|
+
):
|
|
112
|
+
_login(client, "viewer")
|
|
113
|
+
r = client.post("/addproject", data={"project_name": "newproj"}, follow_redirects=False)
|
|
114
|
+
assert r.status_code == 403
|
pygitweb/api/__init__.py
ADDED
|
File without changes
|
pygitweb/api/action.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
|
|
5
|
+
from fastapi import Request
|
|
6
|
+
from starlette.responses import Response
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Action(ABC):
|
|
10
|
+
"""
|
|
11
|
+
Action: A per-project action provided by a plugin.
|
|
12
|
+
|
|
13
|
+
``project`` is the project path/slug as used in URLs (under PROJECTROOT).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
@abstractmethod
|
|
17
|
+
def action_name(self) -> str: ...
|
|
18
|
+
|
|
19
|
+
@abstractmethod
|
|
20
|
+
def action(self, project: str, req: Request | None = None) -> Response | None: ...
|
|
File without changes
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import tempfile
|
|
5
|
+
import zipfile
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from pygitweb.api.project import Project
|
|
9
|
+
from pygitweb.tasks import create_board_for_project
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ProjectZip(Project):
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
path: os.PathLike[str] | str,
|
|
16
|
+
zip_content: bytes,
|
|
17
|
+
create_task_board: bool = False,
|
|
18
|
+
do_maintenance: bool = False,
|
|
19
|
+
) -> None:
|
|
20
|
+
self.path: str = str(Path(path))
|
|
21
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
22
|
+
zip_path = os.path.join(tmpdir, "repo.zip")
|
|
23
|
+
with open(zip_path, "wb") as file_obj:
|
|
24
|
+
file_obj.write(zip_content)
|
|
25
|
+
with zipfile.ZipFile(zip_path, "r") as zip_file:
|
|
26
|
+
zip_file.extractall(tmpdir)
|
|
27
|
+
repo_root: str = self._discover_repo_root(tmpdir)
|
|
28
|
+
super().__init__(
|
|
29
|
+
path=self.path,
|
|
30
|
+
remote_url=repo_root,
|
|
31
|
+
create_task_board=False,
|
|
32
|
+
do_maintenance=do_maintenance,
|
|
33
|
+
)
|
|
34
|
+
if create_task_board:
|
|
35
|
+
create_board_for_project(Path(self.path).name, name="Tasks", description="")
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def _discover_repo_root(tmpdir: str) -> str:
|
|
39
|
+
for name in os.listdir(tmpdir):
|
|
40
|
+
if name == "repo.zip":
|
|
41
|
+
continue
|
|
42
|
+
candidate = os.path.join(tmpdir, name)
|
|
43
|
+
if os.path.isdir(candidate) and os.path.isdir(os.path.join(candidate, ".git")):
|
|
44
|
+
return candidate
|
|
45
|
+
if os.path.isdir(os.path.join(tmpdir, ".git")):
|
|
46
|
+
return tmpdir
|
|
47
|
+
subdirs: list[str] = [
|
|
48
|
+
name for name in os.listdir(tmpdir) if name != "repo.zip" and os.path.isdir(os.path.join(tmpdir, name))
|
|
49
|
+
]
|
|
50
|
+
if len(subdirs) == 1:
|
|
51
|
+
return os.path.join(tmpdir, subdirs[0])
|
|
52
|
+
for name in os.listdir(tmpdir):
|
|
53
|
+
if name != "repo.zip":
|
|
54
|
+
candidate = os.path.join(tmpdir, name)
|
|
55
|
+
if os.path.isdir(candidate):
|
|
56
|
+
return candidate
|
|
57
|
+
return tmpdir
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def form_content(cls) -> str:
|
|
61
|
+
return (
|
|
62
|
+
'<label class="form-label" for="repo_zip">Upload .zip (git repo)</label>'
|
|
63
|
+
'<div class="dropzone border rounded p-4 text-center" id="dropzone" style="min-height: 120px;">'
|
|
64
|
+
'<input type="file" class="form-control d-none" id="repo_zip" name="repo_zip" accept=".zip" '
|
|
65
|
+
"data-dropzone-target>"
|
|
66
|
+
'<div class="dropzone-placeholder text-muted" data-dropzone-placeholder>'
|
|
67
|
+
"Drag a .zip file here or click to choose."
|
|
68
|
+
"</div>"
|
|
69
|
+
'<div class="dropzone-filename d-none text-start small mt-2" data-dropzone-filename></div>'
|
|
70
|
+
"</div>"
|
|
71
|
+
)
|
pygitweb/api/project.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import os
|
|
5
|
+
import subprocess
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from types import TracebackType
|
|
8
|
+
|
|
9
|
+
import pygit2
|
|
10
|
+
|
|
11
|
+
from pygitweb.config import settings
|
|
12
|
+
from pygitweb.tasks import create_board_for_project
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Project:
|
|
16
|
+
"""
|
|
17
|
+
Plugin API: Project - the root class for a project which is always a directory, and _may_ contain a git repository.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
path: os.PathLike[str] | str,
|
|
23
|
+
remote_url: str | None = None,
|
|
24
|
+
create_task_board: bool = False,
|
|
25
|
+
do_maintenance: bool = False,
|
|
26
|
+
) -> None:
|
|
27
|
+
self.path: str = str(Path(path))
|
|
28
|
+
self.remote_url: str | None = remote_url
|
|
29
|
+
os.makedirs(self.path)
|
|
30
|
+
if self.remote_url:
|
|
31
|
+
pygit2.clone_repository(self.remote_url, self.path, bare=True)
|
|
32
|
+
else:
|
|
33
|
+
pygit2.init_repository(self.path, bare=True)
|
|
34
|
+
self.repo: pygit2.Repository = pygit2.Repository(self.path)
|
|
35
|
+
if create_task_board:
|
|
36
|
+
create_board_for_project(Path(self.path).name, name="Tasks", description="")
|
|
37
|
+
if do_maintenance:
|
|
38
|
+
with contextlib.suppress(subprocess.SubprocessError, FileNotFoundError):
|
|
39
|
+
subprocess.run(
|
|
40
|
+
[settings.GIT, "-C", self.path, "maintenance", "start"],
|
|
41
|
+
capture_output=True,
|
|
42
|
+
timeout=60,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
def __enter__(self) -> Project:
|
|
46
|
+
return self
|
|
47
|
+
|
|
48
|
+
def __exit__(
|
|
49
|
+
self,
|
|
50
|
+
exc_type: type[BaseException] | None,
|
|
51
|
+
exc_value: BaseException | None,
|
|
52
|
+
traceback: TracebackType | None,
|
|
53
|
+
) -> None:
|
|
54
|
+
self.repo.free()
|
|
55
|
+
|
|
56
|
+
def __del__(self) -> None:
|
|
57
|
+
self.repo.free()
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def form_content(cls) -> str:
|
|
61
|
+
return (
|
|
62
|
+
'<label class="form-label" for="pull_from_remote">Pull from remote</label>'
|
|
63
|
+
'<input type="url" class="form-control" id="pull_from_remote" name="pull_from_remote" '
|
|
64
|
+
'placeholder="https://example.com/repo.git or ssh://git@host/repo.git or git://host/repo.git">'
|
|
65
|
+
'<small class="form-hint">Optional. Use an <code>ssh://</code>, <code>git://</code>, '
|
|
66
|
+
"or <code>https://</code> URL to clone an existing repository.</small>"
|
|
67
|
+
)
|
pygitweb/api/subpage.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Subpage(ABC):
|
|
7
|
+
"""
|
|
8
|
+
Subpage: A per-project subpage provided by a plugin.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
@abstractmethod
|
|
12
|
+
def subpage_name(self) -> str: ...
|
|
13
|
+
|
|
14
|
+
def link_name(self, project: str) -> str | None:
|
|
15
|
+
return None
|
|
16
|
+
|
|
17
|
+
def subpage_html(self, project: str) -> str | None:
|
|
18
|
+
return None
|
|
19
|
+
|
|
20
|
+
def summary_value_suffix_html(self, project: str, project_enc: str) -> str | None:
|
|
21
|
+
"""Optional HTML appended after the subpage \"view\" link on the project summary table."""
|
|
22
|
+
return None
|
pygitweb/auth.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Authentication: local password login and OAuth2 authorization-code (browser).
|
|
3
|
+
|
|
4
|
+
FastAPI security integration
|
|
5
|
+
----------------------------
|
|
6
|
+
- ``OAuth2PasswordBearer`` + ``APIKeyCookie``: extract PyGitWeb's opaque session id from
|
|
7
|
+
``Authorization: Bearer`` or the login cookie. This is *not* an IdP JWT; OpenAPI still
|
|
8
|
+
documents the password ``/token`` flow that mints these session ids.
|
|
9
|
+
- ``OAuth2PasswordRequestForm``: local ``POST /token`` only (resource-owner password grant).
|
|
10
|
+
- External IdP login (Google/GitHub) uses standard authorization-code redirects implemented
|
|
11
|
+
in ``auth_oauth``; ``OAuth2AuthorizationCodeBearer`` is intentionally not used because
|
|
12
|
+
clients never receive or send the provider's access token—only our session id.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import hmac
|
|
18
|
+
from typing import Annotated
|
|
19
|
+
|
|
20
|
+
from fastapi import APIRouter, Depends, Form, HTTPException, Query, status
|
|
21
|
+
from fastapi.responses import HTMLResponse, RedirectResponse
|
|
22
|
+
from fastapi.security import APIKeyCookie, OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
|
23
|
+
from pydantic import BaseModel
|
|
24
|
+
|
|
25
|
+
from pygitweb.auth_config import (
|
|
26
|
+
auth_config,
|
|
27
|
+
is_auth_configured,
|
|
28
|
+
is_local_auth_available,
|
|
29
|
+
is_oauth_auth_available,
|
|
30
|
+
)
|
|
31
|
+
from pygitweb.auth_oauth import OAUTH_STATE_COOKIE_NAME, oauth_router
|
|
32
|
+
from pygitweb.config import settings
|
|
33
|
+
from pygitweb.gravatar import gravatar_url
|
|
34
|
+
from pygitweb.password_hash import verify_password
|
|
35
|
+
from pygitweb.permissions import Permission, PermissionPrincipal
|
|
36
|
+
from pygitweb.sessions import create_session, get_session, revoke_session
|
|
37
|
+
from pygitweb.templates_env import POSTAMBLE, PREAMBLE, env
|
|
38
|
+
|
|
39
|
+
ACCESS_TOKEN_COOKIE_NAME = "pygitweb_access_token"
|
|
40
|
+
LOGIN_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
|
41
|
+
|
|
42
|
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)
|
|
43
|
+
_access_token_cookie = APIKeyCookie(name=ACCESS_TOKEN_COOKIE_NAME, auto_error=False)
|
|
44
|
+
|
|
45
|
+
TAG_AUTH = "auth"
|
|
46
|
+
TAG_AUTH_LOCAL = "auth - local"
|
|
47
|
+
TAG_AUTH_OAUTH = "auth - OAuth"
|
|
48
|
+
|
|
49
|
+
auth_router = APIRouter()
|
|
50
|
+
auth_router.include_router(oauth_router)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class User(BaseModel):
|
|
54
|
+
username: str
|
|
55
|
+
email: str | None = None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def principal_from_session(token: str | None) -> PermissionPrincipal | None:
|
|
59
|
+
if not token:
|
|
60
|
+
return None
|
|
61
|
+
rec = get_session(token)
|
|
62
|
+
if rec is None:
|
|
63
|
+
return None
|
|
64
|
+
return PermissionPrincipal(username=rec.username, email=rec.email)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def has_permission(
|
|
68
|
+
permission: Permission,
|
|
69
|
+
project: str | None = None,
|
|
70
|
+
*,
|
|
71
|
+
token: str | None = None,
|
|
72
|
+
) -> bool:
|
|
73
|
+
if not settings.AUTH:
|
|
74
|
+
return True
|
|
75
|
+
principal = principal_from_session(token)
|
|
76
|
+
if principal is None:
|
|
77
|
+
return False
|
|
78
|
+
return auth_config.oauth_permissions.has_permission(principal.identity, permission, project)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def ensure_permission(
|
|
82
|
+
permission: Permission,
|
|
83
|
+
project: str | None = None,
|
|
84
|
+
*,
|
|
85
|
+
token: str | None,
|
|
86
|
+
) -> None:
|
|
87
|
+
ensure_active_user_if_auth_enabled(token)
|
|
88
|
+
if has_permission(permission, project, token=token):
|
|
89
|
+
return
|
|
90
|
+
raise HTTPException(
|
|
91
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
92
|
+
detail="Insufficient permissions",
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def require_permission(
|
|
97
|
+
permission: Permission,
|
|
98
|
+
*,
|
|
99
|
+
project_from_query: bool = False,
|
|
100
|
+
project_from_form: bool = False,
|
|
101
|
+
) -> object:
|
|
102
|
+
"""Return a FastAPI dependency that enforces ``permission`` when auth is enabled."""
|
|
103
|
+
|
|
104
|
+
if project_from_query:
|
|
105
|
+
|
|
106
|
+
def _dep_query_project(
|
|
107
|
+
token: Annotated[str | None, Depends(access_token_from_request)],
|
|
108
|
+
project: Annotated[str, Query()],
|
|
109
|
+
) -> None:
|
|
110
|
+
ensure_permission(permission, project, token=token)
|
|
111
|
+
|
|
112
|
+
return _dep_query_project
|
|
113
|
+
|
|
114
|
+
if project_from_form:
|
|
115
|
+
|
|
116
|
+
def _dep_form_project(
|
|
117
|
+
token: Annotated[str | None, Depends(access_token_from_request)],
|
|
118
|
+
project: Annotated[str, Form()],
|
|
119
|
+
) -> None:
|
|
120
|
+
ensure_permission(permission, project, token=token)
|
|
121
|
+
|
|
122
|
+
return _dep_form_project
|
|
123
|
+
|
|
124
|
+
def _dep(
|
|
125
|
+
token: Annotated[str | None, Depends(access_token_from_request)],
|
|
126
|
+
) -> None:
|
|
127
|
+
ensure_permission(permission, None, token=token)
|
|
128
|
+
|
|
129
|
+
return _dep
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def get_local_user(username: str) -> User | None:
|
|
133
|
+
if not settings.AUTH or not is_local_auth_available(auth_config):
|
|
134
|
+
return None
|
|
135
|
+
for entry in auth_config.local_users:
|
|
136
|
+
if not entry.pass_hash and not entry.password:
|
|
137
|
+
continue
|
|
138
|
+
if hmac.compare_digest(entry.user, username):
|
|
139
|
+
return User(username=entry.user, email=entry.email)
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def authenticate_local_user(username: str, password: str) -> User | None:
|
|
144
|
+
if auth_config.auth_mode not in ("local", "both"):
|
|
145
|
+
return None
|
|
146
|
+
for entry in auth_config.local_users:
|
|
147
|
+
if not hmac.compare_digest(entry.user, username):
|
|
148
|
+
continue
|
|
149
|
+
if entry.pass_hash:
|
|
150
|
+
if not verify_password(password, entry.pass_hash, config_salt=auth_config.salt):
|
|
151
|
+
return None
|
|
152
|
+
return User(username=entry.user, email=entry.email)
|
|
153
|
+
if entry.password is not None and hmac.compare_digest(entry.password, password):
|
|
154
|
+
return User(username=entry.user, email=entry.email)
|
|
155
|
+
return None
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def decode_access_token(token: str) -> User | None:
|
|
160
|
+
if not settings.AUTH:
|
|
161
|
+
return None
|
|
162
|
+
rec = get_session(token)
|
|
163
|
+
if rec is None:
|
|
164
|
+
return None
|
|
165
|
+
return User(username=rec.username)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def safe_next_url(next_raw: str | None) -> str:
|
|
169
|
+
n = (next_raw or "/").strip()
|
|
170
|
+
if not n.startswith("/") or n.startswith("//"):
|
|
171
|
+
return "/"
|
|
172
|
+
return n
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def access_token_from_request(
|
|
176
|
+
bearer: Annotated[str | None, Depends(oauth2_scheme)],
|
|
177
|
+
cookie_token: Annotated[str | None, Depends(_access_token_cookie)],
|
|
178
|
+
) -> str | None:
|
|
179
|
+
b = bearer.strip() if bearer else None
|
|
180
|
+
c = cookie_token.strip() if cookie_token else None
|
|
181
|
+
return b or c
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def ensure_active_user_if_auth_enabled(token: str | None) -> None:
|
|
185
|
+
if not settings.AUTH:
|
|
186
|
+
return
|
|
187
|
+
if not is_auth_configured(auth_config):
|
|
188
|
+
raise HTTPException(
|
|
189
|
+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
190
|
+
detail="Authentication enabled but auth.json is not configured",
|
|
191
|
+
)
|
|
192
|
+
if not token:
|
|
193
|
+
raise HTTPException(
|
|
194
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
195
|
+
detail="Not authenticated",
|
|
196
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
197
|
+
)
|
|
198
|
+
if decode_access_token(token) is None:
|
|
199
|
+
raise HTTPException(
|
|
200
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
201
|
+
detail="Not authenticated",
|
|
202
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def require_active_user_if_auth_enabled(
|
|
207
|
+
token: Annotated[str | None, Depends(access_token_from_request)],
|
|
208
|
+
) -> None:
|
|
209
|
+
ensure_active_user_if_auth_enabled(token)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@auth_router.get(
|
|
213
|
+
"/login",
|
|
214
|
+
response_class=HTMLResponse,
|
|
215
|
+
tags=[TAG_AUTH],
|
|
216
|
+
summary="Sign-in page",
|
|
217
|
+
description="HTML sign-in page. Shows local and/or OAuth options depending on auth.json.",
|
|
218
|
+
)
|
|
219
|
+
async def login_page(
|
|
220
|
+
next: Annotated[str, Query()] = "/",
|
|
221
|
+
) -> HTMLResponse:
|
|
222
|
+
if not settings.AUTH:
|
|
223
|
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
|
|
224
|
+
next_safe = safe_next_url(next)
|
|
225
|
+
pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Sign in", site_name=settings.SITE_NAME)
|
|
226
|
+
body = env.get_template("login.html").render(
|
|
227
|
+
site_name=settings.SITE_NAME,
|
|
228
|
+
next=next_safe,
|
|
229
|
+
error=None,
|
|
230
|
+
local_available=is_local_auth_available(auth_config),
|
|
231
|
+
oauth_available=is_oauth_auth_available(auth_config),
|
|
232
|
+
oauth_provider=str(auth_config.oauth_provider).strip() or "OAuth",
|
|
233
|
+
)
|
|
234
|
+
return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@auth_router.post(
|
|
238
|
+
"/login",
|
|
239
|
+
response_model=None,
|
|
240
|
+
tags=[TAG_AUTH_LOCAL],
|
|
241
|
+
summary="Local sign-in (form)",
|
|
242
|
+
description="Browser form login. Sets the pygitweb_access_token session cookie on success.",
|
|
243
|
+
responses={303: {"description": "Redirect to next URL with session cookie set"}},
|
|
244
|
+
)
|
|
245
|
+
async def login_form_submit(
|
|
246
|
+
username: Annotated[str, Form()],
|
|
247
|
+
password: Annotated[str, Form()],
|
|
248
|
+
next: Annotated[str, Form()] = "/",
|
|
249
|
+
) -> HTMLResponse | RedirectResponse:
|
|
250
|
+
if not settings.AUTH:
|
|
251
|
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
|
|
252
|
+
if not is_local_auth_available(auth_config):
|
|
253
|
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Local sign-in is not enabled")
|
|
254
|
+
next_safe = safe_next_url(next)
|
|
255
|
+
user = authenticate_local_user(username.strip(), password)
|
|
256
|
+
if user is None:
|
|
257
|
+
pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Sign in", site_name=settings.SITE_NAME)
|
|
258
|
+
body = env.get_template("login.html").render(
|
|
259
|
+
site_name=settings.SITE_NAME,
|
|
260
|
+
next=next_safe,
|
|
261
|
+
error="Incorrect username or password.",
|
|
262
|
+
local_available=True,
|
|
263
|
+
oauth_available=is_oauth_auth_available(auth_config),
|
|
264
|
+
oauth_provider=str(auth_config.oauth_provider).strip() or "OAuth",
|
|
265
|
+
)
|
|
266
|
+
return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
|
|
267
|
+
sid = create_session(user.username, email=user.email, auth_method="local")
|
|
268
|
+
resp = RedirectResponse(url=next_safe, status_code=303)
|
|
269
|
+
resp.set_cookie(
|
|
270
|
+
key=ACCESS_TOKEN_COOKIE_NAME,
|
|
271
|
+
value=sid,
|
|
272
|
+
httponly=True,
|
|
273
|
+
samesite="lax",
|
|
274
|
+
max_age=LOGIN_COOKIE_MAX_AGE,
|
|
275
|
+
path="/",
|
|
276
|
+
)
|
|
277
|
+
return resp
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@auth_router.get(
|
|
281
|
+
"/logout",
|
|
282
|
+
tags=[TAG_AUTH],
|
|
283
|
+
summary="Sign out",
|
|
284
|
+
description="Revokes the current session (cookie or Bearer) and clears auth cookies.",
|
|
285
|
+
responses={303: {"description": "Redirect to next URL"}},
|
|
286
|
+
)
|
|
287
|
+
async def logout_page(
|
|
288
|
+
token: Annotated[str | None, Depends(access_token_from_request)],
|
|
289
|
+
next: Annotated[str, Query()] = "/",
|
|
290
|
+
) -> RedirectResponse:
|
|
291
|
+
revoke_session(token)
|
|
292
|
+
resp = RedirectResponse(url=safe_next_url(next), status_code=303)
|
|
293
|
+
resp.delete_cookie(key=ACCESS_TOKEN_COOKIE_NAME, path="/")
|
|
294
|
+
resp.delete_cookie(key=OAUTH_STATE_COOKIE_NAME, path="/")
|
|
295
|
+
return resp
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
@auth_router.post(
|
|
299
|
+
"/token",
|
|
300
|
+
tags=[TAG_AUTH_LOCAL],
|
|
301
|
+
summary="Obtain session token (local)",
|
|
302
|
+
description=(
|
|
303
|
+
"OAuth2 password flow for API clients. Returns an opaque session id as access_token; "
|
|
304
|
+
"use Authorization: Bearer on protected routes. Not an identity-provider JWT."
|
|
305
|
+
),
|
|
306
|
+
)
|
|
307
|
+
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]) -> dict[str, str]:
|
|
308
|
+
if not settings.AUTH:
|
|
309
|
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
|
|
310
|
+
if not is_local_auth_available(auth_config):
|
|
311
|
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Local sign-in is not enabled")
|
|
312
|
+
user = authenticate_local_user(form_data.username, form_data.password)
|
|
313
|
+
if user is None:
|
|
314
|
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Incorrect username or password")
|
|
315
|
+
sid = create_session(user.username, email=user.email, auth_method="local")
|
|
316
|
+
return {"access_token": sid, "token_type": "bearer"}
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@auth_router.get(
|
|
320
|
+
"/auth/status",
|
|
321
|
+
tags=[TAG_AUTH],
|
|
322
|
+
summary="Auth status (navbar)",
|
|
323
|
+
description="Lightweight JSON for the navbar script. Does not return 401 when anonymous.",
|
|
324
|
+
)
|
|
325
|
+
async def auth_status(
|
|
326
|
+
token: Annotated[str | None, Depends(access_token_from_request)],
|
|
327
|
+
) -> dict[str, bool | str | None]:
|
|
328
|
+
if not settings.AUTH:
|
|
329
|
+
return {"auth_enabled": False, "username": None, "gravatar_url": None}
|
|
330
|
+
if not token:
|
|
331
|
+
return {"auth_enabled": True, "username": None, "gravatar_url": None}
|
|
332
|
+
rec = get_session(token)
|
|
333
|
+
if rec is None:
|
|
334
|
+
return {"auth_enabled": True, "username": None, "gravatar_url": None}
|
|
335
|
+
avatar = gravatar_url(rec.email) if rec.email else None
|
|
336
|
+
return {"auth_enabled": True, "username": rec.username, "gravatar_url": avatar}
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
@auth_router.get(
|
|
340
|
+
"/user",
|
|
341
|
+
response_class=HTMLResponse,
|
|
342
|
+
response_model=None,
|
|
343
|
+
tags=[TAG_AUTH],
|
|
344
|
+
summary="Account page",
|
|
345
|
+
description="HTML account page for the signed-in user.",
|
|
346
|
+
)
|
|
347
|
+
async def user_account_page(
|
|
348
|
+
token: Annotated[str | None, Depends(access_token_from_request)],
|
|
349
|
+
) -> HTMLResponse | RedirectResponse:
|
|
350
|
+
if not settings.AUTH:
|
|
351
|
+
pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Account", site_name=settings.SITE_NAME)
|
|
352
|
+
body = '<p class="text-muted">Authentication is not enabled on this server.</p>'
|
|
353
|
+
return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
|
|
354
|
+
if not is_auth_configured(auth_config):
|
|
355
|
+
raise HTTPException(
|
|
356
|
+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
357
|
+
detail="Authentication is misconfigured",
|
|
358
|
+
)
|
|
359
|
+
u = decode_access_token(token or "") if token else None
|
|
360
|
+
if u is None:
|
|
361
|
+
return RedirectResponse(url="/login?next=/user", status_code=303)
|
|
362
|
+
pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Account", site_name=settings.SITE_NAME)
|
|
363
|
+
body = env.get_template("user_profile.html").render(username=u.username, site_name=settings.SITE_NAME)
|
|
364
|
+
return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
@auth_router.get(
|
|
368
|
+
"/users/me",
|
|
369
|
+
response_model=User,
|
|
370
|
+
tags=[TAG_AUTH],
|
|
371
|
+
summary="Current user",
|
|
372
|
+
description="Returns the username for the current session (cookie or Bearer).",
|
|
373
|
+
)
|
|
374
|
+
async def read_users_me(
|
|
375
|
+
token: Annotated[str | None, Depends(access_token_from_request)],
|
|
376
|
+
) -> User:
|
|
377
|
+
if not settings.AUTH:
|
|
378
|
+
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
|
|
379
|
+
ensure_active_user_if_auth_enabled(token)
|
|
380
|
+
u = decode_access_token(token or "")
|
|
381
|
+
if u is None:
|
|
382
|
+
raise HTTPException(
|
|
383
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
384
|
+
detail="Not authenticated",
|
|
385
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
386
|
+
)
|
|
387
|
+
return u
|