Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29ea6426fe | ||
|
|
88a170a37b | ||
|
|
38d240d86d | ||
|
|
53362b8061 | ||
|
|
d3d5f5a3c8 | ||
|
|
d156fb9221 | ||
|
|
f868bc59d1 | ||
|
|
0022986d4e | ||
|
|
b08cca754f | ||
|
|
aa58f08bc5 | ||
|
|
1062b5d6c8 | ||
|
|
3d49cbf2d6 | ||
|
|
13c49aebfd | ||
|
|
abec77d561 | ||
|
|
9b505ff553 | ||
|
|
ddd70e6130 | ||
|
|
cf1124c251 | ||
|
|
7504aaf7e0 | ||
|
|
e8247a2c7f | ||
|
|
968964c4c9 | ||
|
|
6aa1a08e39 | ||
|
|
31f40d874c | ||
|
|
7530d7a710 | ||
|
|
90d5f0e45f | ||
|
|
f0d1b86d6b | ||
|
|
dbdd1dbd3c | ||
|
|
8f862fb4d1 | ||
|
|
cfb917da46 | ||
|
|
3a8e7d1f4f | ||
|
|
86966526c4 | ||
|
|
3196aa7688 | ||
|
|
2fadaea19c | ||
|
|
cb84a81a06 | ||
|
|
9bdca1f43a | ||
|
|
0f29544bdb | ||
|
|
4ddaa9fdf4 | ||
|
|
7e568dbd10 | ||
|
|
fbc6108b7a | ||
|
|
6e649f1f07 | ||
|
|
8d68e5d237 | ||
|
|
5ee7443801 | ||
|
|
2100a7e14f | ||
|
|
aae33e60ce | ||
|
|
cebef8adfc | ||
|
|
57a9c60557 | ||
|
|
a9ef20969e | ||
|
|
57748876cb | ||
|
|
ba552e24cd | ||
|
|
dbe4149b63 | ||
|
|
3d5f82c3df | ||
|
|
2a005692ee | ||
|
|
2ec6314264 | ||
|
|
ae4c982a30 | ||
|
|
c2933d60c2 | ||
|
|
d4ebc1bf99 | ||
|
|
0f857ffb78 | ||
|
|
b7ebe68665 | ||
|
|
f9d23a196c | ||
|
|
2c6a5c72d9 | ||
|
|
c13044c085 | ||
|
|
2c783498a4 | ||
|
|
3430c7f0cf | ||
|
|
236d52aa55 | ||
|
|
02e04da2c4 | ||
|
|
7f3763b46d | ||
|
|
0fe55b2b62 | ||
|
|
ccf71bf0a3 | ||
|
|
cdaeecb179 | ||
|
|
82cdee51e4 | ||
|
|
851e0793a6 | ||
|
|
cd681a0599 | ||
|
|
71cb01cfda | ||
|
|
535ac8558d | ||
|
|
c64554aeda | ||
|
|
0bc1bae26c | ||
|
|
156231b142 | ||
|
|
daf397b3b5 | ||
|
|
a1a5ad8520 | ||
|
|
d25124d30b | ||
|
|
0bfb035f76 | ||
|
|
000501b718 | ||
|
|
5a57e78814 | ||
|
|
e5b84dd28c | ||
|
|
4b01fd9e7a | ||
|
|
431c48f1dd | ||
|
|
03c966919f |
@@ -5,6 +5,7 @@ dist/
|
|||||||
*.lock
|
*.lock
|
||||||
package-lock.json
|
package-lock.json
|
||||||
paskia.sqlite
|
paskia.sqlite
|
||||||
|
paskia.jsonl
|
||||||
/paskia/frontend-build
|
/paskia/frontend-build
|
||||||
/paskia/_version.py
|
/paskia/_version.py
|
||||||
coverage-html/
|
coverage-html/
|
||||||
|
|||||||
@@ -1,105 +0,0 @@
|
|||||||
# Paskia API Documentation
|
|
||||||
|
|
||||||
This document lists the HTTP and WebSocket endpoints exposed by the Paskia
|
|
||||||
service and how they behave depending on whether a dedicated authentication host
|
|
||||||
(`--auth-host` / environment `PASSKEY_AUTH_HOST`) is configured.
|
|
||||||
|
|
||||||
## Base Paths & Host Modes
|
|
||||||
|
|
||||||
Two deployment modes:
|
|
||||||
|
|
||||||
1. Multi‑host (default – no `--auth-host` provided)
|
|
||||||
- All endpoints are reachable on any host under the `/auth/` prefix.
|
|
||||||
- A convenience root (`/`) also serves the main app.
|
|
||||||
|
|
||||||
2. Dedicated auth host (`--auth-host auth.example.com`)
|
|
||||||
- The specified auth host serves the UI at the root (`/`, `/admin/`, reset tokens, etc.).
|
|
||||||
- Other (non‑auth) hosts show a lightweight account summary at `/` or `/auth/`, while other UI routes still redirect to the auth host.
|
|
||||||
- Restricted endpoints on non‑auth hosts return `404` instead of redirecting.
|
|
||||||
|
|
||||||
### Path Mapping When Auth Host Enabled
|
|
||||||
|
|
||||||
| Purpose | On Auth Host | On Other Hosts (incoming) | Action |
|
|
||||||
|---------|--------------|---------------------------|--------|
|
|
||||||
| Main UI | `/` | `/auth/` or `/` | Serve account summary SPA (no redirect) |
|
|
||||||
| Admin UI root | `/admin/` | `/auth/admin/` or `/admin/` | Redirect -> auth host `/admin/` (strip `/auth`) |
|
|
||||||
| Reset / device addition token | `/{token}` | `/auth/{token}` | Redirect -> auth host `/{token}` (strip `/auth`) |
|
|
||||||
| Static assets | `/auth/assets/*` | `/auth/assets/*` | Served directly (no redirect) |
|
|
||||||
| Unrestricted API | `/auth/api/...` | `/auth/api/...` | Served directly |
|
|
||||||
| Restricted API (admin,user,ws namespaces) | `/auth/api/{admin|user|ws}*` | same path | 404 on non‑auth hosts |
|
|
||||||
| WebSocket (register/auth) | `/auth/ws/*` | `/auth/ws/*` | 404 on non‑auth hosts |
|
|
||||||
|
|
||||||
Notes:
|
|
||||||
- “Strip `/auth`” means only when the path starts with that exact segment.
|
|
||||||
- A reset token is a single path segment validated by server logic; malformed tokens 404.
|
|
||||||
- Method and body are preserved for UI redirects (307 Temporary Redirect).
|
|
||||||
|
|
||||||
## HTTP UI Endpoints
|
|
||||||
|
|
||||||
| Method | Path (multi‑host) | Path (auth host) | Description |
|
|
||||||
|--------|-------------------|------------------|-------------|
|
|
||||||
| GET | `/auth/` | `/` | Main authentication SPA (non-auth hosts show an account summary view) |
|
|
||||||
| GET | `/auth/admin/` | `/admin/` | Admin SPA root |
|
|
||||||
| GET | `/auth/{reset_token}` | `/{reset_token}` | Reset / device addition SPA (token validated) |
|
|
||||||
|
|
||||||
## Core API (Unrestricted – available on all hosts)
|
|
||||||
|
|
||||||
Always under `/auth/api/` (even on auth host):
|
|
||||||
|
|
||||||
| Method | Path | Description |
|
|
||||||
|--------|------|-------------|
|
|
||||||
| GET | `/auth/restricted/` | Authentication UI for iframe embedding (supports `?mode=login` or `?mode=reauth`) |
|
|
||||||
|--------|------|-------------|
|
|
||||||
| POST | `/auth/api/validate` | Validate & (conditionally) renew session |
|
|
||||||
| GET | `/auth/api/forward` | Auth proxy endpoint for reverse proxies (204 or 4xx) |
|
|
||||||
| POST | `/auth/api/set-session` | Set cookie from Bearer token |
|
|
||||||
| POST | `/auth/api/logout` | Logout current session |
|
|
||||||
| POST | `/auth/api/user-info` | Authenticated user + context info (also handles reset tokens) |
|
|
||||||
| POST | `/auth/api/create-link` | Create a device addition link (reset token) |
|
|
||||||
| DELETE | `/auth/api/credential/{uuid}` | Delete user credential |
|
|
||||||
| DELETE | `/auth/api/session/{session_id}` | Terminate a specific session |
|
|
||||||
| POST | `/auth/api/user/logout-all` | Terminate all sessions for the user |
|
|
||||||
| PUT | `/auth/api/user/display-name` | Update display name |
|
|
||||||
|
|
||||||
## Restricted API Namespaces
|
|
||||||
|
|
||||||
When `--auth-host` is set, requests to these paths on non‑auth hosts return 404:
|
|
||||||
|
|
||||||
| Namespace | Examples |
|
|
||||||
|-----------|----------|
|
|
||||||
| `/auth/api/admin` | `/auth/api/admin/orgs`, `/auth/api/admin/orgs/{uuid}` ... |
|
|
||||||
| `/auth/api/user` | Segment prefix – includes `/auth/api/user/...` endpoints (logout-all, display-name, session, credential) |
|
|
||||||
| `/auth/api/ws` | (Reserved / future) |
|
|
||||||
|
|
||||||
## WebSockets (Passkey)
|
|
||||||
|
|
||||||
| Path | Description | Host Mode Behavior |
|
|
||||||
|------|-------------|--------------------|
|
|
||||||
| `/auth/ws/register` | Register new credential (new or existing user) | 404 on non‑auth hosts when auth host configured |
|
|
||||||
| `/auth/ws/authenticate` | Authenticate user & issue session | 404 on non‑auth hosts when auth host configured |
|
|
||||||
|
|
||||||
## Redirection & Status Codes
|
|
||||||
|
|
||||||
| Scenario | Response |
|
|
||||||
|----------|----------|
|
|
||||||
| UI path on non‑auth host (auth host configured) | 307 redirect to auth host; `/auth` prefix stripped |
|
|
||||||
| Reset token UI path on non‑auth host | 307 redirect (token preserved) |
|
|
||||||
| Restricted API on non‑auth host | 404 |
|
|
||||||
| Unrestricted API on any host | Normal response |
|
|
||||||
| No auth host configured | All hosts behave like multi-host mode (no redirects; everything accessible) |
|
|
||||||
|
|
||||||
## Headers for /auth/api/forward
|
|
||||||
See `Headers.md` for details of headers returned on success (204).
|
|
||||||
|
|
||||||
## Notes for Integrators
|
|
||||||
1. Always use absolute `/auth/api/...` paths for programmatic requests (they do not move when an auth host is introduced).
|
|
||||||
2. Bookmark / deep links to UI should resolve correctly after redirection if users access via a non-auth application host.
|
|
||||||
3. Treat 404 from restricted namespaces on non-auth hosts as a signal to direct users to the central auth site.
|
|
||||||
|
|
||||||
## Environment & CLI Summary
|
|
||||||
| Option | Effect |
|
|
||||||
|--------|--------|
|
|
||||||
| `--auth-host` / `PASSKEY_AUTH_HOST` | Enables dedicated host mode, root-mounts UI there, restricts certain namespaces elsewhere |
|
|
||||||
|
|
||||||
---
|
|
||||||
This document reflects current behavior of the middleware-based host routing logic.
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
## Caddy configuration
|
|
||||||
|
|
||||||
We provide a few Caddy snippets that make the configuration easier, although the `forward_auth` directive of Caddy can be used directly as well. Place the auth folder with the snippets where your Caddyfile is.
|
|
||||||
|
|
||||||
What these snippets do
|
|
||||||
- Mount the auth UI at `/auth/` proxying to `:4401` (auth backend)
|
|
||||||
- Use the forward-auth interface `/auth/api/forward` to verify the required credentials
|
|
||||||
- Render a login page or a permission denied page if needed (without changing URL)
|
|
||||||
|
|
||||||
Your backend may not use authentication at all, or it can make use of the user information passed via `Remote-*` headers by the authentication system, see [Headers.md](Headers.md) for details.
|
|
||||||
|
|
||||||
### 1) Protect the full site (auth/all)
|
|
||||||
|
|
||||||
Use this when you want “login required everywhere” which is useful to protect some service that doesn't have any authentication of its own:
|
|
||||||
|
|
||||||
```caddyfile
|
|
||||||
localhost {
|
|
||||||
import auth/all "" {
|
|
||||||
reverse_proxy :3000 # your app
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The auth/all protects the entire site with a simple directive. Put your normal setup inside the block. In this example we don't require any permissions, only that the user is logged in. Instead of `""` you may specify `perm=myapp:login` or other permissions.
|
|
||||||
|
|
||||||
It is possible to add your own `handle @matcher` blocks prior importing `auth/all` for endpoints that don't require authentication, e.g. to exclude `/favicon.ico`.
|
|
||||||
|
|
||||||
### 2) Different areas, different permissions (auth/setup, auth/require)
|
|
||||||
|
|
||||||
When you need a more fine-grained control, use the auth/setup and auth/require snippets:
|
|
||||||
|
|
||||||
```caddyfile
|
|
||||||
localhost {
|
|
||||||
import auth/setup
|
|
||||||
|
|
||||||
@public path /.well-known/* /favicon.ico
|
|
||||||
handle @public {
|
|
||||||
root * /var/www/
|
|
||||||
file_server
|
|
||||||
}
|
|
||||||
|
|
||||||
@reports path /reports
|
|
||||||
handle @reports {
|
|
||||||
import auth/require perm=myapp:reports
|
|
||||||
reverse_proxy :3000
|
|
||||||
}
|
|
||||||
|
|
||||||
# Anywhere else, require login only
|
|
||||||
handle {
|
|
||||||
import auth/require ""
|
|
||||||
reverse_proxy :3000
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Note: We use the `handle @name` approach rather than `handle_path` to prevent the matched path being removed out of upstream URL. Unlike bare directives, these blocks will be tried in sequence and each can contain what you'd typically put in your site definition.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Override the auth backend URL (AUTH_UPSTREAM)
|
|
||||||
|
|
||||||
By default, the auth service is contacted at localhost port 4401 ("for authentication required"). You can point Caddy to a different by setting the `AUTH_UPSTREAM` environment variable for Caddy.
|
|
||||||
|
|
||||||
If unset, the snippets use `:4401` by default.
|
|
||||||
-17
@@ -1,17 +0,0 @@
|
|||||||
## Headers your app receives
|
|
||||||
|
|
||||||
When a request is allowed, the auth service adds these headers before proxying to your app (e.g., the service at `:3000`). Your app can use them for user context and authorization.
|
|
||||||
|
|
||||||
| Header | Meaning | Example |
|
|
||||||
|---|---|---|
|
|
||||||
| `Remote-User` | Authenticated user UUID | `3f1a2b3c-4d5e-6789-abcd-ef0123456789` |
|
|
||||||
| `Remote-Name` | User display name | `Jane Doe` |
|
|
||||||
| `Remote-Org` | Organization UUID | `a1b2c3d4-1111-2222-3333-444455556666` |
|
|
||||||
| `Remote-Org-Name` | Organization display name | `Acme Inc` |
|
|
||||||
| `Remote-Role` | Role UUID | `b2c3d4e5-2222-3333-4444-555566667777` |
|
|
||||||
| `Remote-Role-Name` | Role display name | `Administrators` |
|
|
||||||
| `Remote-Groups` | Comma‑separated permissions the user has | `myapp:reports,auth:admin` |
|
|
||||||
| `Remote-Session-Expires` | Session expiry timestamp (ISO 8601) | `2025-09-25T14:30:00Z` |
|
|
||||||
| `Remote-Credential` | Credential UUID backing the session | `c3d4e5f6-3333-4444-5555-666677778888` |
|
|
||||||
|
|
||||||
Note: Any incoming `Remote-*` headers from clients are stripped by our [Caddy configuration](Caddy.md), so that apps can trust these values.
|
|
||||||
@@ -30,16 +30,9 @@ Install [UV](https://docs.astral.sh/uv/getting-started/installation/) and run:
|
|||||||
uvx paskia serve --rp-id example.com
|
uvx paskia serve --rp-id example.com
|
||||||
```
|
```
|
||||||
|
|
||||||
On the first run it downloads the software and prints a registration link for the Admin. If you are going to be connecting `localhost` directly, for testing, leave out the rp-id.
|
On the first run it downloads the software and prints a registration link for the Admin. The server will start up on [localhost:4401](http://localhost:4401) *for authentication required*, serving for `*.example.com`. If you are going to be connecting `localhost` directly, for testing, leave out the rp-id.
|
||||||
|
|
||||||
The server will start up on [localhost:4401](http://localhost:4401) "for authentication required", serving for `*.example.com`.
|
Otherwise you will need a web server such as [Caddy](https://caddyserver.com/) to serve HTTPS on your actual domain names and proxy requests to Paskia and your backend apps (see documentation below).
|
||||||
|
|
||||||
Otherwise you will need a web server such as [Caddy](https://caddyserver.com/) to serve HTTPS on your actual domain names and proxy requests to Paskia and your backend apps.
|
|
||||||
|
|
||||||
A quick example without any config file:
|
|
||||||
```fish
|
|
||||||
sudo caddy reverse-proxy --from example.com --to :4401
|
|
||||||
```
|
|
||||||
|
|
||||||
For a permanent install of `paskia` CLI command, not needing `uvx`:
|
For a permanent install of `paskia` CLI command, not needing `uvx`:
|
||||||
|
|
||||||
@@ -55,18 +48,17 @@ There is no config file. Pass only the options on CLI:
|
|||||||
paskia serve [options]
|
paskia serve [options]
|
||||||
```
|
```
|
||||||
|
|
||||||
Optional options:
|
| Option | Description | Default |
|
||||||
|
|--------|-------------|---------|
|
||||||
|
| Listen address | One of *host***:***port* (default all hosts, port 4401) or **unix:***path***/paskia.socket** (Unix socket) | **localhost:4401** |
|
||||||
|
| --rp-id *domain* | Main/top domain | **localhost** |
|
||||||
|
| --rp-name *"text"* | Name of your company or site | Same as rp-id |
|
||||||
|
| --origin *url* | Explicitly list the domain names served | **https://**_rp-id_ |
|
||||||
|
| --auth-host *domain* | Dedicated authentication site (e.g., **auth.example.com**) | **Unspecified:** we use **/auth/** on **every** site under rp-id.|
|
||||||
|
|
||||||
- Listen address (one of):
|
## Further Documentation
|
||||||
* `[host]:port`: Address and port (default: `localhost:4401`)
|
|
||||||
* `unix:/path.sock`: Unix socket
|
|
||||||
- `--rp-id <domain>`: Main domain (required for production)
|
|
||||||
- `--rp-name "<text>"`: Name of your company or site (default: same as rp-id)
|
|
||||||
- `--origin <url>`: Explicit single site (default: `https://<rp-id>`)
|
|
||||||
- `--auth-host <domain>`: Dedicated authentication site (e.g., `auth.example.com`)
|
|
||||||
|
|
||||||
## Documentation
|
- [Caddy configuration](https://git.zi.fi/LeoVasanko/paskia/src/branch/main/docs/Caddy.md)
|
||||||
|
- [Trusted Headers for Backend Apps](https://git.zi.fi/LeoVasanko/paskia/src/branch/main/docs/Headers.md)
|
||||||
- `API.md`: Complete HTTP and WebSocket API reference
|
- [Frontend integration](https://git.zi.fi/LeoVasanko/paskia/src/branch/main/docs/Integration.md)
|
||||||
- `Caddy.md`: Caddy configuration examples
|
- [Paskia API](https://git.zi.fi/LeoVasanko/paskia/src/branch/main/docs/API.md)
|
||||||
- `Headers.md`: HTTP headers passed to protected applications
|
|
||||||
|
|||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
# Paskia API
|
||||||
|
|
||||||
|
For integrating Paskia with your app frontend, see [integration](Integration.md).
|
||||||
|
|
||||||
|
## Web Interface
|
||||||
|
|
||||||
|
| Method | Path | What it is for | Notes |
|
||||||
|
|---:|---|---|---|
|
||||||
|
| GET | `/auth/` | User profile page | |
|
||||||
|
| GET | `/auth/admin/` | Admin panel | Requires auth:admin (master) or org admin permissions. |
|
||||||
|
| GET | `/auth/{token}` | Reset / add credential URL (QR code link) | E.g. `/auth/fun.cotton.fresh.xray.lava` |
|
||||||
|
|
||||||
|
### Public JSON API: `/auth/api/*`
|
||||||
|
|
||||||
|
| Method | Path | Used for | Notes |
|
||||||
|
|---:|---|---|---|
|
||||||
|
| GET | `/auth/api/settings` | Paskia configuration | Returns RP info + base paths + session cookie name |
|
||||||
|
| POST | `/auth/api/user-info` | Full user profile | Basic information, credentials, sessions, permissions |
|
||||||
|
| POST | `/auth/api/logout` | Terminate session and delete session cookie | Signs out of the current site |
|
||||||
|
| POST | `/auth/api/validate` | Validate and renew session cookie | Optional query: `perm=` (repeatable), `max_age=` |
|
||||||
|
| GET | `/auth/api/forward` | Validate access (Caddy/Nginx) | 204 on success; 401/403 otherwise (HTML if requested) |
|
||||||
|
|
||||||
|
The `validate` and `forward` endpoints take query arguments `perm=` and `max_age=` for specific requirements on the validation of the current session.
|
||||||
|
|
||||||
|
### User JSON API: `/auth/api/user/*`
|
||||||
|
|
||||||
|
| Method | Path | Used for | Notes |
|
||||||
|
|---:|---|---|---|
|
||||||
|
| PUT | `/auth/api/user/display-name` | Update the user’s display name | Body: JSON `{ "display_name": "..." }` |
|
||||||
|
| POST | `/auth/api/user/logout-all` | Terminate all user sessions | Clears current host cookie |
|
||||||
|
| DELETE | `/auth/api/user/session/{session_id}` | Terminate one session | Session IDs are server-issued |
|
||||||
|
| DELETE | `/auth/api/user/credential/{uuid}` | Delete a credential | Requires recent authentication |
|
||||||
|
| POST | `/auth/api/user/create-link` | Create a device-add link | Requires recent authentication |
|
||||||
|
|
||||||
|
These are used mostly from the user profile panel and modify the current user.
|
||||||
|
|
||||||
|
### Admin API: `/auth/api/admin/*`
|
||||||
|
|
||||||
|
Normally only used via admin panel, requires auth admin permissions and can modify any users, orgs and permissions the session has access to.
|
||||||
|
|
||||||
|
E.g. Org admin cannot see anything of the other orgs that he has no admin access to. Master admin `auth:admin` can see everything and create and manage orgs.
|
||||||
|
|
||||||
|
### WebSockets: `/auth/ws/*`
|
||||||
|
|
||||||
|
| Path | Used for | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `WS /auth/ws/authenticate` | Passkey authentication | Returns a session token |
|
||||||
|
| `WS /auth/ws/register` | Register a new credential | Adding another passkey to current user or via reset token |
|
||||||
|
| `WS /auth/ws/remote-auth/request` | Start a cross-device login/registration request | Used from unauthenticated client |
|
||||||
|
| `WS /auth/ws/remote-auth/permit` | Approve/deny a pairing code | Used to accept the request, if same words are entered |
|
||||||
|
|
||||||
|
These are for internal use only, but are documented here because they are the core piece in all passkey operations.
|
||||||
|
|
||||||
|
### Auth host mode (`--auth-host`)
|
||||||
|
|
||||||
|
#### On the auth host:
|
||||||
|
- The Web UI is served at site root (e.g. admin UI at `/admin/`), and the `/auth/...` equivalents (e.g. `/auth/admin/`) redirect to the root paths.
|
||||||
|
- All of the API stays under `/auth/api/*`
|
||||||
|
- Auth WebSockets remain at `/auth/ws/*` but take connections from other hosts to issue sessions for each of those.
|
||||||
|
|
||||||
|
#### On non-auth hosts:
|
||||||
|
- `/auth/` shows only minimal profile and allows logging out of the current site
|
||||||
|
- `/auth/api/*` is served normally.
|
||||||
|
- `/auth/api/user/*`, `/auth/api/admin/*`, and `/auth/ws/*` don't exist.
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# Paskia Caddy Configuration
|
||||||
|
|
||||||
|
[Caddy](https://caddyserver.com/) is a modern web server that makes setting up web services easy. We provide a few Caddy snippets that make the configuration even easier, although the `forward_auth` directive of Caddy can be used directly as well. Place the [auth folder](../caddy/auth) with the snippets `require` and `setup` where your config file is (e.g. `/etc/caddy/auth`)
|
||||||
|
|
||||||
|
What these snippets do
|
||||||
|
- `setup`: Mount the auth UI at `/auth/` proxying to `:4401`
|
||||||
|
- `require`: Use `/auth/api/forward` for access control
|
||||||
|
- Render a login page or a permission denied page if needed (without changing URL)
|
||||||
|
|
||||||
|
Your backend may not use authentication at all, or it can make use of the user information passed via `Remote-*` headers by the authentication system, see [trusted headers](Headers.md) for details.
|
||||||
|
|
||||||
|
We assume the normal unprotected **Caddyfile** for your site looks like this:
|
||||||
|
|
||||||
|
```caddyfile
|
||||||
|
app.example.com {
|
||||||
|
@public path /.well-known/* /favicon.ico
|
||||||
|
handle @public {
|
||||||
|
root * /var/www/
|
||||||
|
file_server
|
||||||
|
}
|
||||||
|
|
||||||
|
handle {
|
||||||
|
reverse_proxy :3000 # Your app backend
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Note: We use the `handle @name` approach rather than `handle_path` to keep the path unaltered. Unlike bare directives, these blocks will be tried in sequence and each can contain what you'd typically put in your site definition (by default `reverse_proxy` takes precedence and nothing reaches the static files).
|
||||||
|
|
||||||
|
We will adapt from this to protect your app.
|
||||||
|
|
||||||
|
### Protect your site (auth/setup, auth/require)
|
||||||
|
|
||||||
|
```caddyfile
|
||||||
|
app.example.com {
|
||||||
|
import auth/setup
|
||||||
|
|
||||||
|
@public path /.well-known/* /favicon.ico
|
||||||
|
handle @public {
|
||||||
|
root * /var/www/
|
||||||
|
file_server
|
||||||
|
}
|
||||||
|
|
||||||
|
@reports path /reports
|
||||||
|
handle @reports {
|
||||||
|
import auth/require perm=myapp:reports
|
||||||
|
reverse_proxy :3000
|
||||||
|
}
|
||||||
|
|
||||||
|
handle {
|
||||||
|
import auth/require max-age=12h
|
||||||
|
reverse_proxy :3000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The above setup allows unauthenticated access to certain files, then implements two different access controls for your backend app depending on which path is accessed. Note that the perm and max-age options may be combined, e.g. `perm=myapp:admin&max-age=5min` on a very sensitive endpoint. This will require additional authentication if the passkey hasn't been used in the last 5 minutes (automatic session renewals don't affect this). Use `""` if you only want the user to be authenticated with no time or perm requirements.
|
||||||
|
|
||||||
|
### Dedicated Authentication Site
|
||||||
|
|
||||||
|
When you setup a separate subdomain for the authentication site, just add to your config another section for the auth host:
|
||||||
|
|
||||||
|
```caddyfile
|
||||||
|
auth.example.com {
|
||||||
|
reverse_proxy :4401
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Remember to specify `paskia serve --auth-host auth.example.com` to restrict the authentication services to this domain.
|
||||||
|
|
||||||
|
Note that we still reserve `/auth/` on each site for logout page and any APIs your application may require, while full user profile and global options are only available on the auth host.
|
||||||
|
|
||||||
|
Paskia does not require CORS configuration, but it can access the authentication and registration of auth host WS API from the other sites as WebSockets don't require any CORS.
|
||||||
|
|
||||||
|
### Override the paskia backend address (AUTH_UPSTREAM)
|
||||||
|
|
||||||
|
By default, the auth service is contacted at localhost port 4401. You can point Caddy to a different address by setting the `AUTH_UPSTREAM` environment variable for Caddy.
|
||||||
|
|
||||||
|
If unset, the snippets use `:4401` by default.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Paskia Trusted Headers for Backend Apps
|
||||||
|
|
||||||
|
| HTTP Header | Meaning | Example |
|
||||||
|
|---|---|---|
|
||||||
|
| `Remote-User` | Authenticated user UUID | **01c03276-b8f0-**… (string) |
|
||||||
|
| `Remote-Name` | User display name | **John Doe** |
|
||||||
|
| `Remote-Org` | Organization UUID | Identifier for user's org (string) |
|
||||||
|
| `Remote-Org-Name` | Organization display name | **The Company Ltd.** |
|
||||||
|
| `Remote-Role` | Role UUID | Identifier for user's role (string) |
|
||||||
|
| `Remote-Role-Name` | Role display name | **Employee** |
|
||||||
|
| `Remote-Groups` | Permissions the user has, comma separated | **auth:admin,yourapp:reports** |
|
||||||
|
| `Remote-Session-Expires` | Session expiry timestamp (ISO 8601 UTC) | **2030-12-31T23:59:59Z** |
|
||||||
|
| `Remote-Credential` | Credential UUID | Identifier for the sign-in passkey (string) |
|
||||||
|
|
||||||
|
Similar headers are also used by other authentication systems like [Authelia](https://www.authelia.com/integration/trusted-header-sso/introduction/) to signal the backend application information about the signed in user.
|
||||||
|
|
||||||
|
When a request is allowed, the auth service adds these headers by the forward-auth mechanism before proxying to your app as **request headers**. Your app can use them for user context to show on UI, or for its own authentication needs (e.g. prevent different orgs messing up with each other's data, logging which user performed an action).
|
||||||
|
|
||||||
|
Only the UUID values should be used for identification needs, because they never change, even when things are renamed (display names change), and are never reused (created on authentication server). They are UUIDv7 so you can also extract the creation timestamp from them.
|
||||||
|
|
||||||
|
Any `Remote-*` headers from clients are stripped by our [Caddy configuration](Caddy.md) to avoid dealing with any fake headers.
|
||||||
|
|
||||||
|
Note: the headers are intended primarily for the backend, while either frontend or backend (passing the session cookie) can request `/auth/api/user-info` for more complete information, and that is the recommended way to do it in the frontend. See [integration](Integration.md) for more.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Integrating Paskia with your App
|
||||||
|
|
||||||
|
Protect API routes with forward-auth (see [Caddy configuration](Caddy.md)). Optionally protect your app assets and not just the API.
|
||||||
|
|
||||||
|
Catch response status 401/403 in fetch calls to protected endpoints and implement authentication flow in this case. The response is JSON and contains `detail` (an error message describing what is needed) and `auth.iframe` (a URL). Render that URL in an iframe and retry the request after authentication (see below).
|
||||||
|
|
||||||
|
While the app is in (active) use, call `/auth/api/validate` occasionally to keep the session alive (session lifetime is 24h), otherwise the user will have to login every day. Max-age limits are unaffected by this and can be used on endpoints needing to reauthenticate with passkey more frequently.
|
||||||
|
|
||||||
|
Fetch `/auth/api/user-info` to display user/session details, or link to `/auth/` if you prefer using the built-in profile UI and not having to do anything more.
|
||||||
|
|
||||||
|
## Authentication Flow (iframe)
|
||||||
|
|
||||||
|
```js
|
||||||
|
// Show an authentication dialog
|
||||||
|
const iframe = document.createElement('iframe')
|
||||||
|
iframe.src = auth.url // from 401/403 response JSON
|
||||||
|
iframe.style.cssText = `
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
border: 0;
|
||||||
|
z-index: 9999;
|
||||||
|
background: transparent;
|
||||||
|
backdrop-filter: blur(0.1rem) brightness(0.7);
|
||||||
|
`
|
||||||
|
document.body.appendChild(iframe)
|
||||||
|
|
||||||
|
// Wait until user is finished with the dialog
|
||||||
|
const handler = ev => {
|
||||||
|
if (ev.origin !== location.origin) return
|
||||||
|
iframe.remove()
|
||||||
|
removeEventListener('message', handler)
|
||||||
|
if (ev.data?.type === 'auth-success') retry_original_fetch()
|
||||||
|
}
|
||||||
|
addEventListener('message', handler)
|
||||||
|
```
|
||||||
|
|
||||||
|
This describes the frontend flow for handling 401/403 responses from endpoints protected by Paskia forward-auth, without ever exiting your app.
|
||||||
|
|
||||||
|
When a protected request fails, the backend returns 401 (needs auth / reauth) or 403 (missing permission). For API requests, the response is JSON that includes an iframe URL. Your app should render that URL in a full-screen iframe overlay, and retry the request after the iframe reports success. If it reports `auth-cancel`, don't try again. The backdrop for the dialog is a stylistic choice, and you can style the background shown with the dialog any way you wish, and consider using CSS file with the iframe rather than inline styles as used in the example.
|
||||||
|
|
||||||
|
Following this flow the user gets authenticated properly and after that your app keeps running as if nothing ever happened.
|
||||||
@@ -97,14 +97,14 @@ test.describe('Passkey Authentication E2E', () => {
|
|||||||
// Verify registration result
|
// Verify registration result
|
||||||
expect(result.session_token).toBeDefined()
|
expect(result.session_token).toBeDefined()
|
||||||
expect(result.session_token).toHaveLength(16)
|
expect(result.session_token).toHaveLength(16)
|
||||||
expect(result.user_uuid).toBeDefined()
|
expect(result.user).toBeDefined()
|
||||||
expect(result.credential_uuid).toBeDefined()
|
expect(result.credential).toBeDefined()
|
||||||
expect(result.message).toContain('successfully')
|
expect(result.message).toContain('successfully')
|
||||||
|
|
||||||
// Store for subsequent tests
|
// Store for subsequent tests
|
||||||
sessionToken = result.session_token
|
sessionToken = result.session_token
|
||||||
userUuid = result.user_uuid
|
userUuid = result.user
|
||||||
credentialUuid = result.credential_uuid
|
credentialUuid = result.credential
|
||||||
|
|
||||||
// Save session token for other test groups to use
|
// Save session token for other test groups to use
|
||||||
saveSessionToken(sessionToken)
|
saveSessionToken(sessionToken)
|
||||||
@@ -138,9 +138,9 @@ test.describe('Passkey Authentication E2E', () => {
|
|||||||
const validation = await validateSession(page, baseUrl, sessionToken)
|
const validation = await validateSession(page, baseUrl, sessionToken)
|
||||||
|
|
||||||
expect(validation.valid).toBe(true)
|
expect(validation.valid).toBe(true)
|
||||||
expect(validation.user_uuid).toBe(userUuid)
|
expect(validation.ctx.user.uuid).toBe(userUuid)
|
||||||
|
|
||||||
console.log(`✓ Session validated for user: ${validation.user_uuid}`)
|
console.log(`✓ Session validated for user: ${validation.ctx.user.uuid}`)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('should retrieve user info', async ({ page }) => {
|
test('should retrieve user info', async ({ page }) => {
|
||||||
@@ -148,8 +148,8 @@ test.describe('Passkey Authentication E2E', () => {
|
|||||||
|
|
||||||
const userInfo = await getUserInfo(page, baseUrl, sessionToken)
|
const userInfo = await getUserInfo(page, baseUrl, sessionToken)
|
||||||
|
|
||||||
expect(userInfo.user.user_uuid).toBe(userUuid)
|
expect(userInfo.ctx.user.uuid).toBe(userUuid)
|
||||||
expect(userInfo.user.user_name).toBe('Admin User')
|
expect(userInfo.ctx.user.display_name).toBe('Admin User')
|
||||||
expect(userInfo.credentials).toBeDefined()
|
expect(userInfo.credentials).toBeDefined()
|
||||||
expect(userInfo.credentials.length).toBeGreaterThanOrEqual(1)
|
expect(userInfo.credentials.length).toBeGreaterThanOrEqual(1)
|
||||||
|
|
||||||
@@ -169,7 +169,7 @@ test.describe('Passkey Authentication E2E', () => {
|
|||||||
await page.screenshot({ path: 'test-results/profile-view.png' })
|
await page.screenshot({ path: 'test-results/profile-view.png' })
|
||||||
console.log('✓ Screenshot saved: test-results/profile-view.png')
|
console.log('✓ Screenshot saved: test-results/profile-view.png')
|
||||||
|
|
||||||
console.log(`✓ User info retrieved: ${userInfo.user.user_name}`)
|
console.log(`✓ User info retrieved: ${userInfo.ctx.user.display_name}`)
|
||||||
console.log(`✓ Credentials count: ${userInfo.credentials.length}`)
|
console.log(`✓ Credentials count: ${userInfo.credentials.length}`)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -190,7 +190,7 @@ test.describe('Passkey Authentication E2E', () => {
|
|||||||
displayName: 'Admin User (test device)'
|
displayName: 'Admin User (test device)'
|
||||||
})
|
})
|
||||||
|
|
||||||
console.log(`✓ Added test credential: ${regResult.credential_uuid}`)
|
console.log(`✓ Added test credential: ${regResult.credential}`)
|
||||||
|
|
||||||
// Now logout and authenticate with the fresh credential
|
// Now logout and authenticate with the fresh credential
|
||||||
await logout(page, baseUrl, regResult.session_token)
|
await logout(page, baseUrl, regResult.session_token)
|
||||||
@@ -201,7 +201,7 @@ test.describe('Passkey Authentication E2E', () => {
|
|||||||
|
|
||||||
expect(result.session_token).toBeDefined()
|
expect(result.session_token).toBeDefined()
|
||||||
expect(result.session_token).toHaveLength(16)
|
expect(result.session_token).toHaveLength(16)
|
||||||
expect(result.user_uuid).toBe(userUuid)
|
expect(result.user).toBe(userUuid)
|
||||||
|
|
||||||
// Update session token for subsequent tests
|
// Update session token for subsequent tests
|
||||||
sessionToken = result.session_token
|
sessionToken = result.session_token
|
||||||
@@ -209,7 +209,7 @@ test.describe('Passkey Authentication E2E', () => {
|
|||||||
// Save session token for other test groups to use
|
// Save session token for other test groups to use
|
||||||
saveSessionToken(sessionToken)
|
saveSessionToken(sessionToken)
|
||||||
|
|
||||||
console.log(`✓ Authenticated as user: ${result.user_uuid}`)
|
console.log(`✓ Authenticated as user: ${result.user}`)
|
||||||
console.log(`✓ New session token: ${sessionToken.substring(0, 4)}...`)
|
console.log(`✓ New session token: ${sessionToken.substring(0, 4)}...`)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -219,7 +219,7 @@ test.describe('Passkey Authentication E2E', () => {
|
|||||||
const validation = await validateSession(page, baseUrl, sessionToken)
|
const validation = await validateSession(page, baseUrl, sessionToken)
|
||||||
|
|
||||||
expect(validation.valid).toBe(true)
|
expect(validation.valid).toBe(true)
|
||||||
expect(validation.user_uuid).toBe(userUuid)
|
expect(validation.ctx.user.uuid).toBe(userUuid)
|
||||||
|
|
||||||
console.log(`✓ New session validated`)
|
console.log(`✓ New session validated`)
|
||||||
})
|
})
|
||||||
@@ -291,8 +291,8 @@ test.describe('Device Addition Dialog', () => {
|
|||||||
// Wait for the profile view to load
|
// Wait for the profile view to load
|
||||||
await page.waitForSelector('[data-view="profile"]', { timeout: 5000 })
|
await page.waitForSelector('[data-view="profile"]', { timeout: 5000 })
|
||||||
|
|
||||||
// Click the "Add Another Device" button
|
// Click the "Another Device" button
|
||||||
const addDeviceButton = page.getByRole('button', { name: 'Add Another Device' })
|
const addDeviceButton = page.getByRole('button', { name: 'Another Device' })
|
||||||
await expect(addDeviceButton).toBeVisible()
|
await expect(addDeviceButton).toBeVisible()
|
||||||
await addDeviceButton.click()
|
await addDeviceButton.click()
|
||||||
|
|
||||||
@@ -301,7 +301,7 @@ test.describe('Device Addition Dialog', () => {
|
|||||||
await expect(dialog).toBeVisible({ timeout: 5000 })
|
await expect(dialog).toBeVisible({ timeout: 5000 })
|
||||||
|
|
||||||
// Verify dialog contains expected elements
|
// Verify dialog contains expected elements
|
||||||
await expect(dialog.locator('h2')).toContainText('Device Registration Link')
|
await expect(dialog.locator('h2')).toContainText('Add Another Device')
|
||||||
|
|
||||||
// Wait for QR code to be generated (canvas should have content)
|
// Wait for QR code to be generated (canvas should have content)
|
||||||
const qrCanvas = dialog.locator('.qr-code')
|
const qrCanvas = dialog.locator('.qr-code')
|
||||||
@@ -318,16 +318,16 @@ test.describe('Device Addition Dialog', () => {
|
|||||||
expect(linkHref).toContain('http://localhost:4404/auth/')
|
expect(linkHref).toContain('http://localhost:4404/auth/')
|
||||||
console.log(`✓ Device link displayed: ${linkText} (href: ${linkHref})`)
|
console.log(`✓ Device link displayed: ${linkText} (href: ${linkHref})`)
|
||||||
|
|
||||||
// Verify expiration warning is shown
|
// Verify help text is shown
|
||||||
await expect(dialog.locator('.reg-help')).toContainText('Expires')
|
await expect(dialog.locator('.reg-help')).toContainText('Scan this QR code')
|
||||||
|
|
||||||
// Take screenshot of the dialog
|
// Take screenshot of the dialog
|
||||||
await dialog.screenshot({ path: 'test-results/device-addition-dialog.png' })
|
await dialog.screenshot({ path: 'test-results/device-addition-dialog.png' })
|
||||||
console.log(`✓ Screenshot saved: test-results/device-addition-dialog.png`)
|
console.log(`✓ Screenshot saved: test-results/device-addition-dialog.png`)
|
||||||
|
|
||||||
// Verify Copy Link button exists
|
// Verify the QR link element is clickable (copy functionality is built into clicking it)
|
||||||
const copyButton = dialog.getByRole('button', { name: 'Copy Link' })
|
const qrLink = dialog.locator('a.qr-link')
|
||||||
await expect(copyButton).toBeVisible()
|
await expect(qrLink).toBeVisible()
|
||||||
|
|
||||||
// Close the dialog (use the text button, not the icon button)
|
// Close the dialog (use the text button, not the icon button)
|
||||||
const closeButton = dialog.locator('button.btn-secondary', { hasText: 'Close' })
|
const closeButton = dialog.locator('button.btn-secondary', { hasText: 'Close' })
|
||||||
@@ -357,12 +357,12 @@ test.describe('Device Addition Dialog', () => {
|
|||||||
await page.waitForSelector('[data-view="profile"]', { timeout: 5000 })
|
await page.waitForSelector('[data-view="profile"]', { timeout: 5000 })
|
||||||
|
|
||||||
// Open the dialog
|
// Open the dialog
|
||||||
await page.getByRole('button', { name: 'Add Another Device' }).click()
|
await page.getByRole('button', { name: 'Another Device' }).click()
|
||||||
const dialog = page.locator('.device-dialog')
|
const dialog = page.locator('.device-dialog')
|
||||||
await expect(dialog).toBeVisible({ timeout: 5000 })
|
await expect(dialog).toBeVisible({ timeout: 5000 })
|
||||||
|
|
||||||
// Extract the reset token from the displayed URL
|
// Extract the reset token from the displayed URL
|
||||||
const linkText = dialog.locator('.qr-link p')
|
const linkText = dialog.locator('.qr-link .link-text')
|
||||||
const linkContent = await linkText.textContent()
|
const linkContent = await linkText.textContent()
|
||||||
|
|
||||||
// URL format: localhost/auth/word1.word2.word3.word4.word5
|
// URL format: localhost/auth/word1.word2.word3.word4.word5
|
||||||
@@ -405,7 +405,7 @@ test.describe('Device Addition Dialog', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
test.describe('ProfileView - Add New Passkey', () => {
|
test.describe('ProfileView - Register New', () => {
|
||||||
const baseUrl = process.env.BASE_URL || 'http://localhost:4404'
|
const baseUrl = process.env.BASE_URL || 'http://localhost:4404'
|
||||||
|
|
||||||
test('should show credentials list in profile', async ({ page }) => {
|
test('should show credentials list in profile', async ({ page }) => {
|
||||||
@@ -427,7 +427,7 @@ test.describe('ProfileView - Add New Passkey', () => {
|
|||||||
console.log(`✓ Profile shows ${credentialItems} credential(s) in list`)
|
console.log(`✓ Profile shows ${credentialItems} credential(s) in list`)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('should add a new passkey using Add New Passkey button', async ({ page }) => {
|
test('should add a new passkey using Register New button', async ({ page }) => {
|
||||||
const sessionToken = getSavedSessionToken()
|
const sessionToken = getSavedSessionToken()
|
||||||
test.skip(!sessionToken, 'Requires saved session token')
|
test.skip(!sessionToken, 'Requires saved session token')
|
||||||
|
|
||||||
@@ -444,8 +444,8 @@ test.describe('ProfileView - Add New Passkey', () => {
|
|||||||
const initialCredentialCount = await page.locator('.credential-item').count()
|
const initialCredentialCount = await page.locator('.credential-item').count()
|
||||||
console.log(`Initial credential count: ${initialCredentialCount}`)
|
console.log(`Initial credential count: ${initialCredentialCount}`)
|
||||||
|
|
||||||
// Click "Add New Passkey" button
|
// Click "Register New" button
|
||||||
const addPasskeyBtn = page.locator('button:has-text("Add New Passkey")')
|
const addPasskeyBtn = page.locator('button:has-text("Register New")')
|
||||||
await expect(addPasskeyBtn).toBeVisible()
|
await expect(addPasskeyBtn).toBeVisible()
|
||||||
await addPasskeyBtn.click()
|
await addPasskeyBtn.click()
|
||||||
|
|
||||||
@@ -490,7 +490,7 @@ test.describe('ProfileView - Add New Passkey', () => {
|
|||||||
|
|
||||||
// Try to add a passkey - with excludeCredentials the authenticator should
|
// Try to add a passkey - with excludeCredentials the authenticator should
|
||||||
// prevent re-registration of the same credential
|
// prevent re-registration of the same credential
|
||||||
const addPasskeyBtn = page.locator('button:has-text("Add New Passkey")')
|
const addPasskeyBtn = page.locator('button:has-text("Register New")')
|
||||||
await expect(addPasskeyBtn).toBeVisible()
|
await expect(addPasskeyBtn).toBeVisible()
|
||||||
await addPasskeyBtn.click()
|
await addPasskeyBtn.click()
|
||||||
|
|
||||||
@@ -541,8 +541,8 @@ test.describe('ProfileView - Multi-Authenticator', () => {
|
|||||||
await page.waitForSelector('.credential-list', { timeout: 10000 })
|
await page.waitForSelector('.credential-list', { timeout: 10000 })
|
||||||
const initialCredentialCount = await page.locator('.credential-item').count()
|
const initialCredentialCount = await page.locator('.credential-item').count()
|
||||||
|
|
||||||
// Click "Add New Passkey" button
|
// Click "Register New" button
|
||||||
const addPasskeyBtn = page.locator('button:has-text("Add New Passkey")')
|
const addPasskeyBtn = page.locator('button:has-text("Register New")')
|
||||||
await expect(addPasskeyBtn).toBeVisible()
|
await expect(addPasskeyBtn).toBeVisible()
|
||||||
await addPasskeyBtn.click()
|
await addPasskeyBtn.click()
|
||||||
|
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ async function makeApiCall(page: Page, url: string, method = 'GET'): Promise<{ s
|
|||||||
// Wait a tick for the page's handler to retry, then make our own call
|
// Wait a tick for the page's handler to retry, then make our own call
|
||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, { method, credentials: 'include' });
|
const response = await fetch(url, { method });
|
||||||
if (response.status === 204) {
|
if (response.status === 204) {
|
||||||
resolve({ status: 204 });
|
resolve({ status: 204 });
|
||||||
} else if (response.ok) {
|
} else if (response.ok) {
|
||||||
@@ -111,7 +111,7 @@ async function makeApiCall(page: Page, url: string, method = 'GET'): Promise<{ s
|
|||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
if (resolved) return;
|
if (resolved) return;
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, { method, credentials: 'include' });
|
const response = await fetch(url, { method });
|
||||||
// Only resolve if this is a success or non-auth error
|
// Only resolve if this is a success or non-auth error
|
||||||
if (response.status !== 401 && response.status !== 403) {
|
if (response.status !== 401 && response.status !== 403) {
|
||||||
if (resolved) return;
|
if (resolved) return;
|
||||||
@@ -242,7 +242,7 @@ test.describe('API Mode - 401 Login Flow', () => {
|
|||||||
resetToken: deviceToken,
|
resetToken: deviceToken,
|
||||||
displayName: 'API Test Device',
|
displayName: 'API Test Device',
|
||||||
})
|
})
|
||||||
console.log(`✓ Registered credential: ${regResult.credential_uuid}`)
|
console.log(`✓ Registered credential: ${regResult.credential}`)
|
||||||
|
|
||||||
// Logout to clear session (but keep the passkey in virtual authenticator)
|
// Logout to clear session (but keep the passkey in virtual authenticator)
|
||||||
await logout(page, baseUrl, regResult.session_token)
|
await logout(page, baseUrl, regResult.session_token)
|
||||||
@@ -268,7 +268,7 @@ test.describe('API Mode - 401 Login Flow', () => {
|
|||||||
// Wait for API call to complete and verify result
|
// Wait for API call to complete and verify result
|
||||||
const result = await apiCallPromise
|
const result = await apiCallPromise
|
||||||
expect(result.status).toBe(200)
|
expect(result.status).toBe(200)
|
||||||
expect(result.data.user).toBeDefined()
|
expect(result.data.ctx).toBeDefined()
|
||||||
console.log('✓ API call succeeded after authentication')
|
console.log('✓ API call succeeded after authentication')
|
||||||
|
|
||||||
// Save the session for other tests
|
// Save the session for other tests
|
||||||
|
|||||||
+39
-5
@@ -12,17 +12,51 @@ const stateFile = join(__dirname, '..', '..', 'test-data', 'test-state.json')
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export interface RegistrationResult {
|
export interface RegistrationResult {
|
||||||
user_uuid: string
|
user: string
|
||||||
credential_uuid: string
|
credential: string
|
||||||
session_token: string
|
session_token: string
|
||||||
message: string
|
message: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AuthenticationResult {
|
export interface AuthenticationResult {
|
||||||
user_uuid: string
|
user: string
|
||||||
session_token: string
|
session_token: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SessionContext {
|
||||||
|
user: { uuid: string; display_name: string }
|
||||||
|
org: { uuid: string; display_name: string }
|
||||||
|
role: { uuid: string; display_name: string }
|
||||||
|
permissions: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserInfo {
|
||||||
|
ctx: SessionContext
|
||||||
|
created_at: string
|
||||||
|
last_seen: string
|
||||||
|
visits: number
|
||||||
|
credentials: Array<{
|
||||||
|
credential: string
|
||||||
|
aaguid: string
|
||||||
|
created_at: string
|
||||||
|
last_used: string | null
|
||||||
|
last_verified: string | null
|
||||||
|
sign_count: number
|
||||||
|
is_current_session: boolean
|
||||||
|
}>
|
||||||
|
aaguid_info: Record<string, { name: string; icon_light?: string; icon_dark?: string }>
|
||||||
|
sessions: Array<{
|
||||||
|
id: string
|
||||||
|
credential: string
|
||||||
|
host: string
|
||||||
|
ip: string
|
||||||
|
user_agent: string
|
||||||
|
last_renewed: string
|
||||||
|
is_current: boolean
|
||||||
|
is_current_host: boolean
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the bootstrap reset token from the test state file.
|
* Get the bootstrap reset token from the test state file.
|
||||||
*/
|
*/
|
||||||
@@ -376,7 +410,7 @@ export async function validateSession(
|
|||||||
page: Page,
|
page: Page,
|
||||||
baseUrl: string,
|
baseUrl: string,
|
||||||
sessionToken: string
|
sessionToken: string
|
||||||
): Promise<{ valid: boolean; user_uuid: string; renewed: boolean }> {
|
): Promise<{ valid: boolean; ctx: SessionContext; renewed: boolean }> {
|
||||||
const cookieName = getSessionCookieName()
|
const cookieName = getSessionCookieName()
|
||||||
const response = await page.request.post(`${baseUrl}/auth/api/validate`, {
|
const response = await page.request.post(`${baseUrl}/auth/api/validate`, {
|
||||||
headers: {
|
headers: {
|
||||||
@@ -393,7 +427,7 @@ export async function getUserInfo(
|
|||||||
page: Page,
|
page: Page,
|
||||||
baseUrl: string,
|
baseUrl: string,
|
||||||
sessionToken: string
|
sessionToken: string
|
||||||
): Promise<any> {
|
): Promise<UserInfo> {
|
||||||
const cookieName = getSessionCookieName()
|
const cookieName = getSessionCookieName()
|
||||||
const response = await page.request.post(`${baseUrl}/auth/api/user-info`, {
|
const response = await page.request.post(`${baseUrl}/auth/api/user-info`, {
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
@@ -42,21 +42,23 @@ export default async function globalSetup() {
|
|||||||
const serverArgs = COLLECT_COVERAGE
|
const serverArgs = COLLECT_COVERAGE
|
||||||
? [
|
? [
|
||||||
'run', 'coverage', 'run', '--parallel-mode',
|
'run', 'coverage', 'run', '--parallel-mode',
|
||||||
'-m', 'paskia.fastapi', 'serve', 'localhost:4404',
|
'-m', 'paskia.fastapi', 'localhost:4404',
|
||||||
'--rp-id', 'localhost'
|
'--rp-id', 'localhost'
|
||||||
]
|
]
|
||||||
: [
|
: [
|
||||||
'run', 'paskia', 'serve', 'localhost:4404',
|
'run', 'paskia', 'localhost:4404',
|
||||||
'--rp-id', 'localhost'
|
'--rp-id', 'localhost'
|
||||||
]
|
]
|
||||||
|
|
||||||
|
// Use a temporary jsonl file for test database
|
||||||
|
const testDbFile = join(testDataDir, 'test-db.jsonl')
|
||||||
|
|
||||||
// Start the server using Node's spawn
|
// Start the server using Node's spawn
|
||||||
// Use in-memory SQLite for faster tests
|
|
||||||
const serverProcess = spawn('uv', serverArgs, {
|
const serverProcess = spawn('uv', serverArgs, {
|
||||||
cwd: projectRoot,
|
cwd: projectRoot,
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
PASKIA_DB: 'sqlite+aiosqlite:///:memory:',
|
PASKIA_DB: testDbFile,
|
||||||
COVERAGE_FILE: join(projectRoot, '.coverage'),
|
COVERAGE_FILE: join(projectRoot, '.coverage'),
|
||||||
},
|
},
|
||||||
stdio: ['ignore', 'pipe', 'pipe'],
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
|||||||
@@ -59,18 +59,11 @@ export default async function globalTeardown() {
|
|||||||
rmSync(stateFile, { force: true })
|
rmSync(stateFile, { force: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
// Optionally clean up test database (keep it for debugging by default)
|
// Clean up test database
|
||||||
if (process.env.CLEANUP_TEST_DB === 'true') {
|
const testDbFile = join(testDataDir, 'test-db.jsonl')
|
||||||
const dbPath = join(testDataDir, 'test.sqlite')
|
if (existsSync(testDbFile)) {
|
||||||
if (existsSync(dbPath)) {
|
|
||||||
console.log(' Removing test database...')
|
console.log(' Removing test database...')
|
||||||
rmSync(dbPath)
|
rmSync(testDbFile)
|
||||||
}
|
|
||||||
// Remove wal/shm files too
|
|
||||||
for (const ext of ['-wal', '-shm']) {
|
|
||||||
const file = dbPath + ext
|
|
||||||
if (existsSync(file)) rmSync(file)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate Python coverage report if coverage was collected
|
// Generate Python coverage report if coverage was collected
|
||||||
|
|||||||
+2
-2
@@ -96,7 +96,7 @@
|
|||||||
async function apiCall(url, method = 'GET') {
|
async function apiCall(url, method = 'GET') {
|
||||||
log(`${method} ${url}...`);
|
log(`${method} ${url}...`);
|
||||||
|
|
||||||
const response = await fetch(url, { method, credentials: 'include' });
|
const response = await fetch(url, { method });
|
||||||
|
|
||||||
// Server returns 401 (login/reauth) or 403 (missing permissions)
|
// Server returns 401 (login/reauth) or 403 (missing permissions)
|
||||||
// with a JSON body containing the iframe URL for authentication
|
// with a JSON body containing the iframe URL for authentication
|
||||||
@@ -131,7 +131,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function logout() {
|
async function logout() {
|
||||||
await fetch('/auth/api/logout', { method: 'POST', credentials: 'include' });
|
await fetch('/auth/api/logout', { method: 'POST' });
|
||||||
log('Logged out');
|
log('Logged out');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+20
-36
@@ -2,10 +2,10 @@
|
|||||||
<div class="app-shell">
|
<div class="app-shell">
|
||||||
<StatusMessage />
|
<StatusMessage />
|
||||||
<main class="app-main">
|
<main class="app-main">
|
||||||
<HostProfileView v-if="authenticated && isHostMode" :initializing="loading" />
|
<HostProfileView v-if="viewState === 'profile' && isHostMode" />
|
||||||
<ProfileView v-else-if="authenticated" />
|
<ProfileView v-else-if="viewState === 'profile'" />
|
||||||
<LoadingView v-else-if="loading" :message="loadingMessage" />
|
<LoadingView v-else-if="viewState === 'loading'" :message="loadingMessage" />
|
||||||
<AuthRequiredMessage v-else-if="showBackMessage" @reload="reloadPage" />
|
<AccessDenied v-else-if="viewState === 'terminal'" />
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -18,13 +18,11 @@ import StatusMessage from '@/components/StatusMessage.vue'
|
|||||||
import ProfileView from '@/components/ProfileView.vue'
|
import ProfileView from '@/components/ProfileView.vue'
|
||||||
import HostProfileView from '@/components/HostProfileView.vue'
|
import HostProfileView from '@/components/HostProfileView.vue'
|
||||||
import LoadingView from '@/components/LoadingView.vue'
|
import LoadingView from '@/components/LoadingView.vue'
|
||||||
import AuthRequiredMessage from '@/components/AccessDenied.vue'
|
import AccessDenied from '@/components/AccessDenied.vue'
|
||||||
|
|
||||||
const store = useAuthStore()
|
const store = useAuthStore()
|
||||||
const loading = ref(true)
|
const viewState = ref('loading') // 'loading' | 'profile' | 'terminal'
|
||||||
const loadingMessage = ref('Loading...')
|
const loadingMessage = ref('Loading...')
|
||||||
const authenticated = ref(false)
|
|
||||||
const showBackMessage = ref(false)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalize a host string for comparison (lowercase, strip default ports).
|
* Normalize a host string for comparison (lowercase, strip default ports).
|
||||||
@@ -51,14 +49,19 @@ const isHostMode = computed(() => {
|
|||||||
let validationTimer = null
|
let validationTimer = null
|
||||||
let authIframe = null
|
let authIframe = null
|
||||||
|
|
||||||
|
function terminateSession() {
|
||||||
|
store.userInfo = null
|
||||||
|
viewState.value = 'terminal'
|
||||||
|
}
|
||||||
|
|
||||||
async function loadUserInfo() {
|
async function loadUserInfo() {
|
||||||
try {
|
try {
|
||||||
store.userInfo = await apiJson('/auth/api/user-info', { method: 'POST' })
|
store.userInfo = await apiJson('/auth/api/user-info', { method: 'POST' })
|
||||||
authenticated.value = true
|
viewState.value = 'profile'
|
||||||
loading.value = false
|
|
||||||
startSessionValidation()
|
startSessionValidation()
|
||||||
return true
|
return true
|
||||||
} catch (e) {
|
} catch {
|
||||||
|
store.userInfo = null
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -85,10 +88,6 @@ function hideAuthIframe() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function reloadPage() {
|
|
||||||
window.location.reload()
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleAuthMessage(event) {
|
function handleAuthMessage(event) {
|
||||||
const data = event.data
|
const data = event.data
|
||||||
if (!data?.type) return
|
if (!data?.type) return
|
||||||
@@ -97,7 +96,7 @@ function handleAuthMessage(event) {
|
|||||||
case 'auth-success':
|
case 'auth-success':
|
||||||
// Authentication successful - reload user info
|
// Authentication successful - reload user info
|
||||||
hideAuthIframe()
|
hideAuthIframe()
|
||||||
loading.value = true
|
viewState.value = 'loading'
|
||||||
loadingMessage.value = 'Loading user profile...'
|
loadingMessage.value = 'Loading user profile...'
|
||||||
loadUserInfo()
|
loadUserInfo()
|
||||||
break
|
break
|
||||||
@@ -117,11 +116,9 @@ function handleAuthMessage(event) {
|
|||||||
break
|
break
|
||||||
|
|
||||||
case 'auth-back':
|
case 'auth-back':
|
||||||
// User clicked Back - show message with reload option
|
// User clicked Back - show terminal state
|
||||||
hideAuthIframe()
|
hideAuthIframe()
|
||||||
loading.value = false
|
terminateSession()
|
||||||
showBackMessage.value = true
|
|
||||||
store.showMessage('Authentication cancelled', 'info', 3000)
|
|
||||||
break
|
break
|
||||||
|
|
||||||
case 'auth-close-request':
|
case 'auth-close-request':
|
||||||
@@ -133,23 +130,10 @@ function handleAuthMessage(event) {
|
|||||||
|
|
||||||
async function validateSession() {
|
async function validateSession() {
|
||||||
try {
|
try {
|
||||||
await apiJson('/auth/api/validate', {
|
await apiJson('/auth/api/validate', { method: 'POST' })
|
||||||
method: 'POST',
|
} catch {
|
||||||
credentials: 'include'
|
|
||||||
})
|
|
||||||
// If successful, session was renewed automatically
|
|
||||||
} catch (error) {
|
|
||||||
if (error.status === 401) {
|
|
||||||
// Session expired - need to re-authenticate
|
|
||||||
console.log('Session expired, requiring re-authentication')
|
|
||||||
authenticated.value = false
|
|
||||||
loading.value = true
|
|
||||||
stopSessionValidation()
|
stopSessionValidation()
|
||||||
showAuthIframe()
|
terminateSession()
|
||||||
} else {
|
|
||||||
console.error('Session validation error:', error)
|
|
||||||
// Don't treat network errors as session expiry
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,15 +5,16 @@ import CredentialList from '@/components/CredentialList.vue'
|
|||||||
import UserBasicInfo from '@/components/UserBasicInfo.vue'
|
import UserBasicInfo from '@/components/UserBasicInfo.vue'
|
||||||
import StatusMessage from '@/components/StatusMessage.vue'
|
import StatusMessage from '@/components/StatusMessage.vue'
|
||||||
import LoadingView from '@/components/LoadingView.vue'
|
import LoadingView from '@/components/LoadingView.vue'
|
||||||
import AuthRequiredMessage from '@/components/AccessDenied.vue'
|
import AccessDenied from '@/components/AccessDenied.vue'
|
||||||
import AdminOverview from '@/admin/AdminOverview.vue'
|
import AdminOverview from '@/admin/AdminOverview.vue'
|
||||||
import AdminOrgDetail from '@/admin/AdminOrgDetail.vue'
|
import AdminOrgDetail from '@/admin/AdminOrgDetail.vue'
|
||||||
import AdminUserDetail from '@/admin/AdminUserDetail.vue'
|
import AdminUserDetail from '@/admin/AdminUserDetail.vue'
|
||||||
import AdminDialogs from '@/admin/AdminDialogs.vue'
|
import AdminDialogs from '@/admin/AdminDialogs.vue'
|
||||||
import { useAuthStore } from '@/stores/auth'
|
import { useAuthStore } from '@/stores/auth'
|
||||||
import { getSettings, adminUiPath, makeUiHref } from '@/utils/settings'
|
import { adminUiPath, makeUiHref } from '@/utils/settings'
|
||||||
import { apiJson } from '@/utils/api'
|
import { apiJson } from '@/utils/api'
|
||||||
import { getDirection } from '@/utils/keynav'
|
import { getDirection } from '@/utils/keynav'
|
||||||
|
import { goBack } from '@/utils/helpers'
|
||||||
|
|
||||||
const info = ref(null)
|
const info = ref(null)
|
||||||
const loading = ref(true)
|
const loading = ref(true)
|
||||||
@@ -46,6 +47,10 @@ const adminUserDetailRef = ref(null)
|
|||||||
// Check if any modal/dialog is open (blocks arrow key navigation)
|
// Check if any modal/dialog is open (blocks arrow key navigation)
|
||||||
const hasActiveModal = computed(() => dialog.value.type !== null || showRegModal.value)
|
const hasActiveModal = computed(() => dialog.value.type !== null || showRegModal.value)
|
||||||
|
|
||||||
|
// Derive admin status from permissions
|
||||||
|
const isMasterAdmin = computed(() => info.value?.ctx.permissions.includes('auth:admin'))
|
||||||
|
const isOrgAdmin = computed(() => info.value?.ctx.permissions.includes('auth:org:admin'))
|
||||||
|
|
||||||
function sanitizeRenameId() { if (renameIdValue.value) renameIdValue.value = renameIdValue.value.replace(safeIdRegex, '') }
|
function sanitizeRenameId() { if (renameIdValue.value) renameIdValue.value = renameIdValue.value.replace(safeIdRegex, '') }
|
||||||
|
|
||||||
function handleGlobalClick(e) {
|
function handleGlobalClick(e) {
|
||||||
@@ -60,8 +65,8 @@ function handleGlobalClick(e) {
|
|||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
document.addEventListener('click', handleGlobalClick)
|
document.addEventListener('click', handleGlobalClick)
|
||||||
window.addEventListener('hashchange', parseHash)
|
window.addEventListener('hashchange', parseHash)
|
||||||
const settings = await getSettings()
|
await authStore.loadSettings()
|
||||||
if (settings?.rp_name) document.title = settings.rp_name + ' Admin'
|
if (authStore.settings?.rp_name) document.title = authStore.settings.rp_name + ' Admin'
|
||||||
await load()
|
await load()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -108,7 +113,7 @@ const permissionSummary = computed(() => {
|
|||||||
return display
|
return display
|
||||||
})
|
})
|
||||||
|
|
||||||
function renamePermissionDisplay(p) { openDialog('perm-display', { permission: p, id: p.id, display_name: p.display_name }) }
|
function renamePermissionDisplay(p) { openDialog('perm-display', { permission: p, scope: p.scope, display_name: p.display_name, domain: p.domain || '' }) }
|
||||||
|
|
||||||
|
|
||||||
function parseHash() {
|
function parseHash() {
|
||||||
@@ -125,7 +130,7 @@ function parseHash() {
|
|||||||
async function loadOrgs() {
|
async function loadOrgs() {
|
||||||
const data = await apiJson('/auth/api/admin/orgs')
|
const data = await apiJson('/auth/api/admin/orgs')
|
||||||
orgs.value = data.map(o => {
|
orgs.value = data.map(o => {
|
||||||
const roles = o.roles.map(r => ({ ...r, org_uuid: o.uuid, users: [] }))
|
const roles = o.roles.map(r => ({ ...r, org: o.uuid, users: [] }))
|
||||||
const roleMap = Object.fromEntries(roles.map(r => [r.display_name, r]))
|
const roleMap = Object.fromEntries(roles.map(r => [r.display_name, r]))
|
||||||
for (const u of o.users || []) {
|
for (const u of o.users || []) {
|
||||||
if (roleMap[u.role]) roleMap[u.role].users.push(u)
|
if (roleMap[u.role]) roleMap[u.role].users.push(u)
|
||||||
@@ -139,10 +144,19 @@ async function loadPermissions() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadUserInfo() {
|
async function loadUserInfo() {
|
||||||
info.value = await apiJson('/auth/api/user-info', { method: 'POST' })
|
const data = await apiJson('/auth/api/validate', { method: 'POST' })
|
||||||
|
info.value = data
|
||||||
authenticated.value = true
|
authenticated.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function clearSensitiveState() {
|
||||||
|
info.value = null
|
||||||
|
orgs.value = []
|
||||||
|
permissions.value = []
|
||||||
|
userDetail.value = null
|
||||||
|
authenticated.value = false
|
||||||
|
}
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
loadingMessage.value = 'Loading...'
|
loadingMessage.value = 'Loading...'
|
||||||
@@ -153,7 +167,7 @@ async function load() {
|
|||||||
// If we get here, user has admin access - now fetch user info for display
|
// If we get here, user has admin access - now fetch user info for display
|
||||||
await loadUserInfo()
|
await loadUserInfo()
|
||||||
|
|
||||||
if (!info.value.is_global_admin && info.value.is_org_admin && orgs.value.length === 1) {
|
if (!isMasterAdmin.value && isOrgAdmin.value && orgs.value.length === 1) {
|
||||||
if (!window.location.hash || window.location.hash === '#overview') {
|
if (!window.location.hash || window.location.hash === '#overview') {
|
||||||
currentOrgId.value = orgs.value[0].uuid
|
currentOrgId.value = orgs.value[0].uuid
|
||||||
window.location.hash = `#org/${currentOrgId.value}`
|
window.location.hash = `#org/${currentOrgId.value}`
|
||||||
@@ -163,6 +177,7 @@ async function load() {
|
|||||||
}
|
}
|
||||||
} else parseHash()
|
} else parseHash()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
clearSensitiveState()
|
||||||
if (e.name === 'AuthCancelledError') {
|
if (e.name === 'AuthCancelledError') {
|
||||||
showBackMessage.value = true
|
showBackMessage.value = true
|
||||||
} else {
|
} else {
|
||||||
@@ -186,8 +201,6 @@ async function performOrgDeletion(orgUuid) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function deleteOrg(org) {
|
function deleteOrg(org) {
|
||||||
if (!info.value?.is_global_admin) { authStore.showMessage('Global admin only'); return }
|
|
||||||
|
|
||||||
const userCount = org.roles.reduce((acc, r) => acc + r.users.length, 0)
|
const userCount = org.roles.reduce((acc, r) => acc + r.users.length, 0)
|
||||||
|
|
||||||
if (userCount === 0) {
|
if (userCount === 0) {
|
||||||
@@ -220,7 +233,7 @@ async function moveUserToRole(org, user, targetRoleDisplayName) {
|
|||||||
if (user.role === targetRoleDisplayName) return
|
if (user.role === targetRoleDisplayName) return
|
||||||
try {
|
try {
|
||||||
await apiJson(`/auth/api/admin/orgs/${org.uuid}/users/${user.uuid}/role`, {
|
await apiJson(`/auth/api/admin/orgs/${org.uuid}/users/${user.uuid}/role`, {
|
||||||
method: 'PUT',
|
method: 'PATCH',
|
||||||
body: { role: targetRoleDisplayName }
|
body: { role: targetRoleDisplayName }
|
||||||
})
|
})
|
||||||
await loadOrgs()
|
await loadOrgs()
|
||||||
@@ -229,9 +242,9 @@ async function moveUserToRole(org, user, targetRoleDisplayName) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function onUserDragStart(e, user, org_uuid) {
|
function onUserDragStart(e, user, org) {
|
||||||
e.dataTransfer.effectAllowed = 'move'
|
e.dataTransfer.effectAllowed = 'move'
|
||||||
e.dataTransfer.setData('text/plain', JSON.stringify({ user_uuid: user.uuid, org_uuid }))
|
e.dataTransfer.setData('text/plain', JSON.stringify({ user_uuid: user.uuid, org }))
|
||||||
}
|
}
|
||||||
|
|
||||||
function onRoleDragOver(e) {
|
function onRoleDragOver(e) {
|
||||||
@@ -243,7 +256,7 @@ function onRoleDrop(e, org, role) {
|
|||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(e.dataTransfer.getData('text/plain'))
|
const data = JSON.parse(e.dataTransfer.getData('text/plain'))
|
||||||
if (data.org_uuid !== org.uuid) return // only within same org
|
if (data.org !== org.uuid) return // only within same org
|
||||||
const user = org.roles.flatMap(r => r.users).find(u => u.uuid === data.user_uuid)
|
const user = org.roles.flatMap(r => r.users).find(u => u.uuid === data.user_uuid)
|
||||||
if (user) moveUserToRole(org, user, role.display_name)
|
if (user) moveUserToRole(org, user, role.display_name)
|
||||||
} catch (_) { /* ignore */ }
|
} catch (_) { /* ignore */ }
|
||||||
@@ -256,7 +269,7 @@ function updateRole(role) { openDialog('role-update', { role, name: role.display
|
|||||||
|
|
||||||
function deleteRole(role) {
|
function deleteRole(role) {
|
||||||
// UI only allows deleting empty roles, so no confirmation needed
|
// UI only allows deleting empty roles, so no confirmation needed
|
||||||
apiJson(`/auth/api/admin/orgs/${role.org_uuid}/roles/${role.uuid}`, { method: 'DELETE' })
|
apiJson(`/auth/api/admin/orgs/${role.org}/roles/${role.uuid}`, { method: 'DELETE' })
|
||||||
.then(() => {
|
.then(() => {
|
||||||
authStore.showMessage(`Role "${role.display_name}" deleted.`, 'success', 2500)
|
authStore.showMessage(`Role "${role.display_name}" deleted.`, 'success', 2500)
|
||||||
loadOrgs()
|
loadOrgs()
|
||||||
@@ -267,19 +280,17 @@ function deleteRole(role) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function toggleRolePermission(role, pid, checked) {
|
async function toggleRolePermission(role, pid, checked) {
|
||||||
// Calculate new permissions array
|
// Optimistic update
|
||||||
|
const prevPermissions = [...role.permissions]
|
||||||
const newPermissions = checked
|
const newPermissions = checked
|
||||||
? [...role.permissions, pid]
|
? [...role.permissions, pid]
|
||||||
: role.permissions.filter(p => p !== pid)
|
: role.permissions.filter(p => p !== pid)
|
||||||
|
|
||||||
// Optimistic update
|
|
||||||
const prevPermissions = [...role.permissions]
|
|
||||||
role.permissions = newPermissions
|
role.permissions = newPermissions
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await apiJson(`/auth/api/admin/orgs/${role.org_uuid}/roles/${role.uuid}`, {
|
const method = checked ? 'POST' : 'DELETE'
|
||||||
method: 'PUT',
|
await apiJson(`/auth/api/admin/orgs/${role.org}/roles/${role.uuid}/permissions/${pid}`, {
|
||||||
body: { display_name: role.display_name, permissions: newPermissions }
|
method
|
||||||
})
|
})
|
||||||
await loadOrgs()
|
await loadOrgs()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -289,20 +300,20 @@ async function toggleRolePermission(role, pid, checked) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Permission actions
|
// Permission actions
|
||||||
async function performPermissionDeletion(permissionId) {
|
async function performPermissionDeletion(permissionUuid) {
|
||||||
const params = new URLSearchParams({ permission_id: permissionId })
|
const params = new URLSearchParams({ permission_uuid: permissionUuid })
|
||||||
await apiJson(`/auth/api/admin/permission?${params.toString()}`, { method: 'DELETE' })
|
await apiJson(`/auth/api/admin/permission?${params.toString()}`, { method: 'DELETE' })
|
||||||
await loadPermissions()
|
await loadPermissions()
|
||||||
}
|
}
|
||||||
|
|
||||||
function deletePermission(p) {
|
function deletePermission(p) {
|
||||||
const userCount = permissionSummary.value[p.id]?.userCount || 0
|
const userCount = permissionSummary.value[p.uuid]?.userCount || 0
|
||||||
|
|
||||||
// Count roles that have this permission
|
// Count roles that have this permission
|
||||||
let roleCount = 0
|
let roleCount = 0
|
||||||
for (const org of orgs.value) {
|
for (const org of orgs.value) {
|
||||||
for (const role of org.roles) {
|
for (const role of org.roles) {
|
||||||
if (role.permissions.includes(p.id)) {
|
if (role.permissions.includes(p.uuid)) {
|
||||||
roleCount++
|
roleCount++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -310,7 +321,7 @@ function deletePermission(p) {
|
|||||||
|
|
||||||
if (roleCount === 0) {
|
if (roleCount === 0) {
|
||||||
// No roles have this permission, safe to delete directly
|
// No roles have this permission, safe to delete directly
|
||||||
performPermissionDeletion(p.id)
|
performPermissionDeletion(p.uuid)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
authStore.showMessage(`Permission "${p.display_name}" deleted.`, 'success', 2500)
|
authStore.showMessage(`Permission "${p.display_name}" deleted.`, 'success', 2500)
|
||||||
})
|
})
|
||||||
@@ -326,14 +337,10 @@ function deletePermission(p) {
|
|||||||
const affects = parts.join(', ')
|
const affects = parts.join(', ')
|
||||||
|
|
||||||
openDialog('confirm', { message: `Delete permission "${p.display_name}" (${affects})?`, action: async () => {
|
openDialog('confirm', { message: `Delete permission "${p.display_name}" (${affects})?`, action: async () => {
|
||||||
await performPermissionDeletion(p.id)
|
await performPermissionDeletion(p.uuid)
|
||||||
} })
|
} })
|
||||||
}
|
}
|
||||||
|
|
||||||
function reloadPage() {
|
|
||||||
window.location.reload()
|
|
||||||
}
|
|
||||||
|
|
||||||
const selectedOrg = computed(() => orgs.value.find(o => o.uuid === currentOrgId.value) || null)
|
const selectedOrg = computed(() => orgs.value.find(o => o.uuid === currentOrgId.value) || null)
|
||||||
|
|
||||||
function openOrg(o) {
|
function openOrg(o) {
|
||||||
@@ -353,7 +360,7 @@ const selectedUser = computed(() => {
|
|||||||
for (const o of orgs.value) {
|
for (const o of orgs.value) {
|
||||||
for (const r of o.roles) {
|
for (const r of o.roles) {
|
||||||
const u = r.users.find(x => x.uuid === currentUserId.value)
|
const u = r.users.find(x => x.uuid === currentUserId.value)
|
||||||
if (u) return { ...u, org_uuid: o.uuid, role_display_name: r.display_name }
|
if (u) return { ...u, org: o.uuid, role_display_name: r.display_name }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
@@ -374,14 +381,14 @@ const breadcrumbEntries = computed(() => {
|
|||||||
// Determine organization for user view if selectedOrg not explicitly chosen.
|
// Determine organization for user view if selectedOrg not explicitly chosen.
|
||||||
let orgForUser = null
|
let orgForUser = null
|
||||||
if (selectedUser.value) {
|
if (selectedUser.value) {
|
||||||
orgForUser = orgs.value.find(o => o.uuid === selectedUser.value.org_uuid) || null
|
orgForUser = orgs.value.find(o => o.uuid === selectedUser.value.org) || null
|
||||||
}
|
}
|
||||||
const orgToShow = selectedOrg.value || orgForUser
|
const orgToShow = selectedOrg.value || orgForUser
|
||||||
if (orgToShow) {
|
if (orgToShow) {
|
||||||
entries.push({ label: orgToShow.display_name, href: `#org/${orgToShow.uuid}` })
|
entries.push({ label: orgToShow.display_name, href: `#org/${orgToShow.uuid}` })
|
||||||
}
|
}
|
||||||
if (selectedUser.value) {
|
if (selectedUser.value) {
|
||||||
entries.push({ label: selectedUser.value.display_name || 'User', href: `#user/${selectedUser.value.uuid}` })
|
entries.push({ label: selectedUser.value.display_name, href: `#user/${selectedUser.value.uuid}` })
|
||||||
}
|
}
|
||||||
return entries
|
return entries
|
||||||
})
|
})
|
||||||
@@ -389,7 +396,7 @@ const breadcrumbEntries = computed(() => {
|
|||||||
watch(selectedUser, async (u) => {
|
watch(selectedUser, async (u) => {
|
||||||
if (!u) { userDetail.value = null; return }
|
if (!u) { userDetail.value = null; return }
|
||||||
try {
|
try {
|
||||||
userDetail.value = await apiJson(`/auth/api/admin/orgs/${u.org_uuid}/users/${u.uuid}`)
|
userDetail.value = await apiJson(`/auth/api/admin/orgs/${u.org}/users/${u.uuid}`)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
userDetail.value = { error: e.message }
|
userDetail.value = { error: e.message }
|
||||||
}
|
}
|
||||||
@@ -410,11 +417,11 @@ async function toggleOrgPermission(org, permId, checked) {
|
|||||||
const prev = [...org.permissions]
|
const prev = [...org.permissions]
|
||||||
org.permissions = next
|
org.permissions = next
|
||||||
try {
|
try {
|
||||||
const params = new URLSearchParams({ permission_id: permId })
|
const params = new URLSearchParams({ permission_uuid: permId })
|
||||||
await apiJson(`/auth/api/admin/orgs/${org.uuid}/permission?${params.toString()}`, { method: checked ? 'POST' : 'DELETE' })
|
await apiJson(`/auth/api/admin/orgs/${org.uuid}/permission?${params.toString()}`, { method: checked ? 'POST' : 'DELETE' })
|
||||||
await loadOrgs()
|
await loadOrgs()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
authStore.showMessage(e.message || 'Failed to update organization permission')
|
authStore.showMessage(e.message || 'Failed to update organization permission', 'error')
|
||||||
org.permissions = prev // revert
|
org.permissions = prev // revert
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -525,7 +532,7 @@ async function refreshUserDetail() {
|
|||||||
await loadOrgs()
|
await loadOrgs()
|
||||||
if (selectedUser.value) {
|
if (selectedUser.value) {
|
||||||
try {
|
try {
|
||||||
userDetail.value = await apiJson(`/auth/api/admin/orgs/${selectedUser.value.org_uuid}/users/${selectedUser.value.uuid}`)
|
userDetail.value = await apiJson(`/auth/api/admin/orgs/${selectedUser.value.org}/users/${selectedUser.value.uuid}`)
|
||||||
} catch (e) { authStore.showMessage(e.message || 'Failed to reload user', 'error') }
|
} catch (e) { authStore.showMessage(e.message || 'Failed to reload user', 'error') }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -559,7 +566,7 @@ async function submitDialog() {
|
|||||||
|
|
||||||
// Close dialog immediately, then perform async operation
|
// Close dialog immediately, then perform async operation
|
||||||
closeDialog()
|
closeDialog()
|
||||||
apiJson(`/auth/api/admin/orgs/${org.uuid}`, { method: 'PUT', body: { display_name: name, permissions: org.permissions } })
|
apiJson(`/auth/api/admin/orgs/${org.uuid}`, { method: 'PATCH', body: { display_name: name } })
|
||||||
.then(() => {
|
.then(() => {
|
||||||
authStore.showMessage(`Organization renamed to "${name}".`, 'success', 2500)
|
authStore.showMessage(`Organization renamed to "${name}".`, 'success', 2500)
|
||||||
loadOrgs()
|
loadOrgs()
|
||||||
@@ -587,7 +594,7 @@ async function submitDialog() {
|
|||||||
|
|
||||||
// Close dialog immediately, then perform async operation
|
// Close dialog immediately, then perform async operation
|
||||||
closeDialog()
|
closeDialog()
|
||||||
apiJson(`/auth/api/admin/orgs/${role.org_uuid}/roles/${role.uuid}`, { method: 'PUT', body: { display_name: name, permissions: role.permissions } })
|
apiJson(`/auth/api/admin/orgs/${role.org}/roles/${role.uuid}`, { method: 'PATCH', body: { display_name: name } })
|
||||||
.then(() => {
|
.then(() => {
|
||||||
authStore.showMessage(`Role renamed to "${name}".`, 'success', 2500)
|
authStore.showMessage(`Role renamed to "${name}".`, 'success', 2500)
|
||||||
loadOrgs()
|
loadOrgs()
|
||||||
@@ -615,7 +622,7 @@ async function submitDialog() {
|
|||||||
|
|
||||||
// Close dialog immediately, then perform async operation
|
// Close dialog immediately, then perform async operation
|
||||||
closeDialog()
|
closeDialog()
|
||||||
apiJson(`/auth/api/admin/orgs/${user.org_uuid}/users/${user.uuid}/display-name`, { method: 'PUT', body: { display_name: name } })
|
apiJson(`/auth/api/admin/orgs/${user.org}/users/${user.uuid}/display-name`, { method: 'PATCH', body: { display_name: name } })
|
||||||
.then(() => {
|
.then(() => {
|
||||||
authStore.showMessage(`User renamed to "${name}".`, 'success', 2500)
|
authStore.showMessage(`User renamed to "${name}".`, 'success', 2500)
|
||||||
onUserNameSaved()
|
onUserNameSaved()
|
||||||
@@ -626,28 +633,28 @@ async function submitDialog() {
|
|||||||
return // Don't call closeDialog() again
|
return // Don't call closeDialog() again
|
||||||
} else if (t === 'perm-display') {
|
} else if (t === 'perm-display') {
|
||||||
const { permission } = dialog.value.data
|
const { permission } = dialog.value.data
|
||||||
const newId = dialog.value.data.id?.trim()
|
const newScope = dialog.value.data.scope?.trim()
|
||||||
const newDisplay = dialog.value.data.display_name?.trim()
|
const newDisplay = dialog.value.data.display_name?.trim()
|
||||||
|
const newDomain = dialog.value.data.domain?.trim() || ''
|
||||||
if (!newDisplay) throw new Error('Display name required')
|
if (!newDisplay) throw new Error('Display name required')
|
||||||
if (!newId) throw new Error('ID required')
|
if (!newScope) throw new Error('Scope required')
|
||||||
|
|
||||||
// Close dialog immediately, then perform async operation
|
// Close dialog immediately, then perform async operation
|
||||||
closeDialog()
|
closeDialog()
|
||||||
|
|
||||||
let apiCall;
|
const oldDomain = permission.domain || ''
|
||||||
if (newId !== permission.id) {
|
// Check if anything changed
|
||||||
// ID changed, use rename endpoint
|
if (newScope === permission.scope && newDisplay === permission.display_name && newDomain === oldDomain) {
|
||||||
apiCall = apiJson('/auth/api/admin/permission/rename', { method: 'POST', body: { old_id: permission.id, new_id: newId, display_name: newDisplay } })
|
return // No changes
|
||||||
} else if (newDisplay !== permission.display_name) {
|
|
||||||
// Only display name changed
|
|
||||||
const params = new URLSearchParams({ permission_id: permission.id, display_name: newDisplay })
|
|
||||||
apiCall = apiJson(`/auth/api/admin/permission?${params.toString()}`, { method: 'PUT' })
|
|
||||||
} else {
|
|
||||||
// No changes
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
apiCall
|
// Always use PATCH with permission_uuid
|
||||||
|
const params = new URLSearchParams({ permission_uuid: permission.uuid })
|
||||||
|
if (newScope !== permission.scope) params.set('scope', newScope)
|
||||||
|
if (newDisplay !== permission.display_name) params.set('display_name', newDisplay)
|
||||||
|
if (newDomain !== oldDomain) params.set('domain', newDomain || '')
|
||||||
|
|
||||||
|
apiJson(`/auth/api/admin/permission?${params.toString()}`, { method: 'PATCH' })
|
||||||
.then(() => {
|
.then(() => {
|
||||||
authStore.showMessage(`Permission "${newDisplay}" updated.`, 'success', 2500)
|
authStore.showMessage(`Permission "${newDisplay}" updated.`, 'success', 2500)
|
||||||
loadPermissions()
|
loadPermissions()
|
||||||
@@ -655,13 +662,15 @@ async function submitDialog() {
|
|||||||
.catch(e => {
|
.catch(e => {
|
||||||
authStore.showMessage(e.message || 'Failed to update permission', 'error')
|
authStore.showMessage(e.message || 'Failed to update permission', 'error')
|
||||||
})
|
})
|
||||||
return // Don't call closeDialog() again else if (t === 'perm-create') {
|
return // Don't call closeDialog() again
|
||||||
const id = dialog.value.data.id?.trim(); if (!id) throw new Error('ID required')
|
} else if (t === 'perm-create') {
|
||||||
|
const scope = dialog.value.data.scope?.trim(); if (!scope) throw new Error('Scope required')
|
||||||
const display_name = dialog.value.data.display_name?.trim(); if (!display_name) throw new Error('Display name required')
|
const display_name = dialog.value.data.display_name?.trim(); if (!display_name) throw new Error('Display name required')
|
||||||
|
const domain = dialog.value.data.domain?.trim() || ''
|
||||||
|
|
||||||
// Close dialog immediately, then perform async operation
|
// Close dialog immediately, then perform async operation
|
||||||
closeDialog()
|
closeDialog()
|
||||||
apiJson('/auth/api/admin/permissions', { method: 'POST', body: { id, display_name } })
|
apiJson('/auth/api/admin/permissions', { method: 'POST', body: { scope, display_name, domain: domain || undefined } })
|
||||||
.then(() => {
|
.then(() => {
|
||||||
authStore.showMessage(`Permission "${display_name}" created.`, 'success', 2500)
|
authStore.showMessage(`Permission "${display_name}" created.`, 'success', 2500)
|
||||||
loadPermissions()
|
loadPermissions()
|
||||||
@@ -671,7 +680,17 @@ async function submitDialog() {
|
|||||||
})
|
})
|
||||||
return // Don't call closeDialog() again
|
return // Don't call closeDialog() again
|
||||||
} else if (t === 'confirm') {
|
} else if (t === 'confirm') {
|
||||||
const action = dialog.value.data.action; if (action) await action()
|
const action = dialog.value.data.action
|
||||||
|
// Close dialog first, then perform action (errors shown via showMessage)
|
||||||
|
closeDialog()
|
||||||
|
if (action) {
|
||||||
|
try {
|
||||||
|
await action()
|
||||||
|
} catch (e) {
|
||||||
|
authStore.showMessage(e.message || 'Action failed', 'error')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return // Already closed
|
||||||
}
|
}
|
||||||
closeDialog()
|
closeDialog()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -685,11 +704,19 @@ async function submitDialog() {
|
|||||||
<StatusMessage />
|
<StatusMessage />
|
||||||
<main class="app-main">
|
<main class="app-main">
|
||||||
<LoadingView v-if="loading" :message="loadingMessage" />
|
<LoadingView v-if="loading" :message="loadingMessage" />
|
||||||
<AuthRequiredMessage
|
<AccessDenied v-else-if="showBackMessage" />
|
||||||
v-else-if="showBackMessage"
|
<AccessDenied
|
||||||
@reload="reloadPage"
|
v-else-if="error"
|
||||||
|
icon="⚠️"
|
||||||
|
title="Error"
|
||||||
|
:message="error"
|
||||||
/>
|
/>
|
||||||
<section v-else-if="authenticated && (info?.is_global_admin || info?.is_org_admin)" class="view-root view-root--wide view-admin">
|
<AccessDenied
|
||||||
|
v-else-if="authenticated && !isMasterAdmin && !isOrgAdmin"
|
||||||
|
icon="⛔"
|
||||||
|
message="You do not have admin permissions for this application."
|
||||||
|
/>
|
||||||
|
<section v-else-if="authenticated && (isMasterAdmin || isOrgAdmin)" class="view-root view-root--wide view-admin">
|
||||||
<header class="view-header">
|
<header class="view-header">
|
||||||
<h1>{{ pageHeading }}</h1>
|
<h1>{{ pageHeading }}</h1>
|
||||||
<Breadcrumbs ref="breadcrumbsRef" :entries="breadcrumbEntries" @keydown="handleBreadcrumbKeydown" />
|
<Breadcrumbs ref="breadcrumbsRef" :entries="breadcrumbEntries" @keydown="handleBreadcrumbKeydown" />
|
||||||
@@ -697,10 +724,9 @@ async function submitDialog() {
|
|||||||
|
|
||||||
<section class="section-block admin-section">
|
<section class="section-block admin-section">
|
||||||
<div class="section-body admin-section-body">
|
<div class="section-body admin-section-body">
|
||||||
<div v-if="error" class="surface surface--tight error">{{ error }}</div>
|
<div class="admin-panels">
|
||||||
<div v-else class="admin-panels">
|
|
||||||
<AdminOverview
|
<AdminOverview
|
||||||
v-if="!selectedUser && !selectedOrg && (info.is_global_admin || info.is_org_admin)"
|
v-if="!selectedUser && !selectedOrg && (isMasterAdmin || isOrgAdmin)"
|
||||||
ref="adminOverviewRef"
|
ref="adminOverviewRef"
|
||||||
:info="info"
|
:info="info"
|
||||||
:orgs="orgs"
|
:orgs="orgs"
|
||||||
@@ -763,6 +789,7 @@ async function submitDialog() {
|
|||||||
<AdminDialogs
|
<AdminDialogs
|
||||||
:dialog="dialog"
|
:dialog="dialog"
|
||||||
:permission-id-pattern="PERMISSION_ID_PATTERN"
|
:permission-id-pattern="PERMISSION_ID_PATTERN"
|
||||||
|
:settings="authStore.settings"
|
||||||
@submit-dialog="submitDialog"
|
@submit-dialog="submitDialog"
|
||||||
@close-dialog="closeDialog"
|
@close-dialog="closeDialog"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -71,12 +71,12 @@ const initializing = ref(true)
|
|||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const token = ref('')
|
const token = ref('')
|
||||||
const settings = ref(null)
|
const settings = ref(null)
|
||||||
const userInfo = ref(null)
|
const tokenInfo = ref(null)
|
||||||
const displayName = ref('')
|
const displayName = ref('')
|
||||||
const errorMessage = ref('')
|
const errorMessage = ref('')
|
||||||
let statusTimer = null
|
let statusTimer = null
|
||||||
|
|
||||||
const sessionDescriptor = computed(() => userInfo.value?.session_type || 'your enrollment')
|
const sessionDescriptor = computed(() => tokenInfo.value?.token_type || 'your enrollment')
|
||||||
const subtitleMessage = computed(() => {
|
const subtitleMessage = computed(() => {
|
||||||
if (initializing.value) return 'Preparing your secure enrollment…'
|
if (initializing.value) return 'Preparing your secure enrollment…'
|
||||||
if (!canRegister.value) return 'This authentication link is no longer valid.'
|
if (!canRegister.value) return 'This authentication link is no longer valid.'
|
||||||
@@ -85,7 +85,7 @@ const subtitleMessage = computed(() => {
|
|||||||
|
|
||||||
const basePath = computed(() => uiBasePath())
|
const basePath = computed(() => uiBasePath())
|
||||||
|
|
||||||
const canRegister = computed(() => !!(token.value && userInfo.value))
|
const canRegister = computed(() => !!(token.value && tokenInfo.value))
|
||||||
|
|
||||||
function showMessage(message, type = 'info', duration = 3000) {
|
function showMessage(message, type = 'info', duration = 3000) {
|
||||||
status.show = true
|
status.show = true
|
||||||
@@ -109,15 +109,16 @@ async function fetchSettings() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchUserInfo() {
|
async function fetchTokenInfo() {
|
||||||
if (!token.value) return
|
if (!token.value) return
|
||||||
try {
|
try {
|
||||||
userInfo.value = await apiJson(`/auth/api/user-info?reset=${encodeURIComponent(token.value)}`, {
|
tokenInfo.value = await apiJson('/auth/api/token-info', {
|
||||||
method: 'POST'
|
method: 'GET',
|
||||||
|
headers: { 'Authorization': `Bearer ${token.value}` },
|
||||||
})
|
})
|
||||||
displayName.value = userInfo.value?.user?.user_name || ''
|
displayName.value = tokenInfo.value.display_name
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load user info', error)
|
console.error('Failed to load token info', error)
|
||||||
const message = error instanceof ApiError
|
const message = error instanceof ApiError
|
||||||
? (error.data?.detail || 'The authentication link is invalid or expired.')
|
? (error.data?.detail || 'The authentication link is invalid or expired.')
|
||||||
: getUserFriendlyErrorMessage(error)
|
: getUserFriendlyErrorMessage(error)
|
||||||
@@ -196,7 +197,7 @@ onMounted(async () => {
|
|||||||
initializing.value = false
|
initializing.value = false
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await fetchUserInfo()
|
await fetchTokenInfo()
|
||||||
initializing.value = false
|
initializing.value = false
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -1,15 +1,18 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
|
import { computed } from 'vue'
|
||||||
import Modal from '@/components/Modal.vue'
|
import Modal from '@/components/Modal.vue'
|
||||||
import NameEditForm from '@/components/NameEditForm.vue'
|
import NameEditForm from '@/components/NameEditForm.vue'
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
dialog: Object,
|
dialog: Object,
|
||||||
PERMISSION_ID_PATTERN: String
|
PERMISSION_ID_PATTERN: String,
|
||||||
|
settings: Object
|
||||||
})
|
})
|
||||||
|
|
||||||
const emit = defineEmits(['submitDialog', 'closeDialog'])
|
const emit = defineEmits(['submitDialog', 'closeDialog'])
|
||||||
|
|
||||||
const NAME_EDIT_TYPES = new Set(['org-update', 'role-update', 'user-update-name'])
|
const NAME_EDIT_TYPES = new Set(['org-update', 'role-update', 'user-update-name'])
|
||||||
|
const rpId = computed(() => props.settings?.rp_id || 'the configured domain')
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -21,7 +24,7 @@ const NAME_EDIT_TYPES = new Set(['org-update', 'role-update', 'user-update-name'
|
|||||||
<template v-else-if="dialog.type==='role-update'">Edit Role</template>
|
<template v-else-if="dialog.type==='role-update'">Edit Role</template>
|
||||||
<template v-else-if="dialog.type==='user-create'">Add User To Role</template>
|
<template v-else-if="dialog.type==='user-create'">Add User To Role</template>
|
||||||
<template v-else-if="dialog.type==='user-update-name'">Edit User Name</template>
|
<template v-else-if="dialog.type==='user-update-name'">Edit User Name</template>
|
||||||
<template v-else-if="dialog.type==='perm-create' || dialog.type==='perm-display'">{{ dialog.type === 'perm-create' ? 'Create Permission' : 'Edit Permission Display' }}</template>
|
<template v-else-if="dialog.type==='perm-create' || dialog.type==='perm-display'">{{ dialog.type === 'perm-create' ? 'Create Permission' : 'Edit Permission' }}</template>
|
||||||
<template v-else-if="dialog.type==='confirm'">Confirm</template>
|
<template v-else-if="dialog.type==='confirm'">Confirm</template>
|
||||||
</h3>
|
</h3>
|
||||||
<form @submit.prevent="$emit('submitDialog')" class="modal-form">
|
<form @submit.prevent="$emit('submitDialog')" class="modal-form">
|
||||||
@@ -72,10 +75,14 @@ const NAME_EDIT_TYPES = new Set(['org-update', 'role-update', 'user-update-name'
|
|||||||
<label>Display Name
|
<label>Display Name
|
||||||
<input ref="displayNameInput" v-model="dialog.data.display_name" required />
|
<input ref="displayNameInput" v-model="dialog.data.display_name" required />
|
||||||
</label>
|
</label>
|
||||||
<label>Permission ID
|
<label>Permission Scope
|
||||||
<input v-model="dialog.data.id" :placeholder="dialog.type === 'perm-create' ? 'yourapp:permission' : dialog.data.permission.id" required :pattern="PERMISSION_ID_PATTERN" title="Allowed: A-Za-z0-9:._~-" data-form-type="other" />
|
<input v-model="dialog.data.scope" :placeholder="dialog.type === 'perm-create' ? 'yourapp:permission' : dialog.data.permission.scope" required :pattern="PERMISSION_ID_PATTERN" title="Allowed: A-Za-z0-9:._~-" data-form-type="other" />
|
||||||
</label>
|
</label>
|
||||||
<p class="small muted">The permission ID is used for permission checks in the application. Changing it may break deployed applications that reference this permission.</p>
|
<p class="small muted">E.g. yourapp:reports. Changing the scope name may break deployed applications.</p>
|
||||||
|
<label>Domain Scope
|
||||||
|
<input v-model="dialog.data.domain" placeholder="e.g. app.example.com" data-form-type="other" />
|
||||||
|
</label>
|
||||||
|
<p class="small muted">If set, this permission is effective only on the specified domain, which can be {{ rpId }} or its subdomain.</p>
|
||||||
</template>
|
</template>
|
||||||
<template v-else-if="dialog.type==='confirm'">
|
<template v-else-if="dialog.type==='confirm'">
|
||||||
<p>{{ dialog.data.message }}</p>
|
<p>{{ dialog.data.message }}</p>
|
||||||
@@ -106,4 +113,5 @@ const NAME_EDIT_TYPES = new Set(['org-update', 'role-update', 'user-update-name'
|
|||||||
.error { color: var(--color-danger-text); }
|
.error { color: var(--color-danger-text); }
|
||||||
.small { font-size: 0.9rem; }
|
.small { font-size: 0.9rem; }
|
||||||
.muted { color: var(--color-text-muted); }
|
.muted { color: var(--color-text-muted); }
|
||||||
|
.optional { font-weight: normal; color: var(--color-text-muted); font-size: 0.85em; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -26,8 +26,14 @@ const sortedRoles = computed(() => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
function permissionDisplayName(id) {
|
// Get org's grantable permissions as full permission objects (with UUIDs)
|
||||||
return props.permissions.find(p => p.id === id)?.display_name || id
|
const orgPermissions = computed(() => {
|
||||||
|
const uuidSet = new Set(props.selectedOrg.permissions || [])
|
||||||
|
return props.permissions.filter(p => uuidSet.has(p.uuid))
|
||||||
|
})
|
||||||
|
|
||||||
|
function permissionDisplayName(scope) {
|
||||||
|
return props.permissions.find(p => p.scope === scope)?.display_name || scope
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleRolePermission(role, pid, checked) {
|
function toggleRolePermission(role, pid, checked) {
|
||||||
@@ -302,17 +308,17 @@ defineExpose({ focusFirstElement })
|
|||||||
</div>
|
</div>
|
||||||
<div class="grid-head role-head add-role-head" title="Add role" @click="$emit('createRole', selectedOrg)" role="button" tabindex="0" @keydown.enter="$emit('createRole', selectedOrg)">➕</div>
|
<div class="grid-head role-head add-role-head" title="Add role" @click="$emit('createRole', selectedOrg)" role="button" tabindex="0" @keydown.enter="$emit('createRole', selectedOrg)">➕</div>
|
||||||
|
|
||||||
<template v-for="pid in selectedOrg.permissions" :key="pid">
|
<template v-for="p in orgPermissions" :key="p.uuid">
|
||||||
<div class="perm-name" :title="pid">{{ permissionDisplayName(pid) }}</div>
|
<div class="perm-name" :title="p.scope">{{ p.display_name }}</div>
|
||||||
<div
|
<div
|
||||||
v-for="r in sortedRoles"
|
v-for="r in sortedRoles"
|
||||||
:key="r.uuid + '-' + pid"
|
:key="r.uuid + '-' + p.uuid"
|
||||||
class="matrix-cell"
|
class="matrix-cell"
|
||||||
>
|
>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
:checked="r.permissions.includes(pid)"
|
:checked="r.permissions.includes(p.uuid)"
|
||||||
@change="e => toggleRolePermission(r, pid, e.target.checked)"
|
@change="e => toggleRolePermission(r, p.uuid, e.target.checked)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="matrix-cell add-role-cell" />
|
<div class="matrix-cell add-role-cell" />
|
||||||
|
|||||||
@@ -24,10 +24,14 @@ const sortedOrgs = computed(() => [...props.orgs].sort((a,b)=> {
|
|||||||
const nameCompare = a.display_name.localeCompare(b.display_name)
|
const nameCompare = a.display_name.localeCompare(b.display_name)
|
||||||
return nameCompare !== 0 ? nameCompare : a.uuid.localeCompare(b.uuid)
|
return nameCompare !== 0 ? nameCompare : a.uuid.localeCompare(b.uuid)
|
||||||
}))
|
}))
|
||||||
const sortedPermissions = computed(() => [...props.permissions].sort((a,b)=> a.id.localeCompare(b.id)))
|
const sortedPermissions = computed(() => [...props.permissions].sort((a,b)=> a.scope.localeCompare(b.scope)))
|
||||||
|
|
||||||
function permissionDisplayName(id) {
|
// Derive admin status from permissions (info contains ctx from validate response)
|
||||||
return props.permissions.find(p => p.id === id)?.display_name || id
|
const isMasterAdmin = computed(() => props.info?.ctx.permissions.includes('auth:admin'))
|
||||||
|
const isOrgAdmin = computed(() => props.info?.ctx.permissions.includes('auth:org:admin'))
|
||||||
|
|
||||||
|
function permissionDisplayName(scope) {
|
||||||
|
return props.permissions.find(p => p.scope === scope)?.display_name || scope
|
||||||
}
|
}
|
||||||
|
|
||||||
function getRoleNames(org) {
|
function getRoleNames(org) {
|
||||||
@@ -89,7 +93,7 @@ function handleTableKeydown(event, tableType) {
|
|||||||
} else if (direction === 'down' && currentIndex === rows.length - 1) {
|
} else if (direction === 'down' && currentIndex === rows.length - 1) {
|
||||||
// At bottom of org table, navigate to permissions section
|
// At bottom of org table, navigate to permissions section
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
if (tableType === 'org' && props.info.is_global_admin) {
|
if (tableType === 'org' && isMasterAdmin.value) {
|
||||||
// Navigate to permissions matrix or actions
|
// Navigate to permissions matrix or actions
|
||||||
if (permMatrixRef.value) {
|
if (permMatrixRef.value) {
|
||||||
const firstCheckbox = permMatrixRef.value.querySelector('input[type="checkbox"]')
|
const firstCheckbox = permMatrixRef.value.querySelector('input[type="checkbox"]')
|
||||||
@@ -232,7 +236,7 @@ function handlePermActionsKeydown(event) {
|
|||||||
|
|
||||||
// Focus helper for external navigation
|
// Focus helper for external navigation
|
||||||
function focusFirstElement() {
|
function focusFirstElement() {
|
||||||
if (props.info.is_global_admin) {
|
if (isMasterAdmin.value) {
|
||||||
focusPreferred(orgActionsRef.value, { itemSelector: 'button' })
|
focusPreferred(orgActionsRef.value, { itemSelector: 'button' })
|
||||||
} else {
|
} else {
|
||||||
const firstFocusable = orgTableRef.value?.querySelector('tbody tr a, tbody tr button:not([disabled])')
|
const firstFocusable = orgTableRef.value?.querySelector('tbody tr a, tbody tr button:not([disabled])')
|
||||||
@@ -245,9 +249,9 @@ defineExpose({ focusFirstElement })
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="permissions-section" ref="orgSection">
|
<div class="permissions-section" ref="orgSection">
|
||||||
<h2>{{ info.is_global_admin ? 'Organizations' : 'Your Organizations' }}</h2>
|
<h2>{{ isMasterAdmin ? 'Organizations' : 'Your Organizations' }}</h2>
|
||||||
<div class="actions" ref="orgActionsRef" @keydown="handleOrgActionsKeydown">
|
<div class="actions" ref="orgActionsRef" @keydown="handleOrgActionsKeydown">
|
||||||
<button v-if="info.is_global_admin" @click="$emit('createOrg')">+ Create Org</button>
|
<button v-if="isMasterAdmin" @click="$emit('createOrg')">+ Create Org</button>
|
||||||
</div>
|
</div>
|
||||||
<table class="org-table" ref="orgTableRef" @keydown="e => handleTableKeydown(e, 'org')">
|
<table class="org-table" ref="orgTableRef" @keydown="e => handleTableKeydown(e, 'org')">
|
||||||
<thead>
|
<thead>
|
||||||
@@ -255,18 +259,18 @@ defineExpose({ focusFirstElement })
|
|||||||
<th>Name</th>
|
<th>Name</th>
|
||||||
<th>Roles</th>
|
<th>Roles</th>
|
||||||
<th>Members</th>
|
<th>Members</th>
|
||||||
<th v-if="info.is_global_admin">Actions</th>
|
<th v-if="isMasterAdmin">Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr v-for="o in sortedOrgs" :key="o.uuid">
|
<tr v-for="o in sortedOrgs" :key="o.uuid">
|
||||||
<td>
|
<td>
|
||||||
<a href="#org/{{o.uuid}}" @click.prevent="$emit('openOrg', o)">{{ o.display_name }}</a>
|
<a href="#org/{{o.uuid}}" @click.prevent="$emit('openOrg', o)">{{ o.display_name }}</a>
|
||||||
<button v-if="info.is_global_admin || info.is_org_admin" @click="$emit('updateOrg', o)" class="icon-btn edit-org-btn" aria-label="Rename organization" title="Rename organization">✏️</button>
|
<button v-if="isMasterAdmin || isOrgAdmin" @click="$emit('updateOrg', o)" class="icon-btn edit-org-btn" aria-label="Rename organization" title="Rename organization">✏️</button>
|
||||||
</td>
|
</td>
|
||||||
<td class="role-names">{{ getRoleNames(o) }}</td>
|
<td class="role-names">{{ getRoleNames(o) }}</td>
|
||||||
<td class="center">{{ o.roles.reduce((acc,r)=>acc + r.users.length,0) }}</td>
|
<td class="center">{{ o.roles.reduce((acc,r)=>acc + r.users.length,0) }}</td>
|
||||||
<td v-if="info.is_global_admin" class="center">
|
<td v-if="isMasterAdmin" class="center">
|
||||||
<button @click="$emit('deleteOrg', o)" class="icon-btn delete-icon" aria-label="Delete organization" title="Delete organization">❌</button>
|
<button @click="$emit('deleteOrg', o)" class="icon-btn delete-icon" aria-label="Delete organization" title="Delete organization">❌</button>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -274,7 +278,7 @@ defineExpose({ focusFirstElement })
|
|||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="info.is_global_admin" class="permissions-section">
|
<div v-if="isMasterAdmin" class="permissions-section">
|
||||||
<h2>Permissions</h2>
|
<h2>Permissions</h2>
|
||||||
<div class="matrix-wrapper" ref="permMatrixRef" @keydown="handleMatrixKeydown">
|
<div class="matrix-wrapper" ref="permMatrixRef" @keydown="handleMatrixKeydown">
|
||||||
<div class="matrix-scroll">
|
<div class="matrix-scroll">
|
||||||
@@ -292,19 +296,19 @@ defineExpose({ focusFirstElement })
|
|||||||
<span>{{ o.display_name }}</span>
|
<span>{{ o.display_name }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<template v-for="p in sortedPermissions" :key="p.id">
|
<template v-for="p in sortedPermissions" :key="p.uuid">
|
||||||
<div class="perm-name" :title="p.id">
|
<div class="perm-name" :title="p.scope">
|
||||||
<span class="display-text">{{ p.display_name }}</span>
|
<span class="display-text">{{ p.display_name }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
v-for="o in sortedOrgs"
|
v-for="o in sortedOrgs"
|
||||||
:key="o.uuid + '-' + p.id"
|
:key="o.uuid + '-' + p.uuid"
|
||||||
class="matrix-cell"
|
class="matrix-cell"
|
||||||
>
|
>
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
:checked="o.permissions.includes(p.id)"
|
:checked="o.permissions.includes(p.uuid)"
|
||||||
@change="e => $emit('toggleOrgPermission', o, p.id, e.target.checked)"
|
@change="e => $emit('toggleOrgPermission', o, p.uuid, e.target.checked)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -313,28 +317,30 @@ defineExpose({ focusFirstElement })
|
|||||||
<p class="matrix-hint muted">Toggle which permissions each organization can grant to its members.</p>
|
<p class="matrix-hint muted">Toggle which permissions each organization can grant to its members.</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="actions" ref="permActionsRef" @keydown="handlePermActionsKeydown">
|
<div class="actions" ref="permActionsRef" @keydown="handlePermActionsKeydown">
|
||||||
<button v-if="info.is_global_admin" @click="$emit('openDialog', 'perm-create', { display_name: '', id: '' })">+ Create Permission</button>
|
<button v-if="isMasterAdmin" @click="$emit('openDialog', 'perm-create', { display_name: '', scope: '', domain: '' })">+ Create Permission</button>
|
||||||
</div>
|
</div>
|
||||||
<table class="org-table" ref="permTableRef" @keydown="e => handleTableKeydown(e, 'perm')">
|
<table class="org-table" ref="permTableRef" @keydown="e => handleTableKeydown(e, 'perm')">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th scope="col">Permission</th>
|
<th scope="col">Permission</th>
|
||||||
|
<th scope="col">Domain</th>
|
||||||
<th scope="col" class="center">Members</th>
|
<th scope="col" class="center">Members</th>
|
||||||
<th scope="col" class="center">Actions</th>
|
<th scope="col" class="center">Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<tr v-for="p in sortedPermissions" :key="p.id">
|
<tr v-for="p in sortedPermissions" :key="p.uuid">
|
||||||
<td class="perm-name-cell">
|
<td class="perm-name-cell">
|
||||||
<div class="perm-title">
|
<div class="perm-title">
|
||||||
<span class="display-text">{{ p.display_name }}</span>
|
<span class="display-text">{{ p.display_name }}</span>
|
||||||
<button @click="$emit('renamePermissionDisplay', p)" class="icon-btn edit-display-btn" aria-label="Edit display name" title="Edit display name">✏️</button>
|
<button @click="$emit('renamePermissionDisplay', p)" class="icon-btn edit-display-btn" aria-label="Edit permission" title="Edit permission">✏️</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="perm-id-info">
|
<div class="perm-id-info">
|
||||||
<span class="id-text">{{ p.id }}</span>
|
<span class="id-text">{{ p.scope }}</span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td class="perm-members center">{{ permissionSummary[p.id]?.userCount || 0 }}</td>
|
<td class="perm-domain">{{ p.domain || '—' }}</td>
|
||||||
|
<td class="perm-members center">{{ permissionSummary[p.uuid]?.userCount || 0 }}</td>
|
||||||
<td class="perm-actions center">
|
<td class="perm-actions center">
|
||||||
<button @click="$emit('deletePermission', p)" class="icon-btn delete-icon" aria-label="Delete permission" title="Delete permission">❌</button>
|
<button @click="$emit('deletePermission', p)" class="icon-btn delete-icon" aria-label="Delete permission" title="Delete permission">❌</button>
|
||||||
</td>
|
</td>
|
||||||
@@ -355,7 +361,8 @@ defineExpose({ focusFirstElement })
|
|||||||
.org-table .role-names { max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.org-table .role-names { max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.perm-name-cell { display: flex; flex-direction: column; gap: 0.3rem; }
|
.perm-name-cell { display: flex; flex-direction: column; gap: 0.3rem; }
|
||||||
.perm-title { font-weight: 600; color: var(--color-heading); }
|
.perm-title { font-weight: 600; color: var(--color-heading); }
|
||||||
.perm-id-info { font-size: 0.8rem; color: var(--color-text-muted); }
|
.perm-id-info { font-size: 0.8rem; color: var(--color-text-muted); display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; }
|
||||||
|
.perm-domain { color: var(--color-text-muted); font-size: 0.9rem; }
|
||||||
.icon-btn { background: none; border: none; color: var(--color-text-muted); padding: 0.2rem; border-radius: var(--radius-sm); cursor: pointer; transition: background 0.2s ease, color 0.2s ease; }
|
.icon-btn { background: none; border: none; color: var(--color-text-muted); padding: 0.2rem; border-radius: var(--radius-sm); cursor: pointer; transition: background 0.2s ease, color 0.2s ease; }
|
||||||
.icon-btn:hover { color: var(--color-heading); background: var(--color-surface-muted); }
|
.icon-btn:hover { color: var(--color-heading); background: var(--color-surface-muted); }
|
||||||
.delete-icon { color: var(--color-danger); }
|
.delete-icon { color: var(--color-danger); }
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ function handleEditName() {
|
|||||||
|
|
||||||
async function handleDelete(credential) {
|
async function handleDelete(credential) {
|
||||||
try {
|
try {
|
||||||
const data = await apiJson(`/auth/api/admin/orgs/${props.selectedUser.org_uuid}/users/${props.selectedUser.uuid}/credentials/${credential.credential_uuid}`, { method: 'DELETE' })
|
const data = await apiJson(`/auth/api/admin/orgs/${props.selectedUser.org}/users/${props.selectedUser.uuid}/credentials/${credential.credential}`, { method: 'DELETE' })
|
||||||
if (data.status === 'ok') {
|
if (data.status === 'ok') {
|
||||||
emit('onUserNameSaved') // Reuse to refresh user detail
|
emit('onUserNameSaved') // Reuse to refresh user detail
|
||||||
} else {
|
} else {
|
||||||
@@ -61,7 +61,7 @@ async function handleTerminateSession(session) {
|
|||||||
if (!sessionId) return
|
if (!sessionId) return
|
||||||
terminatingSessions.value = { ...terminatingSessions.value, [sessionId]: true }
|
terminatingSessions.value = { ...terminatingSessions.value, [sessionId]: true }
|
||||||
try {
|
try {
|
||||||
const data = await apiJson(`/auth/api/admin/orgs/${props.selectedUser.org_uuid}/users/${props.selectedUser.uuid}/sessions/${sessionId}`, { method: 'DELETE' })
|
const data = await apiJson(`/auth/api/admin/orgs/${props.selectedUser.org}/users/${props.selectedUser.uuid}/sessions/${sessionId}`, { method: 'DELETE' })
|
||||||
if (data.status === 'ok') {
|
if (data.status === 'ok') {
|
||||||
if (data.current_session_terminated) {
|
if (data.current_session_terminated) {
|
||||||
sessionStorage.clear()
|
sessionStorage.clear()
|
||||||
@@ -183,7 +183,7 @@ defineExpose({ focusFirstElement })
|
|||||||
:loading="loading"
|
:loading="loading"
|
||||||
:org-display-name="userDetail.org.display_name"
|
:org-display-name="userDetail.org.display_name"
|
||||||
:role-name="userDetail.role"
|
:role-name="userDetail.role"
|
||||||
:update-endpoint="`/auth/api/admin/orgs/${selectedUser.org_uuid}/users/${selectedUser.uuid}/display-name`"
|
:update-endpoint="`/auth/api/admin/orgs/${selectedUser.org}/users/${selectedUser.uuid}/display-name`"
|
||||||
@saved="$emit('onUserNameSaved')"
|
@saved="$emit('onUserNameSaved')"
|
||||||
@edit-name="handleEditName"
|
@edit-name="handleEditName"
|
||||||
/>
|
/>
|
||||||
@@ -212,7 +212,7 @@ defineExpose({ focusFirstElement })
|
|||||||
:aaguid-info="userDetail.aaguid_info"
|
:aaguid-info="userDetail.aaguid_info"
|
||||||
:allow-delete="true"
|
:allow-delete="true"
|
||||||
:hovered-credential-uuid="hoveredCredentialUuid"
|
:hovered-credential-uuid="hoveredCredentialUuid"
|
||||||
:hovered-session-credential-uuid="hoveredSession?.credential_uuid"
|
:hovered-session-credential-uuid="hoveredSession?.credential"
|
||||||
:navigation-disabled="hasActiveModal"
|
:navigation-disabled="hasActiveModal"
|
||||||
@delete="handleDelete"
|
@delete="handleDelete"
|
||||||
@credential-hover="hoveredCredentialUuid = $event"
|
@credential-hover="hoveredCredentialUuid = $event"
|
||||||
@@ -238,7 +238,7 @@ defineExpose({ focusFirstElement })
|
|||||||
</div>
|
</div>
|
||||||
<RegistrationLinkModal
|
<RegistrationLinkModal
|
||||||
v-if="showRegModal"
|
v-if="showRegModal"
|
||||||
:endpoint="`/auth/api/admin/orgs/${selectedUser.org_uuid}/users/${selectedUser.uuid}/create-link`"
|
:endpoint="`/auth/api/admin/orgs/${selectedUser.org}/users/${selectedUser.uuid}/create-link`"
|
||||||
:user-name="userDetail?.display_name || selectedUser.display_name"
|
:user-name="userDetail?.display_name || selectedUser.display_name"
|
||||||
@close="$emit('closeRegModal')"
|
@close="$emit('closeRegModal')"
|
||||||
@copied="onLinkCopied"
|
@copied="onLinkCopied"
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="message-container">
|
<div class="message-container">
|
||||||
<div class="message-content">
|
<div class="message-content">
|
||||||
<h2>🔒 Access Denied</h2>
|
<h2>{{ icon }} {{ title }}</h2>
|
||||||
|
<p v-if="message" class="error-detail">{{ message }}</p>
|
||||||
<div class="button-row">
|
<div class="button-row">
|
||||||
<button class="btn-secondary" @click="goBack">Back</button>
|
<button class="btn-secondary" @click="goBack">Back</button>
|
||||||
<button class="btn-primary" @click="$emit('reload')">Reload Page</button>
|
<button class="btn-primary" @click="reload">Reload Page</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -13,7 +14,15 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { goBack } from '@/utils/helpers'
|
import { goBack } from '@/utils/helpers'
|
||||||
|
|
||||||
defineEmits(['reload'])
|
const props = defineProps({
|
||||||
|
title: { type: String, default: 'Access Denied' },
|
||||||
|
icon: { type: String, default: '🔒' },
|
||||||
|
message: { type: String, default: null },
|
||||||
|
})
|
||||||
|
|
||||||
|
function reload() {
|
||||||
|
window.location.reload()
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
@@ -32,10 +41,15 @@ defineEmits(['reload'])
|
|||||||
}
|
}
|
||||||
|
|
||||||
.message-content h2 {
|
.message-content h2 {
|
||||||
margin: 0 0 1.5rem;
|
margin: 0 0 1rem;
|
||||||
color: var(--color-heading);
|
color: var(--color-heading);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.message-content .error-detail {
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
.message-content .button-row {
|
.message-content .button-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 0.75rem;
|
gap: 0.75rem;
|
||||||
|
|||||||
@@ -5,16 +5,16 @@
|
|||||||
<template v-else>
|
<template v-else>
|
||||||
<div
|
<div
|
||||||
v-for="credential in credentials"
|
v-for="credential in credentials"
|
||||||
:key="credential.credential_uuid"
|
:key="credential.credential"
|
||||||
:class="['credential-item', {
|
:class="['credential-item', {
|
||||||
'current-session': credential.is_current_session && !hoveredCredentialUuid && !hoveredSessionCredentialUuid,
|
'current-session': credential.is_current_session && !hoveredCredentialUuid && !hoveredSessionCredentialUuid,
|
||||||
'is-hovered': hoveredCredentialUuid === credential.credential_uuid,
|
'is-hovered': hoveredCredentialUuid === credential.credential,
|
||||||
'is-linked-session': hoveredSessionCredentialUuid === credential.credential_uuid
|
'is-linked-session': hoveredSessionCredentialUuid === credential.credential
|
||||||
}]"
|
}]"
|
||||||
tabindex="-1"
|
tabindex="-1"
|
||||||
@mousedown.prevent
|
@mousedown.prevent
|
||||||
@click.capture="handleCardClick"
|
@click.capture="handleCardClick"
|
||||||
@focusin="handleCredentialFocus(credential.credential_uuid)"
|
@focusin="handleCredentialFocus(credential.credential)"
|
||||||
@focusout="handleCredentialBlur($event)"
|
@focusout="handleCredentialBlur($event)"
|
||||||
@keydown="handleItemKeydown($event, credential)"
|
@keydown="handleItemKeydown($event, credential)"
|
||||||
>
|
>
|
||||||
@@ -33,8 +33,8 @@
|
|||||||
<h4 class="item-title">{{ getCredentialAuthName(credential) }}</h4>
|
<h4 class="item-title">{{ getCredentialAuthName(credential) }}</h4>
|
||||||
<div class="item-actions">
|
<div class="item-actions">
|
||||||
<span v-if="credential.is_current_session && !hoveredCredentialUuid && !hoveredSessionCredentialUuid" class="badge badge-current">Current</span>
|
<span v-if="credential.is_current_session && !hoveredCredentialUuid && !hoveredSessionCredentialUuid" class="badge badge-current">Current</span>
|
||||||
<span v-else-if="hoveredCredentialUuid === credential.credential_uuid" class="badge badge-current">Selected</span>
|
<span v-else-if="hoveredCredentialUuid === credential.credential" class="badge badge-current">Selected</span>
|
||||||
<span v-else-if="hoveredSessionCredentialUuid === credential.credential_uuid" class="badge badge-current">Linked</span>
|
<span v-else-if="hoveredSessionCredentialUuid === credential.credential" class="badge badge-current">Linked</span>
|
||||||
<button
|
<button
|
||||||
v-if="allowDelete"
|
v-if="allowDelete"
|
||||||
@click="$emit('delete', credential)"
|
@click="$emit('delete', credential)"
|
||||||
|
|||||||
@@ -8,11 +8,11 @@
|
|||||||
<section class="section-block" ref="userInfoSection">
|
<section class="section-block" ref="userInfoSection">
|
||||||
<div class="section-body">
|
<div class="section-body">
|
||||||
<UserBasicInfo
|
<UserBasicInfo
|
||||||
v-if="user"
|
v-if="ctx"
|
||||||
:name="user.user_name"
|
:name="ctx.user.display_name"
|
||||||
:visits="user.visits || 0"
|
:visits="authStore.userInfo?.visits || 0"
|
||||||
:created-at="user.created_at"
|
:created-at="authStore.userInfo?.created_at"
|
||||||
:last-seen="user.last_seen"
|
:last-seen="authStore.userInfo?.last_seen"
|
||||||
:org-display-name="orgDisplayName"
|
:org-display-name="orgDisplayName"
|
||||||
:role-name="roleDisplayName"
|
:role-name="roleDisplayName"
|
||||||
:can-edit="false"
|
:can-edit="false"
|
||||||
@@ -78,9 +78,9 @@ const currentHost = window.location.host
|
|||||||
const userInfoSection = ref(null)
|
const userInfoSection = ref(null)
|
||||||
const buttonRow = ref(null)
|
const buttonRow = ref(null)
|
||||||
|
|
||||||
const user = computed(() => authStore.userInfo?.user || null)
|
const ctx = computed(() => authStore.userInfo?.ctx || null)
|
||||||
const orgDisplayName = computed(() => authStore.userInfo?.org?.display_name || '')
|
const orgDisplayName = computed(() => ctx.value?.org.display_name ?? '')
|
||||||
const roleDisplayName = computed(() => authStore.userInfo?.role?.display_name || '')
|
const roleDisplayName = computed(() => ctx.value?.role.display_name ?? '')
|
||||||
|
|
||||||
const headingTitle = computed(() => {
|
const headingTitle = computed(() => {
|
||||||
const service = authStore.settings?.rp_name
|
const service = authStore.settings?.rp_name
|
||||||
|
|||||||
@@ -8,12 +8,12 @@
|
|||||||
|
|
||||||
<section class="section-block" ref="userInfoSection">
|
<section class="section-block" ref="userInfoSection">
|
||||||
<UserBasicInfo
|
<UserBasicInfo
|
||||||
v-if="authStore.userInfo?.user"
|
v-if="authStore.userInfo?.ctx"
|
||||||
ref="userBasicInfo"
|
ref="userBasicInfo"
|
||||||
:name="authStore.userInfo.user.user_name"
|
:name="authStore.userInfo.ctx.user.display_name"
|
||||||
:visits="authStore.userInfo.user.visits || 0"
|
:visits="authStore.userInfo.visits"
|
||||||
:created-at="authStore.userInfo.user.created_at"
|
:created-at="authStore.userInfo.created_at"
|
||||||
:last-seen="authStore.userInfo.user.last_seen"
|
:last-seen="authStore.userInfo.last_seen"
|
||||||
:loading="authStore.isLoading"
|
:loading="authStore.isLoading"
|
||||||
update-endpoint="/auth/api/user/display-name"
|
update-endpoint="/auth/api/user/display-name"
|
||||||
@saved="authStore.loadUserInfo()"
|
@saved="authStore.loadUserInfo()"
|
||||||
@@ -47,7 +47,7 @@
|
|||||||
:aaguid-info="authStore.userInfo?.aaguid_info || {}"
|
:aaguid-info="authStore.userInfo?.aaguid_info || {}"
|
||||||
:loading="authStore.isLoading"
|
:loading="authStore.isLoading"
|
||||||
:hovered-credential-uuid="hoveredCredentialUuid"
|
:hovered-credential-uuid="hoveredCredentialUuid"
|
||||||
:hovered-session-credential-uuid="hoveredSession?.credential_uuid"
|
:hovered-session-credential-uuid="hoveredSession?.credential"
|
||||||
:navigation-disabled="hasActiveModal"
|
:navigation-disabled="hasActiveModal"
|
||||||
allow-delete
|
allow-delete
|
||||||
@delete="handleDelete"
|
@delete="handleDelete"
|
||||||
@@ -151,7 +151,7 @@ const userInfoSection = ref(null)
|
|||||||
// Check if any modal/dialog is open (blocks arrow key navigation)
|
// Check if any modal/dialog is open (blocks arrow key navigation)
|
||||||
const hasActiveModal = computed(() => showNameDialog.value || showRegLink.value)
|
const hasActiveModal = computed(() => showNameDialog.value || showRegLink.value)
|
||||||
|
|
||||||
watch(showNameDialog, (newVal) => { if (newVal) newName.value = authStore.userInfo?.user?.user_name || '' })
|
watch(showNameDialog, (newVal) => { if (newVal) newName.value = authStore.userInfo?.ctx.user.display_name ?? '' })
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
updateInterval.value = setInterval(() => { if (authStore.userInfo) authStore.userInfo = { ...authStore.userInfo } }, 60000)
|
updateInterval.value = setInterval(() => { if (authStore.userInfo) authStore.userInfo = { ...authStore.userInfo } }, 60000)
|
||||||
@@ -292,7 +292,7 @@ const handleLogoutButtonKeydown = (event) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleDelete = async (credential) => {
|
const handleDelete = async (credential) => {
|
||||||
const credentialId = credential?.credential_uuid
|
const credentialId = credential?.credential
|
||||||
if (!credentialId) return
|
if (!credentialId) return
|
||||||
try {
|
try {
|
||||||
await authStore.deleteCredential(credentialId)
|
await authStore.deleteCredential(credentialId)
|
||||||
@@ -323,8 +323,11 @@ const terminateSession = async (session) => {
|
|||||||
|
|
||||||
const logoutEverywhere = async () => { await authStore.logoutEverywhere() }
|
const logoutEverywhere = async () => { await authStore.logoutEverywhere() }
|
||||||
const logout = async () => { await authStore.logout() }
|
const logout = async () => { await authStore.logout() }
|
||||||
const openNameDialog = () => { newName.value = authStore.userInfo?.user?.user_name || ''; showNameDialog.value = true }
|
const openNameDialog = () => { newName.value = authStore.userInfo?.ctx.user.display_name ?? ''; showNameDialog.value = true }
|
||||||
const isAdmin = computed(() => !!(authStore.userInfo?.is_global_admin || authStore.userInfo?.is_org_admin))
|
const isAdmin = computed(() => {
|
||||||
|
const perms = authStore.userInfo?.ctx.permissions
|
||||||
|
return perms.includes('auth:admin') || perms.includes('auth:org:admin')
|
||||||
|
})
|
||||||
const hasMultipleSessions = computed(() => sessions.value.length > 1)
|
const hasMultipleSessions = computed(() => sessions.value.length > 1)
|
||||||
const breadcrumbEntries = computed(() => { const entries = [{ label: 'Auth', href: makeUiHref() }]; if (isAdmin.value) entries.push({ label: 'Admin', href: adminUiPath() }); return entries })
|
const breadcrumbEntries = computed(() => { const entries = [{ label: 'Auth', href: makeUiHref() }]; if (isAdmin.value) entries.push({ label: 'Admin', href: adminUiPath() }); return entries })
|
||||||
|
|
||||||
@@ -333,7 +336,7 @@ const saveName = async () => {
|
|||||||
if (!name) { authStore.showMessage('Name cannot be empty', 'error'); return }
|
if (!name) { authStore.showMessage('Name cannot be empty', 'error'); return }
|
||||||
try {
|
try {
|
||||||
saving.value = true
|
saving.value = true
|
||||||
await apiJson('/auth/api/user/display-name', { method: 'PUT', body: { display_name: name } })
|
await apiJson('/auth/api/user/display-name', { method: 'PATCH', body: { display_name: name } })
|
||||||
showNameDialog.value = false
|
showNameDialog.value = false
|
||||||
await authStore.loadUserInfo()
|
await authStore.loadUserInfo()
|
||||||
authStore.showMessage('Name updated successfully!', 'success', 3000)
|
authStore.showMessage('Name updated successfully!', 'success', 3000)
|
||||||
|
|||||||
@@ -76,13 +76,13 @@ const status = reactive({ show: false, message: '', type: 'info' })
|
|||||||
const initializing = ref(true)
|
const initializing = ref(true)
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const settings = ref(null)
|
const settings = ref(null)
|
||||||
const userInfo = ref(null)
|
const session = ref(null)
|
||||||
const currentView = ref('initial') // 'initial', 'login', 'forbidden'
|
const currentView = ref('initial') // 'initial', 'login', 'forbidden'
|
||||||
const authView = ref('local') // 'local' or 'remote'
|
const authView = ref('local') // 'local' or 'remote'
|
||||||
const buttonRow = ref(null)
|
const buttonRow = ref(null)
|
||||||
let statusTimer = null
|
let statusTimer = null
|
||||||
|
|
||||||
const isAuthenticated = computed(() => !!userInfo.value?.authenticated)
|
const isAuthenticated = computed(() => !!session.value)
|
||||||
|
|
||||||
const canAuthenticate = computed(() => {
|
const canAuthenticate = computed(() => {
|
||||||
if (initializing.value) return false
|
if (initializing.value) return false
|
||||||
@@ -115,7 +115,7 @@ const headerMessage = computed(() => {
|
|||||||
return 'Please sign in with your passkey.'
|
return 'Please sign in with your passkey.'
|
||||||
})
|
})
|
||||||
|
|
||||||
const userDisplayName = computed(() => userInfo.value?.user?.user_name || 'User')
|
const userDisplayName = computed(() => session.value?.ctx.user.display_name || 'User')
|
||||||
|
|
||||||
function showMessage(message, type = 'info', duration = 3000) {
|
function showMessage(message, type = 'info', duration = 3000) {
|
||||||
status.show = true
|
status.show = true
|
||||||
@@ -140,22 +140,21 @@ async function fetchSettings() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchUserInfo() {
|
async function validateSession() {
|
||||||
try {
|
try {
|
||||||
userInfo.value = await fetchJson('/auth/api/user-info', { method: 'POST' })
|
session.value = await fetchJson('/auth/api/validate', { method: 'POST' })
|
||||||
if (isAuthenticated.value && props.mode !== 'reauth') {
|
if (isAuthenticated.value && props.mode !== 'reauth') {
|
||||||
currentView.value = 'forbidden'
|
currentView.value = 'forbidden'
|
||||||
emit('forbidden', userInfo.value)
|
emit('forbidden', session.value)
|
||||||
} else {
|
} else {
|
||||||
currentView.value = 'login'
|
currentView.value = 'login'
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load user info', error)
|
session.value = null
|
||||||
|
currentView.value = 'login'
|
||||||
if (error.status !== 401 && error.status !== 403) {
|
if (error.status !== 401 && error.status !== 403) {
|
||||||
showMessage(getUserFriendlyErrorMessage(error), 'error', 4000)
|
showMessage(getUserFriendlyErrorMessage(error), 'error', 4000)
|
||||||
}
|
}
|
||||||
userInfo.value = null
|
|
||||||
currentView.value = 'login'
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,7 +187,7 @@ async function logoutUser() {
|
|||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
await fetchJson('/auth/api/logout', { method: 'POST' })
|
await fetchJson('/auth/api/logout', { method: 'POST' })
|
||||||
userInfo.value = null
|
session.value = null
|
||||||
currentView.value = 'login'
|
currentView.value = 'login'
|
||||||
showMessage('Logged out. You can sign in with a different account.', 'info', 3000)
|
showMessage('Logged out. You can sign in with a different account.', 'info', 3000)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -266,7 +265,7 @@ watch(initializing, (newVal) => {
|
|||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await fetchSettings()
|
await fetchSettings()
|
||||||
await fetchUserInfo()
|
await validateSession()
|
||||||
initializing.value = false
|
initializing.value = false
|
||||||
|
|
||||||
// Add click handler for inline links
|
// Add click handler for inline links
|
||||||
@@ -280,7 +279,7 @@ onUnmounted(() => {
|
|||||||
defineExpose({
|
defineExpose({
|
||||||
showMessage,
|
showMessage,
|
||||||
isAuthenticated,
|
isAuthenticated,
|
||||||
userInfo
|
session
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,7 @@
|
|||||||
:class="['session-item', {
|
:class="['session-item', {
|
||||||
'is-current': session.is_current && !hoveredIp && !hoveredCredentialUuid,
|
'is-current': session.is_current && !hoveredIp && !hoveredCredentialUuid,
|
||||||
'is-hovered': hoveredSession?.id === session.id,
|
'is-hovered': hoveredSession?.id === session.id,
|
||||||
'is-linked-credential': hoveredCredentialUuid === session.credential_uuid
|
'is-linked-credential': hoveredCredentialUuid === session.credential
|
||||||
}]"
|
}]"
|
||||||
tabindex="-1"
|
tabindex="-1"
|
||||||
@mousedown.prevent
|
@mousedown.prevent
|
||||||
@@ -34,7 +34,7 @@
|
|||||||
<div class="item-actions">
|
<div class="item-actions">
|
||||||
<span v-if="session.is_current && !hoveredIp && !hoveredCredentialUuid" class="badge badge-current">Current</span>
|
<span v-if="session.is_current && !hoveredIp && !hoveredCredentialUuid" class="badge badge-current">Current</span>
|
||||||
<span v-else-if="hoveredSession?.id === session.id" class="badge badge-current">Selected</span>
|
<span v-else-if="hoveredSession?.id === session.id" class="badge badge-current">Selected</span>
|
||||||
<span v-else-if="hoveredCredentialUuid === session.credential_uuid" class="badge badge-current">Linked</span>
|
<span v-else-if="hoveredCredentialUuid === session.credential" class="badge badge-current">Linked</span>
|
||||||
<span v-else-if="!hoveredCredentialUuid && isSameHost(session.ip)" class="badge">Same IP</span>
|
<span v-else-if="!hoveredCredentialUuid && isSameHost(session.ip)" class="badge">Same IP</span>
|
||||||
<button
|
<button
|
||||||
@click="$emit('terminate', session)"
|
@click="$emit('terminate', session)"
|
||||||
|
|||||||
@@ -26,16 +26,18 @@ export const useAuthStore = defineStore('auth', {
|
|||||||
setLoading(flag) {
|
setLoading(flag) {
|
||||||
this.isLoading = !!flag
|
this.isLoading = !!flag
|
||||||
},
|
},
|
||||||
showMessage(message, type = 'info', duration = 3000) {
|
showMessage(message, type = 'info', duration = null) {
|
||||||
|
// Default duration: 5 seconds for errors, 3 seconds for others
|
||||||
|
const effectiveDuration = duration ?? (type === 'error' ? 5000 : 3000)
|
||||||
this.status = {
|
this.status = {
|
||||||
message,
|
message,
|
||||||
type,
|
type,
|
||||||
show: true
|
show: true
|
||||||
}
|
}
|
||||||
if (duration > 0) {
|
if (effectiveDuration > 0) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.status.show = false
|
this.status.show = false
|
||||||
}, duration)
|
}, effectiveDuration)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
async setSessionCookie(result) {
|
async setSessionCookie(result) {
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ export async function getAuthIframeUrl(mode = 'login') {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fetch from forward endpoint - it returns URL in auth.iframe on 401/403
|
// Fetch from forward endpoint - it returns URL in auth.iframe on 401/403
|
||||||
const response = await fetch('/auth/api/forward', { credentials: 'include' })
|
const response = await fetch('/auth/api/forward')
|
||||||
if (response.status === 401 || response.status === 403) {
|
if (response.status === 401 || response.status === 403) {
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
if (data.auth?.iframe) {
|
if (data.auth?.iframe) {
|
||||||
@@ -321,7 +321,6 @@ export async function apiJson(url, options = {}) {
|
|||||||
*/
|
*/
|
||||||
export async function fetchJson(url, options = {}) {
|
export async function fetchJson(url, options = {}) {
|
||||||
const fetchOptions = {
|
const fetchOptions = {
|
||||||
credentials: 'include',
|
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
'Accept': 'application/json',
|
'Accept': 'application/json',
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/**
|
||||||
|
* FastAPI-Vue Vite Plugin
|
||||||
|
*
|
||||||
|
* Configures Vite for FastAPI backend integration:
|
||||||
|
* - Proxies /api/* requests to the FastAPI backend
|
||||||
|
* - Builds to the Python module's frontend-build directory
|
||||||
|
*
|
||||||
|
* Environment variables (with defaults):
|
||||||
|
* FASTAPI_VUE_BACKEND_URL=http://localhost:5180 - Backend API URL for proxying
|
||||||
|
*/
|
||||||
|
|
||||||
|
const backendUrl = process.env.FASTAPI_VUE_BACKEND_URL || "http://localhost:5180"
|
||||||
|
|
||||||
|
export default function fastapiVue({ paths = ["/api"] } = {}) {
|
||||||
|
// Build proxy configuration for each path
|
||||||
|
const proxy = {}
|
||||||
|
for (const path of paths) {
|
||||||
|
proxy[path] = {
|
||||||
|
target: backendUrl,
|
||||||
|
changeOrigin: false,
|
||||||
|
ws: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: "fastapi-vite",
|
||||||
|
config: () => ({
|
||||||
|
server: { proxy },
|
||||||
|
build: {
|
||||||
|
outDir: "../paskia/frontend-build",
|
||||||
|
emptyOutDir: true,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-18
@@ -4,6 +4,7 @@ import { resolve } from 'node:path'
|
|||||||
import vue from '@vitejs/plugin-vue'
|
import vue from '@vitejs/plugin-vue'
|
||||||
import { existsSync, renameSync, mkdirSync } from 'node:fs'
|
import { existsSync, renameSync, mkdirSync } from 'node:fs'
|
||||||
import sirv from 'sirv'
|
import sirv from 'sirv'
|
||||||
|
import fastapiVue from './vite-plugin-fastapi.js'
|
||||||
|
|
||||||
// Auth host mode: when set, clients accessing the auth host get /auth/ at / and /auth/admin/ at /admin/
|
// Auth host mode: when set, clients accessing the auth host get /auth/ at / and /auth/admin/ at /admin/
|
||||||
const authHost = process.env.PASKIA_AUTH_HOST
|
const authHost = process.env.PASKIA_AUTH_HOST
|
||||||
@@ -12,6 +13,14 @@ export default defineConfig(({ command }) => ({
|
|||||||
appType: 'mpa',
|
appType: 'mpa',
|
||||||
publicDir: 'public',
|
publicDir: 'public',
|
||||||
plugins: [
|
plugins: [
|
||||||
|
fastapiVue({ paths: [
|
||||||
|
"/auth/api",
|
||||||
|
"/auth/ws",
|
||||||
|
// Passphrase links: /auth/word1.word2.word3.word4.word5
|
||||||
|
"^/auth/[a-z]+\\.[a-z]+\\.[a-z]+\\.[a-z]+\\.[a-z]+$",
|
||||||
|
// Passphrase links: /word1.word2.word3.word4.word5
|
||||||
|
"^/[a-z]+\\.[a-z]+\\.[a-z]+\\.[a-z]+\\.[a-z]+$",
|
||||||
|
] }),
|
||||||
vue(),
|
vue(),
|
||||||
// Auth host routing: rewrite paths when accessing dedicated auth host
|
// Auth host routing: rewrite paths when accessing dedicated auth host
|
||||||
// Must run before serve-examples to handle / correctly
|
// Must run before serve-examples to handle / correctly
|
||||||
@@ -89,24 +98,6 @@ export default defineConfig(({ command }) => ({
|
|||||||
allowedHosts: true,
|
allowedHosts: true,
|
||||||
fs: {
|
fs: {
|
||||||
allow: ['..']
|
allow: ['..']
|
||||||
},
|
|
||||||
proxy: {
|
|
||||||
// Only proxy these two specific backend API paths
|
|
||||||
'/auth/api': {
|
|
||||||
target: 'http://localhost:4402'
|
|
||||||
},
|
|
||||||
'/auth/ws': {
|
|
||||||
target: 'http://localhost:4402',
|
|
||||||
ws: true
|
|
||||||
},
|
|
||||||
// Passphrase links: /auth/word1.word2.word3.word4.word5
|
|
||||||
'^/auth/[a-z]+\\.[a-z]+\\.[a-z]+\\.[a-z]+\\.[a-z]+$': {
|
|
||||||
target: 'http://localhost:4402'
|
|
||||||
},
|
|
||||||
// Passphrase links: /word1.word2.word3.word4.word5
|
|
||||||
'^/[a-z]+\\.[a-z]+\\.[a-z]+\\.[a-z]+\\.[a-z]+$': {
|
|
||||||
target: 'http://localhost:4402'
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
build: {
|
build: {
|
||||||
|
|||||||
+20
-70
@@ -9,13 +9,15 @@ independent of any web framework:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from paskia.config import SESSION_LIFETIME
|
from paskia import db
|
||||||
from paskia.db import ResetToken, Session
|
from paskia.config import RESET_LIFETIME, SESSION_LIFETIME
|
||||||
from paskia.globals import db, passkey
|
|
||||||
from paskia.util import hostutil
|
from paskia.util import hostutil
|
||||||
from paskia.util.tokens import create_token, reset_key, session_key
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from paskia.db import ResetToken
|
||||||
|
|
||||||
EXPIRES = SESSION_LIFETIME
|
EXPIRES = SESSION_LIFETIME
|
||||||
|
|
||||||
@@ -25,88 +27,36 @@ def expires() -> datetime:
|
|||||||
|
|
||||||
|
|
||||||
def reset_expires() -> datetime:
|
def reset_expires() -> datetime:
|
||||||
from .config import RESET_LIFETIME
|
|
||||||
|
|
||||||
return datetime.now(timezone.utc) + RESET_LIFETIME
|
return datetime.now(timezone.utc) + RESET_LIFETIME
|
||||||
|
|
||||||
|
|
||||||
def session_expiry(session: Session) -> datetime:
|
def get_reset(token: str) -> "ResetToken":
|
||||||
"""Calculate the expiration timestamp for a session (UTC aware)."""
|
"""Validate a credential reset token."""
|
||||||
# After migration all renewed timestamps are timezone-aware UTC
|
|
||||||
return session.renewed + EXPIRES
|
|
||||||
|
|
||||||
|
record = db.get_reset_token(token)
|
||||||
async def create_session(
|
if record:
|
||||||
user_uuid: UUID,
|
|
||||||
credential_uuid: UUID,
|
|
||||||
*,
|
|
||||||
host: str,
|
|
||||||
ip: str,
|
|
||||||
user_agent: str,
|
|
||||||
) -> str:
|
|
||||||
"""Create a new session and return a session token."""
|
|
||||||
normalized_host = hostutil.normalize_host(host)
|
|
||||||
if not normalized_host:
|
|
||||||
raise ValueError("Host required for session creation")
|
|
||||||
hostname = normalized_host.split(":")[0] # Domain names only, IPs aren't supported
|
|
||||||
rp_id = passkey.instance.rp_id
|
|
||||||
if not (hostname == rp_id or hostname.endswith(f".{rp_id}")):
|
|
||||||
raise ValueError(f"Host must be the same as or a subdomain of {rp_id}")
|
|
||||||
token = create_token()
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
await db.instance.create_session(
|
|
||||||
user_uuid=user_uuid,
|
|
||||||
credential_uuid=credential_uuid,
|
|
||||||
key=session_key(token),
|
|
||||||
host=normalized_host,
|
|
||||||
ip=ip,
|
|
||||||
user_agent=user_agent,
|
|
||||||
renewed=now,
|
|
||||||
)
|
|
||||||
return token
|
|
||||||
|
|
||||||
|
|
||||||
async def get_reset(token: str) -> ResetToken:
|
|
||||||
"""Validate a credential reset token. Returns None if the token is not well formed (i.e. it is another type of token)."""
|
|
||||||
record = await db.instance.get_reset_token(reset_key(token))
|
|
||||||
if record and record.expiry >= datetime.now(timezone.utc):
|
|
||||||
return record
|
return record
|
||||||
raise ValueError("This authentication link is no longer valid.")
|
raise ValueError("This authentication link is no longer valid.")
|
||||||
|
|
||||||
|
|
||||||
async def get_session(token: str, host: str | None = None) -> Session:
|
def refresh_session_token(token: str, *, ip: str, user_agent: str):
|
||||||
"""Validate a session token and return session data if valid."""
|
|
||||||
host = hostutil.normalize_host(host)
|
|
||||||
if not host:
|
|
||||||
raise ValueError("Invalid host")
|
|
||||||
session = await db.instance.get_session(session_key(token))
|
|
||||||
if session and session_expiry(session) >= datetime.now(timezone.utc):
|
|
||||||
if session.host is None:
|
|
||||||
# First time binding: store exact host:port (or IPv6 form) now.
|
|
||||||
await db.instance.set_session_host(session.key, host)
|
|
||||||
session.host = host
|
|
||||||
elif session.host != host:
|
|
||||||
raise ValueError("Session host mismatch")
|
|
||||||
return session
|
|
||||||
raise ValueError("Your session has expired. Please sign in again!")
|
|
||||||
|
|
||||||
|
|
||||||
async def refresh_session_token(token: str, *, ip: str, user_agent: str):
|
|
||||||
"""Refresh a session extending its expiry."""
|
"""Refresh a session extending its expiry."""
|
||||||
session_record = await db.instance.get_session(session_key(token))
|
session_record = db.data().sessions.get(token)
|
||||||
if not session_record:
|
if not session_record:
|
||||||
raise ValueError("Session not found or expired")
|
raise ValueError("Session not found or expired")
|
||||||
updated = await db.instance.update_session(
|
updated = db.update_session(
|
||||||
session_key(token),
|
token,
|
||||||
ip=ip,
|
ip=ip,
|
||||||
user_agent=user_agent,
|
user_agent=user_agent,
|
||||||
renewed=datetime.now(timezone.utc),
|
expiry=expires(),
|
||||||
)
|
)
|
||||||
if not updated:
|
if not updated:
|
||||||
raise ValueError("Session not found or expired")
|
raise ValueError("Session not found or expired")
|
||||||
|
|
||||||
|
|
||||||
async def delete_credential(credential_uuid: UUID, auth: str, host: str | None = None):
|
def delete_credential(credential_uuid: UUID, auth: str, host: str | None = None):
|
||||||
"""Delete a specific credential for the current user."""
|
"""Delete a specific credential for the current user."""
|
||||||
s = await get_session(auth, host=host)
|
ctx = db.get_session_context(auth, hostutil.normalize_host(host))
|
||||||
await db.instance.delete_credential(credential_uuid, s.user_uuid)
|
if not ctx:
|
||||||
|
raise ValueError("Session expired")
|
||||||
|
db.delete_credential(credential_uuid, ctx.user.uuid)
|
||||||
|
|||||||
+28
-95
@@ -8,26 +8,11 @@ generating a reset link for initial admin setup.
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
import uuid7
|
from paskia import authsession, db, globals
|
||||||
|
from paskia.util import hostutil, passphrase
|
||||||
|
|
||||||
from paskia import authsession, globals
|
|
||||||
from paskia.db import Org, Permission, Role, User
|
|
||||||
from paskia.util import hostutil, passphrase, tokens
|
|
||||||
|
|
||||||
|
|
||||||
def _init_logger() -> logging.Logger:
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
if not logger.handlers and not logging.getLogger().handlers:
|
|
||||||
h = logging.StreamHandler()
|
|
||||||
h.setFormatter(logging.Formatter("%(message)s"))
|
|
||||||
logger.addHandler(h)
|
|
||||||
logger.setLevel(logging.INFO)
|
|
||||||
return logger
|
|
||||||
|
|
||||||
|
|
||||||
logger = _init_logger()
|
|
||||||
|
|
||||||
# Shared log message template for admin reset links
|
# Shared log message template for admin reset links
|
||||||
ADMIN_RESET_MESSAGE = """\
|
ADMIN_RESET_MESSAGE = """\
|
||||||
@@ -38,73 +23,25 @@ ADMIN_RESET_MESSAGE = """\
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
async def _create_and_log_admin_reset_link(user_uuid, message, session_type) -> str:
|
def _log_reset_link(message: str, passphrase: str) -> str:
|
||||||
"""Create an admin reset link and log it with the provided message."""
|
"""Log a reset link message and return the URL."""
|
||||||
token = passphrase.generate()
|
reset_link = hostutil.reset_link_url(passphrase)
|
||||||
expiry = authsession.reset_expires()
|
|
||||||
await globals.db.instance.create_reset_token(
|
|
||||||
user_uuid=user_uuid,
|
|
||||||
key=tokens.reset_key(token),
|
|
||||||
expiry=expiry,
|
|
||||||
token_type=session_type,
|
|
||||||
)
|
|
||||||
reset_link = hostutil.reset_link_url(token)
|
|
||||||
logger.info(ADMIN_RESET_MESSAGE, message, reset_link)
|
logger.info(ADMIN_RESET_MESSAGE, message, reset_link)
|
||||||
return reset_link
|
return reset_link
|
||||||
|
|
||||||
|
|
||||||
async def bootstrap_system() -> dict:
|
async def bootstrap_system() -> None:
|
||||||
"""
|
"""
|
||||||
Bootstrap the entire system with default data.
|
Bootstrap the entire system with default data.
|
||||||
|
|
||||||
Returns:
|
Uses db.bootstrap() which performs all operations in a single transaction.
|
||||||
dict: Contains information about created entities and reset link
|
The transaction log will show a single "bootstrap" action with all changes.
|
||||||
"""
|
"""
|
||||||
# Create permission first - will fail if already exists
|
# Call the single-transaction bootstrap function
|
||||||
perm0 = Permission(id="auth:admin", display_name="Master Admin")
|
reset_passphrase = db.bootstrap()
|
||||||
await globals.db.instance.create_permission(perm0)
|
|
||||||
|
|
||||||
org = Org(uuid7.create(), "Organization")
|
# Log the reset link (this is separate from the transaction log)
|
||||||
await globals.db.instance.create_organization(org)
|
_log_reset_link("✅ Bootstrap completed!", reset_passphrase)
|
||||||
|
|
||||||
# After creation, org.permissions now includes the auto-created org admin permission
|
|
||||||
# Allow this org to grant global admin explicitly
|
|
||||||
await globals.db.instance.add_permission_to_organization(str(org.uuid), perm0.id)
|
|
||||||
|
|
||||||
# Create an Administration role granting both org and global admin
|
|
||||||
# Compose permissions for Administration role: global admin + org admin auto-perm
|
|
||||||
role = Role(
|
|
||||||
uuid7.create(),
|
|
||||||
org.uuid,
|
|
||||||
"Administration",
|
|
||||||
permissions=[perm0.id, *org.permissions],
|
|
||||||
)
|
|
||||||
await globals.db.instance.create_role(role)
|
|
||||||
|
|
||||||
user = User(
|
|
||||||
uuid=uuid7.create(),
|
|
||||||
display_name="Admin",
|
|
||||||
role_uuid=role.uuid,
|
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
visits=0,
|
|
||||||
)
|
|
||||||
await globals.db.instance.create_user(user)
|
|
||||||
|
|
||||||
# Generate reset link and log it
|
|
||||||
reset_link = await _create_and_log_admin_reset_link(
|
|
||||||
user.uuid, "✅ Bootstrap completed!", "admin bootstrap"
|
|
||||||
)
|
|
||||||
|
|
||||||
return {
|
|
||||||
"user": user,
|
|
||||||
"org": org,
|
|
||||||
"role": role,
|
|
||||||
"permissions": [
|
|
||||||
perm0,
|
|
||||||
*[Permission(id=p, display_name="") for p in org.permissions],
|
|
||||||
],
|
|
||||||
"reset_link": reset_link,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def check_admin_credentials() -> bool:
|
async def check_admin_credentials() -> bool:
|
||||||
@@ -116,17 +53,15 @@ async def check_admin_credentials() -> bool:
|
|||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# Get permission organizations to find admin users
|
# Get permission organizations to find admin users
|
||||||
permission_orgs = await globals.db.instance.get_permission_organizations(
|
p = next(
|
||||||
"auth:admin"
|
(p for p in db.data().permissions.values() if p.scope == "auth:admin"), None
|
||||||
)
|
)
|
||||||
|
if not p or not p.orgs:
|
||||||
if not permission_orgs:
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Get users from the first organization with admin permission
|
# Get users from the first organization with admin permission
|
||||||
org_users = await globals.db.instance.get_organization_users(
|
first_org_uuid = next(iter(p.orgs))
|
||||||
str(permission_orgs[0].uuid)
|
org_users = db.get_organization_users(first_org_uuid)
|
||||||
)
|
|
||||||
admin_users = [user for user, role in org_users if role == "Administration"]
|
admin_users = [user for user, role in org_users if role == "Administration"]
|
||||||
|
|
||||||
if not admin_users:
|
if not admin_users:
|
||||||
@@ -134,17 +69,19 @@ async def check_admin_credentials() -> bool:
|
|||||||
|
|
||||||
# Check first admin user for credentials
|
# Check first admin user for credentials
|
||||||
admin_user = admin_users[0]
|
admin_user = admin_users[0]
|
||||||
credentials = await globals.db.instance.get_credentials_by_user_uuid(
|
|
||||||
admin_user.uuid
|
|
||||||
)
|
|
||||||
|
|
||||||
if not credentials:
|
if not db.get_user_credential_ids(admin_user.uuid):
|
||||||
# Admin exists but has no credentials, create reset link
|
# Admin exists but has no credentials, create reset link
|
||||||
await _create_and_log_admin_reset_link(
|
|
||||||
admin_user.uuid,
|
token = passphrase.generate()
|
||||||
"⚠️ Admin user has no credentials!",
|
expiry = authsession.reset_expires()
|
||||||
"admin registration",
|
db.create_reset_token(
|
||||||
|
user_uuid=admin_user.uuid,
|
||||||
|
passphrase=token,
|
||||||
|
expiry=expiry,
|
||||||
|
token_type="admin registration",
|
||||||
)
|
)
|
||||||
|
_log_reset_link("⚠️ Admin user has no credentials!", token)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
return False
|
return False
|
||||||
@@ -160,16 +97,12 @@ async def bootstrap_if_needed() -> bool:
|
|||||||
Returns:
|
Returns:
|
||||||
bool: True if bootstrapping was performed, False if system was already set up
|
bool: True if bootstrapping was performed, False if system was already set up
|
||||||
"""
|
"""
|
||||||
try:
|
|
||||||
# Check if the admin permission exists - if it does, system is already bootstrapped
|
# Check if the admin permission exists - if it does, system is already bootstrapped
|
||||||
await globals.db.instance.get_permission("auth:admin")
|
if any(p.scope == "auth:admin" for p in db.data().permissions.values()):
|
||||||
# Permission exists, system is already bootstrapped
|
# Permission exists, system is already bootstrapped
|
||||||
# Check if admin needs credentials (only for already-bootstrapped systems)
|
# Check if admin needs credentials (only for already-bootstrapped systems)
|
||||||
await check_admin_credentials()
|
await check_admin_credentials()
|
||||||
return False
|
return False
|
||||||
except Exception:
|
|
||||||
# Permission doesn't exist, need to bootstrap
|
|
||||||
pass
|
|
||||||
|
|
||||||
# No admin permission found, need to bootstrap
|
# No admin permission found, need to bootstrap
|
||||||
# Bootstrap creates the admin user AND the reset link, so no need to check credentials after
|
# Bootstrap creates the admin user AND the reset link, so no need to check credentials after
|
||||||
|
|||||||
@@ -22,4 +22,3 @@ class PaskiaConfig:
|
|||||||
host: str | None = None
|
host: str | None = None
|
||||||
port: int | None = None
|
port: int | None = None
|
||||||
uds: str | None = None
|
uds: str | None = None
|
||||||
devmode: bool = False
|
|
||||||
|
|||||||
+140
-403
@@ -1,415 +1,152 @@
|
|||||||
"""
|
"""
|
||||||
Database module for WebAuthn passkey authentication.
|
Database module for WebAuthn passkey authentication.
|
||||||
|
|
||||||
This module provides dataclasses and database abstractions for managing
|
Read: Access data() directly, use build_* to convert to public structs.
|
||||||
users, credentials, and sessions in a WebAuthn authentication system.
|
CTX: get_session_context(key) returns SessionContext with effective permissions.
|
||||||
|
Write: Functions validate and commit, or raise ValueError.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
from paskia import db
|
||||||
|
|
||||||
|
# Read (after init)
|
||||||
|
user_data = db.data().users[user_uuid]
|
||||||
|
user = db.build_user(user_uuid)
|
||||||
|
|
||||||
|
# Context
|
||||||
|
ctx = db.get_session_context(session_key)
|
||||||
|
|
||||||
|
# Write
|
||||||
|
db.create_user(user)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
import paskia.db.operations as operations
|
||||||
from dataclasses import dataclass, field
|
from paskia.db.background import (
|
||||||
from datetime import datetime
|
start_background,
|
||||||
from uuid import UUID
|
start_cleanup,
|
||||||
|
stop_background,
|
||||||
|
stop_cleanup,
|
||||||
@dataclass
|
)
|
||||||
class Permission:
|
from paskia.db.operations import (
|
||||||
id: str # String primary key (max 128 chars)
|
add_permission_to_org,
|
||||||
display_name: str
|
add_permission_to_role,
|
||||||
|
bootstrap,
|
||||||
|
cleanup_expired,
|
||||||
@dataclass
|
create_credential,
|
||||||
class Role:
|
create_credential_session,
|
||||||
uuid: UUID
|
create_org,
|
||||||
org_uuid: UUID
|
create_permission,
|
||||||
display_name: str
|
create_reset_token,
|
||||||
# List of permission IDs this role grants to its members
|
create_role,
|
||||||
permissions: list[str] = field(default_factory=list) # permission IDs
|
create_session,
|
||||||
|
create_user,
|
||||||
|
delete_credential,
|
||||||
@dataclass
|
delete_org,
|
||||||
class Org:
|
delete_permission,
|
||||||
uuid: UUID
|
delete_reset_token,
|
||||||
display_name: str
|
delete_role,
|
||||||
# All permission IDs that the Org is allowed to grant to its roles
|
delete_session,
|
||||||
permissions: list[str] = field(default_factory=list) # permission IDs
|
delete_sessions_for_user,
|
||||||
# Roles belonging to this org
|
delete_user,
|
||||||
roles: list[Role] = field(default_factory=list)
|
get_organization_users,
|
||||||
|
get_reset_token,
|
||||||
|
get_session_context,
|
||||||
@dataclass
|
get_user_credential_ids,
|
||||||
class User:
|
get_user_organization,
|
||||||
uuid: UUID
|
init,
|
||||||
display_name: str
|
login,
|
||||||
role_uuid: UUID
|
remove_permission_from_org,
|
||||||
created_at: datetime | None = None
|
remove_permission_from_role,
|
||||||
last_seen: datetime | None = None
|
set_session_host,
|
||||||
visits: int = 0
|
update_credential_sign_count,
|
||||||
|
update_org_name,
|
||||||
|
update_permission,
|
||||||
@dataclass
|
update_role_name,
|
||||||
class Credential:
|
update_session,
|
||||||
uuid: UUID
|
update_user_display_name,
|
||||||
credential_id: bytes # Long binary ID passed from the authenticator
|
update_user_role,
|
||||||
user_uuid: UUID
|
update_user_role_in_organization,
|
||||||
aaguid: UUID
|
)
|
||||||
public_key: bytes
|
from paskia.db.structs import (
|
||||||
sign_count: int
|
DB,
|
||||||
created_at: datetime
|
Credential,
|
||||||
last_used: datetime | None = None
|
Org,
|
||||||
last_verified: datetime | None = None
|
Permission,
|
||||||
|
ResetToken,
|
||||||
|
Role,
|
||||||
@dataclass
|
Session,
|
||||||
class Session:
|
SessionContext,
|
||||||
key: bytes
|
User,
|
||||||
user_uuid: UUID
|
)
|
||||||
credential_uuid: UUID
|
|
||||||
host: str
|
|
||||||
ip: str
|
def data() -> DB:
|
||||||
user_agent: str
|
"""Get the database instance for direct read access."""
|
||||||
renewed: datetime
|
return operations._db
|
||||||
|
|
||||||
def metadata(self) -> dict:
|
|
||||||
"""Return session metadata for backwards compatibility."""
|
|
||||||
return {
|
|
||||||
"ip": self.ip,
|
|
||||||
"user_agent": self.user_agent,
|
|
||||||
"renewed": self.renewed.isoformat(),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class ResetToken:
|
|
||||||
key: bytes
|
|
||||||
user_uuid: UUID
|
|
||||||
expiry: datetime
|
|
||||||
token_type: str
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class SessionContext:
|
|
||||||
session: Session
|
|
||||||
user: User
|
|
||||||
org: Org
|
|
||||||
role: Role
|
|
||||||
credential: Credential | None = None
|
|
||||||
permissions: list[Permission] | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class DatabaseInterface(ABC):
|
|
||||||
"""Abstract base class defining the database interface.
|
|
||||||
|
|
||||||
This class defines the public API that database implementations should provide.
|
|
||||||
Implementations may use decorators like @with_session that modify method signatures
|
|
||||||
at runtime, so this interface focuses on the logical operations rather than
|
|
||||||
exact parameter matching.
|
|
||||||
"""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def init_db(self) -> None:
|
|
||||||
"""Initialize database tables."""
|
|
||||||
pass
|
|
||||||
|
|
||||||
# User operations
|
|
||||||
@abstractmethod
|
|
||||||
async def get_user_by_uuid(self, user_uuid: UUID) -> User:
|
|
||||||
"""Get user record by WebAuthn user UUID."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def create_user(self, user: User) -> None:
|
|
||||||
"""Create a new user."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def update_user_display_name(
|
|
||||||
self, user_uuid: UUID, display_name: str
|
|
||||||
) -> None:
|
|
||||||
"""Update a user's display name."""
|
|
||||||
|
|
||||||
# Role operations
|
|
||||||
@abstractmethod
|
|
||||||
async def create_role(self, role: Role) -> None:
|
|
||||||
"""Create new role."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def update_role(self, role: Role) -> None:
|
|
||||||
"""Update a role's display name and synchronize its permissions."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def delete_role(self, role_uuid: UUID) -> None:
|
|
||||||
"""Delete a role by UUID. Implementations may prevent deletion if users exist."""
|
|
||||||
|
|
||||||
# Credential operations
|
|
||||||
@abstractmethod
|
|
||||||
async def create_credential(self, credential: Credential) -> None:
|
|
||||||
"""Store a credential for a user."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_credential_by_id(self, credential_id: bytes) -> Credential:
|
|
||||||
"""Get credential by credential ID."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_credentials_by_user_uuid(self, user_uuid: UUID) -> list[bytes]:
|
|
||||||
"""Get all credential IDs for a user."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def update_credential(self, credential: Credential) -> None:
|
|
||||||
"""Update the sign count, created_at, last_used, and last_verified for a credential."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def delete_credential(self, uuid: UUID, user_uuid: UUID) -> None:
|
|
||||||
"""Delete a specific credential for a user."""
|
|
||||||
|
|
||||||
# Session operations
|
|
||||||
@abstractmethod
|
|
||||||
async def create_session(
|
|
||||||
self,
|
|
||||||
user_uuid: UUID,
|
|
||||||
key: bytes,
|
|
||||||
credential_uuid: UUID,
|
|
||||||
host: str,
|
|
||||||
ip: str,
|
|
||||||
user_agent: str,
|
|
||||||
renewed: datetime,
|
|
||||||
) -> None:
|
|
||||||
"""Create a new session."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_session(self, key: bytes) -> Session | None:
|
|
||||||
"""Get session by key."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def delete_session(self, key: bytes) -> None:
|
|
||||||
"""Delete session by key."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def update_session(
|
|
||||||
self,
|
|
||||||
key: bytes,
|
|
||||||
*,
|
|
||||||
ip: str,
|
|
||||||
user_agent: str,
|
|
||||||
renewed: datetime,
|
|
||||||
) -> Session | None:
|
|
||||||
"""Update session metadata and touch renewed timestamp."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def set_session_host(self, key: bytes, host: str) -> None:
|
|
||||||
"""Bind a session to a specific host if not already set."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def list_sessions_for_user(self, user_uuid: UUID) -> list[Session]:
|
|
||||||
"""Return all sessions for a user (including other hosts)."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def cleanup(self) -> None:
|
|
||||||
"""Called periodically to clean up expired records."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def delete_sessions_for_user(self, user_uuid: UUID) -> None:
|
|
||||||
"""Delete all sessions belonging to the provided user."""
|
|
||||||
|
|
||||||
# Reset token operations
|
|
||||||
@abstractmethod
|
|
||||||
async def create_reset_token(
|
|
||||||
self,
|
|
||||||
user_uuid: UUID,
|
|
||||||
key: bytes,
|
|
||||||
expiry: datetime,
|
|
||||||
token_type: str,
|
|
||||||
) -> None:
|
|
||||||
"""Create a reset token for a user."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_reset_token(self, key: bytes) -> ResetToken | None:
|
|
||||||
"""Retrieve a reset token by key."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def delete_reset_token(self, key: bytes) -> None:
|
|
||||||
"""Delete a reset token by key."""
|
|
||||||
|
|
||||||
# Organization operations
|
|
||||||
@abstractmethod
|
|
||||||
async def create_organization(self, org: Org) -> None:
|
|
||||||
"""Add a new organization."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_organization(self, org_id: str) -> Org:
|
|
||||||
"""Get organization by ID, including its permission IDs and roles (with their permission IDs)."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def list_organizations(self) -> list[Org]:
|
|
||||||
"""List all organizations with their roles and permission IDs."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def update_organization(self, org: Org) -> None:
|
|
||||||
"""Update organization options."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def delete_organization(self, org_uuid: UUID) -> None:
|
|
||||||
"""Delete organization by ID."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def add_user_to_organization(
|
|
||||||
self, user_uuid: UUID, org_id: str, role: str
|
|
||||||
) -> None:
|
|
||||||
"""Set a user's organization and role."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def transfer_user_to_organization(
|
|
||||||
self, user_uuid: UUID, new_org_id: str, new_role: str | None = None
|
|
||||||
) -> None:
|
|
||||||
"""Transfer a user to another organization with an optional role."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_user_organization(self, user_uuid: UUID) -> tuple[Org, str]:
|
|
||||||
"""Get the organization and role for a user."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_organization_users(self, org_id: str) -> list[tuple[User, str]]:
|
|
||||||
"""Get all users in an organization with their roles."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_roles_by_organization(self, org_id: str) -> list[Role]:
|
|
||||||
"""List roles belonging to an organization."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_user_role_in_organization(
|
|
||||||
self, user_uuid: UUID, org_id: str
|
|
||||||
) -> str | None:
|
|
||||||
"""Get a user's role in a specific organization."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def update_user_role_in_organization(
|
|
||||||
self, user_uuid: UUID, new_role: str
|
|
||||||
) -> None:
|
|
||||||
"""Update a user's role in their organization."""
|
|
||||||
|
|
||||||
# Permission operations
|
|
||||||
@abstractmethod
|
|
||||||
async def create_permission(self, permission: Permission) -> None:
|
|
||||||
"""Create a new permission."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_permission(self, permission_id: str) -> Permission:
|
|
||||||
"""Get permission by ID."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def list_permissions(self) -> list[Permission]:
|
|
||||||
"""List all permissions."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def update_permission(self, permission: Permission) -> None:
|
|
||||||
"""Update permission details."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def delete_permission(self, permission_id: str) -> None:
|
|
||||||
"""Delete permission by ID."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def rename_permission(
|
|
||||||
self, old_id: str, new_id: str, display_name: str
|
|
||||||
) -> None:
|
|
||||||
"""Rename a permission's ID (and display name) updating all references.
|
|
||||||
|
|
||||||
This must update:
|
|
||||||
- permissions.id (primary key)
|
|
||||||
- org_permissions.permission_id
|
|
||||||
- role_permissions.permission_id
|
|
||||||
"""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def add_permission_to_organization(
|
|
||||||
self, org_id: str, permission_id: str
|
|
||||||
) -> None:
|
|
||||||
"""Add a permission to an organization."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def remove_permission_from_organization(
|
|
||||||
self, org_id: str, permission_id: str
|
|
||||||
) -> None:
|
|
||||||
"""Remove a permission from an organization."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_organization_permissions(self, org_id: str) -> list[Permission]:
|
|
||||||
"""Get all permissions assigned to an organization."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_permission_organizations(self, permission_id: str) -> list[Org]:
|
|
||||||
"""Get all organizations that have a specific permission."""
|
|
||||||
|
|
||||||
# Role-permission operations
|
|
||||||
@abstractmethod
|
|
||||||
async def add_permission_to_role(self, role_uuid: UUID, permission_id: str) -> None:
|
|
||||||
"""Add a permission to a role."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def remove_permission_from_role(
|
|
||||||
self, role_uuid: UUID, permission_id: str
|
|
||||||
) -> None:
|
|
||||||
"""Remove a permission from a role."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_role_permissions(self, role_uuid: UUID) -> list[Permission]:
|
|
||||||
"""List all permissions granted to a role."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_permission_roles(self, permission_id: str) -> list[Role]:
|
|
||||||
"""List all roles that grant a permission."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_role(self, role_uuid: UUID) -> Role:
|
|
||||||
"""Get a role by UUID, including its permission IDs."""
|
|
||||||
|
|
||||||
# Combined operations
|
|
||||||
@abstractmethod
|
|
||||||
async def login(self, user_uuid: UUID, credential: Credential) -> None:
|
|
||||||
"""Update user and credential timestamps after successful login."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def create_user_and_credential(
|
|
||||||
self, user: User, credential: Credential
|
|
||||||
) -> None:
|
|
||||||
"""Create a new user and their first credential in a transaction."""
|
|
||||||
|
|
||||||
@abstractmethod
|
|
||||||
async def get_session_context(
|
|
||||||
self, session_key: bytes, host: str | None = None
|
|
||||||
) -> SessionContext | None:
|
|
||||||
"""Get complete session context including user, organization, role, and permissions."""
|
|
||||||
|
|
||||||
# Combined atomic operations
|
|
||||||
@abstractmethod
|
|
||||||
async def create_credential_session(
|
|
||||||
self,
|
|
||||||
user_uuid: UUID,
|
|
||||||
credential: Credential,
|
|
||||||
reset_key: bytes | None,
|
|
||||||
session_key: bytes,
|
|
||||||
*,
|
|
||||||
display_name: str | None = None,
|
|
||||||
host: str | None = None,
|
|
||||||
ip: str | None = None,
|
|
||||||
user_agent: str | None = None,
|
|
||||||
) -> None:
|
|
||||||
"""Atomically add a credential and create a session.
|
|
||||||
|
|
||||||
Steps (single transaction):
|
|
||||||
1. Insert credential
|
|
||||||
2. Optionally delete old reset token if provided
|
|
||||||
3. Optionally update user's display name
|
|
||||||
4. Insert new session referencing the credential
|
|
||||||
5. Update user's last_seen and increment visits (treat as a login)
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"User",
|
# Types
|
||||||
"Credential",
|
"Credential",
|
||||||
"Session",
|
"DB",
|
||||||
"ResetToken",
|
|
||||||
"SessionContext",
|
|
||||||
"Org",
|
"Org",
|
||||||
"Role",
|
|
||||||
"Permission",
|
"Permission",
|
||||||
"DatabaseInterface",
|
"ResetToken",
|
||||||
|
"Role",
|
||||||
|
"Session",
|
||||||
|
"SessionContext",
|
||||||
|
"User",
|
||||||
|
# Instance
|
||||||
|
"data",
|
||||||
|
"init",
|
||||||
|
# Background
|
||||||
|
"start_background",
|
||||||
|
"stop_background",
|
||||||
|
"start_cleanup",
|
||||||
|
"stop_cleanup",
|
||||||
|
# Builders
|
||||||
|
"build_credential",
|
||||||
|
"build_permission",
|
||||||
|
"build_reset_token",
|
||||||
|
"build_role",
|
||||||
|
"build_session",
|
||||||
|
"build_user",
|
||||||
|
# Read ops
|
||||||
|
"get_organization_users",
|
||||||
|
"get_reset_token",
|
||||||
|
"get_session_context",
|
||||||
|
"get_user_credential_ids",
|
||||||
|
"get_user_organization",
|
||||||
|
# Write ops
|
||||||
|
"add_permission_to_org",
|
||||||
|
"add_permission_to_role",
|
||||||
|
"bootstrap",
|
||||||
|
"cleanup_expired",
|
||||||
|
"create_credential",
|
||||||
|
"create_credential_session",
|
||||||
|
"create_org",
|
||||||
|
"create_permission",
|
||||||
|
"create_reset_token",
|
||||||
|
"create_role",
|
||||||
|
"create_session",
|
||||||
|
"create_user",
|
||||||
|
"delete_credential",
|
||||||
|
"delete_org",
|
||||||
|
"delete_permission",
|
||||||
|
"delete_reset_token",
|
||||||
|
"delete_role",
|
||||||
|
"delete_session",
|
||||||
|
"delete_sessions_for_user",
|
||||||
|
"delete_user",
|
||||||
|
"login",
|
||||||
|
"remove_permission_from_org",
|
||||||
|
"remove_permission_from_role",
|
||||||
|
"set_session_host",
|
||||||
|
"update_credential_sign_count",
|
||||||
|
"update_org_name",
|
||||||
|
"update_permission",
|
||||||
|
"update_role_name",
|
||||||
|
"update_session",
|
||||||
|
"update_user_display_name",
|
||||||
|
"update_user_role",
|
||||||
|
"update_user_role_in_organization",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""
|
||||||
|
Background task for database maintenance.
|
||||||
|
|
||||||
|
Periodically flushes pending changes to disk and cleans up expired items.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from paskia.db.operations import _store, cleanup_expired
|
||||||
|
|
||||||
|
FLUSH_INTERVAL = 0.1 # Flush to disk
|
||||||
|
CLEANUP_INTERVAL = 1 # Expired item cleanup
|
||||||
|
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
_background_task: asyncio.Task | None = None
|
||||||
|
|
||||||
|
|
||||||
|
async def flush() -> None:
|
||||||
|
"""Write all pending database changes to disk."""
|
||||||
|
|
||||||
|
if _store is None:
|
||||||
|
_logger.warning("flush() called but _store is None")
|
||||||
|
return
|
||||||
|
await _store.flush()
|
||||||
|
|
||||||
|
|
||||||
|
async def _background_loop():
|
||||||
|
"""Background task that periodically flushes changes and cleans up."""
|
||||||
|
# Run cleanup immediately on startup to clear old expired items
|
||||||
|
cleanup_expired()
|
||||||
|
await flush()
|
||||||
|
|
||||||
|
last_cleanup = datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await asyncio.sleep(FLUSH_INTERVAL)
|
||||||
|
# Flush pending changes to disk
|
||||||
|
await flush()
|
||||||
|
|
||||||
|
# Run cleanup periodically
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
if (now - last_cleanup).total_seconds() >= CLEANUP_INTERVAL:
|
||||||
|
cleanup_expired()
|
||||||
|
await flush() # Flush cleanup changes
|
||||||
|
last_cleanup = now
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
# Final flush before exit
|
||||||
|
await flush()
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
_logger.debug("Error in database background loop", exc_info=True)
|
||||||
|
|
||||||
|
|
||||||
|
async def start_background():
|
||||||
|
"""Start the background flush/cleanup task."""
|
||||||
|
global _background_task
|
||||||
|
|
||||||
|
# Check if task exists but is no longer running (e.g., after uvicorn reload)
|
||||||
|
if _background_task is not None:
|
||||||
|
if _background_task.done():
|
||||||
|
_logger.debug("Previous background task was done, restarting")
|
||||||
|
_background_task = None
|
||||||
|
else:
|
||||||
|
# Task exists and is running - but might be in a dead event loop
|
||||||
|
try:
|
||||||
|
# Check if task is in current event loop
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
task_loop = _background_task.get_loop()
|
||||||
|
if loop is not task_loop:
|
||||||
|
_logger.debug("Background task in different event loop, restarting")
|
||||||
|
_background_task = None
|
||||||
|
else:
|
||||||
|
# Task is running in the same event loop - this is an error
|
||||||
|
raise RuntimeError(
|
||||||
|
"Background task is already running. "
|
||||||
|
"start_background() must not be called multiple times in the same event loop."
|
||||||
|
)
|
||||||
|
except RuntimeError:
|
||||||
|
raise # Re-raise RuntimeError from above
|
||||||
|
except Exception as e:
|
||||||
|
_logger.debug("Error checking background task loop: %s, restarting", e)
|
||||||
|
_background_task = None
|
||||||
|
|
||||||
|
if _background_task is None:
|
||||||
|
_background_task = asyncio.create_task(_background_loop())
|
||||||
|
else:
|
||||||
|
_logger.debug("Background task already running: %s", _background_task)
|
||||||
|
|
||||||
|
|
||||||
|
async def stop_background():
|
||||||
|
"""Stop the background task and flush any pending changes."""
|
||||||
|
global _background_task
|
||||||
|
if _background_task:
|
||||||
|
_background_task.cancel()
|
||||||
|
try:
|
||||||
|
await _background_task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
_background_task = None
|
||||||
|
|
||||||
|
|
||||||
|
# Aliases for backwards compatibility
|
||||||
|
start_cleanup = start_background
|
||||||
|
stop_cleanup = stop_background
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
"""
|
||||||
|
JSONL persistence layer for the database.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
from collections import deque
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
import aiofiles
|
||||||
|
import jsondiff
|
||||||
|
import msgspec
|
||||||
|
|
||||||
|
from paskia.db.migrations import apply_migrations
|
||||||
|
from paskia.db.structs import DB, SessionContext
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Default database path
|
||||||
|
DB_PATH_DEFAULT = "paskia.jsonl"
|
||||||
|
|
||||||
|
|
||||||
|
class _ChangeRecord(msgspec.Struct, omit_defaults=True):
|
||||||
|
"""A single change record in the JSONL file."""
|
||||||
|
|
||||||
|
ts: datetime
|
||||||
|
a: str # action - describes the operation (e.g., "migrate", "login", "create_user")
|
||||||
|
u: str | None = None # user UUID who performed the action (None for system)
|
||||||
|
diff: dict = {}
|
||||||
|
|
||||||
|
|
||||||
|
# msgspec encoder for change records
|
||||||
|
_change_encoder = msgspec.json.Encoder()
|
||||||
|
|
||||||
|
|
||||||
|
async def load_jsonl(db_path: Path) -> dict:
|
||||||
|
"""Load data from disk by applying change log.
|
||||||
|
|
||||||
|
Replays all changes from JSONL file using plain dicts (to handle
|
||||||
|
schema evolution).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db_path: Path to the JSONL database file
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The final state after applying all changes
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If file doesn't exist or cannot be loaded
|
||||||
|
"""
|
||||||
|
if not db_path.exists():
|
||||||
|
raise ValueError(f"Database file not found: {db_path}")
|
||||||
|
data_dict: dict = {}
|
||||||
|
try:
|
||||||
|
# Read entire file at once and split into lines
|
||||||
|
async with aiofiles.open(db_path, "rb") as f:
|
||||||
|
content = await f.read()
|
||||||
|
for line_num, line in enumerate(content.split(b"\n"), 1):
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
change = msgspec.json.decode(line)
|
||||||
|
# Apply the diff to current state (marshal=True for $-prefixed keys)
|
||||||
|
data_dict = jsondiff.patch(data_dict, change["diff"], marshal=True)
|
||||||
|
except Exception as e:
|
||||||
|
raise ValueError(f"Error parsing line {line_num}: {e}")
|
||||||
|
except (OSError, ValueError, msgspec.DecodeError) as e:
|
||||||
|
raise ValueError(f"Failed to load database: {e}")
|
||||||
|
return data_dict
|
||||||
|
|
||||||
|
|
||||||
|
def compute_diff(previous: dict, current: dict) -> dict | None:
|
||||||
|
"""Compute JSON diff between two states.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
previous: Previous state (JSON-compatible dict)
|
||||||
|
current: Current state (JSON-compatible dict)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The diff, or None if no changes
|
||||||
|
"""
|
||||||
|
diff = jsondiff.diff(previous, current, marshal=True)
|
||||||
|
return diff if diff else None
|
||||||
|
|
||||||
|
|
||||||
|
def create_change_record(
|
||||||
|
action: str, diff: dict, user: str | None = None
|
||||||
|
) -> _ChangeRecord:
|
||||||
|
"""Create a change record for persistence."""
|
||||||
|
return _ChangeRecord(
|
||||||
|
ts=datetime.now(timezone.utc),
|
||||||
|
a=action,
|
||||||
|
u=user,
|
||||||
|
diff=diff,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Actions that are allowed to create a new database file
|
||||||
|
_BOOTSTRAP_ACTIONS = frozenset({"bootstrap", "migrate"})
|
||||||
|
|
||||||
|
|
||||||
|
async def flush_changes(
|
||||||
|
db_path: Path,
|
||||||
|
pending_changes: deque[_ChangeRecord],
|
||||||
|
) -> bool:
|
||||||
|
"""Write all pending changes to disk.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db_path: Path to the JSONL database file
|
||||||
|
pending_changes: Queue of pending change records (will be cleared on success)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if flush succeeded, False otherwise
|
||||||
|
"""
|
||||||
|
if not pending_changes:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if not db_path.exists():
|
||||||
|
first_action = pending_changes[0].a
|
||||||
|
if first_action not in _BOOTSTRAP_ACTIONS:
|
||||||
|
_logger.error(
|
||||||
|
"Refusing to create database file with action '%s' - "
|
||||||
|
"only bootstrap or migrate can create a new database",
|
||||||
|
first_action,
|
||||||
|
)
|
||||||
|
pending_changes.clear()
|
||||||
|
return False
|
||||||
|
|
||||||
|
changes_to_write = list(pending_changes)
|
||||||
|
pending_changes.clear()
|
||||||
|
|
||||||
|
try:
|
||||||
|
lines = [_change_encoder.encode(change) for change in changes_to_write]
|
||||||
|
if not lines:
|
||||||
|
return True
|
||||||
|
|
||||||
|
async with aiofiles.open(db_path, "ab") as f:
|
||||||
|
await f.write(b"\n".join(lines) + b"\n")
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
_logger.exception("Failed to flush database changes")
|
||||||
|
# Re-queue the changes on failure
|
||||||
|
for change in reversed(changes_to_write):
|
||||||
|
pending_changes.appendleft(change)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class JsonlStore:
|
||||||
|
"""JSONL persistence layer for a DB instance."""
|
||||||
|
|
||||||
|
def __init__(self, db: DB, db_path: str = DB_PATH_DEFAULT):
|
||||||
|
self.db: DB = db
|
||||||
|
self.db_path = Path(db_path)
|
||||||
|
self._previous_builtins: dict[str, Any] = {}
|
||||||
|
self._pending_changes: deque[_ChangeRecord] = deque()
|
||||||
|
self._current_action: str = "system"
|
||||||
|
self._current_user: str | None = None
|
||||||
|
self._in_transaction: bool = False
|
||||||
|
self._transaction_snapshot: dict[str, Any] | None = None
|
||||||
|
|
||||||
|
async def load(self, db_path: str | None = None) -> None:
|
||||||
|
"""Load data from JSONL change log."""
|
||||||
|
if db_path is not None:
|
||||||
|
self.db_path = Path(db_path)
|
||||||
|
try:
|
||||||
|
data_dict = await load_jsonl(self.db_path)
|
||||||
|
if data_dict:
|
||||||
|
# Preserve original state before migrations (deep copy for nested dicts)
|
||||||
|
original_dict = copy.deepcopy(data_dict)
|
||||||
|
|
||||||
|
# Apply schema migrations (modifies data_dict in place)
|
||||||
|
migrated = apply_migrations(data_dict)
|
||||||
|
|
||||||
|
decoder = msgspec.json.Decoder(DB)
|
||||||
|
self.db = decoder.decode(msgspec.json.encode(data_dict))
|
||||||
|
self.db._store = self
|
||||||
|
|
||||||
|
# Update previous state to migrated data FIRST (to avoid transaction hardening reset)
|
||||||
|
self._previous_builtins = data_dict
|
||||||
|
|
||||||
|
# Persist migration by manually computing and queueing the diff
|
||||||
|
if migrated:
|
||||||
|
diff = compute_diff(original_dict, data_dict)
|
||||||
|
if diff:
|
||||||
|
self._pending_changes.append(
|
||||||
|
create_change_record("migrate", diff, user=None)
|
||||||
|
)
|
||||||
|
_logger.info("Queued migration changes for persistence")
|
||||||
|
await self.flush()
|
||||||
|
except ValueError:
|
||||||
|
if self.db_path.exists():
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _queue_change(self) -> None:
|
||||||
|
current = msgspec.to_builtins(self.db)
|
||||||
|
diff = compute_diff(self._previous_builtins, current)
|
||||||
|
if diff:
|
||||||
|
self._pending_changes.append(
|
||||||
|
create_change_record(self._current_action, diff, self._current_user)
|
||||||
|
)
|
||||||
|
self._previous_builtins = current
|
||||||
|
# Log the change with user display name if available
|
||||||
|
user_display = None
|
||||||
|
if self._current_user:
|
||||||
|
try:
|
||||||
|
user_uuid = UUID(self._current_user)
|
||||||
|
if user_uuid in self.db.users:
|
||||||
|
user_display = self.db.users[user_uuid].display_name
|
||||||
|
except (ValueError, KeyError):
|
||||||
|
user_display = self._current_user
|
||||||
|
|
||||||
|
diff_json = json.dumps(diff, default=str)
|
||||||
|
if user_display:
|
||||||
|
print(
|
||||||
|
f"{self._current_action} by {user_display}: {diff_json}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
print(f"{self._current_action}: {diff_json}", file=sys.stderr)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def transaction(
|
||||||
|
self,
|
||||||
|
action: str,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
*,
|
||||||
|
user: str | None = None,
|
||||||
|
):
|
||||||
|
"""Wrap writes in transaction. Queues change on successful exit.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
action: Describes the operation (e.g., "Created user", "Login")
|
||||||
|
ctx: Session context of user performing the action (None for system operations)
|
||||||
|
user: User UUID string (alternative to ctx when full context unavailable)
|
||||||
|
"""
|
||||||
|
if self._in_transaction:
|
||||||
|
raise RuntimeError("Nested transactions are not supported")
|
||||||
|
|
||||||
|
# Check for out-of-transaction modifications
|
||||||
|
current_state = msgspec.to_builtins(self.db)
|
||||||
|
if current_state != self._previous_builtins:
|
||||||
|
diff = compute_diff(self._previous_builtins, current_state)
|
||||||
|
diff_json = json.dumps(diff, default=str, indent=2)
|
||||||
|
_logger.error(
|
||||||
|
"Database state modified outside of transaction! "
|
||||||
|
"This indicates a bug where DB changes occurred without a transaction wrapper. "
|
||||||
|
"Resetting to last known state from JSONL file.\n"
|
||||||
|
f"Changes detected:\n{diff_json}"
|
||||||
|
)
|
||||||
|
# Hard reset to last known good state
|
||||||
|
decoder = msgspec.json.Decoder(DB)
|
||||||
|
self.db = decoder.decode(msgspec.json.encode(self._previous_builtins))
|
||||||
|
self.db._store = self
|
||||||
|
current_state = self._previous_builtins.copy()
|
||||||
|
|
||||||
|
old_action = self._current_action
|
||||||
|
old_user = self._current_user
|
||||||
|
self._current_action = action
|
||||||
|
# Prefer ctx.user.uuid if ctx provided, otherwise use user param
|
||||||
|
self._current_user = str(ctx.user.uuid) if ctx else user
|
||||||
|
self._in_transaction = True
|
||||||
|
self._transaction_snapshot = current_state
|
||||||
|
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
self._queue_change()
|
||||||
|
except Exception:
|
||||||
|
# Rollback on error: restore from snapshot
|
||||||
|
_logger.warning("Transaction '%s' failed, rolling back changes", action)
|
||||||
|
if self._transaction_snapshot is not None:
|
||||||
|
decoder = msgspec.json.Decoder(DB)
|
||||||
|
self.db = decoder.decode(
|
||||||
|
msgspec.json.encode(self._transaction_snapshot)
|
||||||
|
)
|
||||||
|
self.db._store = self
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
self._current_action = old_action
|
||||||
|
self._current_user = old_user
|
||||||
|
self._in_transaction = False
|
||||||
|
self._transaction_snapshot = None
|
||||||
|
|
||||||
|
async def flush(self) -> bool:
|
||||||
|
"""Write all pending changes to disk."""
|
||||||
|
return await flush_changes(self.db_path, self._pending_changes)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""
|
||||||
|
Database schema migrations.
|
||||||
|
|
||||||
|
Migrations are applied during database load based on the version field.
|
||||||
|
Each migration should be idempotent and only run when needed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_migrations(data_dict: dict) -> bool:
|
||||||
|
"""Apply any pending schema migrations to the database dictionary.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
data_dict: The raw database dictionary loaded from JSONL
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if any migrations were applied, False otherwise
|
||||||
|
"""
|
||||||
|
db_version = data_dict.get("v", 0)
|
||||||
|
migrated = False
|
||||||
|
|
||||||
|
if db_version == 0:
|
||||||
|
# Migration v0 -> v1: Remove created_at from orgs (field removed from schema)
|
||||||
|
if "orgs" in data_dict:
|
||||||
|
for org_data in data_dict["orgs"].values():
|
||||||
|
org_data.pop("created_at", None)
|
||||||
|
data_dict["v"] = 1
|
||||||
|
migrated = True
|
||||||
|
_logger.info("Applied schema migration: v0 -> v1 (removed org.created_at)")
|
||||||
|
|
||||||
|
return migrated
|
||||||
@@ -0,0 +1,918 @@
|
|||||||
|
"""
|
||||||
|
Database for WebAuthn passkey authentication.
|
||||||
|
|
||||||
|
Read operations: Access _db directly, use build_* helpers to get public structs.
|
||||||
|
Context lookup: get_session_context() returns full SessionContext with effective permissions.
|
||||||
|
Write operations: Functions that validate and commit, or raise ValueError.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
import uuid7
|
||||||
|
|
||||||
|
from paskia.config import SESSION_LIFETIME
|
||||||
|
from paskia.db.jsonl import (
|
||||||
|
DB_PATH_DEFAULT,
|
||||||
|
JsonlStore,
|
||||||
|
)
|
||||||
|
from paskia.db.structs import (
|
||||||
|
DB,
|
||||||
|
Credential,
|
||||||
|
Org,
|
||||||
|
Permission,
|
||||||
|
ResetToken,
|
||||||
|
Role,
|
||||||
|
Session,
|
||||||
|
SessionContext,
|
||||||
|
User,
|
||||||
|
)
|
||||||
|
from paskia.util.hostutil import normalize_host
|
||||||
|
from paskia.util.passphrase import generate as generate_passphrase
|
||||||
|
from paskia.util.passphrase import is_well_formed as _is_passphrase
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Global database instance (empty until init() loads data)
|
||||||
|
_db = DB()
|
||||||
|
_store = JsonlStore(_db)
|
||||||
|
_db._store = _store
|
||||||
|
_initialized = False
|
||||||
|
|
||||||
|
|
||||||
|
async def init(*args, **kwargs):
|
||||||
|
"""Load database from JSONL file."""
|
||||||
|
global _db, _initialized
|
||||||
|
if _initialized:
|
||||||
|
_logger.debug("Database already initialized, skipping reload")
|
||||||
|
return
|
||||||
|
db_path = os.environ.get("PASKIA_DB", DB_PATH_DEFAULT)
|
||||||
|
if db_path.startswith("json:"):
|
||||||
|
db_path = db_path[5:]
|
||||||
|
await _store.load(db_path)
|
||||||
|
_db = _store.db
|
||||||
|
_initialized = True
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Read/lookup functions
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_organization(user_uuid: UUID) -> tuple[Org, str]:
|
||||||
|
"""Get the organization a user belongs to and their role name.
|
||||||
|
|
||||||
|
Raises ValueError if user not found.
|
||||||
|
|
||||||
|
Call sites:
|
||||||
|
- Get user's organization when updating user role (admin.py:493)
|
||||||
|
- Get user's organization for user credential listing (admin.py:530)
|
||||||
|
- Get user's organization for user details API (admin.py:579)
|
||||||
|
- Get user's organization for updating user display name (admin.py:721)
|
||||||
|
- Get user's organization for deleting user credential (admin.py:754)
|
||||||
|
- Get user's organization for deleting user session (admin.py:783)
|
||||||
|
"""
|
||||||
|
if user_uuid not in _db.users:
|
||||||
|
raise ValueError(f"User {user_uuid} not found")
|
||||||
|
role_uuid = _db.users[user_uuid].role
|
||||||
|
if role_uuid not in _db.roles:
|
||||||
|
raise ValueError(f"Role {role_uuid} not found")
|
||||||
|
role_data = _db.roles[role_uuid]
|
||||||
|
org_uuid = role_data.org
|
||||||
|
return _db.orgs[org_uuid], role_data.display_name
|
||||||
|
|
||||||
|
|
||||||
|
def get_organization_users(org_uuid: UUID) -> list[tuple[User, str]]:
|
||||||
|
"""Get all users in an organization with their role names.
|
||||||
|
|
||||||
|
Returns list of (User, role_display_name) tuples.
|
||||||
|
"""
|
||||||
|
role_map = {
|
||||||
|
rid: r.display_name for rid, r in _db.roles.items() if r.org == org_uuid
|
||||||
|
}
|
||||||
|
return [(u, role_map[u.role]) for u in _db.users.values() if u.role in role_map]
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_credential_ids(user_uuid: UUID) -> list[bytes]:
|
||||||
|
"""Get credential IDs for a user (for WebAuthn exclude lists).
|
||||||
|
|
||||||
|
Returns empty list if user has no credentials.
|
||||||
|
"""
|
||||||
|
return [c.credential_id for c in _db.credentials.values() if c.user == user_uuid]
|
||||||
|
|
||||||
|
|
||||||
|
def _reset_key(passphrase: str) -> bytes:
|
||||||
|
"""Hash a passphrase to bytes for reset token storage."""
|
||||||
|
if not _is_passphrase(passphrase):
|
||||||
|
raise ValueError(
|
||||||
|
"Trying to reset with a session token in place of a passphrase"
|
||||||
|
if len(passphrase) == 16
|
||||||
|
else "Invalid passphrase format"
|
||||||
|
)
|
||||||
|
return hashlib.sha512(passphrase.encode()).digest()[:9]
|
||||||
|
|
||||||
|
|
||||||
|
def get_reset_token(passphrase: str) -> ResetToken | None:
|
||||||
|
"""Get reset token by passphrase.
|
||||||
|
|
||||||
|
Call sites:
|
||||||
|
- Get reset token to validate it (authsession.py:34)
|
||||||
|
"""
|
||||||
|
key = _reset_key(passphrase)
|
||||||
|
return _db.reset_tokens.get(key)
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Context lookup
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def get_session_context(
|
||||||
|
session_key: str, host: str | None = None
|
||||||
|
) -> SessionContext | None:
|
||||||
|
"""Get full session context with effective permissions.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
session_key: The session key string
|
||||||
|
host: Optional host for binding/validation and domain-scoped permissions
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
SessionContext if valid, None if session not found, expired, or host mismatch
|
||||||
|
|
||||||
|
Call sites:
|
||||||
|
- Example usage in docstring (db/__init__.py:16)
|
||||||
|
- Get session context from auth token (util/permutil.py:43)
|
||||||
|
"""
|
||||||
|
|
||||||
|
if session_key not in _db.sessions:
|
||||||
|
return None
|
||||||
|
|
||||||
|
s = _db.sessions[session_key]
|
||||||
|
if s.expiry < datetime.now(timezone.utc):
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Validate host matches (sessions are always created with a host)
|
||||||
|
if host is not None and s.host != host:
|
||||||
|
# Session bound to different host
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Validate user exists
|
||||||
|
if s.user not in _db.users:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Validate role exists
|
||||||
|
role_uuid = _db.users[s.user].role
|
||||||
|
if role_uuid not in _db.roles:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Validate org exists
|
||||||
|
org_uuid = _db.roles[role_uuid].org
|
||||||
|
if org_uuid not in _db.orgs:
|
||||||
|
return None
|
||||||
|
|
||||||
|
session = _db.sessions[session_key]
|
||||||
|
user = _db.users[s.user]
|
||||||
|
role = _db.roles[role_uuid]
|
||||||
|
org = _db.orgs[org_uuid]
|
||||||
|
|
||||||
|
# Credential must exist (sessions are cascade-deleted when credential is deleted)
|
||||||
|
if s.credential not in _db.credentials:
|
||||||
|
return None
|
||||||
|
credential = _db.credentials[s.credential]
|
||||||
|
|
||||||
|
# Effective permissions: role's permissions that the org can grant
|
||||||
|
# Also filter by domain if host is provided
|
||||||
|
org_perm_uuids = {pid for pid, p in _db.permissions.items() if org_uuid in p.orgs}
|
||||||
|
normalized_host = normalize_host(host)
|
||||||
|
host_without_port = normalized_host.rsplit(":", 1)[0] if normalized_host else None
|
||||||
|
|
||||||
|
effective_perms = []
|
||||||
|
for perm_uuid in role.permission_set:
|
||||||
|
if perm_uuid not in org_perm_uuids:
|
||||||
|
continue
|
||||||
|
if perm_uuid not in _db.permissions:
|
||||||
|
continue
|
||||||
|
p = _db.permissions[perm_uuid]
|
||||||
|
# Check domain restriction
|
||||||
|
if p.domain is not None and p.domain != host_without_port:
|
||||||
|
continue
|
||||||
|
effective_perms.append(_db.permissions[perm_uuid])
|
||||||
|
|
||||||
|
return SessionContext(
|
||||||
|
session=session,
|
||||||
|
user=user,
|
||||||
|
org=org,
|
||||||
|
role=role,
|
||||||
|
credential=credential,
|
||||||
|
permissions=effective_perms,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Write operations (validate, modify, commit or raise ValueError)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def create_permission(perm: Permission, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Create a new permission."""
|
||||||
|
if perm.uuid in _db.permissions:
|
||||||
|
raise ValueError(f"Permission {perm.uuid} already exists")
|
||||||
|
with _db.transaction("admin:create_permission", ctx):
|
||||||
|
_db.permissions[perm.uuid] = perm
|
||||||
|
|
||||||
|
|
||||||
|
def update_permission(
|
||||||
|
uuid: UUID,
|
||||||
|
scope: str,
|
||||||
|
display_name: str,
|
||||||
|
domain: str | None = None,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update a permission's scope, display_name, and domain.
|
||||||
|
|
||||||
|
Only these fields can be modified; created_at and other metadata remain immutable.
|
||||||
|
"""
|
||||||
|
if uuid not in _db.permissions:
|
||||||
|
raise ValueError(f"Permission {uuid} not found")
|
||||||
|
with _db.transaction("admin:update_permission", ctx):
|
||||||
|
_db.permissions[uuid].scope = scope
|
||||||
|
_db.permissions[uuid].display_name = display_name
|
||||||
|
_db.permissions[uuid].domain = domain
|
||||||
|
|
||||||
|
|
||||||
|
def delete_permission(uuid: UUID, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Delete a permission and remove it from all roles."""
|
||||||
|
if uuid not in _db.permissions:
|
||||||
|
raise ValueError(f"Permission {uuid} not found")
|
||||||
|
with _db.transaction("admin:delete_permission", ctx):
|
||||||
|
# Remove this permission from all roles
|
||||||
|
for role in _db.roles.values():
|
||||||
|
role.permissions.pop(uuid, None)
|
||||||
|
del _db.permissions[uuid]
|
||||||
|
|
||||||
|
|
||||||
|
def create_org(org: Org, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Create a new organization with an Administration role.
|
||||||
|
|
||||||
|
Automatically creates an 'Administration' role with auth:org:admin permission.
|
||||||
|
"""
|
||||||
|
if org.uuid in _db.orgs:
|
||||||
|
raise ValueError(f"Organization {org.uuid} already exists")
|
||||||
|
with _db.transaction("admin:create_org", ctx):
|
||||||
|
new_org = Org(display_name=org.display_name)
|
||||||
|
_db.orgs[org.uuid] = new_org
|
||||||
|
new_org.uuid = org.uuid
|
||||||
|
# Create Administration role with org admin permission
|
||||||
|
|
||||||
|
admin_role_uuid = uuid7.create()
|
||||||
|
# Find the auth:org:admin permission UUID
|
||||||
|
org_admin_perm_uuid = None
|
||||||
|
for pid, p in _db.permissions.items():
|
||||||
|
if p.scope == "auth:org:admin":
|
||||||
|
org_admin_perm_uuid = pid
|
||||||
|
break
|
||||||
|
role_permissions = {org_admin_perm_uuid: True} if org_admin_perm_uuid else {}
|
||||||
|
admin_role = Role(
|
||||||
|
org=org.uuid,
|
||||||
|
display_name="Administration",
|
||||||
|
permissions=role_permissions,
|
||||||
|
)
|
||||||
|
admin_role.uuid = admin_role_uuid
|
||||||
|
_db.roles[admin_role_uuid] = admin_role
|
||||||
|
|
||||||
|
|
||||||
|
def update_org_name(
|
||||||
|
uuid: UUID,
|
||||||
|
display_name: str,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update organization display name."""
|
||||||
|
if uuid not in _db.orgs:
|
||||||
|
raise ValueError(f"Organization {uuid} not found")
|
||||||
|
with _db.transaction("admin:update_org_name", ctx):
|
||||||
|
_db.orgs[uuid].display_name = display_name
|
||||||
|
|
||||||
|
|
||||||
|
def delete_org(uuid: UUID, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Delete organization and all its roles/users."""
|
||||||
|
if uuid not in _db.orgs:
|
||||||
|
raise ValueError(f"Organization {uuid} not found")
|
||||||
|
with _db.transaction("admin:delete_org", ctx):
|
||||||
|
# Remove org from all permissions
|
||||||
|
for p in _db.permissions.values():
|
||||||
|
p.orgs.pop(uuid, None)
|
||||||
|
# Delete roles in this org
|
||||||
|
role_uuids = [rid for rid, r in _db.roles.items() if r.org == uuid]
|
||||||
|
for rid in role_uuids:
|
||||||
|
del _db.roles[rid]
|
||||||
|
# Delete users with those roles
|
||||||
|
user_uuids = [uid for uid, u in _db.users.items() if u.role in role_uuids]
|
||||||
|
for uid in user_uuids:
|
||||||
|
del _db.users[uid]
|
||||||
|
del _db.orgs[uuid]
|
||||||
|
|
||||||
|
|
||||||
|
def add_permission_to_org(
|
||||||
|
org_uuid: UUID,
|
||||||
|
permission_uuid: UUID,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Grant a permission to an organization by UUID."""
|
||||||
|
if org_uuid not in _db.orgs:
|
||||||
|
raise ValueError(f"Organization {org_uuid} not found")
|
||||||
|
|
||||||
|
if permission_uuid not in _db.permissions:
|
||||||
|
raise ValueError(f"Permission {permission_uuid} not found")
|
||||||
|
|
||||||
|
with _db.transaction("admin:add_permission_to_org", ctx):
|
||||||
|
_db.permissions[permission_uuid].orgs[org_uuid] = True
|
||||||
|
|
||||||
|
|
||||||
|
def remove_permission_from_org(
|
||||||
|
org_uuid: UUID,
|
||||||
|
permission_uuid: UUID,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Remove a permission from an organization by UUID."""
|
||||||
|
if org_uuid not in _db.orgs:
|
||||||
|
raise ValueError(f"Organization {org_uuid} not found")
|
||||||
|
|
||||||
|
if permission_uuid not in _db.permissions:
|
||||||
|
return # Permission not found, silently return
|
||||||
|
|
||||||
|
with _db.transaction("admin:remove_permission_from_org", ctx):
|
||||||
|
_db.permissions[permission_uuid].orgs.pop(org_uuid, None)
|
||||||
|
|
||||||
|
|
||||||
|
def create_role(role: Role, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Create a new role."""
|
||||||
|
if role.uuid in _db.roles:
|
||||||
|
raise ValueError(f"Role {role.uuid} already exists")
|
||||||
|
if role.org not in _db.orgs:
|
||||||
|
raise ValueError(f"Organization {role.org} not found")
|
||||||
|
with _db.transaction("admin:create_role", ctx):
|
||||||
|
_db.roles[role.uuid] = role
|
||||||
|
|
||||||
|
|
||||||
|
def update_role_name(
|
||||||
|
uuid: UUID,
|
||||||
|
display_name: str,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update role display name."""
|
||||||
|
if uuid not in _db.roles:
|
||||||
|
raise ValueError(f"Role {uuid} not found")
|
||||||
|
with _db.transaction("admin:update_role_name", ctx):
|
||||||
|
_db.roles[uuid].display_name = display_name
|
||||||
|
|
||||||
|
|
||||||
|
def add_permission_to_role(
|
||||||
|
role_uuid: UUID,
|
||||||
|
permission_uuid: UUID,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Add permission to role by UUID."""
|
||||||
|
if role_uuid not in _db.roles:
|
||||||
|
raise ValueError(f"Role {role_uuid} not found")
|
||||||
|
if permission_uuid not in _db.permissions:
|
||||||
|
raise ValueError(f"Permission {permission_uuid} not found")
|
||||||
|
with _db.transaction("admin:add_permission_to_role", ctx):
|
||||||
|
_db.roles[role_uuid].permissions[permission_uuid] = True
|
||||||
|
|
||||||
|
|
||||||
|
def remove_permission_from_role(
|
||||||
|
role_uuid: UUID,
|
||||||
|
permission_uuid: UUID,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Remove permission from role by UUID."""
|
||||||
|
if role_uuid not in _db.roles:
|
||||||
|
raise ValueError(f"Role {role_uuid} not found")
|
||||||
|
with _db.transaction("admin:remove_permission_from_role", ctx):
|
||||||
|
_db.roles[role_uuid].permissions.pop(permission_uuid, None)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_role(uuid: UUID, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Delete a role."""
|
||||||
|
if uuid not in _db.roles:
|
||||||
|
raise ValueError(f"Role {uuid} not found")
|
||||||
|
# Check no users have this role
|
||||||
|
if any(u.role == uuid for u in _db.users.values()):
|
||||||
|
raise ValueError(f"Cannot delete role {uuid}: users still assigned")
|
||||||
|
with _db.transaction("admin:delete_role", ctx):
|
||||||
|
del _db.roles[uuid]
|
||||||
|
|
||||||
|
|
||||||
|
def create_user(new_user: User, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Create a new user."""
|
||||||
|
if new_user.uuid in _db.users:
|
||||||
|
raise ValueError(f"User {new_user.uuid} already exists")
|
||||||
|
if new_user.role not in _db.roles:
|
||||||
|
raise ValueError(f"Role {new_user.role} not found")
|
||||||
|
with _db.transaction("admin:create_user", ctx):
|
||||||
|
_db.users[new_user.uuid] = new_user
|
||||||
|
|
||||||
|
|
||||||
|
def update_user_display_name(
|
||||||
|
uuid: UUID,
|
||||||
|
display_name: str,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update user display name.
|
||||||
|
|
||||||
|
The acting user should be logged via ctx.
|
||||||
|
For self-service (user updating own name), pass user's ctx.
|
||||||
|
For admin operations, pass admin's ctx.
|
||||||
|
"""
|
||||||
|
if isinstance(uuid, str):
|
||||||
|
uuid = UUID(uuid)
|
||||||
|
if uuid not in _db.users:
|
||||||
|
raise ValueError(f"User {uuid} not found")
|
||||||
|
with _db.transaction("update_user_display_name", ctx):
|
||||||
|
_db.users[uuid].display_name = display_name
|
||||||
|
|
||||||
|
|
||||||
|
def update_user_role(
|
||||||
|
uuid: UUID,
|
||||||
|
role_uuid: UUID,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update user's role."""
|
||||||
|
if uuid not in _db.users:
|
||||||
|
raise ValueError(f"User {uuid} not found")
|
||||||
|
if role_uuid not in _db.roles:
|
||||||
|
raise ValueError(f"Role {role_uuid} not found")
|
||||||
|
with _db.transaction("admin:update_user_role", ctx):
|
||||||
|
_db.users[uuid].role = role_uuid
|
||||||
|
|
||||||
|
|
||||||
|
def update_user_role_in_organization(
|
||||||
|
user_uuid: UUID,
|
||||||
|
role_name: str,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update user's role by role name within their current organization."""
|
||||||
|
if user_uuid not in _db.users:
|
||||||
|
raise ValueError(f"User {user_uuid} not found")
|
||||||
|
current_role_uuid = _db.users[user_uuid].role
|
||||||
|
if current_role_uuid not in _db.roles:
|
||||||
|
raise ValueError("Current role not found")
|
||||||
|
org_uuid = _db.roles[current_role_uuid].org
|
||||||
|
# Find role by name in the same org
|
||||||
|
new_role_uuid = None
|
||||||
|
for rid, r in _db.roles.items():
|
||||||
|
if r.org == org_uuid and r.display_name == role_name:
|
||||||
|
new_role_uuid = rid
|
||||||
|
break
|
||||||
|
if new_role_uuid is None:
|
||||||
|
raise ValueError(f"Role '{role_name}' not found in organization")
|
||||||
|
with _db.transaction("admin:update_user_role", ctx):
|
||||||
|
_db.users[user_uuid].role = new_role_uuid
|
||||||
|
|
||||||
|
|
||||||
|
def delete_user(uuid: UUID, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Delete user and their credentials/sessions."""
|
||||||
|
if uuid not in _db.users:
|
||||||
|
raise ValueError(f"User {uuid} not found")
|
||||||
|
with _db.transaction("admin:delete_user", ctx):
|
||||||
|
# Delete credentials
|
||||||
|
cred_uuids = [cid for cid, c in _db.credentials.items() if c.user == uuid]
|
||||||
|
for cid in cred_uuids:
|
||||||
|
del _db.credentials[cid]
|
||||||
|
# Delete sessions
|
||||||
|
sess_keys = [k for k, s in _db.sessions.items() if s.user == uuid]
|
||||||
|
for k in sess_keys:
|
||||||
|
del _db.sessions[k]
|
||||||
|
# Delete reset tokens
|
||||||
|
token_keys = [k for k, t in _db.reset_tokens.items() if t.user == uuid]
|
||||||
|
for k in token_keys:
|
||||||
|
del _db.reset_tokens[k]
|
||||||
|
del _db.users[uuid]
|
||||||
|
|
||||||
|
|
||||||
|
def create_credential(cred: Credential, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Create a new credential."""
|
||||||
|
if cred.uuid in _db.credentials:
|
||||||
|
raise ValueError(f"Credential {cred.uuid} already exists")
|
||||||
|
if cred.user not in _db.users:
|
||||||
|
raise ValueError(f"User {cred.user} not found")
|
||||||
|
with _db.transaction("create_credential", ctx):
|
||||||
|
_db.credentials[cred.uuid] = cred
|
||||||
|
|
||||||
|
|
||||||
|
def update_credential_sign_count(
|
||||||
|
uuid: UUID,
|
||||||
|
sign_count: int,
|
||||||
|
last_used: datetime | None = None,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update credential sign count and last_used."""
|
||||||
|
if uuid not in _db.credentials:
|
||||||
|
raise ValueError(f"Credential {uuid} not found")
|
||||||
|
with _db.transaction("update_credential_sign_count", ctx):
|
||||||
|
_db.credentials[uuid].sign_count = sign_count
|
||||||
|
if last_used:
|
||||||
|
_db.credentials[uuid].last_used = last_used
|
||||||
|
|
||||||
|
|
||||||
|
def delete_credential(
|
||||||
|
uuid: UUID,
|
||||||
|
user_uuid: UUID | None = None,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Delete a credential and all sessions using it.
|
||||||
|
|
||||||
|
If user_uuid is provided, validates that the credential belongs to that user.
|
||||||
|
"""
|
||||||
|
if uuid not in _db.credentials:
|
||||||
|
raise ValueError(f"Credential {uuid} not found")
|
||||||
|
if user_uuid is not None:
|
||||||
|
cred_user = _db.credentials[uuid].user
|
||||||
|
if cred_user != user_uuid:
|
||||||
|
raise ValueError(f"Credential {uuid} does not belong to user {user_uuid}")
|
||||||
|
with _db.transaction("delete_credential", ctx):
|
||||||
|
# Delete all sessions using this credential
|
||||||
|
keys = [k for k, s in _db.sessions.items() if s.credential == uuid]
|
||||||
|
for k in keys:
|
||||||
|
del _db.sessions[k]
|
||||||
|
del _db.credentials[uuid]
|
||||||
|
|
||||||
|
|
||||||
|
def create_session(
|
||||||
|
key: str,
|
||||||
|
user_uuid: UUID,
|
||||||
|
credential_uuid: UUID,
|
||||||
|
host: str,
|
||||||
|
ip: str,
|
||||||
|
user_agent: str,
|
||||||
|
expiry: datetime,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Create a new session."""
|
||||||
|
if key in _db.sessions:
|
||||||
|
raise ValueError("Session already exists")
|
||||||
|
if user_uuid not in _db.users:
|
||||||
|
raise ValueError(f"User {user_uuid} not found")
|
||||||
|
if credential_uuid not in _db.credentials:
|
||||||
|
raise ValueError(f"Credential {credential_uuid} not found")
|
||||||
|
with _db.transaction("create_session", ctx):
|
||||||
|
_db.sessions[key] = Session(
|
||||||
|
user=user_uuid,
|
||||||
|
credential=credential_uuid,
|
||||||
|
host=host,
|
||||||
|
ip=ip,
|
||||||
|
user_agent=user_agent,
|
||||||
|
expiry=expiry,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def update_session(
|
||||||
|
key: str,
|
||||||
|
host: str | None = None,
|
||||||
|
ip: str | None = None,
|
||||||
|
user_agent: str | None = None,
|
||||||
|
expiry: datetime | None = None,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update session metadata."""
|
||||||
|
if key not in _db.sessions:
|
||||||
|
raise ValueError("Session not found")
|
||||||
|
with _db.transaction("update_session", ctx):
|
||||||
|
s = _db.sessions[key]
|
||||||
|
if host is not None:
|
||||||
|
s.host = host
|
||||||
|
if ip is not None:
|
||||||
|
s.ip = ip
|
||||||
|
if user_agent is not None:
|
||||||
|
s.user_agent = user_agent
|
||||||
|
if expiry is not None:
|
||||||
|
s.expiry = expiry
|
||||||
|
|
||||||
|
|
||||||
|
def set_session_host(key: str, host: str, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Set the host for a session (first-time binding)."""
|
||||||
|
update_session(key, host=host, ctx=ctx)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_session(key: str, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Delete a session.
|
||||||
|
|
||||||
|
The acting user should be logged via ctx.
|
||||||
|
For user logout, pass ctx of the user's session.
|
||||||
|
For admin terminating a session, pass admin's ctx.
|
||||||
|
"""
|
||||||
|
if key not in _db.sessions:
|
||||||
|
raise ValueError("Session not found")
|
||||||
|
with _db.transaction("delete_session", ctx):
|
||||||
|
del _db.sessions[key]
|
||||||
|
|
||||||
|
|
||||||
|
def delete_sessions_for_user(
|
||||||
|
user_uuid: UUID, *, ctx: SessionContext | None = None
|
||||||
|
) -> None:
|
||||||
|
"""Delete all sessions for a user.
|
||||||
|
|
||||||
|
The acting user should be logged via ctx.
|
||||||
|
For user logout-all, pass ctx of the user's session.
|
||||||
|
For admin bulk termination, pass admin's ctx.
|
||||||
|
"""
|
||||||
|
with _db.transaction("admin:delete_sessions_for_user", ctx):
|
||||||
|
keys = [k for k, s in _db.sessions.items() if s.user == user_uuid]
|
||||||
|
for k in keys:
|
||||||
|
del _db.sessions[k]
|
||||||
|
|
||||||
|
|
||||||
|
def create_reset_token(
|
||||||
|
passphrase: str,
|
||||||
|
user_uuid: UUID,
|
||||||
|
expiry: datetime,
|
||||||
|
token_type: str,
|
||||||
|
*,
|
||||||
|
ctx: SessionContext | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Create a reset token from a passphrase.
|
||||||
|
|
||||||
|
The acting user should be logged via ctx.
|
||||||
|
For self-service (user creating own recovery link), pass user's ctx.
|
||||||
|
For admin operations, pass admin's ctx.
|
||||||
|
For system operations (bootstrap), pass neither to log no user.
|
||||||
|
"""
|
||||||
|
key = _reset_key(passphrase)
|
||||||
|
if key in _db.reset_tokens:
|
||||||
|
raise ValueError("Reset token already exists")
|
||||||
|
if user_uuid not in _db.users:
|
||||||
|
raise ValueError(f"User {user_uuid} not found")
|
||||||
|
with _db.transaction("create_reset_token", ctx):
|
||||||
|
_db.reset_tokens[key] = ResetToken(
|
||||||
|
user=user_uuid, expiry=expiry, token_type=token_type
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_reset_token(key: bytes, *, ctx: SessionContext | None = None) -> None:
|
||||||
|
"""Delete a reset token."""
|
||||||
|
if key not in _db.reset_tokens:
|
||||||
|
raise ValueError("Reset token not found")
|
||||||
|
with _db.transaction("delete_reset_token", ctx):
|
||||||
|
del _db.reset_tokens[key]
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Cleanup (called by background task)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def cleanup_expired() -> int:
|
||||||
|
"""Remove expired sessions and reset tokens. Returns count removed."""
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
count = 0
|
||||||
|
with _db.transaction("expiry"):
|
||||||
|
expired_sessions = [k for k, s in _db.sessions.items() if s.expiry < now]
|
||||||
|
for k in expired_sessions:
|
||||||
|
del _db.sessions[k]
|
||||||
|
count += 1
|
||||||
|
expired_tokens = [k for k, t in _db.reset_tokens.items() if t.expiry < now]
|
||||||
|
for k in expired_tokens:
|
||||||
|
del _db.reset_tokens[k]
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Composite operations (used by app code)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _create_token() -> str:
|
||||||
|
"""Generate a 16-character URL-safe session token."""
|
||||||
|
return secrets.token_urlsafe(12)
|
||||||
|
|
||||||
|
|
||||||
|
def login(
|
||||||
|
user_uuid: UUID,
|
||||||
|
credential_uuid: UUID,
|
||||||
|
sign_count: int,
|
||||||
|
host: str,
|
||||||
|
ip: str,
|
||||||
|
user_agent: str,
|
||||||
|
expiry: datetime,
|
||||||
|
) -> str:
|
||||||
|
"""Update user/credential on login and create session in a single transaction.
|
||||||
|
|
||||||
|
Updates:
|
||||||
|
- user.last_seen, user.visits
|
||||||
|
- credential.sign_count, credential.last_used
|
||||||
|
Creates:
|
||||||
|
- new session
|
||||||
|
|
||||||
|
Returns the generated session token.
|
||||||
|
"""
|
||||||
|
if isinstance(user_uuid, str):
|
||||||
|
user_uuid = UUID(user_uuid)
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
if user_uuid not in _db.users:
|
||||||
|
raise ValueError(f"User {user_uuid} not found")
|
||||||
|
if credential_uuid not in _db.credentials:
|
||||||
|
raise ValueError(f"Credential {credential_uuid} not found")
|
||||||
|
|
||||||
|
session_key = _create_token()
|
||||||
|
user_str = str(user_uuid)
|
||||||
|
with _db.transaction("login", user=user_str):
|
||||||
|
# Update user
|
||||||
|
_db.users[user_uuid].last_seen = now
|
||||||
|
_db.users[user_uuid].visits += 1
|
||||||
|
# Update credential
|
||||||
|
_db.credentials[credential_uuid].sign_count = sign_count
|
||||||
|
_db.credentials[credential_uuid].last_used = now
|
||||||
|
# Create session
|
||||||
|
_db.sessions[session_key] = Session(
|
||||||
|
user=user_uuid,
|
||||||
|
credential=credential_uuid,
|
||||||
|
host=host,
|
||||||
|
ip=ip,
|
||||||
|
user_agent=user_agent,
|
||||||
|
expiry=expiry,
|
||||||
|
)
|
||||||
|
return session_key
|
||||||
|
|
||||||
|
|
||||||
|
def create_credential_session(
|
||||||
|
user_uuid: UUID,
|
||||||
|
credential: Credential,
|
||||||
|
host: str,
|
||||||
|
ip: str,
|
||||||
|
user_agent: str,
|
||||||
|
display_name: str | None = None,
|
||||||
|
reset_key: bytes | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Create a credential and session together, optionally consuming a reset token.
|
||||||
|
|
||||||
|
Used during registration to atomically:
|
||||||
|
1. Update user display_name if provided
|
||||||
|
2. Create the credential
|
||||||
|
3. Create the session
|
||||||
|
4. Delete the reset token if provided
|
||||||
|
|
||||||
|
Returns the generated session token.
|
||||||
|
"""
|
||||||
|
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
expiry = now + SESSION_LIFETIME
|
||||||
|
session_key = _create_token()
|
||||||
|
|
||||||
|
if user_uuid not in _db.users:
|
||||||
|
raise ValueError(f"User {user_uuid} not found")
|
||||||
|
|
||||||
|
user_str = str(user_uuid)
|
||||||
|
with _db.transaction("create_credential_session", user=user_str):
|
||||||
|
# Update display name if provided
|
||||||
|
if display_name:
|
||||||
|
_db.users[user_uuid].display_name = display_name
|
||||||
|
|
||||||
|
# Create credential
|
||||||
|
_db.credentials[credential.uuid] = credential
|
||||||
|
|
||||||
|
# Create session
|
||||||
|
_db.sessions[session_key] = Session(
|
||||||
|
user=user_uuid,
|
||||||
|
credential=credential.uuid,
|
||||||
|
host=host,
|
||||||
|
ip=ip,
|
||||||
|
user_agent=user_agent,
|
||||||
|
expiry=expiry,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Delete reset token if provided
|
||||||
|
if reset_key:
|
||||||
|
if reset_key in _db.reset_tokens:
|
||||||
|
del _db.reset_tokens[reset_key]
|
||||||
|
return session_key
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Bootstrap (single transaction for initial system setup)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap(
|
||||||
|
org_name: str = "Organization",
|
||||||
|
admin_name: str = "Admin",
|
||||||
|
reset_passphrase: str | None = None,
|
||||||
|
reset_expiry: datetime | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""Bootstrap the entire system in a single transaction.
|
||||||
|
|
||||||
|
Creates:
|
||||||
|
- auth:admin permission (Master Admin)
|
||||||
|
- auth:org:admin permission (Org Admin)
|
||||||
|
- Organization with Administration role
|
||||||
|
- Admin user with Administration role
|
||||||
|
- Reset token for admin registration
|
||||||
|
|
||||||
|
This is the only way to create a new database file (besides migrate).
|
||||||
|
All data is created atomically - if any step fails, nothing is written.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
org_name: Display name for the organization (default: "Organization")
|
||||||
|
admin_name: Display name for the admin user (default: "Admin")
|
||||||
|
reset_passphrase: Passphrase for the reset token (generated if not provided)
|
||||||
|
reset_expiry: Expiry datetime for the reset token (default: 14 days)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The reset passphrase for admin registration.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Check if system is already bootstrapped
|
||||||
|
for p in _db.permissions.values():
|
||||||
|
if p.scope == "auth:admin":
|
||||||
|
raise ValueError(
|
||||||
|
"System already bootstrapped (auth:admin permission exists)"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Generate UUIDs upfront
|
||||||
|
perm_admin_uuid = uuid7.create()
|
||||||
|
perm_org_admin_uuid = uuid7.create()
|
||||||
|
org_uuid = uuid7.create()
|
||||||
|
role_uuid = uuid7.create()
|
||||||
|
user_uuid = uuid7.create()
|
||||||
|
|
||||||
|
# Generate reset token components
|
||||||
|
if reset_passphrase is None:
|
||||||
|
reset_passphrase = generate_passphrase()
|
||||||
|
if reset_expiry is None:
|
||||||
|
from paskia.authsession import reset_expires # noqa: PLC0415
|
||||||
|
|
||||||
|
reset_expiry = reset_expires()
|
||||||
|
reset_key = _reset_key(reset_passphrase)
|
||||||
|
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
with _db.transaction("bootstrap"):
|
||||||
|
# Create auth:admin permission
|
||||||
|
perm_admin = Permission(
|
||||||
|
scope="auth:admin",
|
||||||
|
display_name="Master Admin",
|
||||||
|
orgs={org_uuid: True}, # Grant to org
|
||||||
|
)
|
||||||
|
perm_admin.uuid = perm_admin_uuid
|
||||||
|
_db.permissions[perm_admin_uuid] = perm_admin
|
||||||
|
|
||||||
|
# Create auth:org:admin permission
|
||||||
|
perm_org_admin = Permission(
|
||||||
|
scope="auth:org:admin",
|
||||||
|
display_name="Org Admin",
|
||||||
|
orgs={org_uuid: True}, # Grant to org
|
||||||
|
)
|
||||||
|
perm_org_admin.uuid = perm_org_admin_uuid
|
||||||
|
_db.permissions[perm_org_admin_uuid] = perm_org_admin
|
||||||
|
|
||||||
|
# Create organization
|
||||||
|
new_org = Org(display_name=org_name)
|
||||||
|
new_org.uuid = org_uuid
|
||||||
|
_db.orgs[org_uuid] = new_org
|
||||||
|
|
||||||
|
# Create Administration role with both permissions
|
||||||
|
admin_role = Role(
|
||||||
|
org=org_uuid,
|
||||||
|
display_name="Administration",
|
||||||
|
permissions={perm_admin_uuid: True, perm_org_admin_uuid: True},
|
||||||
|
)
|
||||||
|
admin_role.uuid = role_uuid
|
||||||
|
_db.roles[role_uuid] = admin_role
|
||||||
|
|
||||||
|
# Create admin user
|
||||||
|
admin_user = User(
|
||||||
|
display_name=admin_name,
|
||||||
|
role=role_uuid,
|
||||||
|
created_at=now,
|
||||||
|
last_seen=None,
|
||||||
|
visits=0,
|
||||||
|
)
|
||||||
|
admin_user.uuid = user_uuid
|
||||||
|
_db.users[user_uuid] = admin_user
|
||||||
|
|
||||||
|
# Create reset token
|
||||||
|
_db.reset_tokens[reset_key] = ResetToken(
|
||||||
|
user=user_uuid,
|
||||||
|
expiry=reset_expiry,
|
||||||
|
token_type="admin bootstrap",
|
||||||
|
)
|
||||||
|
|
||||||
|
return reset_passphrase
|
||||||
-1424
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,272 @@
|
|||||||
|
from datetime import datetime, timezone
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
import msgspec
|
||||||
|
import uuid7
|
||||||
|
|
||||||
|
# Sentinel for uuid fields before they are set by create() or DB post init
|
||||||
|
_UUID_UNSET = UUID(int=0)
|
||||||
|
|
||||||
|
|
||||||
|
class Permission(msgspec.Struct, dict=True, omit_defaults=True):
|
||||||
|
"""Permission data structure.
|
||||||
|
|
||||||
|
Mutable fields: scope, display_name, domain, orgs
|
||||||
|
Immutable fields: None (all fields can be updated via update_permission)
|
||||||
|
uuid is generated at creation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
scope: str # Permission scope identifier (e.g. "auth:admin", "myapp:write")
|
||||||
|
display_name: str
|
||||||
|
domain: str | None = None # If set, scopes permission to this domain
|
||||||
|
orgs: dict[UUID, bool] = {} # org_uuid -> True (which orgs can grant this)
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
self.uuid: UUID = _UUID_UNSET # Convenience field, not serialized
|
||||||
|
|
||||||
|
@property
|
||||||
|
def org_set(self) -> set[UUID]:
|
||||||
|
"""Get orgs that can grant this permission as a set."""
|
||||||
|
return set(self.orgs.keys())
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create(
|
||||||
|
cls,
|
||||||
|
scope: str,
|
||||||
|
display_name: str,
|
||||||
|
domain: str | None = None,
|
||||||
|
) -> "Permission":
|
||||||
|
"""Create a new Permission with auto-generated uuid7."""
|
||||||
|
perm = cls(
|
||||||
|
scope=scope,
|
||||||
|
display_name=display_name,
|
||||||
|
domain=domain,
|
||||||
|
)
|
||||||
|
perm.uuid = uuid7.create()
|
||||||
|
return perm
|
||||||
|
|
||||||
|
|
||||||
|
class Role(msgspec.Struct, dict=True, omit_defaults=True):
|
||||||
|
"""Role data structure.
|
||||||
|
|
||||||
|
Mutable fields: display_name, permissions
|
||||||
|
Immutable fields: org (set at creation, never modified)
|
||||||
|
uuid is generated at creation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
org: UUID
|
||||||
|
display_name: str
|
||||||
|
permissions: dict[UUID, bool] = {} # permission_uuid -> True
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
self.uuid: UUID = _UUID_UNSET # Convenience field, not serialized
|
||||||
|
|
||||||
|
@property
|
||||||
|
def permission_set(self) -> set[UUID]:
|
||||||
|
"""Get permissions as a set of UUIDs."""
|
||||||
|
return set(self.permissions.keys())
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create(
|
||||||
|
cls,
|
||||||
|
org: UUID,
|
||||||
|
display_name: str,
|
||||||
|
permissions: set[UUID] | None = None,
|
||||||
|
) -> "Role":
|
||||||
|
"""Create a new Role with auto-generated uuid7."""
|
||||||
|
role = cls(
|
||||||
|
org=org,
|
||||||
|
display_name=display_name,
|
||||||
|
permissions={p: True for p in (permissions or set())},
|
||||||
|
)
|
||||||
|
role.uuid = uuid7.create()
|
||||||
|
return role
|
||||||
|
|
||||||
|
|
||||||
|
class Org(msgspec.Struct, dict=True):
|
||||||
|
"""Organization data structure."""
|
||||||
|
|
||||||
|
display_name: str
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
self.uuid: UUID = _UUID_UNSET # Convenience field, not serialized
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create(cls, display_name: str) -> "Org":
|
||||||
|
"""Create a new Org with auto-generated uuid7."""
|
||||||
|
org = cls(display_name=display_name)
|
||||||
|
org.uuid = uuid7.create()
|
||||||
|
return org
|
||||||
|
|
||||||
|
|
||||||
|
class User(msgspec.Struct, dict=True):
|
||||||
|
"""User data structure.
|
||||||
|
|
||||||
|
Mutable fields: display_name, role, last_seen, visits
|
||||||
|
Immutable fields: created_at (set at creation, never modified)
|
||||||
|
uuid is derived from created_at using uuid7.
|
||||||
|
"""
|
||||||
|
|
||||||
|
display_name: str
|
||||||
|
role: UUID
|
||||||
|
created_at: datetime
|
||||||
|
last_seen: datetime | None = None
|
||||||
|
visits: int = 0
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
self.uuid: UUID = _UUID_UNSET # Convenience field, not serialized
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create(
|
||||||
|
cls,
|
||||||
|
display_name: str,
|
||||||
|
role: UUID,
|
||||||
|
created_at: datetime | None = None,
|
||||||
|
) -> "User":
|
||||||
|
"""Create a new User with auto-generated uuid7."""
|
||||||
|
|
||||||
|
user = cls(
|
||||||
|
display_name=display_name,
|
||||||
|
role=role,
|
||||||
|
created_at=created_at or datetime.now(timezone.utc),
|
||||||
|
)
|
||||||
|
user.uuid = uuid7.create(user.created_at)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
class Credential(msgspec.Struct, dict=True):
|
||||||
|
"""Credential (passkey) data structure.
|
||||||
|
|
||||||
|
Mutable fields: sign_count, last_used, last_verified
|
||||||
|
Immutable fields: credential_id, user, aaguid, public_key, created_at
|
||||||
|
uuid is derived from created_at using uuid7.
|
||||||
|
"""
|
||||||
|
|
||||||
|
credential_id: bytes # Long binary ID from the authenticator
|
||||||
|
user: UUID
|
||||||
|
aaguid: UUID
|
||||||
|
public_key: bytes
|
||||||
|
sign_count: int
|
||||||
|
created_at: datetime
|
||||||
|
last_used: datetime | None = None
|
||||||
|
last_verified: datetime | None = None
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
self.uuid: UUID = _UUID_UNSET # Convenience field, not serialized
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def create(
|
||||||
|
cls,
|
||||||
|
credential_id: bytes,
|
||||||
|
user: UUID,
|
||||||
|
aaguid: UUID,
|
||||||
|
public_key: bytes,
|
||||||
|
sign_count: int,
|
||||||
|
created_at: datetime | None = None,
|
||||||
|
) -> "Credential":
|
||||||
|
"""Create a new Credential with auto-generated uuid7."""
|
||||||
|
now = created_at or datetime.now(timezone.utc)
|
||||||
|
cred = cls(
|
||||||
|
credential_id=credential_id,
|
||||||
|
user=user,
|
||||||
|
aaguid=aaguid,
|
||||||
|
public_key=public_key,
|
||||||
|
sign_count=sign_count,
|
||||||
|
created_at=now,
|
||||||
|
last_used=now,
|
||||||
|
last_verified=now,
|
||||||
|
)
|
||||||
|
cred.uuid = uuid7.create(now)
|
||||||
|
return cred
|
||||||
|
|
||||||
|
|
||||||
|
class Session(msgspec.Struct, dict=True):
|
||||||
|
"""Session data structure.
|
||||||
|
|
||||||
|
Mutable fields: expiry (updated on session refresh)
|
||||||
|
Immutable fields: user, credential, host, ip, user_agent
|
||||||
|
key is stored in the dict key, not in the struct.
|
||||||
|
"""
|
||||||
|
|
||||||
|
user: UUID
|
||||||
|
credential: UUID
|
||||||
|
host: str
|
||||||
|
ip: str
|
||||||
|
user_agent: str
|
||||||
|
expiry: datetime
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
self.key: str = "" # Convenience field, not serialized
|
||||||
|
|
||||||
|
def metadata(self) -> dict:
|
||||||
|
"""Return session metadata for backwards compatibility."""
|
||||||
|
return {
|
||||||
|
"ip": self.ip,
|
||||||
|
"user_agent": self.user_agent,
|
||||||
|
"expiry": self.expiry.isoformat(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ResetToken(msgspec.Struct, dict=True):
|
||||||
|
"""Reset/device-addition token data structure.
|
||||||
|
|
||||||
|
Immutable fields: All fields (tokens are created and deleted, never modified)
|
||||||
|
key is stored in the dict key, not in the struct.
|
||||||
|
"""
|
||||||
|
|
||||||
|
user: UUID
|
||||||
|
expiry: datetime
|
||||||
|
token_type: str
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
self.key: bytes = b"" # Convenience field, not serialized
|
||||||
|
|
||||||
|
|
||||||
|
class SessionContext(msgspec.Struct):
|
||||||
|
session: Session
|
||||||
|
user: User
|
||||||
|
org: Org
|
||||||
|
role: Role
|
||||||
|
credential: Credential
|
||||||
|
permissions: list[Permission] = []
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Database storage structure
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class DB(msgspec.Struct, dict=True, omit_defaults=False):
|
||||||
|
"""In-memory database. Access fields directly for reads."""
|
||||||
|
|
||||||
|
permissions: dict[UUID, Permission] = {}
|
||||||
|
orgs: dict[UUID, Org] = {}
|
||||||
|
roles: dict[UUID, Role] = {}
|
||||||
|
users: dict[UUID, User] = {}
|
||||||
|
credentials: dict[UUID, Credential] = {}
|
||||||
|
sessions: dict[str, Session] = {}
|
||||||
|
reset_tokens: dict[bytes, ResetToken] = {}
|
||||||
|
v: int = 0
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
# Store reference for persistence (not serialized)
|
||||||
|
self._store = None
|
||||||
|
# Set the key fields on all stored objects
|
||||||
|
for uuid, perm in self.permissions.items():
|
||||||
|
perm.uuid = uuid
|
||||||
|
for uuid, org in self.orgs.items():
|
||||||
|
org.uuid = uuid
|
||||||
|
for uuid, role in self.roles.items():
|
||||||
|
role.uuid = uuid
|
||||||
|
for uuid, user in self.users.items():
|
||||||
|
user.uuid = uuid
|
||||||
|
for uuid, cred in self.credentials.items():
|
||||||
|
cred.uuid = uuid
|
||||||
|
for key, session in self.sessions.items():
|
||||||
|
session.key = key
|
||||||
|
for key, token in self.reset_tokens.items():
|
||||||
|
token.key = key
|
||||||
|
|
||||||
|
def transaction(self, action, ctx=None, *, user=None):
|
||||||
|
"""Wrap writes in transaction. Delegates to JsonlStore."""
|
||||||
|
return self._store.transaction(action, ctx, user=user)
|
||||||
+76
-176
@@ -1,16 +1,31 @@
|
|||||||
import argparse
|
import argparse
|
||||||
import asyncio
|
import asyncio
|
||||||
import ipaddress
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
import uvicorn
|
from fastapi_vue.hostutil import parse_endpoint
|
||||||
|
from uvicorn import Config, Server
|
||||||
|
|
||||||
|
from paskia import globals as _globals
|
||||||
|
from paskia.bootstrap import bootstrap_if_needed
|
||||||
|
from paskia.config import PaskiaConfig
|
||||||
|
from paskia.db.background import flush
|
||||||
|
from paskia.fastapi import app as fastapi_app
|
||||||
|
from paskia.fastapi import reset as reset_cmd
|
||||||
|
from paskia.util import startupbox
|
||||||
from paskia.util.hostutil import normalize_origin
|
from paskia.util.hostutil import normalize_origin
|
||||||
|
|
||||||
DEFAULT_HOST = "localhost"
|
DEFAULT_PORT = 4401
|
||||||
DEFAULT_SERVE_PORT = 4401
|
|
||||||
|
EPILOG = """\
|
||||||
|
Examples:
|
||||||
|
paskia # localhost:4401
|
||||||
|
paskia :8080 # All interfaces, port 8080
|
||||||
|
paskia unix:/tmp/paskia.sock
|
||||||
|
paskia reset [user] # Generate passkey reset link
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
def is_subdomain(sub: str, domain: str) -> bool:
|
def is_subdomain(sub: str, domain: str) -> bool:
|
||||||
@@ -34,80 +49,6 @@ def validate_auth_host(auth_host: str, rp_id: str) -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def parse_endpoint(
|
|
||||||
value: str | None, default_port: int
|
|
||||||
) -> tuple[str | None, int | None, str | None, bool]:
|
|
||||||
"""Parse an endpoint using stdlib (urllib.parse, ipaddress).
|
|
||||||
|
|
||||||
Returns (host, port, uds_path). If uds_path is not None, host/port are None.
|
|
||||||
|
|
||||||
Supported forms:
|
|
||||||
- host[:port]
|
|
||||||
- :port (uses default host)
|
|
||||||
- [ipv6][:port] (bracketed for port usage)
|
|
||||||
- ipv6 (unbracketed, no port allowed -> default port)
|
|
||||||
- unix:/path/to/socket.sock
|
|
||||||
- None -> defaults (localhost:4401)
|
|
||||||
|
|
||||||
Notes:
|
|
||||||
- For IPv6 with an explicit port you MUST use brackets (e.g. [::1]:8080)
|
|
||||||
- Unbracketed IPv6 like ::1 implies the default port.
|
|
||||||
"""
|
|
||||||
if not value:
|
|
||||||
return DEFAULT_HOST, default_port, None, False
|
|
||||||
|
|
||||||
# Port only (numeric) -> localhost:port
|
|
||||||
if value.isdigit():
|
|
||||||
try:
|
|
||||||
port_only = int(value)
|
|
||||||
except ValueError: # pragma: no cover (isdigit guards)
|
|
||||||
raise SystemExit(f"Invalid port '{value}'")
|
|
||||||
return DEFAULT_HOST, port_only, None, False
|
|
||||||
|
|
||||||
# Leading colon :port -> bind all interfaces (0.0.0.0 + ::)
|
|
||||||
if value.startswith(":") and value != ":":
|
|
||||||
port_part = value[1:]
|
|
||||||
if not port_part.isdigit():
|
|
||||||
raise SystemExit(f"Invalid port in '{value}'")
|
|
||||||
return None, int(port_part), None, True
|
|
||||||
|
|
||||||
# UNIX domain socket
|
|
||||||
if value.startswith("unix:"):
|
|
||||||
uds_path = value[5:] or None
|
|
||||||
if uds_path is None:
|
|
||||||
raise SystemExit("unix: path must not be empty")
|
|
||||||
return None, None, uds_path, False
|
|
||||||
|
|
||||||
# Unbracketed IPv6 (cannot safely contain a port) -> detect by multiple colons
|
|
||||||
if value.count(":") > 1 and not value.startswith("["):
|
|
||||||
try:
|
|
||||||
ipaddress.IPv6Address(value)
|
|
||||||
except ValueError as e: # pragma: no cover
|
|
||||||
raise SystemExit(f"Invalid IPv6 address '{value}': {e}")
|
|
||||||
return value, default_port, None, False
|
|
||||||
|
|
||||||
# Use urllib.parse for everything else (host[:port], :port, [ipv6][:port])
|
|
||||||
parsed = urlparse(f"//{value}") # // prefix lets urlparse treat it as netloc
|
|
||||||
host = parsed.hostname
|
|
||||||
port = parsed.port
|
|
||||||
|
|
||||||
# Host may be None if empty (e.g. ':5500')
|
|
||||||
if not host:
|
|
||||||
host = DEFAULT_HOST
|
|
||||||
if port is None:
|
|
||||||
port = default_port
|
|
||||||
|
|
||||||
# Validate IP literals (optional; hostname passes through)
|
|
||||||
try:
|
|
||||||
# Strip brackets if somehow present (urlparse removes them already)
|
|
||||||
ipaddress.ip_address(host)
|
|
||||||
except ValueError:
|
|
||||||
# Not an IP address -> treat as hostname; no action
|
|
||||||
pass
|
|
||||||
|
|
||||||
return host, port, None, False
|
|
||||||
|
|
||||||
|
|
||||||
def add_common_options(p: argparse.ArgumentParser) -> None:
|
def add_common_options(p: argparse.ArgumentParser) -> None:
|
||||||
p.add_argument(
|
p.add_argument(
|
||||||
"--rp-id", default="localhost", help="Relying Party ID (default: localhost)"
|
"--rp-id", default="localhost", help="Relying Party ID (default: localhost)"
|
||||||
@@ -134,45 +75,44 @@ def main():
|
|||||||
logging.basicConfig(level=logging.INFO, format="%(message)s", force=True)
|
logging.basicConfig(level=logging.INFO, format="%(message)s", force=True)
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
prog="paskia", description="Paskia authentication server"
|
prog="paskia",
|
||||||
|
description="Paskia authentication server",
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||||
|
epilog=EPILOG,
|
||||||
)
|
)
|
||||||
sub = parser.add_subparsers(dest="command", required=True)
|
|
||||||
|
|
||||||
# serve subcommand
|
# Primary argument: either host:port or "reset" subcommand
|
||||||
serve = sub.add_parser(
|
parser.add_argument(
|
||||||
"serve", help="Run the server (production style, no auto-reload)"
|
|
||||||
)
|
|
||||||
serve.add_argument(
|
|
||||||
"hostport",
|
"hostport",
|
||||||
nargs="?",
|
nargs="?",
|
||||||
help=(
|
help=(
|
||||||
"Endpoint (default: localhost:4401). Forms: host[:port] | :port | "
|
"Endpoint (default: localhost:4401). Forms: host[:port] | :port | "
|
||||||
"[ipv6][:port] | ipv6 | unix:/path.sock"
|
"[ipv6][:port] | ipv6 | unix:/path.sock | 'reset' for credential reset"
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
add_common_options(serve)
|
parser.add_argument(
|
||||||
|
"reset_query",
|
||||||
# reset subcommand
|
|
||||||
reset = sub.add_parser(
|
|
||||||
"reset",
|
|
||||||
help=(
|
|
||||||
"Create a credential reset link for a user. Provide part of the display name or UUID. "
|
|
||||||
"If omitted, targets the master admin (first Administration role user in an auth:admin org)."
|
|
||||||
),
|
|
||||||
)
|
|
||||||
reset.add_argument(
|
|
||||||
"query",
|
|
||||||
nargs="?",
|
nargs="?",
|
||||||
help="User UUID (full) or case-insensitive substring of display name. If omitted, master admin is used.",
|
help="For 'reset' command: user UUID or substring of display name",
|
||||||
)
|
)
|
||||||
add_common_options(reset)
|
add_common_options(parser)
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
if args.command == "serve":
|
# Detect "reset" subcommand (first positional is "reset")
|
||||||
host, port, uds, all_ifaces = parse_endpoint(args.hostport, DEFAULT_SERVE_PORT)
|
is_reset = args.hostport == "reset"
|
||||||
|
|
||||||
|
if is_reset:
|
||||||
|
endpoints = []
|
||||||
else:
|
else:
|
||||||
host = port = uds = all_ifaces = None # type: ignore
|
# Parse endpoint using fastapi_vue.hostutil
|
||||||
|
endpoints = parse_endpoint(args.hostport, DEFAULT_PORT)
|
||||||
|
|
||||||
|
# Extract host/port/uds from first endpoint for config display and site_url
|
||||||
|
ep = endpoints[0] if endpoints else {}
|
||||||
|
host = ep.get("host")
|
||||||
|
port = ep.get("port")
|
||||||
|
uds = ep.get("uds")
|
||||||
|
|
||||||
# Collect and normalize origins, handle auth_host
|
# Collect and normalize origins, handle auth_host
|
||||||
origins = [normalize_origin(o) for o in (getattr(args, "origins", None) or [])]
|
origins = [normalize_origin(o) for o in (getattr(args, "origins", None) or [])]
|
||||||
@@ -193,8 +133,13 @@ def main():
|
|||||||
origins = [x for x in origins if not (x in seen or seen.add(x))]
|
origins = [x for x in origins if not (x in seen or seen.add(x))]
|
||||||
|
|
||||||
# Compute site_url and site_path for reset links
|
# Compute site_url and site_path for reset links
|
||||||
# Priority: auth_host > first origin with localhost > http://localhost:port
|
# Priority: PASKIA_SITE_URL (explicit) > auth_host > first origin with localhost > http://localhost:port
|
||||||
if args.auth_host:
|
explicit_site_url = os.environ.get("PASKIA_SITE_URL")
|
||||||
|
if explicit_site_url:
|
||||||
|
# Explicit site URL from devserver or deployment config
|
||||||
|
site_url = explicit_site_url.rstrip("/")
|
||||||
|
site_path = "/" if args.auth_host else "/auth/"
|
||||||
|
elif args.auth_host:
|
||||||
site_url = args.auth_host.rstrip("/")
|
site_url = args.auth_host.rstrip("/")
|
||||||
site_path = "/"
|
site_path = "/"
|
||||||
elif origins:
|
elif origins:
|
||||||
@@ -215,8 +160,6 @@ def main():
|
|||||||
site_path = "/auth/"
|
site_path = "/auth/"
|
||||||
|
|
||||||
# Build runtime configuration
|
# Build runtime configuration
|
||||||
from paskia.config import PaskiaConfig
|
|
||||||
|
|
||||||
config = PaskiaConfig(
|
config = PaskiaConfig(
|
||||||
rp_id=args.rp_id,
|
rp_id=args.rp_id,
|
||||||
rp_name=args.rp_name or None,
|
rp_name=args.rp_name or None,
|
||||||
@@ -230,8 +173,6 @@ def main():
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Export configuration via single JSON env variable for worker processes
|
# Export configuration via single JSON env variable for worker processes
|
||||||
import json
|
|
||||||
|
|
||||||
config_json = {
|
config_json = {
|
||||||
"rp_id": config.rp_id,
|
"rp_id": config.rp_id,
|
||||||
"rp_name": config.rp_name,
|
"rp_name": config.rp_name,
|
||||||
@@ -242,42 +183,14 @@ def main():
|
|||||||
}
|
}
|
||||||
os.environ["PASKIA_CONFIG"] = json.dumps(config_json)
|
os.environ["PASKIA_CONFIG"] = json.dumps(config_json)
|
||||||
|
|
||||||
# Initialize globals (without bootstrap yet)
|
|
||||||
from paskia import globals as _globals # local import
|
|
||||||
|
|
||||||
asyncio.run(
|
|
||||||
_globals.init(
|
|
||||||
rp_id=config.rp_id,
|
|
||||||
rp_name=config.rp_name,
|
|
||||||
origins=config.origins,
|
|
||||||
bootstrap=False,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
# Print startup configuration
|
|
||||||
from paskia.util import startupbox
|
|
||||||
|
|
||||||
startupbox.print_startup_config(config)
|
startupbox.print_startup_config(config)
|
||||||
|
|
||||||
# Bootstrap after startup box is printed
|
devmode = bool(os.environ.get("FASTAPI_VUE_FRONTEND_URL"))
|
||||||
from paskia.bootstrap import bootstrap_if_needed
|
|
||||||
|
|
||||||
asyncio.run(bootstrap_if_needed())
|
|
||||||
|
|
||||||
# Handle recover-admin command (no server start)
|
|
||||||
if args.command == "reset":
|
|
||||||
from paskia.fastapi import reset as reset_cmd # local import
|
|
||||||
|
|
||||||
exit_code = reset_cmd.run(getattr(args, "query", None))
|
|
||||||
raise SystemExit(exit_code)
|
|
||||||
|
|
||||||
if args.command == "serve":
|
|
||||||
run_kwargs: dict = {
|
run_kwargs: dict = {
|
||||||
"log_level": "info",
|
"log_level": "info",
|
||||||
}
|
}
|
||||||
|
|
||||||
# Dev mode: enable reload when PASKIA_DEVMODE is set
|
|
||||||
devmode = bool(os.environ.get("PASKIA_DEVMODE"))
|
|
||||||
if devmode:
|
if devmode:
|
||||||
# Security: dev mode must run on localhost:4402 to prevent
|
# Security: dev mode must run on localhost:4402 to prevent
|
||||||
# accidental public exposure of the Vite dev server
|
# accidental public exposure of the Vite dev server
|
||||||
@@ -288,47 +201,34 @@ def main():
|
|||||||
# Suppress uvicorn startup messages in dev mode
|
# Suppress uvicorn startup messages in dev mode
|
||||||
run_kwargs["log_level"] = "warning"
|
run_kwargs["log_level"] = "warning"
|
||||||
|
|
||||||
if uds:
|
async def async_main():
|
||||||
run_kwargs["uds"] = uds
|
await _globals.init(
|
||||||
else:
|
rp_id=config.rp_id,
|
||||||
if not all_ifaces:
|
rp_name=config.rp_name,
|
||||||
run_kwargs["host"] = host
|
origins=config.origins,
|
||||||
run_kwargs["port"] = port
|
bootstrap=False,
|
||||||
|
|
||||||
if all_ifaces and not uds:
|
|
||||||
# Dev mode with all interfaces: use simple single-server approach
|
|
||||||
if devmode:
|
|
||||||
run_kwargs["host"] = "::"
|
|
||||||
run_kwargs["port"] = port
|
|
||||||
uvicorn.run("paskia.fastapi:app", **run_kwargs)
|
|
||||||
else:
|
|
||||||
# Production: run separate servers for IPv4 and IPv6
|
|
||||||
from uvicorn import Config, Server # noqa: E402 local import
|
|
||||||
|
|
||||||
from paskia.fastapi import (
|
|
||||||
app as fastapi_app, # noqa: E402 local import
|
|
||||||
)
|
)
|
||||||
|
await bootstrap_if_needed()
|
||||||
|
await flush()
|
||||||
|
|
||||||
|
if is_reset:
|
||||||
|
exit_code = reset_cmd.run(args.reset_query)
|
||||||
|
raise SystemExit(exit_code)
|
||||||
|
|
||||||
|
if len(endpoints) > 1:
|
||||||
|
async with asyncio.TaskGroup() as tg:
|
||||||
|
for ep in endpoints:
|
||||||
|
tg.create_task(
|
||||||
|
Server(Config(app=fastapi_app, **run_kwargs, **ep)).serve()
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
server = Server(Config(app=fastapi_app, **run_kwargs, **endpoints[0]))
|
||||||
|
await server.serve()
|
||||||
|
|
||||||
async def serve_both():
|
|
||||||
servers = []
|
|
||||||
assert port is not None
|
|
||||||
for h in ("0.0.0.0", "::"):
|
|
||||||
try:
|
try:
|
||||||
cfg = Config(
|
asyncio.run(async_main())
|
||||||
app=fastapi_app,
|
except KeyboardInterrupt:
|
||||||
host=h,
|
pass
|
||||||
port=port,
|
|
||||||
log_level="info",
|
|
||||||
)
|
|
||||||
servers.append(Server(cfg))
|
|
||||||
except Exception as e: # pragma: no cover
|
|
||||||
logging.warning(f"Failed to configure server for {h}: {e}")
|
|
||||||
tasks = [asyncio.create_task(s.serve()) for s in servers]
|
|
||||||
await asyncio.gather(*tasks)
|
|
||||||
|
|
||||||
asyncio.run(serve_both())
|
|
||||||
else:
|
|
||||||
uvicorn.run("paskia.fastapi:app", **run_kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
+452
-270
File diff suppressed because it is too large
Load Diff
+55
-90
@@ -13,23 +13,20 @@ from fastapi import (
|
|||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from fastapi.security import HTTPBearer
|
from fastapi.security import HTTPBearer
|
||||||
|
|
||||||
|
from paskia import db
|
||||||
from paskia.authsession import (
|
from paskia.authsession import (
|
||||||
EXPIRES,
|
EXPIRES,
|
||||||
get_reset,
|
get_reset,
|
||||||
get_session,
|
|
||||||
refresh_session_token,
|
refresh_session_token,
|
||||||
session_expiry,
|
|
||||||
)
|
)
|
||||||
from paskia.fastapi import authz, session, user
|
from paskia.fastapi import authz, session, user
|
||||||
from paskia.fastapi.session import AUTH_COOKIE, AUTH_COOKIE_NAME
|
from paskia.fastapi.session import AUTH_COOKIE, AUTH_COOKIE_NAME
|
||||||
from paskia.globals import db
|
|
||||||
from paskia.globals import passkey as global_passkey
|
from paskia.globals import passkey as global_passkey
|
||||||
from paskia.util import frontend, hostutil, htmlutil, passphrase, userinfo
|
from paskia.util import hostutil, htmlutil, passphrase, userinfo, vitedev
|
||||||
from paskia.util.tokens import session_key
|
|
||||||
|
|
||||||
bearer_auth = HTTPBearer(auto_error=True)
|
bearer_auth = HTTPBearer(auto_error=True)
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
|
|
||||||
app.mount("/user", user.app)
|
app.mount("/user", user.app)
|
||||||
|
|
||||||
@@ -77,26 +74,26 @@ async def validate_token(
|
|||||||
request: Request,
|
request: Request,
|
||||||
response: Response,
|
response: Response,
|
||||||
perm: list[str] = Query([]),
|
perm: list[str] = Query([]),
|
||||||
|
max_age: str | None = Query(None),
|
||||||
auth=AUTH_COOKIE,
|
auth=AUTH_COOKIE,
|
||||||
):
|
):
|
||||||
"""Validate the current session and extend its expiry.
|
"""Validate session and return context. Refreshes session expiry."""
|
||||||
|
|
||||||
Always refreshes the session (sliding expiration) and re-sets the cookie with a
|
|
||||||
renewed max-age. This keeps active users logged in without needing a separate
|
|
||||||
refresh endpoint.
|
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
ctx = await authz.verify(auth, perm, host=request.headers.get("host"))
|
ctx = await authz.verify(
|
||||||
|
auth,
|
||||||
|
perm,
|
||||||
|
host=request.headers.get("host"),
|
||||||
|
max_age=max_age,
|
||||||
|
)
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
# Global handler will clear cookie if 401
|
# Global handler will clear cookie if 401
|
||||||
raise
|
raise
|
||||||
renewed = False
|
renewed = False
|
||||||
if auth:
|
if auth:
|
||||||
current_expiry = session_expiry(ctx.session)
|
consumed = EXPIRES - (ctx.session.expiry - datetime.now(timezone.utc))
|
||||||
consumed = EXPIRES - (current_expiry - datetime.now(timezone.utc))
|
|
||||||
if not timedelta(0) < consumed < _REFRESH_INTERVAL:
|
if not timedelta(0) < consumed < _REFRESH_INTERVAL:
|
||||||
try:
|
try:
|
||||||
await refresh_session_token(
|
refresh_session_token(
|
||||||
auth,
|
auth,
|
||||||
ip=request.client.host if request.client else "",
|
ip=request.client.host if request.client else "",
|
||||||
user_agent=request.headers.get("user-agent") or "",
|
user_agent=request.headers.get("user-agent") or "",
|
||||||
@@ -110,8 +107,26 @@ async def validate_token(
|
|||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
"valid": True,
|
"valid": True,
|
||||||
"user_uuid": str(ctx.session.user_uuid),
|
|
||||||
"renewed": renewed,
|
"renewed": renewed,
|
||||||
|
"ctx": userinfo.format_session_context(ctx),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/token-info")
|
||||||
|
async def token_info(credentials=Depends(bearer_auth)):
|
||||||
|
"""Get reset/device-add token info. Pass token via Bearer header."""
|
||||||
|
token = credentials.credentials
|
||||||
|
if not passphrase.is_well_formed(token):
|
||||||
|
raise HTTPException(400, "Invalid token format")
|
||||||
|
try:
|
||||||
|
reset_token = get_reset(token)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(401, str(e))
|
||||||
|
|
||||||
|
u = db.data().users.get(reset_token.user)
|
||||||
|
return {
|
||||||
|
"token_type": reset_token.token_type,
|
||||||
|
"display_name": u.display_name,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -141,9 +156,10 @@ async def forward_authentication(
|
|||||||
ctx = await authz.verify(
|
ctx = await authz.verify(
|
||||||
auth, perm, host=request.headers.get("host"), max_age=max_age
|
auth, perm, host=request.headers.get("host"), max_age=max_age
|
||||||
)
|
)
|
||||||
role_permissions = set(ctx.role.permissions or [])
|
# Build permission scopes for Remote-Groups header
|
||||||
if ctx.permissions:
|
role_permissions = (
|
||||||
role_permissions.update(permission.id for permission in ctx.permissions)
|
{p.scope for p in ctx.permissions} if ctx.permissions else set()
|
||||||
|
)
|
||||||
|
|
||||||
remote_headers: dict[str, str] = {
|
remote_headers: dict[str, str] = {
|
||||||
"Remote-User": str(ctx.user.uuid),
|
"Remote-User": str(ctx.user.uuid),
|
||||||
@@ -154,17 +170,15 @@ async def forward_authentication(
|
|||||||
"Remote-Role": str(ctx.role.uuid),
|
"Remote-Role": str(ctx.role.uuid),
|
||||||
"Remote-Role-Name": ctx.role.display_name,
|
"Remote-Role-Name": ctx.role.display_name,
|
||||||
"Remote-Session-Expires": (
|
"Remote-Session-Expires": (
|
||||||
session_expiry(ctx.session)
|
ctx.session.expiry.astimezone(timezone.utc)
|
||||||
.astimezone(timezone.utc)
|
|
||||||
.isoformat()
|
.isoformat()
|
||||||
.replace("+00:00", "Z")
|
.replace("+00:00", "Z")
|
||||||
if session_expiry(ctx.session).tzinfo
|
if ctx.session.expiry.tzinfo
|
||||||
else session_expiry(ctx.session)
|
else ctx.session.expiry.replace(tzinfo=timezone.utc)
|
||||||
.replace(tzinfo=timezone.utc)
|
|
||||||
.isoformat()
|
.isoformat()
|
||||||
.replace("+00:00", "Z")
|
.replace("+00:00", "Z")
|
||||||
),
|
),
|
||||||
"Remote-Credential": str(ctx.session.credential_uuid),
|
"Remote-Credential": str(ctx.session.credential),
|
||||||
}
|
}
|
||||||
return Response(status_code=204, headers=remote_headers)
|
return Response(status_code=204, headers=remote_headers)
|
||||||
except authz.AuthException as e:
|
except authz.AuthException as e:
|
||||||
@@ -179,7 +193,7 @@ async def forward_authentication(
|
|||||||
if wants_html:
|
if wants_html:
|
||||||
# Browser request - return full-page HTML with metadata
|
# Browser request - return full-page HTML with metadata
|
||||||
data_attrs = {"mode": e.mode, **e.metadata}
|
data_attrs = {"mode": e.mode, **e.metadata}
|
||||||
html = (await frontend.read("/int/forward/index.html"))[0]
|
html = (await vitedev.read("/int/forward/index.html"))[0]
|
||||||
html = htmlutil.patch_html_data_attrs(html, **data_attrs)
|
html = htmlutil.patch_html_data_attrs(html, **data_attrs)
|
||||||
return Response(
|
return Response(
|
||||||
html, status_code=e.status_code, media_type="text/html; charset=UTF-8"
|
html, status_code=e.status_code, media_type="text/html; charset=UTF-8"
|
||||||
@@ -206,78 +220,27 @@ async def get_settings():
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/token-info")
|
|
||||||
async def api_token_info(token: str):
|
|
||||||
"""Get information about a reset token.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
- type: "reset"
|
|
||||||
- user_name: display name of the user
|
|
||||||
- token_type: type of reset token
|
|
||||||
"""
|
|
||||||
if not passphrase.is_well_formed(token):
|
|
||||||
raise HTTPException(status_code=404, detail="Invalid token")
|
|
||||||
|
|
||||||
# Check if this is a reset token
|
|
||||||
try:
|
|
||||||
reset_token = await get_reset(token)
|
|
||||||
user = await db.instance.get_user_by_uuid(reset_token.user_uuid)
|
|
||||||
return {
|
|
||||||
"type": "reset",
|
|
||||||
"user_name": user.display_name,
|
|
||||||
"token_type": reset_token.token_type,
|
|
||||||
}
|
|
||||||
except (ValueError, Exception):
|
|
||||||
raise HTTPException(status_code=404, detail="Token not found or expired")
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/user-info")
|
@app.post("/user-info")
|
||||||
async def api_user_info(
|
async def api_user_info(
|
||||||
request: Request,
|
request: Request,
|
||||||
response: Response,
|
response: Response,
|
||||||
reset: str | None = None,
|
|
||||||
auth=AUTH_COOKIE,
|
auth=AUTH_COOKIE,
|
||||||
):
|
):
|
||||||
"""Get user information including credentials, sessions, and permissions.
|
"""Get full user profile including credentials and sessions."""
|
||||||
|
|
||||||
Can be called with either:
|
|
||||||
- A session cookie (auth) for authenticated users
|
|
||||||
- A reset token for users in password reset flow
|
|
||||||
"""
|
|
||||||
authenticated = False
|
|
||||||
session_record = None
|
|
||||||
reset_token = None
|
|
||||||
try:
|
|
||||||
if reset:
|
|
||||||
if not passphrase.is_well_formed(reset):
|
|
||||||
raise ValueError("Invalid reset token")
|
|
||||||
reset_token = await get_reset(reset)
|
|
||||||
target_user_uuid = reset_token.user_uuid
|
|
||||||
else:
|
|
||||||
if auth is None:
|
if auth is None:
|
||||||
raise authz.AuthException(
|
raise authz.AuthException(
|
||||||
status_code=401,
|
status_code=401,
|
||||||
detail="Authentication required",
|
detail="Authentication required",
|
||||||
mode="login",
|
mode="login",
|
||||||
)
|
)
|
||||||
session_record = await get_session(auth, host=request.headers.get("host"))
|
ctx = db.get_session_context(auth, request.headers.get("host"))
|
||||||
authenticated = True
|
if not ctx:
|
||||||
target_user_uuid = session_record.user_uuid
|
raise HTTPException(401, "Session expired")
|
||||||
except ValueError as e:
|
|
||||||
raise HTTPException(401, str(e))
|
|
||||||
|
|
||||||
# Return minimal response for reset tokens
|
|
||||||
if not authenticated and reset_token:
|
|
||||||
return await userinfo.format_reset_user_info(target_user_uuid, reset_token)
|
|
||||||
|
|
||||||
# Return full user info for authenticated users
|
|
||||||
assert auth is not None
|
|
||||||
assert session_record is not None
|
|
||||||
|
|
||||||
return await userinfo.format_user_info(
|
return await userinfo.format_user_info(
|
||||||
user_uuid=target_user_uuid,
|
user_uuid=ctx.user.uuid,
|
||||||
auth=auth,
|
auth=auth,
|
||||||
session_record=session_record,
|
session_record=ctx.session,
|
||||||
request_host=request.headers.get("host"),
|
request_host=request.headers.get("host"),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -286,12 +249,12 @@ async def api_user_info(
|
|||||||
async def api_logout(request: Request, response: Response, auth=AUTH_COOKIE):
|
async def api_logout(request: Request, response: Response, auth=AUTH_COOKIE):
|
||||||
if not auth:
|
if not auth:
|
||||||
return {"message": "Already logged out"}
|
return {"message": "Already logged out"}
|
||||||
try:
|
host = request.headers.get("host")
|
||||||
await get_session(auth, host=request.headers.get("host"))
|
ctx = db.get_session_context(auth, host)
|
||||||
except ValueError:
|
if not ctx:
|
||||||
return {"message": "Already logged out"}
|
return {"message": "Already logged out"}
|
||||||
with suppress(Exception):
|
with suppress(Exception):
|
||||||
await db.instance.delete_session(session_key(auth))
|
db.delete_session(auth, ctx=ctx)
|
||||||
session.clear_session_cookie(response)
|
session.clear_session_cookie(response)
|
||||||
return {"message": "Logged out successfully"}
|
return {"message": "Logged out successfully"}
|
||||||
|
|
||||||
@@ -300,9 +263,11 @@ async def api_logout(request: Request, response: Response, auth=AUTH_COOKIE):
|
|||||||
async def api_set_session(
|
async def api_set_session(
|
||||||
request: Request, response: Response, auth=Depends(bearer_auth)
|
request: Request, response: Response, auth=Depends(bearer_auth)
|
||||||
):
|
):
|
||||||
user = await get_session(auth.credentials, host=request.headers.get("host"))
|
ctx = db.get_session_context(auth.credentials, request.headers.get("host"))
|
||||||
|
if not ctx:
|
||||||
|
raise HTTPException(401, "Session expired")
|
||||||
session.set_session_cookie(response, auth.credentials)
|
session.set_session_cookie(response, auth.credentials)
|
||||||
return {
|
return {
|
||||||
"message": "Session cookie set successfully",
|
"message": "Session cookie set successfully",
|
||||||
"user_uuid": str(user.user_uuid),
|
"user": str(ctx.user.uuid),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -94,14 +94,19 @@ async def verify(
|
|||||||
|
|
||||||
if not match(ctx, perm):
|
if not match(ctx, perm):
|
||||||
# Determine which permissions are missing for clearer diagnostics
|
# Determine which permissions are missing for clearer diagnostics
|
||||||
missing = sorted(set(perm) - set(ctx.role.permissions))
|
effective_scopes = (
|
||||||
|
{p.scope for p in (ctx.permissions or [])}
|
||||||
|
if ctx.permissions
|
||||||
|
else set(ctx.role.permissions or [])
|
||||||
|
)
|
||||||
|
missing = sorted(set(perm) - effective_scopes)
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Permission denied: user=%s role=%s missing=%s required=%s granted=%s", # noqa: E501
|
"Permission denied: user=%s role=%s missing=%s required=%s granted=%s", # noqa: E501
|
||||||
getattr(ctx.user, "uuid", "?"),
|
getattr(ctx.user, "uuid", "?"),
|
||||||
getattr(ctx.role, "display_name", "?"),
|
getattr(ctx.role, "display_name", "?"),
|
||||||
missing,
|
missing,
|
||||||
perm,
|
perm,
|
||||||
ctx.role.permissions,
|
list(effective_scopes),
|
||||||
)
|
)
|
||||||
raise AuthException(
|
raise AuthException(
|
||||||
status_code=403, mode="forbidden", detail="Permission required"
|
status_code=403, mode="forbidden", detail="Permission required"
|
||||||
|
|||||||
+31
-19
@@ -1,3 +1,4 @@
|
|||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
@@ -5,11 +6,20 @@ from pathlib import Path
|
|||||||
|
|
||||||
from fastapi import FastAPI, HTTPException, Request, Response
|
from fastapi import FastAPI, HTTPException, Request, Response
|
||||||
from fastapi.responses import FileResponse, RedirectResponse
|
from fastapi.responses import FileResponse, RedirectResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi_vue import Frontend
|
||||||
|
|
||||||
|
from paskia import globals
|
||||||
|
from paskia.db import start_background, stop_background
|
||||||
from paskia.fastapi import admin, api, auth_host, ws
|
from paskia.fastapi import admin, api, auth_host, ws
|
||||||
from paskia.fastapi.session import AUTH_COOKIE
|
from paskia.fastapi.session import AUTH_COOKIE
|
||||||
from paskia.util import frontend, hostutil, passphrase
|
from paskia.util import hostutil, passphrase, vitedev
|
||||||
|
|
||||||
|
# Vue Frontend static files
|
||||||
|
frontend = Frontend(
|
||||||
|
Path(__file__).parent.parent / "frontend-build",
|
||||||
|
cached=["/auth/assets/"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# Path to examples/index.html when running from source tree
|
# Path to examples/index.html when running from source tree
|
||||||
_EXAMPLES_DIR = Path(__file__).parent.parent.parent / "examples"
|
_EXAMPLES_DIR = Path(__file__).parent.parent.parent / "examples"
|
||||||
@@ -23,10 +33,6 @@ async def lifespan(app: FastAPI): # pragma: no cover - startup path
|
|||||||
so that uvicorn reload / multiprocess workers inherit the settings.
|
so that uvicorn reload / multiprocess workers inherit the settings.
|
||||||
All keys are guaranteed to exist; values are already normalized by __main__.py.
|
All keys are guaranteed to exist; values are already normalized by __main__.py.
|
||||||
"""
|
"""
|
||||||
import json
|
|
||||||
|
|
||||||
from paskia import globals
|
|
||||||
|
|
||||||
config = json.loads(os.environ["PASKIA_CONFIG"])
|
config = json.loads(os.environ["PASKIA_CONFIG"])
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -43,14 +49,23 @@ async def lifespan(app: FastAPI): # pragma: no cover - startup path
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
# Restore info level logging after startup (suppressed during uvicorn init in dev mode)
|
# Restore info level logging after startup (suppressed during uvicorn init in dev mode)
|
||||||
if frontend.is_dev_mode():
|
if frontend.devmode:
|
||||||
logging.getLogger("uvicorn").setLevel(logging.INFO)
|
logging.getLogger("uvicorn").setLevel(logging.INFO)
|
||||||
logging.getLogger("uvicorn.access").setLevel(logging.INFO)
|
logging.getLogger("uvicorn.access").setLevel(logging.INFO)
|
||||||
|
|
||||||
|
await frontend.load()
|
||||||
|
await start_background()
|
||||||
yield
|
yield
|
||||||
|
await stop_background()
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(lifespan=lifespan)
|
app = FastAPI(
|
||||||
|
lifespan=lifespan,
|
||||||
|
redirect_slashes=False,
|
||||||
|
docs_url=None,
|
||||||
|
redoc_url=None,
|
||||||
|
openapi_url=None,
|
||||||
|
)
|
||||||
|
|
||||||
# Apply redirections to auth-host if configured (deny access to restricted endpoints, remove /auth/)
|
# Apply redirections to auth-host if configured (deny access to restricted endpoints, remove /auth/)
|
||||||
app.middleware("http")(auth_host.redirect_middleware)
|
app.middleware("http")(auth_host.redirect_middleware)
|
||||||
@@ -59,19 +74,11 @@ app.mount("/auth/api/admin/", admin.app)
|
|||||||
app.mount("/auth/api/", api.app)
|
app.mount("/auth/api/", api.app)
|
||||||
app.mount("/auth/ws/", ws.app)
|
app.mount("/auth/ws/", ws.app)
|
||||||
|
|
||||||
# In dev mode (PASKIA_DEVMODE=1), Vite serves assets directly; skip static files mount
|
|
||||||
if not frontend.is_dev_mode():
|
|
||||||
app.mount(
|
|
||||||
"/auth/assets/",
|
|
||||||
StaticFiles(directory=frontend.file("auth", "assets")),
|
|
||||||
name="assets",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/auth/restricted/")
|
@app.get("/auth/restricted/")
|
||||||
async def restricted_view():
|
async def restricted_view():
|
||||||
"""Serve the restricted/authentication UI for iframe embedding."""
|
"""Serve the restricted/authentication UI for iframe embedding."""
|
||||||
return Response(*await frontend.read("/auth/restricted/index.html"))
|
return Response(*await vitedev.read("/auth/restricted/index.html"))
|
||||||
|
|
||||||
|
|
||||||
# Navigable URLs are defined here. We support both / and /auth/ as the base path
|
# Navigable URLs are defined here. We support both / and /auth/ as the base path
|
||||||
@@ -86,7 +93,7 @@ async def frontapp(request: Request, response: Response, auth=AUTH_COOKIE):
|
|||||||
The frontend handles mode detection (host mode vs full profile) based on settings.
|
The frontend handles mode detection (host mode vs full profile) based on settings.
|
||||||
Access control is handled via APIs.
|
Access control is handled via APIs.
|
||||||
"""
|
"""
|
||||||
return Response(*await frontend.read("/auth/index.html"))
|
return Response(*await vitedev.read("/auth/index.html"))
|
||||||
|
|
||||||
|
|
||||||
@app.get("/admin", include_in_schema=False)
|
@app.get("/admin", include_in_schema=False)
|
||||||
@@ -96,6 +103,7 @@ async def admin_root_redirect():
|
|||||||
|
|
||||||
|
|
||||||
@app.get("/admin/", include_in_schema=False)
|
@app.get("/admin/", include_in_schema=False)
|
||||||
|
@app.get("/auth/admin/", include_in_schema=False)
|
||||||
async def admin_root(request: Request, auth=AUTH_COOKIE):
|
async def admin_root(request: Request, auth=AUTH_COOKIE):
|
||||||
return await admin.adminapp(request, auth) # Delegated to admin app
|
return await admin.adminapp(request, auth) # Delegated to admin app
|
||||||
|
|
||||||
@@ -127,4 +135,8 @@ async def token_link(token: str):
|
|||||||
if not passphrase.is_well_formed(token):
|
if not passphrase.is_well_formed(token):
|
||||||
raise HTTPException(status_code=404)
|
raise HTTPException(status_code=404)
|
||||||
|
|
||||||
return Response(*await frontend.read("/int/reset/index.html"))
|
return Response(*await vitedev.read("/int/reset/index.html"))
|
||||||
|
|
||||||
|
|
||||||
|
# Final catch-all route for frontend files (keep at end of file)
|
||||||
|
frontend.route(app, "/")
|
||||||
|
|||||||
+29
-52
@@ -15,15 +15,15 @@ from uuid import UUID
|
|||||||
import base64url
|
import base64url
|
||||||
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
||||||
|
|
||||||
from paskia import remoteauth
|
from paskia import db, remoteauth
|
||||||
from paskia.authsession import create_session
|
from paskia.authsession import expires
|
||||||
from paskia.fastapi.session import infodict
|
from paskia.fastapi.session import infodict
|
||||||
|
from paskia.fastapi.wschat import authenticate_chat
|
||||||
from paskia.fastapi.wsutil import validate_origin, websocket_error_handler
|
from paskia.fastapi.wsutil import validate_origin, websocket_error_handler
|
||||||
from paskia.globals import db, passkey
|
from paskia.util import hostutil, passphrase, pow, useragent
|
||||||
from paskia.util import passphrase, pow
|
|
||||||
|
|
||||||
# Create a FastAPI subapp for remote auth WebSocket endpoints
|
# Create a FastAPI subapp for remote auth WebSocket endpoints
|
||||||
app = FastAPI()
|
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
|
|
||||||
|
|
||||||
@app.websocket("/request")
|
@app.websocket("/request")
|
||||||
@@ -180,7 +180,7 @@ async def websocket_remote_auth_request(ws: WebSocket):
|
|||||||
):
|
):
|
||||||
response = {
|
response = {
|
||||||
"status": "authenticated",
|
"status": "authenticated",
|
||||||
"user_uuid": str(result_data["user_uuid"]),
|
"user": str(result_data["user_uuid"]),
|
||||||
}
|
}
|
||||||
if result_data.get("session_token"):
|
if result_data.get("session_token"):
|
||||||
response["session_token"] = result_data["session_token"]
|
response["session_token"] = result_data["session_token"]
|
||||||
@@ -269,7 +269,6 @@ async def websocket_remote_auth_permit(ws: WebSocket):
|
|||||||
6. Client sends WebAuthn response
|
6. Client sends WebAuthn response
|
||||||
7. Server sends {status: "success", message: "..."}
|
7. Server sends {status: "success", message: "..."}
|
||||||
"""
|
"""
|
||||||
from paskia.util import useragent
|
|
||||||
|
|
||||||
origin = validate_origin(ws)
|
origin = validate_origin(ws)
|
||||||
|
|
||||||
@@ -290,7 +289,6 @@ async def websocket_remote_auth_permit(ws: WebSocket):
|
|||||||
)
|
)
|
||||||
|
|
||||||
request = None
|
request = None
|
||||||
webauthn_challenge = None
|
|
||||||
explicitly_denied = False
|
explicitly_denied = False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -312,78 +310,57 @@ async def websocket_remote_auth_permit(ws: WebSocket):
|
|||||||
|
|
||||||
# Handle authenticate request (no PoW needed - already validated during lookup)
|
# Handle authenticate request (no PoW needed - already validated during lookup)
|
||||||
if msg.get("authenticate") and request is not None:
|
if msg.get("authenticate") and request is not None:
|
||||||
# Generate authentication options
|
cred, new_sign_count = await authenticate_chat(ws, origin)
|
||||||
options, webauthn_challenge = passkey.instance.auth_generate_options(
|
|
||||||
credential_ids=None
|
|
||||||
)
|
|
||||||
await ws.send_json({"optionsJSON": options})
|
|
||||||
|
|
||||||
# Wait for WebAuthn response
|
|
||||||
credential = passkey.instance.auth_parse(await ws.receive_json())
|
|
||||||
|
|
||||||
# Fetch and verify credential
|
|
||||||
try:
|
|
||||||
stored_cred = await db.instance.get_credential_by_id(
|
|
||||||
credential.raw_id
|
|
||||||
)
|
|
||||||
except ValueError:
|
|
||||||
raise ValueError(
|
|
||||||
f"This passkey is no longer registered with {passkey.instance.rp_name}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Verify the credential
|
|
||||||
passkey.instance.auth_verify(
|
|
||||||
credential, webauthn_challenge, stored_cred, origin
|
|
||||||
)
|
|
||||||
|
|
||||||
# Update credential last_used
|
|
||||||
await db.instance.login(stored_cred.user_uuid, stored_cred)
|
|
||||||
|
|
||||||
# Create a session for the REQUESTING device
|
# Create a session for the REQUESTING device
|
||||||
assert stored_cred.uuid is not None
|
assert cred.uuid is not None
|
||||||
|
|
||||||
session_token = None
|
session_token = None
|
||||||
reset_token = None
|
reset_token = None
|
||||||
|
|
||||||
if request.action == "register":
|
if request.action == "register":
|
||||||
# For registration, create a reset token for device addition
|
# For registration, create a reset token for device addition
|
||||||
from paskia.authsession import expires
|
|
||||||
from paskia.util import tokens
|
|
||||||
|
|
||||||
token_str = passphrase.generate()
|
token_str = passphrase.generate()
|
||||||
expiry = expires()
|
expiry = expires()
|
||||||
await db.instance.create_reset_token(
|
db.create_reset_token(
|
||||||
user_uuid=stored_cred.user_uuid,
|
user_uuid=cred.user,
|
||||||
key=tokens.reset_key(token_str),
|
passphrase=token_str,
|
||||||
expiry=expiry,
|
expiry=expiry,
|
||||||
token_type="device addition",
|
token_type="device addition",
|
||||||
)
|
)
|
||||||
reset_token = token_str
|
reset_token = token_str
|
||||||
# Also create a session so the device is logged in?
|
# Also create a session so the device is logged in
|
||||||
# User requested: "We can make the flow always create a new session, but make additional tokens for other possibilities."
|
normalized_host = hostutil.normalize_host(request.host)
|
||||||
session_token = await create_session(
|
session_token = db.login(
|
||||||
user_uuid=stored_cred.user_uuid,
|
user_uuid=cred.user,
|
||||||
credential_uuid=stored_cred.uuid,
|
credential_uuid=cred.uuid,
|
||||||
host=request.host,
|
sign_count=new_sign_count,
|
||||||
|
host=normalized_host,
|
||||||
ip=request.ip,
|
ip=request.ip,
|
||||||
user_agent=request.user_agent,
|
user_agent=request.user_agent,
|
||||||
|
expiry=expires(),
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# Default login action
|
# Default login action
|
||||||
session_token = await create_session(
|
|
||||||
user_uuid=stored_cred.user_uuid,
|
normalized_host = hostutil.normalize_host(request.host)
|
||||||
credential_uuid=stored_cred.uuid,
|
session_token = db.login(
|
||||||
host=request.host,
|
user_uuid=cred.user,
|
||||||
|
credential_uuid=cred.uuid,
|
||||||
|
sign_count=new_sign_count,
|
||||||
|
host=normalized_host,
|
||||||
ip=request.ip,
|
ip=request.ip,
|
||||||
user_agent=request.user_agent,
|
user_agent=request.user_agent,
|
||||||
|
expiry=expires(),
|
||||||
)
|
)
|
||||||
|
|
||||||
# Complete the remote auth request (notifies the waiting device)
|
# Complete the remote auth request (notifies the waiting device)
|
||||||
completed = await remoteauth.instance.complete_request(
|
completed = await remoteauth.instance.complete_request(
|
||||||
token=request.key,
|
token=request.key,
|
||||||
session_token=session_token,
|
session_token=session_token,
|
||||||
user_uuid=stored_cred.user_uuid,
|
user_uuid=cred.user,
|
||||||
credential_uuid=stored_cred.uuid,
|
credential_uuid=cred.uuid,
|
||||||
reset_token=reset_token,
|
reset_token=reset_token,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+22
-13
@@ -16,9 +16,8 @@ import asyncio
|
|||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from paskia import authsession as _authsession
|
from paskia import authsession as _authsession
|
||||||
from paskia import globals as _g
|
from paskia import db
|
||||||
from paskia.util import hostutil, passphrase
|
from paskia.util import hostutil, passphrase
|
||||||
from paskia.util import tokens as _tokens
|
|
||||||
|
|
||||||
|
|
||||||
async def _resolve_targets(query: str | None):
|
async def _resolve_targets(query: str | None):
|
||||||
@@ -27,9 +26,13 @@ async def _resolve_targets(query: str | None):
|
|||||||
targets: list[tuple] = []
|
targets: list[tuple] = []
|
||||||
try:
|
try:
|
||||||
q_uuid = UUID(query)
|
q_uuid = UUID(query)
|
||||||
perm_orgs = await _g.db.instance.get_permission_organizations("auth:admin")
|
p = next(
|
||||||
for o in perm_orgs:
|
(p for p in db.data().permissions.values() if p.scope == "auth:admin"),
|
||||||
users = await _g.db.instance.get_organization_users(str(o.uuid))
|
None,
|
||||||
|
)
|
||||||
|
if p:
|
||||||
|
for org_uuid in p.orgs:
|
||||||
|
users = db.get_organization_users(org_uuid)
|
||||||
for u, role_name in users:
|
for u, role_name in users:
|
||||||
if u.uuid == q_uuid:
|
if u.uuid == q_uuid:
|
||||||
return [(u, role_name)]
|
return [(u, role_name)]
|
||||||
@@ -38,9 +41,12 @@ async def _resolve_targets(query: str | None):
|
|||||||
pass
|
pass
|
||||||
# Substring search
|
# Substring search
|
||||||
needle = query.lower()
|
needle = query.lower()
|
||||||
perm_orgs = await _g.db.instance.get_permission_organizations("auth:admin")
|
p = next(
|
||||||
for o in perm_orgs:
|
(p for p in db.data().permissions.values() if p.scope == "auth:admin"), None
|
||||||
users = await _g.db.instance.get_organization_users(str(o.uuid))
|
)
|
||||||
|
if p:
|
||||||
|
for org_uuid in p.orgs:
|
||||||
|
users = db.get_organization_users(org_uuid)
|
||||||
for u, role_name in users:
|
for u, role_name in users:
|
||||||
if needle in (u.display_name or "").lower():
|
if needle in (u.display_name or "").lower():
|
||||||
targets.append((u, role_name))
|
targets.append((u, role_name))
|
||||||
@@ -53,10 +59,13 @@ async def _resolve_targets(query: str | None):
|
|||||||
deduped.append((u, role_name))
|
deduped.append((u, role_name))
|
||||||
return deduped
|
return deduped
|
||||||
# No query -> master admin
|
# No query -> master admin
|
||||||
perm_orgs = await _g.db.instance.get_permission_organizations("auth:admin")
|
p = next(
|
||||||
if not perm_orgs:
|
(p for p in db.data().permissions.values() if p.scope == "auth:admin"), None
|
||||||
|
)
|
||||||
|
if not p or not p.orgs:
|
||||||
return []
|
return []
|
||||||
users = await _g.db.instance.get_organization_users(str(perm_orgs[0].uuid))
|
first_org_uuid = next(iter(p.orgs))
|
||||||
|
users = db.get_organization_users(first_org_uuid)
|
||||||
admin_users = [pair for pair in users if pair[1] == "Administration"]
|
admin_users = [pair for pair in users if pair[1] == "Administration"]
|
||||||
return admin_users[:1]
|
return admin_users[:1]
|
||||||
|
|
||||||
@@ -64,9 +73,9 @@ async def _resolve_targets(query: str | None):
|
|||||||
async def _create_reset(user, role_name: str):
|
async def _create_reset(user, role_name: str):
|
||||||
token = passphrase.generate()
|
token = passphrase.generate()
|
||||||
expiry = _authsession.reset_expires()
|
expiry = _authsession.reset_expires()
|
||||||
await _g.db.instance.create_reset_token(
|
db.create_reset_token(
|
||||||
|
passphrase=token,
|
||||||
user_uuid=user.uuid,
|
user_uuid=user.uuid,
|
||||||
key=_tokens.reset_key(token),
|
|
||||||
expiry=expiry,
|
expiry=expiry,
|
||||||
token_type="manual reset",
|
token_type="manual reset",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ AUTH_COOKIE = Cookie(None, alias=AUTH_COOKIE_NAME)
|
|||||||
def infodict(request: Request | WebSocket, type: str) -> dict:
|
def infodict(request: Request | WebSocket, type: str) -> dict:
|
||||||
"""Extract client information from request."""
|
"""Extract client information from request."""
|
||||||
return {
|
return {
|
||||||
"ip": request.client.host if request.client else None,
|
"ip": request.client.host if request.client else "",
|
||||||
"user_agent": request.headers.get("user-agent", "")[:500] or None,
|
"user_agent": request.headers.get("user-agent", "")[:500],
|
||||||
"session_type": type,
|
"session_type": type,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+27
-41
@@ -10,18 +10,16 @@ from fastapi import (
|
|||||||
)
|
)
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
from paskia import db
|
||||||
from paskia.authsession import (
|
from paskia.authsession import (
|
||||||
delete_credential,
|
delete_credential,
|
||||||
expires,
|
expires,
|
||||||
get_session,
|
|
||||||
)
|
)
|
||||||
from paskia.fastapi import authz, session
|
from paskia.fastapi import authz, session
|
||||||
from paskia.fastapi.session import AUTH_COOKIE
|
from paskia.fastapi.session import AUTH_COOKIE
|
||||||
from paskia.globals import db
|
from paskia.util import hostutil, passphrase
|
||||||
from paskia.util import hostutil, passphrase, tokens
|
|
||||||
from paskia.util.tokens import decode_session_key, session_key
|
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(authz.AuthException)
|
@app.exception_handler(authz.AuthException)
|
||||||
@@ -33,7 +31,7 @@ async def auth_exception_handler(_request, exc: authz.AuthException):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.put("/display-name")
|
@app.patch("/display-name")
|
||||||
async def user_update_display_name(
|
async def user_update_display_name(
|
||||||
request: Request,
|
request: Request,
|
||||||
response: Response,
|
response: Response,
|
||||||
@@ -44,18 +42,18 @@ async def user_update_display_name(
|
|||||||
raise authz.AuthException(
|
raise authz.AuthException(
|
||||||
status_code=401, detail="Authentication Required", mode="login"
|
status_code=401, detail="Authentication Required", mode="login"
|
||||||
)
|
)
|
||||||
try:
|
host = request.headers.get("host")
|
||||||
s = await get_session(auth, host=request.headers.get("host"))
|
ctx = db.get_session_context(auth, host)
|
||||||
except ValueError as e:
|
if not ctx:
|
||||||
raise authz.AuthException(
|
raise authz.AuthException(
|
||||||
status_code=401, detail="Session expired", mode="login"
|
status_code=401, detail="Session expired", mode="login"
|
||||||
) from e
|
)
|
||||||
new_name = (payload.get("display_name") or "").strip()
|
new_name = (payload.get("display_name") or "").strip()
|
||||||
if not new_name:
|
if not new_name:
|
||||||
raise HTTPException(status_code=400, detail="display_name required")
|
raise HTTPException(status_code=400, detail="display_name required")
|
||||||
if len(new_name) > 64:
|
if len(new_name) > 64:
|
||||||
raise HTTPException(status_code=400, detail="display_name too long")
|
raise HTTPException(status_code=400, detail="display_name too long")
|
||||||
await db.instance.update_user_display_name(s.user_uuid, new_name)
|
db.update_user_display_name(ctx.user.uuid, new_name, ctx=ctx)
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
@@ -63,13 +61,13 @@ async def user_update_display_name(
|
|||||||
async def api_logout_all(request: Request, response: Response, auth=AUTH_COOKIE):
|
async def api_logout_all(request: Request, response: Response, auth=AUTH_COOKIE):
|
||||||
if not auth:
|
if not auth:
|
||||||
return {"message": "Already logged out"}
|
return {"message": "Already logged out"}
|
||||||
try:
|
host = request.headers.get("host")
|
||||||
s = await get_session(auth, host=request.headers.get("host"))
|
ctx = db.get_session_context(auth, host)
|
||||||
except ValueError:
|
if not ctx:
|
||||||
raise authz.AuthException(
|
raise authz.AuthException(
|
||||||
status_code=401, detail="Session expired", mode="login"
|
status_code=401, detail="Session expired", mode="login"
|
||||||
)
|
)
|
||||||
await db.instance.delete_sessions_for_user(s.user_uuid)
|
db.delete_sessions_for_user(ctx.user.uuid, ctx=ctx)
|
||||||
session.clear_session_cookie(response)
|
session.clear_session_cookie(response)
|
||||||
return {"message": "Logged out from all hosts"}
|
return {"message": "Logged out from all hosts"}
|
||||||
|
|
||||||
@@ -85,26 +83,19 @@ async def api_delete_session(
|
|||||||
raise authz.AuthException(
|
raise authz.AuthException(
|
||||||
status_code=401, detail="Authentication Required", mode="login"
|
status_code=401, detail="Authentication Required", mode="login"
|
||||||
)
|
)
|
||||||
try:
|
host = request.headers.get("host")
|
||||||
current_session = await get_session(auth, host=request.headers.get("host"))
|
ctx = db.get_session_context(auth, host)
|
||||||
except ValueError as exc:
|
if not ctx:
|
||||||
raise authz.AuthException(
|
raise authz.AuthException(
|
||||||
status_code=401, detail="Session expired", mode="login"
|
status_code=401, detail="Session expired", mode="login"
|
||||||
) from exc
|
)
|
||||||
|
|
||||||
try:
|
target_session = db.data().sessions.get(session_id)
|
||||||
target_key = decode_session_key(session_id)
|
if not target_session or target_session.user != ctx.user.uuid:
|
||||||
except ValueError as exc:
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=400, detail="Invalid session identifier"
|
|
||||||
) from exc
|
|
||||||
|
|
||||||
target_session = await db.instance.get_session(target_key)
|
|
||||||
if not target_session or target_session.user_uuid != current_session.user_uuid:
|
|
||||||
raise HTTPException(status_code=404, detail="Session not found")
|
raise HTTPException(status_code=404, detail="Session not found")
|
||||||
|
|
||||||
await db.instance.delete_session(target_key)
|
db.delete_session(session_id, ctx=ctx)
|
||||||
current_terminated = target_key == session_key(auth)
|
current_terminated = session_id == auth
|
||||||
if current_terminated:
|
if current_terminated:
|
||||||
session.clear_session_cookie(response) # explicit because 200
|
session.clear_session_cookie(response) # explicit because 200
|
||||||
return {"status": "ok", "current_session_terminated": current_terminated}
|
return {"status": "ok", "current_session_terminated": current_terminated}
|
||||||
@@ -120,7 +111,7 @@ async def api_delete_credential(
|
|||||||
# Require recent authentication for sensitive operation
|
# Require recent authentication for sensitive operation
|
||||||
await authz.verify(auth, [], host=request.headers.get("host"), max_age="5m")
|
await authz.verify(auth, [], host=request.headers.get("host"), max_age="5m")
|
||||||
try:
|
try:
|
||||||
await delete_credential(uuid, auth, host=request.headers.get("host"))
|
delete_credential(uuid, auth, host=request.headers.get("host"))
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
raise authz.AuthException(
|
raise authz.AuthException(
|
||||||
status_code=401, detail="Session expired", mode="login"
|
status_code=401, detail="Session expired", mode="login"
|
||||||
@@ -135,20 +126,15 @@ async def api_create_link(
|
|||||||
auth=AUTH_COOKIE,
|
auth=AUTH_COOKIE,
|
||||||
):
|
):
|
||||||
# Require recent authentication for sensitive operation
|
# Require recent authentication for sensitive operation
|
||||||
await authz.verify(auth, [], host=request.headers.get("host"), max_age="5m")
|
ctx = await authz.verify(auth, [], host=request.headers.get("host"), max_age="5m")
|
||||||
try:
|
|
||||||
s = await get_session(auth, host=request.headers.get("host"))
|
|
||||||
except ValueError as e:
|
|
||||||
raise authz.AuthException(
|
|
||||||
status_code=401, detail="Session expired", mode="login"
|
|
||||||
) from e
|
|
||||||
token = passphrase.generate()
|
token = passphrase.generate()
|
||||||
expiry = expires()
|
expiry = expires()
|
||||||
await db.instance.create_reset_token(
|
db.create_reset_token(
|
||||||
user_uuid=s.user_uuid,
|
user_uuid=ctx.user.uuid,
|
||||||
key=tokens.reset_key(token),
|
passphrase=token,
|
||||||
expiry=expiry,
|
expiry=expiry,
|
||||||
token_type="device addition",
|
token_type="device addition",
|
||||||
|
ctx=ctx,
|
||||||
)
|
)
|
||||||
url = hostutil.reset_link_url(token)
|
url = hostutil.reset_link_url(token)
|
||||||
return {
|
return {
|
||||||
|
|||||||
+42
-74
@@ -1,40 +1,21 @@
|
|||||||
from uuid import UUID
|
|
||||||
|
|
||||||
from fastapi import FastAPI, WebSocket
|
from fastapi import FastAPI, WebSocket
|
||||||
|
|
||||||
from paskia.authsession import create_session, get_reset, get_session
|
from paskia import db
|
||||||
|
from paskia.authsession import expires, get_reset
|
||||||
from paskia.fastapi import authz, remote
|
from paskia.fastapi import authz, remote
|
||||||
from paskia.fastapi.session import AUTH_COOKIE, infodict
|
from paskia.fastapi.session import AUTH_COOKIE, infodict
|
||||||
|
from paskia.fastapi.wschat import authenticate_chat, register_chat
|
||||||
from paskia.fastapi.wsutil import validate_origin, websocket_error_handler
|
from paskia.fastapi.wsutil import validate_origin, websocket_error_handler
|
||||||
from paskia.globals import db, passkey
|
from paskia.globals import passkey
|
||||||
from paskia.util import passphrase
|
from paskia.util import hostutil, passphrase
|
||||||
from paskia.util.tokens import create_token, session_key
|
|
||||||
|
|
||||||
# Create a FastAPI subapp for WebSocket endpoints
|
# Create a FastAPI subapp for WebSocket endpoints
|
||||||
app = FastAPI()
|
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
|
|
||||||
# Mount the remote auth WebSocket endpoints
|
# Mount the remote auth WebSocket endpoints
|
||||||
app.mount("/remote-auth", remote.app)
|
app.mount("/remote-auth", remote.app)
|
||||||
|
|
||||||
|
|
||||||
async def register_chat(
|
|
||||||
ws: WebSocket,
|
|
||||||
user_uuid: UUID,
|
|
||||||
user_name: str,
|
|
||||||
origin: str,
|
|
||||||
credential_ids: list[bytes] | None = None,
|
|
||||||
):
|
|
||||||
"""Generate registration options and send them to the client."""
|
|
||||||
options, challenge = passkey.instance.reg_generate_options(
|
|
||||||
user_id=user_uuid,
|
|
||||||
user_name=user_name,
|
|
||||||
credential_ids=credential_ids,
|
|
||||||
)
|
|
||||||
await ws.send_json({"optionsJSON": options})
|
|
||||||
response = await ws.receive_json()
|
|
||||||
return passkey.instance.reg_verify(response, challenge, user_uuid, origin=origin)
|
|
||||||
|
|
||||||
|
|
||||||
@app.websocket("/register")
|
@app.websocket("/register")
|
||||||
@websocket_error_handler
|
@websocket_error_handler
|
||||||
async def websocket_register_add(
|
async def websocket_register_add(
|
||||||
@@ -56,46 +37,44 @@ async def websocket_register_add(
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"The reset link for {passkey.instance.rp_name} is invalid or has expired"
|
f"The reset link for {passkey.instance.rp_name} is invalid or has expired"
|
||||||
)
|
)
|
||||||
s = await get_reset(reset)
|
s = get_reset(reset)
|
||||||
user_uuid = s.user_uuid
|
user_uuid = s.user
|
||||||
else:
|
else:
|
||||||
# Require recent authentication for adding a new passkey
|
# Require recent authentication for adding a new passkey
|
||||||
ctx = await authz.verify(auth, perm=[], host=host, max_age="5m")
|
ctx = await authz.verify(auth, perm=[], host=host, max_age="5m")
|
||||||
user_uuid = ctx.session.user_uuid
|
user_uuid = ctx.session.user
|
||||||
s = ctx.session
|
s = ctx.session
|
||||||
|
|
||||||
# Get user information and determine effective user_name for this registration
|
# Get user information and determine effective user_name for this registration
|
||||||
user = await db.instance.get_user_by_uuid(user_uuid)
|
user = db.data().users.get(user_uuid)
|
||||||
user_name = user.display_name
|
user_name = user.display_name
|
||||||
if name is not None:
|
if name is not None:
|
||||||
stripped = name.strip()
|
stripped = name.strip()
|
||||||
if stripped:
|
if stripped:
|
||||||
user_name = stripped
|
user_name = stripped
|
||||||
challenge_ids = await db.instance.get_credentials_by_user_uuid(user_uuid)
|
credential_ids = db.get_user_credential_ids(user_uuid) or None
|
||||||
|
|
||||||
# WebAuthn registration
|
# WebAuthn registration
|
||||||
credential = await register_chat(ws, user_uuid, user_name, origin, challenge_ids)
|
credential = await register_chat(ws, user_uuid, user_name, origin, credential_ids)
|
||||||
|
|
||||||
# Create a new session and store everything in database
|
# Create a new session and store everything in database
|
||||||
token = create_token()
|
|
||||||
metadata = infodict(ws, "authenticated")
|
metadata = infodict(ws, "authenticated")
|
||||||
await db.instance.create_credential_session( # type: ignore[attr-defined]
|
token = db.create_credential_session( # type: ignore[attr-defined]
|
||||||
user_uuid=user_uuid,
|
user_uuid=user_uuid,
|
||||||
credential=credential,
|
credential=credential,
|
||||||
reset_key=(s.key if reset is not None else None),
|
reset_key=(s.key if reset is not None else None),
|
||||||
session_key=session_key(token),
|
|
||||||
display_name=user_name,
|
display_name=user_name,
|
||||||
host=host,
|
host=host,
|
||||||
ip=metadata.get("ip"),
|
ip=metadata["ip"],
|
||||||
user_agent=metadata.get("user_agent"),
|
user_agent=metadata["user_agent"],
|
||||||
)
|
)
|
||||||
auth = token
|
auth = token
|
||||||
|
|
||||||
assert isinstance(auth, str) and len(auth) == 16
|
assert isinstance(auth, str) and len(auth) == 16
|
||||||
await ws.send_json(
|
await ws.send_json(
|
||||||
{
|
{
|
||||||
"user_uuid": str(user.uuid),
|
"user": str(user.uuid),
|
||||||
"credential_uuid": str(credential.uuid),
|
"credential": str(credential.uuid),
|
||||||
"session_token": auth,
|
"session_token": auth,
|
||||||
"message": "New credential added successfully",
|
"message": "New credential added successfully",
|
||||||
}
|
}
|
||||||
@@ -112,52 +91,41 @@ async def websocket_authenticate(ws: WebSocket, auth=AUTH_COOKIE):
|
|||||||
session_user_uuid = None
|
session_user_uuid = None
|
||||||
credential_ids = None
|
credential_ids = None
|
||||||
if auth:
|
if auth:
|
||||||
try:
|
ctx = db.get_session_context(auth, host)
|
||||||
session = await get_session(auth, host=host)
|
if ctx:
|
||||||
session_user_uuid = session.user_uuid
|
session_user_uuid = ctx.user.uuid
|
||||||
credential_ids = await db.instance.get_credentials_by_user_uuid(
|
credential_ids = db.get_user_credential_ids(session_user_uuid) or None
|
||||||
session_user_uuid
|
|
||||||
)
|
|
||||||
except ValueError:
|
|
||||||
pass # Invalid/expired session - allow normal authentication
|
|
||||||
|
|
||||||
options, challenge = passkey.instance.auth_generate_options(
|
cred, new_sign_count = await authenticate_chat(ws, origin, credential_ids)
|
||||||
credential_ids=credential_ids
|
|
||||||
)
|
|
||||||
await ws.send_json({"optionsJSON": options})
|
|
||||||
# Wait for the client to use his authenticator to authenticate
|
|
||||||
credential = passkey.instance.auth_parse(await ws.receive_json())
|
|
||||||
# Fetch from the database by credential ID
|
|
||||||
try:
|
|
||||||
stored_cred = await db.instance.get_credential_by_id(credential.raw_id)
|
|
||||||
except ValueError:
|
|
||||||
raise ValueError(
|
|
||||||
f"This passkey is no longer registered with {passkey.instance.rp_name}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# If reauth mode, verify the credential belongs to the session's user
|
# If reauth mode, verify the credential belongs to the session's user
|
||||||
if session_user_uuid and stored_cred.user_uuid != session_user_uuid:
|
if session_user_uuid and cred.user != session_user_uuid:
|
||||||
raise ValueError("This passkey belongs to a different account")
|
raise ValueError("This passkey belongs to a different account")
|
||||||
|
|
||||||
# Verify the credential matches the stored data
|
# Create session and update user/credential in a single transaction
|
||||||
passkey.instance.auth_verify(credential, challenge, stored_cred, origin)
|
assert cred.uuid is not None
|
||||||
# Update both credential and user's last_seen timestamp
|
|
||||||
await db.instance.login(stored_cred.user_uuid, stored_cred)
|
|
||||||
|
|
||||||
# Create a session token for the authenticated user
|
|
||||||
assert stored_cred.uuid is not None
|
|
||||||
metadata = infodict(ws, "auth")
|
metadata = infodict(ws, "auth")
|
||||||
token = await create_session(
|
normalized_host = hostutil.normalize_host(host)
|
||||||
user_uuid=stored_cred.user_uuid,
|
if not normalized_host:
|
||||||
credential_uuid=stored_cred.uuid,
|
raise ValueError("Host required for session creation")
|
||||||
host=host,
|
hostname = normalized_host.split(":")[0]
|
||||||
ip=metadata.get("ip") or "",
|
rp_id = passkey.instance.rp_id
|
||||||
user_agent=metadata.get("user_agent") or "",
|
if not (hostname == rp_id or hostname.endswith(f".{rp_id}")):
|
||||||
|
raise ValueError(f"Host must be the same as or a subdomain of {rp_id}")
|
||||||
|
|
||||||
|
token = db.login(
|
||||||
|
user_uuid=cred.user,
|
||||||
|
credential_uuid=cred.uuid,
|
||||||
|
sign_count=new_sign_count,
|
||||||
|
host=normalized_host,
|
||||||
|
ip=metadata["ip"],
|
||||||
|
user_agent=metadata["user_agent"],
|
||||||
|
expiry=expires(),
|
||||||
)
|
)
|
||||||
|
|
||||||
await ws.send_json(
|
await ws.send_json(
|
||||||
{
|
{
|
||||||
"user_uuid": str(stored_cred.user_uuid),
|
"user": str(cred.user),
|
||||||
"session_token": token,
|
"session_token": token,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""
|
||||||
|
WebSocket chat functions for WebAuthn registration and authentication flows.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from fastapi import WebSocket
|
||||||
|
|
||||||
|
from paskia import db
|
||||||
|
from paskia.db import Credential
|
||||||
|
from paskia.globals import passkey
|
||||||
|
|
||||||
|
|
||||||
|
async def register_chat(
|
||||||
|
ws: WebSocket,
|
||||||
|
user_uuid: UUID,
|
||||||
|
user_name: str,
|
||||||
|
origin: str,
|
||||||
|
credential_ids: list[bytes] | None = None,
|
||||||
|
):
|
||||||
|
"""Run WebAuthn registration flow and return the verified credential."""
|
||||||
|
options, challenge = passkey.instance.reg_generate_options(
|
||||||
|
user_id=user_uuid,
|
||||||
|
user_name=user_name,
|
||||||
|
credential_ids=credential_ids,
|
||||||
|
)
|
||||||
|
await ws.send_json({"optionsJSON": options})
|
||||||
|
response = await ws.receive_json()
|
||||||
|
return passkey.instance.reg_verify(response, challenge, user_uuid, origin=origin)
|
||||||
|
|
||||||
|
|
||||||
|
async def authenticate_chat(
|
||||||
|
ws: WebSocket,
|
||||||
|
origin: str,
|
||||||
|
credential_ids: list[bytes] | None = None,
|
||||||
|
) -> tuple[Credential, int]:
|
||||||
|
"""Run WebAuthn authentication flow and return the credential and new sign count.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple of (credential, new_sign_count) where new_sign_count comes from WebAuthn verification
|
||||||
|
"""
|
||||||
|
options, challenge = passkey.instance.auth_generate_options(
|
||||||
|
credential_ids=credential_ids
|
||||||
|
)
|
||||||
|
await ws.send_json({"optionsJSON": options})
|
||||||
|
authcred = passkey.instance.auth_parse(await ws.receive_json())
|
||||||
|
|
||||||
|
cred = next(
|
||||||
|
(
|
||||||
|
c
|
||||||
|
for c in db.data().credentials.values()
|
||||||
|
if c.credential_id == authcred.raw_id
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if not cred:
|
||||||
|
raise ValueError(
|
||||||
|
f"This passkey is no longer registered with {passkey.instance.rp_name}"
|
||||||
|
)
|
||||||
|
|
||||||
|
verification = passkey.instance.auth_verify(authcred, challenge, cred, origin)
|
||||||
|
return cred, verification.new_sign_count
|
||||||
+8
-11
@@ -1,6 +1,7 @@
|
|||||||
from typing import Generic, TypeVar
|
from typing import Generic, TypeVar
|
||||||
|
|
||||||
from paskia.db import DatabaseInterface
|
from paskia import db, remoteauth
|
||||||
|
from paskia.bootstrap import bootstrap_if_needed
|
||||||
from paskia.sansio import Passkey
|
from paskia.sansio import Passkey
|
||||||
|
|
||||||
T = TypeVar("T")
|
T = TypeVar("T")
|
||||||
@@ -38,8 +39,11 @@ async def init(
|
|||||||
If bootstrap=True (default) the system bootstrap_if_needed() will be invoked.
|
If bootstrap=True (default) the system bootstrap_if_needed() will be invoked.
|
||||||
In FastAPI lifespan we call with bootstrap=False to avoid duplicate bootstrapping
|
In FastAPI lifespan we call with bootstrap=False to avoid duplicate bootstrapping
|
||||||
since the CLI performs it once before servers start.
|
since the CLI performs it once before servers start.
|
||||||
|
|
||||||
|
Database configuration:
|
||||||
|
Set PASKIA_DB environment variable to specify the JSONL database file path.
|
||||||
|
Default: paskia.jsonl
|
||||||
"""
|
"""
|
||||||
from . import remoteauth
|
|
||||||
|
|
||||||
# Initialize passkey instance with provided parameters
|
# Initialize passkey instance with provided parameters
|
||||||
passkey.instance = Passkey(
|
passkey.instance = Passkey(
|
||||||
@@ -48,24 +52,17 @@ async def init(
|
|||||||
origins=origins,
|
origins=origins,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Test if we have a database already initialized, otherwise use SQL
|
# Initialize database
|
||||||
try:
|
await db.init()
|
||||||
db.instance
|
|
||||||
except RuntimeError:
|
|
||||||
from .db import sql
|
|
||||||
|
|
||||||
await sql.init()
|
|
||||||
|
|
||||||
# Initialize remote auth manager
|
# Initialize remote auth manager
|
||||||
await remoteauth.init()
|
await remoteauth.init()
|
||||||
|
|
||||||
if bootstrap:
|
if bootstrap:
|
||||||
# Bootstrap system if needed
|
# Bootstrap system if needed
|
||||||
from .bootstrap import bootstrap_if_needed
|
|
||||||
|
|
||||||
await bootstrap_if_needed()
|
await bootstrap_if_needed()
|
||||||
|
|
||||||
|
|
||||||
# Global instances
|
# Global instances
|
||||||
passkey = Manager[Passkey]("Passkey")
|
passkey = Manager[Passkey]("Passkey")
|
||||||
db = Manager[DatabaseInterface]("Database")
|
|
||||||
|
|||||||
@@ -0,0 +1,281 @@
|
|||||||
|
"""
|
||||||
|
SQL to JSON migration module for Paskia.
|
||||||
|
|
||||||
|
This module contains the legacy SQL database implementation and migration tools
|
||||||
|
for converting from the old SQLite database to the new JSONL format.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python -m paskia.migrate --sql sqlite+aiosqlite:///paskia.sqlite --json paskia.jsonl
|
||||||
|
|
||||||
|
Or via the CLI entry point (if installed):
|
||||||
|
paskia-migrate --sql sqlite+aiosqlite:///paskia.sqlite --json paskia.jsonl
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
import base64url
|
||||||
|
import uuid7
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from paskia.authsession import EXPIRES
|
||||||
|
from paskia.db.jsonl import JsonlStore
|
||||||
|
from paskia.db.structs import (
|
||||||
|
DB,
|
||||||
|
Credential,
|
||||||
|
Org,
|
||||||
|
Permission,
|
||||||
|
ResetToken,
|
||||||
|
Role,
|
||||||
|
Session,
|
||||||
|
User,
|
||||||
|
)
|
||||||
|
|
||||||
|
from .sql import (
|
||||||
|
DB as SQLDB,
|
||||||
|
)
|
||||||
|
from .sql import (
|
||||||
|
CredentialModel,
|
||||||
|
ResetTokenModel,
|
||||||
|
SessionModel,
|
||||||
|
UserModel,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Re-export for convenience
|
||||||
|
__all__ = ["migrate_from_sql", "main", "SQLDB"]
|
||||||
|
|
||||||
|
# Default paths
|
||||||
|
SQL_DB_DEFAULT = "sqlite+aiosqlite:///paskia.sqlite"
|
||||||
|
JSON_DB_DEFAULT = "paskia.jsonl"
|
||||||
|
|
||||||
|
|
||||||
|
async def migrate_from_sql(
|
||||||
|
sql_db_path: str = SQL_DB_DEFAULT,
|
||||||
|
json_db_path: str = JSON_DB_DEFAULT,
|
||||||
|
) -> None:
|
||||||
|
"""Migrate data from SQL database to JSON format.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
sql_db_path: SQLAlchemy connection string for the source SQL database
|
||||||
|
json_db_path: Path for the destination JSONL file
|
||||||
|
"""
|
||||||
|
# Initialize source SQL database
|
||||||
|
sql_db = SQLDB(sql_db_path)
|
||||||
|
await sql_db.init_db()
|
||||||
|
|
||||||
|
# Initialize destination JSON database (fresh, don't load existing)
|
||||||
|
db = DB()
|
||||||
|
store = JsonlStore(db, json_db_path)
|
||||||
|
db._store = store
|
||||||
|
|
||||||
|
print(f"Migrating from {sql_db_path} to {json_db_path}...")
|
||||||
|
|
||||||
|
# Build all data directly without saving (we'll save once at the end)
|
||||||
|
# Track old permission ID -> new scope mapping for migration
|
||||||
|
# Also track org-specific admin permissions to consolidate
|
||||||
|
old_org_admin_pattern = re.compile(r"^auth:org:([0-9a-f-]+)$", re.IGNORECASE)
|
||||||
|
org_admin_uuids = set() # org UUIDs that had org-specific admin permissions
|
||||||
|
|
||||||
|
# First pass: identify org-specific admin permissions
|
||||||
|
permissions = await sql_db.list_permissions()
|
||||||
|
for perm in permissions:
|
||||||
|
match = old_org_admin_pattern.match(perm.id)
|
||||||
|
if match:
|
||||||
|
org_admin_uuids.add(match.group(1).lower())
|
||||||
|
|
||||||
|
# Migrate permissions with UUID keys and scope field
|
||||||
|
# Always create exactly one common auth:org:admin permission for all org admin needs
|
||||||
|
org_admin_perm_uuid: UUID = uuid7.create()
|
||||||
|
org_admin_perm = Permission(
|
||||||
|
scope="auth:org:admin",
|
||||||
|
display_name="Org Admin",
|
||||||
|
orgs={},
|
||||||
|
)
|
||||||
|
org_admin_perm.uuid = org_admin_perm_uuid
|
||||||
|
db.permissions[org_admin_perm_uuid] = org_admin_perm
|
||||||
|
|
||||||
|
# Mapping from old permission ID to new permission UUID
|
||||||
|
perm_id_to_uuid: dict[str, UUID] = {}
|
||||||
|
|
||||||
|
for perm in permissions:
|
||||||
|
# Skip old org-specific admin permissions (auth:org:{uuid}) - they map to auth:org:admin
|
||||||
|
match = old_org_admin_pattern.match(perm.id)
|
||||||
|
if match:
|
||||||
|
perm_id_to_uuid[perm.id] = org_admin_perm_uuid
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Skip if this is already auth:org:admin - we created one above
|
||||||
|
if perm.id == "auth:org:admin":
|
||||||
|
perm_id_to_uuid[perm.id] = org_admin_perm_uuid
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Regular permission - create with UUID key
|
||||||
|
perm_uuid: UUID = uuid7.create()
|
||||||
|
new_perm = Permission(
|
||||||
|
scope=perm.id, # Old ID becomes the scope
|
||||||
|
display_name=perm.display_name,
|
||||||
|
orgs={},
|
||||||
|
)
|
||||||
|
new_perm.uuid = perm_uuid
|
||||||
|
db.permissions[perm_uuid] = new_perm
|
||||||
|
perm_id_to_uuid[perm.id] = perm_uuid
|
||||||
|
print(
|
||||||
|
f" Migrated {len(permissions)} permissions (with {len(org_admin_uuids)} org-specific admins consolidated to auth:org:admin)"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Migrate organizations
|
||||||
|
orgs = await sql_db.list_organizations()
|
||||||
|
for org in orgs:
|
||||||
|
org_key: UUID = org.uuid
|
||||||
|
new_org = Org(display_name=org.display_name)
|
||||||
|
new_org.uuid = org_key
|
||||||
|
db.orgs[org_key] = new_org
|
||||||
|
# Update permissions to allow this org to grant them (by UUID)
|
||||||
|
for old_perm_id in org.permissions:
|
||||||
|
perm_uuid = perm_id_to_uuid.get(old_perm_id)
|
||||||
|
if perm_uuid and perm_uuid in db.permissions:
|
||||||
|
db.permissions[perm_uuid].orgs[org_key] = True
|
||||||
|
# Ensure every org can grant auth:org:admin
|
||||||
|
db.permissions[org_admin_perm_uuid].orgs[org_key] = True
|
||||||
|
print(f" Migrated {len(orgs)} organizations")
|
||||||
|
|
||||||
|
# Migrate roles - convert old permission IDs to UUIDs
|
||||||
|
role_count = 0
|
||||||
|
for org in orgs:
|
||||||
|
for role in org.roles:
|
||||||
|
role_key: UUID = role.uuid
|
||||||
|
# Convert old permission IDs to UUIDs
|
||||||
|
new_permissions: dict[UUID, bool] = {}
|
||||||
|
for old_perm_id in role.permissions or []:
|
||||||
|
perm_uuid = perm_id_to_uuid.get(old_perm_id)
|
||||||
|
if perm_uuid:
|
||||||
|
new_permissions[perm_uuid] = True
|
||||||
|
new_role = Role(
|
||||||
|
org=role.org_uuid,
|
||||||
|
display_name=role.display_name,
|
||||||
|
permissions=new_permissions,
|
||||||
|
)
|
||||||
|
new_role.uuid = role_key
|
||||||
|
db.roles[role_key] = new_role
|
||||||
|
role_count += 1
|
||||||
|
print(f" Migrated {role_count} roles")
|
||||||
|
|
||||||
|
# Migrate users
|
||||||
|
async with sql_db.session() as session:
|
||||||
|
result = await session.execute(select(UserModel))
|
||||||
|
user_models = result.scalars().all()
|
||||||
|
for um in user_models:
|
||||||
|
legacy_user = um.as_dataclass()
|
||||||
|
user_key: UUID = legacy_user.uuid
|
||||||
|
new_user = User(
|
||||||
|
display_name=legacy_user.display_name,
|
||||||
|
role=legacy_user.role_uuid,
|
||||||
|
created_at=legacy_user.created_at or datetime.now(timezone.utc),
|
||||||
|
last_seen=legacy_user.last_seen,
|
||||||
|
visits=legacy_user.visits,
|
||||||
|
)
|
||||||
|
new_user.uuid = user_key
|
||||||
|
db.users[user_key] = new_user
|
||||||
|
print(f" Migrated {len(user_models)} users")
|
||||||
|
|
||||||
|
# Migrate credentials
|
||||||
|
async with sql_db.session() as session:
|
||||||
|
result = await session.execute(select(CredentialModel))
|
||||||
|
cred_models = result.scalars().all()
|
||||||
|
for cm in cred_models:
|
||||||
|
legacy_cred = cm.as_dataclass()
|
||||||
|
cred_key: UUID = legacy_cred.uuid
|
||||||
|
new_cred = Credential(
|
||||||
|
credential_id=legacy_cred.credential_id,
|
||||||
|
user=legacy_cred.user_uuid,
|
||||||
|
aaguid=legacy_cred.aaguid,
|
||||||
|
public_key=legacy_cred.public_key,
|
||||||
|
sign_count=legacy_cred.sign_count,
|
||||||
|
created_at=legacy_cred.created_at,
|
||||||
|
last_used=legacy_cred.last_used,
|
||||||
|
last_verified=legacy_cred.last_verified,
|
||||||
|
)
|
||||||
|
new_cred.uuid = cred_key
|
||||||
|
db.credentials[cred_key] = new_cred
|
||||||
|
print(f" Migrated {len(cred_models)} credentials")
|
||||||
|
|
||||||
|
# Migrate sessions
|
||||||
|
# Old format: b"sess" + 12 bytes -> New format: base64url string (16 chars)
|
||||||
|
async with sql_db.session() as session:
|
||||||
|
result = await session.execute(select(SessionModel))
|
||||||
|
session_models = result.scalars().all()
|
||||||
|
for sm in session_models:
|
||||||
|
sess = sm.as_dataclass()
|
||||||
|
old_key: bytes = sess.key
|
||||||
|
# Strip b"sess" prefix and encode remaining 12 bytes as base64url
|
||||||
|
if old_key.startswith(b"sess"):
|
||||||
|
session_key = base64url.enc(old_key[4:])
|
||||||
|
else:
|
||||||
|
# Already in new format or unknown - try to use as-is
|
||||||
|
session_key = base64url.enc(old_key[:12])
|
||||||
|
db.sessions[session_key] = Session(
|
||||||
|
user=sess.user_uuid,
|
||||||
|
credential=sess.credential_uuid,
|
||||||
|
host=sess.host,
|
||||||
|
ip=sess.ip,
|
||||||
|
user_agent=sess.user_agent,
|
||||||
|
expiry=sess.renewed + EXPIRES, # Convert renewed to expiry
|
||||||
|
)
|
||||||
|
print(f" Migrated {len(session_models)} sessions")
|
||||||
|
|
||||||
|
# Migrate reset tokens
|
||||||
|
# Old format: b"rset" + 16 bytes hash -> New format: 9 bytes (truncated hash)
|
||||||
|
async with sql_db.session() as session:
|
||||||
|
result = await session.execute(select(ResetTokenModel))
|
||||||
|
token_models = result.scalars().all()
|
||||||
|
for tm in token_models:
|
||||||
|
token = tm.as_dataclass()
|
||||||
|
old_key: bytes = token.key
|
||||||
|
# Strip b"rset" prefix and take first 9 bytes of hash
|
||||||
|
if old_key.startswith(b"rset"):
|
||||||
|
token_key = old_key[4:13] # 9 bytes after prefix
|
||||||
|
else:
|
||||||
|
# Already in new format or unknown - truncate to 9 bytes
|
||||||
|
token_key = old_key[:9]
|
||||||
|
db.reset_tokens[token_key] = ResetToken(
|
||||||
|
user=token.user_uuid,
|
||||||
|
expiry=token.expiry,
|
||||||
|
token_type=token.token_type,
|
||||||
|
)
|
||||||
|
print(f" Migrated {len(token_models)} reset tokens")
|
||||||
|
|
||||||
|
# Queue and flush all changes using the transaction mechanism
|
||||||
|
with db.transaction("migrate"):
|
||||||
|
pass # All data already added to _data, transaction commits on exit
|
||||||
|
|
||||||
|
await store.flush()
|
||||||
|
|
||||||
|
print("Migration complete!")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""CLI entry point for migration."""
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Migrate Paskia database from SQL to JSON"
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--sql",
|
||||||
|
default=SQL_DB_DEFAULT,
|
||||||
|
help=f"Source SQL database connection string (default: {SQL_DB_DEFAULT})",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--json",
|
||||||
|
default=JSON_DB_DEFAULT,
|
||||||
|
help=f"Destination JSONL file path (default: {JSON_DB_DEFAULT})",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
asyncio.run(migrate_from_sql(args.sql, args.json))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
"""
|
||||||
|
Legacy SQL database implementation for migration purposes.
|
||||||
|
|
||||||
|
This module provides the async SQLAlchemy database layer that was used
|
||||||
|
before the JSONL format. It is kept here for migration purposes only.
|
||||||
|
|
||||||
|
DO NOT use this module for new code. Use paskia.db instead.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from sqlalchemy import (
|
||||||
|
DateTime,
|
||||||
|
ForeignKey,
|
||||||
|
Integer,
|
||||||
|
LargeBinary,
|
||||||
|
String,
|
||||||
|
event,
|
||||||
|
select,
|
||||||
|
)
|
||||||
|
from sqlalchemy.dialects.sqlite import BLOB
|
||||||
|
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||||
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||||
|
|
||||||
|
from paskia.db import (
|
||||||
|
Org,
|
||||||
|
Role,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Legacy User class for SQL schema (uses 'role_uuid' not 'role')
|
||||||
|
@dataclass
|
||||||
|
class _LegacyUser:
|
||||||
|
"""User as stored in the old SQL schema with role_uuid field."""
|
||||||
|
|
||||||
|
uuid: UUID
|
||||||
|
display_name: str
|
||||||
|
role_uuid: UUID
|
||||||
|
created_at: datetime | None = None
|
||||||
|
last_seen: datetime | None = None
|
||||||
|
visits: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
# Legacy Credential class for SQL schema (uses 'user_uuid' not 'user')
|
||||||
|
@dataclass
|
||||||
|
class _LegacyCredential:
|
||||||
|
"""Credential as stored in the old SQL schema with user_uuid field."""
|
||||||
|
|
||||||
|
uuid: UUID
|
||||||
|
credential_id: bytes
|
||||||
|
user_uuid: UUID
|
||||||
|
aaguid: UUID
|
||||||
|
public_key: bytes
|
||||||
|
sign_count: int
|
||||||
|
created_at: datetime
|
||||||
|
last_used: datetime | None = None
|
||||||
|
last_verified: datetime | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# Legacy Role class for SQL schema (uses 'org_uuid' not 'org')
|
||||||
|
@dataclass
|
||||||
|
class _LegacyRole:
|
||||||
|
"""Role as stored in the old SQL schema with org_uuid field."""
|
||||||
|
|
||||||
|
uuid: UUID
|
||||||
|
org_uuid: UUID
|
||||||
|
display_name: str
|
||||||
|
permissions: list[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
# Legacy Session class for SQL schema (uses 'key' as field, 'user_uuid', 'credential_uuid')
|
||||||
|
@dataclass
|
||||||
|
class _LegacySession:
|
||||||
|
"""Session as stored in the old SQL schema."""
|
||||||
|
|
||||||
|
key: bytes
|
||||||
|
user_uuid: UUID
|
||||||
|
credential_uuid: UUID
|
||||||
|
host: str
|
||||||
|
ip: str
|
||||||
|
user_agent: str
|
||||||
|
renewed: datetime
|
||||||
|
|
||||||
|
|
||||||
|
# Legacy ResetToken class for SQL schema (uses 'key' as field, 'user_uuid')
|
||||||
|
@dataclass
|
||||||
|
class _LegacyResetToken:
|
||||||
|
"""ResetToken as stored in the old SQL schema."""
|
||||||
|
|
||||||
|
key: bytes
|
||||||
|
user_uuid: UUID
|
||||||
|
token_type: str
|
||||||
|
expiry: datetime
|
||||||
|
|
||||||
|
|
||||||
|
# Local Permission class for SQL schema (uses 'id' not 'uuid' + 'scope')
|
||||||
|
@dataclass
|
||||||
|
class SqlPermission:
|
||||||
|
"""Permission as stored in the old SQL schema with id field."""
|
||||||
|
|
||||||
|
id: str
|
||||||
|
display_name: str
|
||||||
|
|
||||||
|
|
||||||
|
DB_PATH_DEFAULT = "sqlite+aiosqlite:///paskia.sqlite"
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_dt(value: datetime | None) -> datetime | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if value.tzinfo is None:
|
||||||
|
return value.replace(tzinfo=timezone.utc)
|
||||||
|
return value.astimezone(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class OrgModel(Base):
|
||||||
|
__tablename__ = "orgs"
|
||||||
|
|
||||||
|
uuid: Mapped[bytes] = mapped_column(LargeBinary(16), primary_key=True)
|
||||||
|
display_name: Mapped[str] = mapped_column(String, nullable=False)
|
||||||
|
|
||||||
|
def as_dataclass(self):
|
||||||
|
# Base Org without permissions/roles (filled by data accessors)
|
||||||
|
org = Org(display_name=self.display_name)
|
||||||
|
org.uuid = UUID(bytes=self.uuid)
|
||||||
|
return org
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_dataclass(org: Org):
|
||||||
|
return OrgModel(uuid=org.uuid.bytes, display_name=org.display_name)
|
||||||
|
|
||||||
|
|
||||||
|
class RoleModel(Base):
|
||||||
|
__tablename__ = "roles"
|
||||||
|
|
||||||
|
uuid: Mapped[bytes] = mapped_column(LargeBinary(16), primary_key=True)
|
||||||
|
org_uuid: Mapped[bytes] = mapped_column(
|
||||||
|
LargeBinary(16), ForeignKey("orgs.uuid", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
display_name: Mapped[str] = mapped_column(String, nullable=False)
|
||||||
|
|
||||||
|
def as_dataclass(self):
|
||||||
|
# Base Role without permissions (filled by data accessors)
|
||||||
|
return _LegacyRole(
|
||||||
|
uuid=UUID(bytes=self.uuid),
|
||||||
|
org_uuid=UUID(bytes=self.org_uuid),
|
||||||
|
display_name=self.display_name,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_dataclass(role: _LegacyRole):
|
||||||
|
return RoleModel(
|
||||||
|
uuid=role.uuid.bytes,
|
||||||
|
org_uuid=role.org_uuid.bytes,
|
||||||
|
display_name=role.display_name,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class UserModel(Base):
|
||||||
|
__tablename__ = "users"
|
||||||
|
|
||||||
|
uuid: Mapped[bytes] = mapped_column(LargeBinary(16), primary_key=True)
|
||||||
|
display_name: Mapped[str] = mapped_column(String, nullable=False)
|
||||||
|
role_uuid: Mapped[bytes] = mapped_column(
|
||||||
|
LargeBinary(16), ForeignKey("roles.uuid", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
|
||||||
|
)
|
||||||
|
last_seen: Mapped[datetime | None] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=True
|
||||||
|
)
|
||||||
|
visits: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||||
|
|
||||||
|
def as_dataclass(self) -> "_LegacyUser":
|
||||||
|
return _LegacyUser(
|
||||||
|
uuid=UUID(bytes=self.uuid),
|
||||||
|
display_name=self.display_name,
|
||||||
|
role_uuid=UUID(bytes=self.role_uuid),
|
||||||
|
created_at=_normalize_dt(self.created_at) or self.created_at,
|
||||||
|
last_seen=_normalize_dt(self.last_seen) or self.last_seen,
|
||||||
|
visits=self.visits,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_dataclass(user: "_LegacyUser"):
|
||||||
|
return UserModel(
|
||||||
|
uuid=user.uuid.bytes,
|
||||||
|
display_name=user.display_name,
|
||||||
|
role_uuid=user.role_uuid.bytes,
|
||||||
|
created_at=user.created_at or datetime.now(timezone.utc),
|
||||||
|
last_seen=user.last_seen,
|
||||||
|
visits=user.visits,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class CredentialModel(Base):
|
||||||
|
__tablename__ = "credentials"
|
||||||
|
|
||||||
|
uuid: Mapped[bytes] = mapped_column(LargeBinary(16), primary_key=True)
|
||||||
|
credential_id: Mapped[bytes] = mapped_column(
|
||||||
|
LargeBinary(64), unique=True, index=True
|
||||||
|
)
|
||||||
|
user_uuid: Mapped[bytes] = mapped_column(
|
||||||
|
LargeBinary(16), ForeignKey("users.uuid", ondelete="CASCADE")
|
||||||
|
)
|
||||||
|
aaguid: Mapped[bytes] = mapped_column(LargeBinary(16), nullable=False)
|
||||||
|
public_key: Mapped[bytes] = mapped_column(BLOB, nullable=False)
|
||||||
|
sign_count: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
|
||||||
|
)
|
||||||
|
last_used: Mapped[datetime | None] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=True
|
||||||
|
)
|
||||||
|
last_verified: Mapped[datetime | None] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=True
|
||||||
|
)
|
||||||
|
|
||||||
|
def as_dataclass(self):
|
||||||
|
return _LegacyCredential(
|
||||||
|
uuid=UUID(bytes=self.uuid),
|
||||||
|
credential_id=self.credential_id,
|
||||||
|
user_uuid=UUID(bytes=self.user_uuid),
|
||||||
|
aaguid=UUID(bytes=self.aaguid),
|
||||||
|
public_key=self.public_key,
|
||||||
|
sign_count=self.sign_count,
|
||||||
|
created_at=_normalize_dt(self.created_at) or self.created_at,
|
||||||
|
last_used=_normalize_dt(self.last_used) or self.last_used,
|
||||||
|
last_verified=_normalize_dt(self.last_verified) or self.last_verified,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SessionModel(Base):
|
||||||
|
__tablename__ = "sessions"
|
||||||
|
|
||||||
|
key: Mapped[bytes] = mapped_column(LargeBinary(16), primary_key=True)
|
||||||
|
user_uuid: Mapped[bytes] = mapped_column(
|
||||||
|
LargeBinary(16), ForeignKey("users.uuid", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
credential_uuid: Mapped[bytes] = mapped_column(
|
||||||
|
LargeBinary(16),
|
||||||
|
ForeignKey("credentials.uuid", ondelete="CASCADE"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
host: Mapped[str] = mapped_column(String, nullable=False)
|
||||||
|
ip: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
user_agent: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||||
|
renewed: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True),
|
||||||
|
default=lambda: datetime.now(timezone.utc),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
def as_dataclass(self):
|
||||||
|
return _LegacySession(
|
||||||
|
key=self.key,
|
||||||
|
user_uuid=UUID(bytes=self.user_uuid),
|
||||||
|
credential_uuid=UUID(bytes=self.credential_uuid),
|
||||||
|
host=self.host,
|
||||||
|
ip=self.ip,
|
||||||
|
user_agent=self.user_agent,
|
||||||
|
renewed=_normalize_dt(self.renewed) or self.renewed,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_dataclass(session: _LegacySession):
|
||||||
|
return SessionModel(
|
||||||
|
key=session.key,
|
||||||
|
user_uuid=session.user_uuid.bytes,
|
||||||
|
credential_uuid=session.credential_uuid.bytes,
|
||||||
|
host=session.host,
|
||||||
|
ip=session.ip,
|
||||||
|
user_agent=session.user_agent,
|
||||||
|
renewed=session.renewed,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ResetTokenModel(Base):
|
||||||
|
__tablename__ = "reset_tokens"
|
||||||
|
|
||||||
|
key: Mapped[bytes] = mapped_column(LargeBinary(16), primary_key=True)
|
||||||
|
user_uuid: Mapped[bytes] = mapped_column(
|
||||||
|
LargeBinary(16), ForeignKey("users.uuid", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
token_type: Mapped[str] = mapped_column(String, nullable=False)
|
||||||
|
expiry: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
|
||||||
|
def as_dataclass(self) -> _LegacyResetToken:
|
||||||
|
return _LegacyResetToken(
|
||||||
|
key=self.key,
|
||||||
|
user_uuid=UUID(bytes=self.user_uuid),
|
||||||
|
token_type=self.token_type,
|
||||||
|
expiry=_normalize_dt(self.expiry) or self.expiry,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class PermissionModel(Base):
|
||||||
|
__tablename__ = "permissions"
|
||||||
|
|
||||||
|
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||||
|
display_name: Mapped[str] = mapped_column(String, nullable=False)
|
||||||
|
|
||||||
|
def as_dataclass(self):
|
||||||
|
return SqlPermission(self.id, self.display_name)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_dataclass(permission: SqlPermission):
|
||||||
|
return PermissionModel(
|
||||||
|
id=permission.id,
|
||||||
|
display_name=permission.display_name,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class OrgPermission(Base):
|
||||||
|
"""Permissions each organization is allowed to grant to its roles."""
|
||||||
|
|
||||||
|
__tablename__ = "org_permissions"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
org_uuid: Mapped[bytes] = mapped_column(
|
||||||
|
LargeBinary(16), ForeignKey("orgs.uuid", ondelete="CASCADE")
|
||||||
|
)
|
||||||
|
permission_id: Mapped[str] = mapped_column(
|
||||||
|
String(64), ForeignKey("permissions.id", ondelete="CASCADE")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RolePermission(Base):
|
||||||
|
"""Permissions that each role grants to its members."""
|
||||||
|
|
||||||
|
__tablename__ = "role_permissions"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
|
role_uuid: Mapped[bytes] = mapped_column(
|
||||||
|
LargeBinary(16), ForeignKey("roles.uuid", ondelete="CASCADE")
|
||||||
|
)
|
||||||
|
permission_id: Mapped[str] = mapped_column(
|
||||||
|
String(64), ForeignKey("permissions.id", ondelete="CASCADE")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class DB:
|
||||||
|
"""Legacy SQL database class for migration purposes only."""
|
||||||
|
|
||||||
|
def __init__(self, db_path: str = DB_PATH_DEFAULT):
|
||||||
|
"""Initialize with database path."""
|
||||||
|
self.engine = create_async_engine(db_path, echo=False)
|
||||||
|
# Ensure SQLite foreign key enforcement is ON for every new connection
|
||||||
|
if db_path.startswith("sqlite"):
|
||||||
|
|
||||||
|
@event.listens_for(self.engine.sync_engine, "connect")
|
||||||
|
def _fk_on(dbapi_connection, connection_record):
|
||||||
|
try:
|
||||||
|
cursor = dbapi_connection.cursor()
|
||||||
|
cursor.execute("PRAGMA foreign_keys=ON;")
|
||||||
|
cursor.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
self.async_session_factory = async_sessionmaker(
|
||||||
|
self.engine, expire_on_commit=False
|
||||||
|
)
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def session(self):
|
||||||
|
"""Async context manager that provides a database session with transaction."""
|
||||||
|
async with self.async_session_factory() as session:
|
||||||
|
async with session.begin():
|
||||||
|
yield session
|
||||||
|
await session.flush()
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
async def init_db(self) -> None:
|
||||||
|
"""Initialize database tables."""
|
||||||
|
async with self.engine.begin() as conn:
|
||||||
|
await conn.run_sync(Base.metadata.create_all)
|
||||||
|
|
||||||
|
async def list_permissions(self) -> list[SqlPermission]:
|
||||||
|
async with self.session() as session:
|
||||||
|
result = await session.execute(select(PermissionModel))
|
||||||
|
return [p.as_dataclass() for p in result.scalars().all()]
|
||||||
|
|
||||||
|
async def list_organizations(self) -> list[Org]:
|
||||||
|
async with self.session() as session:
|
||||||
|
# Load all orgs
|
||||||
|
orgs_result = await session.execute(select(OrgModel))
|
||||||
|
org_models = orgs_result.scalars().all()
|
||||||
|
if not org_models:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# Preload org permissions mapping
|
||||||
|
org_perms_result = await session.execute(select(OrgPermission))
|
||||||
|
org_perms = org_perms_result.scalars().all()
|
||||||
|
perms_by_org: dict[bytes, list[str]] = {}
|
||||||
|
for op in org_perms:
|
||||||
|
perms_by_org.setdefault(op.org_uuid, []).append(op.permission_id)
|
||||||
|
|
||||||
|
# Preload roles
|
||||||
|
roles_result = await session.execute(select(RoleModel))
|
||||||
|
role_models = roles_result.scalars().all()
|
||||||
|
|
||||||
|
# Preload role permissions mapping
|
||||||
|
rp_result = await session.execute(select(RolePermission))
|
||||||
|
rps = rp_result.scalars().all()
|
||||||
|
perms_by_role: dict[bytes, list[str]] = {}
|
||||||
|
for rp in rps:
|
||||||
|
perms_by_role.setdefault(rp.role_uuid, []).append(rp.permission_id)
|
||||||
|
|
||||||
|
# Build org dataclasses with roles and permission IDs
|
||||||
|
roles_by_org: dict[bytes, list[Role]] = {}
|
||||||
|
for rm in role_models:
|
||||||
|
r_dc = rm.as_dataclass()
|
||||||
|
r_dc.permissions = perms_by_role.get(rm.uuid, [])
|
||||||
|
roles_by_org.setdefault(rm.org_uuid, []).append(r_dc)
|
||||||
|
|
||||||
|
orgs: list[Org] = []
|
||||||
|
for om in org_models:
|
||||||
|
o_dc = om.as_dataclass()
|
||||||
|
o_dc.permissions = perms_by_org.get(om.uuid, [])
|
||||||
|
o_dc.roles = roles_by_org.get(om.uuid, [])
|
||||||
|
orgs.append(o_dc)
|
||||||
|
|
||||||
|
return orgs
|
||||||
@@ -24,7 +24,7 @@ from datetime import datetime, timedelta, timezone
|
|||||||
from typing import Callable
|
from typing import Callable
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from paskia.util import passphrase
|
from paskia.util import passphrase, pow
|
||||||
|
|
||||||
# Remote auth requests expire after this duration
|
# Remote auth requests expire after this duration
|
||||||
REMOTE_AUTH_LIFETIME = timedelta(minutes=5)
|
REMOTE_AUTH_LIFETIME = timedelta(minutes=5)
|
||||||
@@ -319,7 +319,6 @@ class RemoteAuthManager:
|
|||||||
Returns:
|
Returns:
|
||||||
PoW work units (pow.NORMAL or pow.HARD)
|
PoW work units (pow.NORMAL or pow.HARD)
|
||||||
"""
|
"""
|
||||||
from paskia.util import pow
|
|
||||||
|
|
||||||
count = self.get_connection_count()
|
count = self.get_connection_count()
|
||||||
return pow.HARD if count >= 10 else pow.NORMAL
|
return pow.HARD if count >= 10 else pow.NORMAL
|
||||||
|
|||||||
+6
-12
@@ -8,11 +8,9 @@ This module provides a unified interface for WebAuthn operations including:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from datetime import datetime, timezone
|
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
import uuid7
|
|
||||||
from webauthn import (
|
from webauthn import (
|
||||||
generate_authentication_options,
|
generate_authentication_options,
|
||||||
generate_registration_options,
|
generate_registration_options,
|
||||||
@@ -176,14 +174,12 @@ class Passkey:
|
|||||||
expected_origin=origin,
|
expected_origin=origin,
|
||||||
expected_rp_id=self.rp_id,
|
expected_rp_id=self.rp_id,
|
||||||
)
|
)
|
||||||
return Credential(
|
return Credential.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
credential_id=credential.raw_id,
|
credential_id=credential.raw_id,
|
||||||
user_uuid=user_uuid,
|
user=user_uuid,
|
||||||
aaguid=UUID(registration.aaguid),
|
aaguid=UUID(registration.aaguid),
|
||||||
public_key=registration.credential_public_key,
|
public_key=registration.credential_public_key,
|
||||||
sign_count=registration.sign_count,
|
sign_count=registration.sign_count,
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
### Authentication Methods ###
|
### Authentication Methods ###
|
||||||
@@ -234,8 +230,11 @@ class Passkey:
|
|||||||
Args:
|
Args:
|
||||||
credential: The authentication credential response from the client
|
credential: The authentication credential response from the client
|
||||||
expected_challenge: The earlier generated challenge bytes
|
expected_challenge: The earlier generated challenge bytes
|
||||||
stored_cred: The server stored credential record (modified by this function)
|
stored_cred: The server stored credential record (NOT modified)
|
||||||
origin: The origin URL (required, must be pre-validated)
|
origin: The origin URL (required, must be pre-validated)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
VerifiedAuthentication with new_sign_count and user_verified status
|
||||||
"""
|
"""
|
||||||
# Verify the authentication response
|
# Verify the authentication response
|
||||||
verification = verify_authentication_response(
|
verification = verify_authentication_response(
|
||||||
@@ -246,11 +245,6 @@ class Passkey:
|
|||||||
credential_public_key=stored_cred.public_key,
|
credential_public_key=stored_cred.public_key,
|
||||||
credential_current_sign_count=stored_cred.sign_count,
|
credential_current_sign_count=stored_cred.sign_count,
|
||||||
)
|
)
|
||||||
stored_cred.sign_count = verification.new_sign_count
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
stored_cred.last_used = now
|
|
||||||
if verification.user_verified:
|
|
||||||
stored_cred.last_verified = now
|
|
||||||
return verification
|
return verification
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ __all__ = ["path", "file", "read", "is_dev_mode"]
|
|||||||
|
|
||||||
def _get_dev_server() -> str | None:
|
def _get_dev_server() -> str | None:
|
||||||
"""Get the dev server URL from environment, or None if not in dev mode."""
|
"""Get the dev server URL from environment, or None if not in dev mode."""
|
||||||
return os.environ.get("PASKIA_DEVMODE") or None
|
return os.environ.get("FASTAPI_VUE_FRONTEND_URL") or None
|
||||||
|
|
||||||
|
|
||||||
def _resolve_static_dir() -> Path:
|
def _resolve_static_dir() -> Path:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
from urllib.parse import urlsplit
|
from urllib.parse import urlparse, urlsplit
|
||||||
|
|
||||||
|
|
||||||
@lru_cache(maxsize=1)
|
@lru_cache(maxsize=1)
|
||||||
@@ -24,7 +24,6 @@ def dedicated_auth_host() -> str | None:
|
|||||||
auth_host = _load_config().get("auth_host")
|
auth_host = _load_config().get("auth_host")
|
||||||
if not auth_host:
|
if not auth_host:
|
||||||
return None
|
return None
|
||||||
from urllib.parse import urlparse
|
|
||||||
|
|
||||||
parsed = urlparse(auth_host if "://" in auth_host else f"//{auth_host}")
|
parsed = urlparse(auth_host if "://" in auth_host else f"//{auth_host}")
|
||||||
return parsed.netloc or parsed.path or None
|
return parsed.netloc or parsed.path or None
|
||||||
|
|||||||
+16
-5
@@ -3,9 +3,8 @@
|
|||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
from fnmatch import fnmatchcase
|
from fnmatch import fnmatchcase
|
||||||
|
|
||||||
from paskia.globals import db
|
from paskia import db
|
||||||
from paskia.util.hostutil import normalize_host
|
from paskia.util.hostutil import normalize_host
|
||||||
from paskia.util.tokens import session_key
|
|
||||||
|
|
||||||
__all__ = ["has_any", "has_all", "session_context"]
|
__all__ = ["has_any", "has_all", "session_context"]
|
||||||
|
|
||||||
@@ -17,16 +16,28 @@ def _match(perms: set[str], patterns: Sequence[str]):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _get_effective_scopes(ctx) -> set[str]:
|
||||||
|
"""Get effective permission scopes from context.
|
||||||
|
|
||||||
|
Returns scopes from ctx.permissions (filtered by org) if available,
|
||||||
|
otherwise falls back to ctx.role.permissions for backwards compatibility.
|
||||||
|
"""
|
||||||
|
if ctx.permissions:
|
||||||
|
return {p.scope for p in ctx.permissions}
|
||||||
|
# Fallback for contexts without effective permissions computed
|
||||||
|
return set(ctx.role.permissions or [])
|
||||||
|
|
||||||
|
|
||||||
def has_any(ctx, patterns: Sequence[str]) -> bool:
|
def has_any(ctx, patterns: Sequence[str]) -> bool:
|
||||||
return any(_match(ctx.role.permissions, patterns)) if ctx else False
|
return any(_match(_get_effective_scopes(ctx), patterns)) if ctx else False
|
||||||
|
|
||||||
|
|
||||||
def has_all(ctx, patterns: Sequence[str]) -> bool:
|
def has_all(ctx, patterns: Sequence[str]) -> bool:
|
||||||
return all(_match(ctx.role.permissions, patterns)) if ctx else False
|
return all(_match(_get_effective_scopes(ctx), patterns)) if ctx else False
|
||||||
|
|
||||||
|
|
||||||
async def session_context(auth: str | None, host: str | None = None):
|
async def session_context(auth: str | None, host: str | None = None):
|
||||||
if not auth:
|
if not auth:
|
||||||
return None
|
return None
|
||||||
normalized_host = normalize_host(host) if host else None
|
normalized_host = normalize_host(host) if host else None
|
||||||
return await db.instance.get_session_context(session_key(auth), normalized_host)
|
return db.get_session_context(auth, normalized_host)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from paskia.authsession import EXPIRES
|
||||||
from paskia.db import SessionContext
|
from paskia.db import SessionContext
|
||||||
from paskia.util.timeutil import parse_duration
|
from paskia.util.timeutil import parse_duration
|
||||||
|
|
||||||
@@ -27,11 +28,11 @@ def check_session_age(ctx: SessionContext, max_age: str | None) -> bool:
|
|||||||
|
|
||||||
max_age_delta = parse_duration(max_age)
|
max_age_delta = parse_duration(max_age)
|
||||||
|
|
||||||
# Use credential's last_used time if available, fall back to session renewed
|
# Use credential's last_used time if available, fall back to session renewed time
|
||||||
if ctx.credential and ctx.credential.last_used:
|
if ctx.credential and ctx.credential.last_used:
|
||||||
auth_time = ctx.credential.last_used
|
auth_time = ctx.credential.last_used
|
||||||
else:
|
else:
|
||||||
auth_time = ctx.session.renewed
|
auth_time = ctx.session.expiry - EXPIRES
|
||||||
|
|
||||||
time_since_auth = datetime.now(timezone.utc) - auth_time
|
time_since_auth = datetime.now(timezone.utc) - auth_time
|
||||||
return time_since_auth <= max_age_delta
|
return time_since_auth <= max_age_delta
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ def print_startup_config(config: "PaskiaConfig") -> None:
|
|||||||
lines.append(line(f"Auth Host: {config.auth_host}"))
|
lines.append(line(f"Auth Host: {config.auth_host}"))
|
||||||
|
|
||||||
# Show frontend URL if in dev mode
|
# Show frontend URL if in dev mode
|
||||||
devmode = os.environ.get("PASKIA_DEVMODE")
|
devmode = os.environ.get("FASTAPI_VUE_FRONTEND_URL")
|
||||||
if devmode:
|
if devmode:
|
||||||
lines.append(line(f"Dev Frontend: {devmode}"))
|
lines.append(line(f"Dev Frontend: {devmode}"))
|
||||||
|
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
import hashlib
|
|
||||||
import secrets
|
|
||||||
|
|
||||||
import base64url
|
|
||||||
|
|
||||||
from paskia.util.passphrase import is_well_formed
|
|
||||||
|
|
||||||
|
|
||||||
def create_token() -> str:
|
|
||||||
return secrets.token_urlsafe(12) # 16 characters Base64
|
|
||||||
|
|
||||||
|
|
||||||
def session_key(token: str) -> bytes:
|
|
||||||
if len(token) != 16:
|
|
||||||
raise ValueError("Session token must be exactly 16 characters long")
|
|
||||||
return b"sess" + base64url.dec(token)
|
|
||||||
|
|
||||||
|
|
||||||
def encode_session_key(key: bytes) -> str:
|
|
||||||
"""Encode an opaque session key for external representation."""
|
|
||||||
return base64url.enc(key)
|
|
||||||
|
|
||||||
|
|
||||||
def decode_session_key(encoded: str) -> bytes:
|
|
||||||
"""Decode an opaque session key from its public representation."""
|
|
||||||
if not encoded:
|
|
||||||
raise ValueError("Invalid session identifier")
|
|
||||||
try:
|
|
||||||
raw = base64url.dec(encoded)
|
|
||||||
except Exception as exc: # pragma: no cover - defensive
|
|
||||||
raise ValueError("Invalid session identifier") from exc
|
|
||||||
if not raw.startswith(b"sess"):
|
|
||||||
raise ValueError("Invalid session identifier")
|
|
||||||
return raw
|
|
||||||
|
|
||||||
|
|
||||||
def reset_key(passphrase: str) -> bytes:
|
|
||||||
if not is_well_formed(passphrase):
|
|
||||||
raise ValueError(
|
|
||||||
"Trying to reset with a session token in place of a passphrase"
|
|
||||||
if len(passphrase) == 16
|
|
||||||
else "Invalid passphrase format"
|
|
||||||
)
|
|
||||||
return b"rset" + hashlib.sha512(passphrase.encode()).digest()[:12]
|
|
||||||
+39
-91
@@ -2,10 +2,10 @@
|
|||||||
|
|
||||||
from datetime import timezone
|
from datetime import timezone
|
||||||
|
|
||||||
from paskia import aaguid
|
from paskia import aaguid, db
|
||||||
from paskia.authsession import session_key
|
from paskia.authsession import EXPIRES
|
||||||
from paskia.globals import db
|
from paskia.db import SessionContext
|
||||||
from paskia.util import hostutil, permutil, tokens, useragent
|
from paskia.util import hostutil, permutil, useragent
|
||||||
|
|
||||||
|
|
||||||
def _format_datetime(dt):
|
def _format_datetime(dt):
|
||||||
@@ -18,6 +18,25 @@ def _format_datetime(dt):
|
|||||||
return dt.replace(tzinfo=timezone.utc).isoformat().replace("+00:00", "Z")
|
return dt.replace(tzinfo=timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
def format_session_context(ctx: SessionContext) -> dict:
|
||||||
|
"""Format SessionContext for JSON response."""
|
||||||
|
return {
|
||||||
|
"user": {
|
||||||
|
"uuid": str(ctx.user.uuid),
|
||||||
|
"display_name": ctx.user.display_name,
|
||||||
|
},
|
||||||
|
"org": {
|
||||||
|
"uuid": str(ctx.org.uuid),
|
||||||
|
"display_name": ctx.org.display_name,
|
||||||
|
},
|
||||||
|
"role": {
|
||||||
|
"uuid": str(ctx.role.uuid),
|
||||||
|
"display_name": ctx.role.display_name,
|
||||||
|
},
|
||||||
|
"permissions": [p.scope for p in ctx.permissions],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
async def format_user_info(
|
async def format_user_info(
|
||||||
*,
|
*,
|
||||||
user_uuid,
|
user_uuid,
|
||||||
@@ -25,92 +44,49 @@ async def format_user_info(
|
|||||||
session_record,
|
session_record,
|
||||||
request_host: str | None,
|
request_host: str | None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Format complete user information for authenticated users.
|
"""Format complete user information for authenticated users."""
|
||||||
|
|
||||||
Args:
|
|
||||||
user_uuid: UUID of the user to fetch information for
|
|
||||||
auth: Authentication token
|
|
||||||
session_record: Current session record
|
|
||||||
request_host: Host header from the request
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Dictionary containing formatted user information including:
|
|
||||||
- User details
|
|
||||||
- Organization and role information
|
|
||||||
- Credentials list
|
|
||||||
- Sessions list
|
|
||||||
- Permissions
|
|
||||||
"""
|
|
||||||
u = await db.instance.get_user_by_uuid(user_uuid)
|
|
||||||
ctx = await permutil.session_context(auth, request_host)
|
ctx = await permutil.session_context(auth, request_host)
|
||||||
|
|
||||||
# Fetch and format credentials
|
# Fetch and format credentials
|
||||||
credential_ids = await db.instance.get_credentials_by_user_uuid(user_uuid)
|
user_credentials = [
|
||||||
|
c for c in db.data().credentials.values() if c.user == user_uuid
|
||||||
|
]
|
||||||
credentials: list[dict] = []
|
credentials: list[dict] = []
|
||||||
user_aaguids: set[str] = set()
|
user_aaguids: set[str] = set()
|
||||||
|
|
||||||
for cred_id in credential_ids:
|
for c in user_credentials:
|
||||||
try:
|
|
||||||
c = await db.instance.get_credential_by_id(cred_id)
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
|
|
||||||
aaguid_str = str(c.aaguid)
|
aaguid_str = str(c.aaguid)
|
||||||
user_aaguids.add(aaguid_str)
|
user_aaguids.add(aaguid_str)
|
||||||
credentials.append(
|
credentials.append(
|
||||||
{
|
{
|
||||||
"credential_uuid": str(c.uuid),
|
"credential": str(c.uuid),
|
||||||
"aaguid": aaguid_str,
|
"aaguid": aaguid_str,
|
||||||
"created_at": _format_datetime(c.created_at),
|
"created_at": _format_datetime(c.created_at),
|
||||||
"last_used": _format_datetime(c.last_used),
|
"last_used": _format_datetime(c.last_used),
|
||||||
"last_verified": _format_datetime(c.last_verified),
|
"last_verified": _format_datetime(c.last_verified),
|
||||||
"sign_count": c.sign_count,
|
"sign_count": c.sign_count,
|
||||||
"is_current_session": session_record.credential_uuid == c.uuid,
|
"is_current_session": session_record.credential == c.uuid,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
credentials.sort(key=lambda cred: cred["created_at"])
|
credentials.sort(key=lambda cred: cred["created_at"])
|
||||||
aaguid_info = aaguid.filter(user_aaguids)
|
aaguid_info = aaguid.filter(user_aaguids)
|
||||||
|
|
||||||
# Format role and org information
|
|
||||||
role_info = None
|
|
||||||
org_info = None
|
|
||||||
effective_permissions: list[str] = []
|
|
||||||
is_global_admin = False
|
|
||||||
is_org_admin = False
|
|
||||||
|
|
||||||
if ctx:
|
|
||||||
role_info = {
|
|
||||||
"uuid": str(ctx.role.uuid),
|
|
||||||
"display_name": ctx.role.display_name,
|
|
||||||
"permissions": ctx.role.permissions,
|
|
||||||
}
|
|
||||||
org_info = {
|
|
||||||
"uuid": str(ctx.org.uuid),
|
|
||||||
"display_name": ctx.org.display_name,
|
|
||||||
"permissions": ctx.org.permissions,
|
|
||||||
}
|
|
||||||
effective_permissions = [p.id for p in (ctx.permissions or [])]
|
|
||||||
is_global_admin = "auth:admin" in (role_info["permissions"] or [])
|
|
||||||
is_org_admin = any(
|
|
||||||
p.startswith("auth:org:") for p in (role_info["permissions"] or [])
|
|
||||||
)
|
|
||||||
|
|
||||||
# Format sessions
|
# Format sessions
|
||||||
normalized_request_host = hostutil.normalize_host(request_host)
|
normalized_request_host = hostutil.normalize_host(request_host)
|
||||||
session_records = await db.instance.list_sessions_for_user(user_uuid)
|
session_records = [s for s in db.data().sessions.values() if s.user == user_uuid]
|
||||||
current_session_key = session_key(auth)
|
current_session_key = auth
|
||||||
sessions_payload: list[dict] = []
|
sessions_payload: list[dict] = []
|
||||||
|
|
||||||
for entry in session_records:
|
for entry in session_records:
|
||||||
sessions_payload.append(
|
sessions_payload.append(
|
||||||
{
|
{
|
||||||
"id": tokens.encode_session_key(entry.key),
|
"id": entry.key,
|
||||||
"credential_uuid": str(entry.credential_uuid),
|
"credential": str(entry.credential),
|
||||||
"host": entry.host,
|
"host": entry.host,
|
||||||
"ip": entry.ip,
|
"ip": entry.ip,
|
||||||
"user_agent": useragent.compact_user_agent(entry.user_agent),
|
"user_agent": useragent.compact_user_agent(entry.user_agent),
|
||||||
"last_renewed": _format_datetime(entry.renewed),
|
"last_renewed": _format_datetime(entry.expiry - EXPIRES),
|
||||||
"is_current": entry.key == current_session_key,
|
"is_current": entry.key == current_session_key,
|
||||||
"is_current_host": bool(
|
"is_current_host": bool(
|
||||||
normalized_request_host
|
normalized_request_host
|
||||||
@@ -121,39 +97,11 @@ async def format_user_info(
|
|||||||
)
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"authenticated": True,
|
"ctx": format_session_context(ctx),
|
||||||
"user": {
|
"created_at": _format_datetime(ctx.user.created_at),
|
||||||
"user_uuid": str(u.uuid),
|
"last_seen": _format_datetime(ctx.user.last_seen),
|
||||||
"user_name": u.display_name,
|
"visits": ctx.user.visits,
|
||||||
"created_at": _format_datetime(u.created_at),
|
|
||||||
"last_seen": _format_datetime(u.last_seen),
|
|
||||||
"visits": u.visits,
|
|
||||||
},
|
|
||||||
"org": org_info,
|
|
||||||
"role": role_info,
|
|
||||||
"permissions": effective_permissions,
|
|
||||||
"is_global_admin": is_global_admin,
|
|
||||||
"is_org_admin": is_org_admin,
|
|
||||||
"credentials": credentials,
|
"credentials": credentials,
|
||||||
"aaguid_info": aaguid_info,
|
"aaguid_info": aaguid_info,
|
||||||
"sessions": sessions_payload,
|
"sessions": sessions_payload,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async def format_reset_user_info(user_uuid, reset_token) -> dict:
|
|
||||||
"""Format minimal user information for reset token requests.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
user_uuid: UUID of the user
|
|
||||||
reset_token: Reset token record
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Dictionary with minimal user info for password reset flow
|
|
||||||
"""
|
|
||||||
u = await db.instance.get_user_by_uuid(user_uuid)
|
|
||||||
|
|
||||||
return {
|
|
||||||
"authenticated": False,
|
|
||||||
"session_type": reset_token.token_type,
|
|
||||||
"user": {"user_uuid": str(u.uuid), "user_name": u.display_name},
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""Vite dev server proxy for fetching frontend files during development.
|
||||||
|
|
||||||
|
In dev mode (FASTAPI_VUE_FRONTEND_URL set), fetches files from Vite.
|
||||||
|
In production, reads from the static build directory.
|
||||||
|
|
||||||
|
This complements fastapi_vue.Frontend which handles static file serving
|
||||||
|
but doesn't provide server-side fetching of HTML content.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import mimetypes
|
||||||
|
import os
|
||||||
|
from importlib import resources
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
__all__ = ["read"]
|
||||||
|
|
||||||
|
|
||||||
|
def _get_dev_server() -> str | None:
|
||||||
|
"""Get the dev server URL from environment, or None if not in dev mode."""
|
||||||
|
return os.environ.get("FASTAPI_VUE_FRONTEND_URL") or None
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_static_dir() -> Path:
|
||||||
|
"""Resolve the static files directory."""
|
||||||
|
|
||||||
|
# Try packaged path via importlib.resources (works for wheel/installed).
|
||||||
|
try: # pragma: no cover - trivial path resolution
|
||||||
|
pkg_dir = resources.files("paskia") / "frontend-build"
|
||||||
|
fs_path = Path(str(pkg_dir))
|
||||||
|
if fs_path.is_dir():
|
||||||
|
return fs_path
|
||||||
|
except Exception: # pragma: no cover - defensive
|
||||||
|
pass
|
||||||
|
# Fallback for editable/development before build.
|
||||||
|
return Path(__file__).parent.parent / "frontend-build"
|
||||||
|
|
||||||
|
|
||||||
|
_static_dir: Path = _resolve_static_dir()
|
||||||
|
|
||||||
|
|
||||||
|
async def read(filepath: str) -> tuple[bytes, int, dict[str, str]]:
|
||||||
|
"""Read file content and return response tuple.
|
||||||
|
|
||||||
|
In dev mode, fetches from the Vite dev server.
|
||||||
|
In production, reads from the static build directory.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
filepath: Path relative to frontend root, e.g. "/auth/index.html"
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (content, status_code, headers) suitable for
|
||||||
|
FastAPI Response(*args).
|
||||||
|
"""
|
||||||
|
dev_server = _get_dev_server()
|
||||||
|
if dev_server:
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
resp = await client.get(f"{dev_server}{filepath}")
|
||||||
|
resp.raise_for_status()
|
||||||
|
mime = resp.headers.get("content-type", "application/octet-stream")
|
||||||
|
# Strip charset suffix if present
|
||||||
|
mime = mime.split(";")[0].strip()
|
||||||
|
return resp.content, resp.status_code, {"content-type": mime}
|
||||||
|
else:
|
||||||
|
# Production: read from static build
|
||||||
|
file_path = _static_dir / filepath.lstrip("/")
|
||||||
|
content = await asyncio.to_thread(file_path.read_bytes)
|
||||||
|
mime, _ = mimetypes.guess_type(str(file_path))
|
||||||
|
return content, 200, {"content-type": mime or "application/octet-stream"}
|
||||||
+13
-4
@@ -16,13 +16,15 @@ dependencies = [
|
|||||||
"websockets>=12.0",
|
"websockets>=12.0",
|
||||||
"webauthn>=1.11.1",
|
"webauthn>=1.11.1",
|
||||||
"base64url>=1.0.0",
|
"base64url>=1.0.0",
|
||||||
"sqlalchemy[asyncio]>=2.0.0",
|
|
||||||
"aiosqlite>=0.19.0",
|
|
||||||
"uuid7-standard>=1.0.0",
|
"uuid7-standard>=1.0.0",
|
||||||
"pyjwt>=2.8.0",
|
"pyjwt>=2.8.0",
|
||||||
"user-agents>=2.2.0",
|
"user-agents>=2.2.0",
|
||||||
|
"jsondiff>=2.2.1",
|
||||||
|
"msgspec>=0.20.0",
|
||||||
|
"aiofiles>=25.1.0",
|
||||||
|
"fastapi-vue>=0.3.0",
|
||||||
]
|
]
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.11"
|
||||||
|
|
||||||
[project.urls]
|
[project.urls]
|
||||||
Homepage = "https://git.zi.fi/LeoVasanko/paskia"
|
Homepage = "https://git.zi.fi/LeoVasanko/paskia"
|
||||||
@@ -42,6 +44,10 @@ dev = [
|
|||||||
"pytest-asyncio>=0.24.0",
|
"pytest-asyncio>=0.24.0",
|
||||||
"httpx>=0.27.0",
|
"httpx>=0.27.0",
|
||||||
]
|
]
|
||||||
|
migrate = [
|
||||||
|
"sqlalchemy[asyncio]>=2.0.0",
|
||||||
|
"aiosqlite>=0.19.0",
|
||||||
|
]
|
||||||
|
|
||||||
[tool.coverage.run]
|
[tool.coverage.run]
|
||||||
source = ["paskia"]
|
source = ["paskia"]
|
||||||
@@ -73,7 +79,7 @@ target-version = "py39"
|
|||||||
line-length = 88
|
line-length = 88
|
||||||
|
|
||||||
[tool.ruff.lint]
|
[tool.ruff.lint]
|
||||||
select = ["E", "F", "I", "N", "W", "UP"]
|
select = ["E", "F", "I", "N", "W", "UP", "PLC0415"]
|
||||||
ignore = ["E501"] # Line too long
|
ignore = ["E501"] # Line too long
|
||||||
isort.known-first-party = ["paskia"]
|
isort.known-first-party = ["paskia"]
|
||||||
|
|
||||||
@@ -89,7 +95,10 @@ dev = [
|
|||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
paskia = "paskia.fastapi.__main__:main"
|
paskia = "paskia.fastapi.__main__:main"
|
||||||
|
paskia-migrate = "paskia.migrate:main"
|
||||||
|
|
||||||
[tool.hatch.build]
|
[tool.hatch.build]
|
||||||
artifacts = ["paskia/frontend-build"]
|
artifacts = ["paskia/frontend-build"]
|
||||||
targets.sdist.hooks.custom.path = "scripts/build-frontend.py"
|
targets.sdist.hooks.custom.path = "scripts/build-frontend.py"
|
||||||
|
packages = ["paskia"]
|
||||||
|
only-packages = true
|
||||||
|
|||||||
Executable
+277
@@ -0,0 +1,277 @@
|
|||||||
|
#!/usr/bin/env -S uv run
|
||||||
|
# auto-upgrade@fastapi-vue-setup - remove this if you modify this file
|
||||||
|
"""Run Vite development server for frontend and FastAPI backend with auto-reload.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
uv run scripts/devserver.py [host:port] [--backend host:port]
|
||||||
|
|
||||||
|
The optional host:port argument sets where the Vite frontend listens.
|
||||||
|
Supported forms: host[:port], :port (all interfaces), or just port.
|
||||||
|
The --backend option sets where the FastAPI backend listens (default: localhost:5180).
|
||||||
|
|
||||||
|
Environment:
|
||||||
|
JS_RUNTIME Path or name of JS runtime to use (deno, npm/node or bun).
|
||||||
|
FASTAPI_VUE_FRONTEND_URL Set by this script for the backend to know where Vite is.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import contextlib
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from sys import stderr
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi_vue.hostutil import parse_endpoint
|
||||||
|
|
||||||
|
exec((Path(__file__).parent / "fastapi-vue/util.py").read_text("UTF-8")) # noqa: S102
|
||||||
|
|
||||||
|
DEFAULT_VITE_PORT = 5173
|
||||||
|
DEFAULT_BACKEND_PORT = 5180
|
||||||
|
FRONTEND_PATH = Path(__file__).parent.parent / "frontend"
|
||||||
|
|
||||||
|
EPILOG = """
|
||||||
|
scripts/devserver.py # Default ports on localhost
|
||||||
|
scripts/devserver.py 3000 # Vite on localhost:3000
|
||||||
|
scripts/devserver.py :3000 --backend 8000 # *:3000, localhost:8000
|
||||||
|
"""
|
||||||
|
|
||||||
|
BUN_BUG = """\
|
||||||
|
┃ ⚠️ Bun cannot correctly proxy API requests to the backend.
|
||||||
|
┃ Bug report: https://github.com/oven-sh/bun/issues/9882
|
||||||
|
┃
|
||||||
|
┃ Consider using deno or npm instead for development.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_frontend_tools(
|
||||||
|
vite_port: int, all_ifaces: bool
|
||||||
|
) -> tuple[list[str], list[str], str]:
|
||||||
|
"""Resolve frontend install and dev commands.
|
||||||
|
|
||||||
|
Returns (install_cmd, dev_cmd, tool_name).
|
||||||
|
Raises SystemExit if tools are not available.
|
||||||
|
"""
|
||||||
|
if not (FRONTEND_PATH / "package.json").exists():
|
||||||
|
stderr.write(f"┃ ⚠️ Frontend source not found at {FRONTEND_PATH}\n")
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
result = find_js_runtime() # noqa # type: ignore
|
||||||
|
if result is None:
|
||||||
|
if not os.environ.get("JS_RUNTIME"):
|
||||||
|
stderr.write("┃ ⚠️ deno, npm or bun needed to run the frontend server.\n")
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
tool, name = result
|
||||||
|
|
||||||
|
install_args = {
|
||||||
|
"deno": ("install", "--quiet", "--allow-scripts=npm:vue-demi"),
|
||||||
|
"npm": ("install", "--silent"),
|
||||||
|
"bun": ("install", "--silent"),
|
||||||
|
}
|
||||||
|
dev_args = {
|
||||||
|
"deno": ("run", "dev", "--"),
|
||||||
|
"npm": ("--silent", "run", "dev", "--"),
|
||||||
|
"bun": ("run", "dev", "--"),
|
||||||
|
}
|
||||||
|
|
||||||
|
install_cmd = [tool, *install_args[name]]
|
||||||
|
dev_cmd = [
|
||||||
|
tool,
|
||||||
|
*dev_args[name],
|
||||||
|
"--clearScreen=false",
|
||||||
|
f"--port={vite_port}",
|
||||||
|
]
|
||||||
|
|
||||||
|
if all_ifaces:
|
||||||
|
dev_cmd.append("--host")
|
||||||
|
|
||||||
|
if name == "bun":
|
||||||
|
stderr.write(BUN_BUG)
|
||||||
|
|
||||||
|
return install_cmd, dev_cmd, name
|
||||||
|
|
||||||
|
|
||||||
|
async def wait_for_backend(host: str, port: int):
|
||||||
|
"""Wait for the backend to be ready by polling the health endpoint."""
|
||||||
|
max_attempts = 50
|
||||||
|
url = f"http://{host}:{port}"
|
||||||
|
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
for attempt in range(max_attempts):
|
||||||
|
try:
|
||||||
|
await client.get(url, timeout=1.0)
|
||||||
|
stderr.write("✓ Backend ready!\n")
|
||||||
|
return True
|
||||||
|
except httpx.RequestError:
|
||||||
|
if attempt == max_attempts - 1:
|
||||||
|
stderr.write("┃ ⚠️ Backend didn't start in time\n")
|
||||||
|
return False
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
async def _terminate_process(proc: asyncio.subprocess.Process, name: str) -> None:
|
||||||
|
"""Gracefully terminate a subprocess."""
|
||||||
|
if proc.returncode is not None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
proc.terminate()
|
||||||
|
except ProcessLookupError:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(proc.wait(), timeout=2)
|
||||||
|
except TimeoutError:
|
||||||
|
try:
|
||||||
|
proc.kill()
|
||||||
|
except ProcessLookupError:
|
||||||
|
return
|
||||||
|
await proc.wait()
|
||||||
|
|
||||||
|
|
||||||
|
async def run_devserver(
|
||||||
|
vite_port: int,
|
||||||
|
all_ifaces: bool,
|
||||||
|
backend_host: str,
|
||||||
|
backend_port: int,
|
||||||
|
) -> None:
|
||||||
|
"""Run the development server with install, backend, and frontend."""
|
||||||
|
install_cmd, dev_cmd, tool_name = resolve_frontend_tools(vite_port, all_ifaces)
|
||||||
|
|
||||||
|
# Tell the backend where the Vite dev server is
|
||||||
|
os.environ["FASTAPI_VUE_FRONTEND_URL"] = f"http://localhost:{vite_port}"
|
||||||
|
# Tell Vite where the backend is (for proxying /api requests)
|
||||||
|
os.environ["FASTAPI_VUE_BACKEND_URL"] = f"http://{backend_host}:{backend_port}"
|
||||||
|
|
||||||
|
backend_cmd = [
|
||||||
|
"uvicorn",
|
||||||
|
"paskia.app:app",
|
||||||
|
"--host",
|
||||||
|
backend_host,
|
||||||
|
"--port",
|
||||||
|
str(backend_port),
|
||||||
|
"--reload",
|
||||||
|
]
|
||||||
|
|
||||||
|
cwd = str(Path(__file__).parent.parent)
|
||||||
|
frontend_cwd = str(FRONTEND_PATH)
|
||||||
|
|
||||||
|
backend_proc: asyncio.subprocess.Process | None = None
|
||||||
|
install_proc: asyncio.subprocess.Process | None = None
|
||||||
|
frontend_proc: asyncio.subprocess.Process | None = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Start install (concurrent with backend)
|
||||||
|
stderr.write(f">>> {tool_name} {' '.join(install_cmd[1:])}\n")
|
||||||
|
install_proc = await asyncio.create_subprocess_exec(
|
||||||
|
*install_cmd, cwd=frontend_cwd
|
||||||
|
)
|
||||||
|
|
||||||
|
await asyncio.sleep(0.1)
|
||||||
|
|
||||||
|
# Start backend (concurrent with install)
|
||||||
|
stderr.write(f">>> {' '.join(backend_cmd)}\n")
|
||||||
|
backend_proc = await asyncio.create_subprocess_exec(*backend_cmd, cwd=cwd)
|
||||||
|
|
||||||
|
# Wait for install to complete and backend to be ready
|
||||||
|
install_task = asyncio.create_task(install_proc.wait(), name="install")
|
||||||
|
backend_ready_task = asyncio.create_task(
|
||||||
|
wait_for_backend(backend_host, backend_port), name="backend_ready"
|
||||||
|
)
|
||||||
|
|
||||||
|
done, pending = await asyncio.wait(
|
||||||
|
{install_task, backend_ready_task},
|
||||||
|
return_when=asyncio.FIRST_COMPLETED,
|
||||||
|
)
|
||||||
|
|
||||||
|
for task in done:
|
||||||
|
if task.get_name() == "install":
|
||||||
|
if task.result() != 0:
|
||||||
|
stderr.write("┃ ⚠️ Install failed\n")
|
||||||
|
raise SystemExit(1)
|
||||||
|
elif task.get_name() == "backend_ready" and not task.result():
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
if pending:
|
||||||
|
done2, _ = await asyncio.wait(pending)
|
||||||
|
for task in done2:
|
||||||
|
if task.get_name() == "install":
|
||||||
|
if task.result() != 0:
|
||||||
|
stderr.write("┃ ⚠️ Install failed\n")
|
||||||
|
raise SystemExit(1)
|
||||||
|
elif task.get_name() == "backend_ready" and not task.result():
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
install_proc = None
|
||||||
|
|
||||||
|
# Start Vite dev server
|
||||||
|
stderr.write(f">>> {tool_name} {' '.join(dev_cmd[1:])}\n")
|
||||||
|
frontend_proc = await asyncio.create_subprocess_exec(*dev_cmd, cwd=frontend_cwd)
|
||||||
|
|
||||||
|
# Wait for either process to exit
|
||||||
|
done, pending = await asyncio.wait(
|
||||||
|
{
|
||||||
|
asyncio.create_task(backend_proc.wait(), name="backend"),
|
||||||
|
asyncio.create_task(frontend_proc.wait(), name="frontend"),
|
||||||
|
},
|
||||||
|
return_when=asyncio.FIRST_COMPLETED,
|
||||||
|
)
|
||||||
|
for t in done:
|
||||||
|
t.result()
|
||||||
|
for t in pending:
|
||||||
|
t.cancel()
|
||||||
|
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
stderr.write("\n✓ Shutting down...\n")
|
||||||
|
finally:
|
||||||
|
if frontend_proc is not None:
|
||||||
|
await _terminate_process(frontend_proc, "frontend")
|
||||||
|
if install_proc is not None:
|
||||||
|
await _terminate_process(install_proc, "install")
|
||||||
|
if backend_proc is not None:
|
||||||
|
await _terminate_process(backend_proc, "backend")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Run Vite and FastAPI development servers",
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||||
|
epilog=EPILOG,
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"frontend",
|
||||||
|
nargs="?",
|
||||||
|
metavar="host:port",
|
||||||
|
help="Vite frontend endpoint (default: localhost:5173)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--backend",
|
||||||
|
metavar="host:port",
|
||||||
|
help="FastAPI backend endpoint (default: localhost:5180)",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# parse_endpoint returns list of dicts with host/port or uds keys
|
||||||
|
# Multiple entries means bind all interfaces (IPv4 + IPv6)
|
||||||
|
vite_endpoints = parse_endpoint(args.frontend, DEFAULT_VITE_PORT)
|
||||||
|
backend_endpoints = parse_endpoint(args.backend, DEFAULT_BACKEND_PORT)
|
||||||
|
|
||||||
|
# Vite doesn't support unix sockets
|
||||||
|
if "uds" in vite_endpoints[0]:
|
||||||
|
stderr.write("┃ ⚠️ Unix sockets not supported for frontend\n")
|
||||||
|
raise SystemExit(1)
|
||||||
|
if "uds" in backend_endpoints[0]:
|
||||||
|
stderr.write("┃ ⚠️ Unix sockets not supported for backend\n")
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
vite_port = vite_endpoints[0]["port"]
|
||||||
|
all_ifaces = len(vite_endpoints) > 1
|
||||||
|
backend_host = backend_endpoints[0]["host"]
|
||||||
|
backend_port = backend_endpoints[0]["port"]
|
||||||
|
|
||||||
|
with contextlib.suppress(KeyboardInterrupt):
|
||||||
|
asyncio.run(run_devserver(vite_port, all_ifaces, backend_host, backend_port))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+32
-13
@@ -6,12 +6,17 @@ not from the installed package. It starts both the Vite frontend dev server
|
|||||||
and the FastAPI backend with auto-reload enabled.
|
and the FastAPI backend with auto-reload enabled.
|
||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
uv run scripts/dev.py [host:port] [options...]
|
uv run scripts/devserver.py [host:port] [options...]
|
||||||
|
|
||||||
The optional host:port argument sets where the Vite frontend listens.
|
The optional host:port argument sets where the Vite frontend listens.
|
||||||
All other options are forwarded to `paskia serve`.
|
All other options are forwarded to `paskia`.
|
||||||
Backend always listens on localhost:4402.
|
Backend always listens on localhost:4402.
|
||||||
|
|
||||||
|
Environment:
|
||||||
|
FASTAPI_VUE_FRONTEND_URL Set by this script for the backend to know where Vite is.
|
||||||
|
FASTAPI_VUE_BACKEND_URL Set by this script for Vite to know where to proxy API calls.
|
||||||
|
PASKIA_SITE_URL User-facing URL for reset links (Caddy HTTPS or Vite HTTP).
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
--caddy Run Caddy as HTTPS proxy on port 443 (requires sudo)
|
--caddy Run Caddy as HTTPS proxy on port 443 (requires sudo)
|
||||||
--rp-id HOST Relying Party ID (used as hostname for Caddy)
|
--rp-id HOST Relying Party ID (used as hostname for Caddy)
|
||||||
@@ -118,7 +123,13 @@ def parse_endpoint(
|
|||||||
return host, port, None, False
|
return host, port, None, False
|
||||||
|
|
||||||
|
|
||||||
def run_vite(vite_url: str, vite_host: str | None, vite_port: int, auth_host: str | None = None):
|
def run_vite(
|
||||||
|
vite_url: str,
|
||||||
|
vite_host: str | None,
|
||||||
|
vite_port: int,
|
||||||
|
env: dict,
|
||||||
|
auth_host: str | None = None,
|
||||||
|
):
|
||||||
"""Spawn the frontend dev server (deno, npm, or bunx) as a background process."""
|
"""Spawn the frontend dev server (deno, npm, or bunx) as a background process."""
|
||||||
devpath = Path(__file__).parent.parent / "frontend"
|
devpath = Path(__file__).parent.parent / "frontend"
|
||||||
if not (devpath / "package.json").exists():
|
if not (devpath / "package.json").exists():
|
||||||
@@ -160,10 +171,12 @@ def run_vite(vite_url: str, vite_host: str | None, vite_port: int, auth_host: st
|
|||||||
|
|
||||||
full_cmd = cmd + vite_args
|
full_cmd = cmd + vite_args
|
||||||
stderr.write(f">>> {' '.join([tool_name, *full_cmd[1:]])}\n")
|
stderr.write(f">>> {' '.join([tool_name, *full_cmd[1:]])}\n")
|
||||||
vite_env = os.environ.copy()
|
vite_env = env.copy()
|
||||||
if auth_host:
|
if auth_host:
|
||||||
vite_env["PASKIA_AUTH_HOST"] = auth_host
|
vite_env["PASKIA_AUTH_HOST"] = auth_host
|
||||||
vite_process = subprocess.Popen(full_cmd, cwd=str(devpath), shell=False, env=vite_env)
|
vite_process = subprocess.Popen(
|
||||||
|
full_cmd, cwd=str(devpath), shell=False, env=vite_env
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
stderr.write(
|
stderr.write(
|
||||||
f"┃ ⚠️ Vite couldn't start: {e}\n"
|
f"┃ ⚠️ Vite couldn't start: {e}\n"
|
||||||
@@ -387,7 +400,7 @@ def main():
|
|||||||
if all_ifaces:
|
if all_ifaces:
|
||||||
vite_host = "0.0.0.0"
|
vite_host = "0.0.0.0"
|
||||||
|
|
||||||
# Build Vite URL for PASKIA_DEVMODE (always use localhost for URL)
|
# Build Vite URL for FASTAPI_VUE_FRONTEND_URL (always use localhost for URL)
|
||||||
vite_url = f"http://localhost:{vite_port}"
|
vite_url = f"http://localhost:{vite_port}"
|
||||||
|
|
||||||
# Compute origins for Caddy (user-specified or auto-generated)
|
# Compute origins for Caddy (user-specified or auto-generated)
|
||||||
@@ -420,15 +433,21 @@ def main():
|
|||||||
if not run_caddy(caddy_origins, vite_port):
|
if not run_caddy(caddy_origins, vite_port):
|
||||||
raise SystemExit(1)
|
raise SystemExit(1)
|
||||||
|
|
||||||
# Start Vite dev server
|
# Set dev mode env vars for subprocesses (fastapi-vue convention)
|
||||||
run_vite(vite_url, vite_host, vite_port, args.auth_host)
|
|
||||||
|
|
||||||
# Set dev mode with Vite URL in environment for subprocess
|
|
||||||
env = os.environ.copy()
|
env = os.environ.copy()
|
||||||
env["PASKIA_DEVMODE"] = vite_url
|
env["FASTAPI_VUE_FRONTEND_URL"] = vite_url
|
||||||
|
env["FASTAPI_VUE_BACKEND_URL"] = f"http://localhost:{BACKEND_PORT}"
|
||||||
|
# User-facing URL: Caddy HTTPS when running, else Vite HTTP
|
||||||
|
if args.caddy:
|
||||||
|
env["PASKIA_SITE_URL"] = caddy_origins[0] # auth-host or https://{rp-id}
|
||||||
|
else:
|
||||||
|
env["PASKIA_SITE_URL"] = vite_url
|
||||||
|
|
||||||
# Build command with origin args
|
# Start Vite dev server
|
||||||
cmd = ["paskia", "serve", f"localhost:{BACKEND_PORT}"]
|
run_vite(vite_url, vite_host, vite_port, env, args.auth_host)
|
||||||
|
|
||||||
|
# Build command with origin args (no serve subcommand, host:port is first arg)
|
||||||
|
cmd = ["paskia", f"localhost:{BACKEND_PORT}"]
|
||||||
|
|
||||||
# Pass through rp-id (always pass, has default)
|
# Pass through rp-id (always pass, has default)
|
||||||
cmd.extend(["--rp-id", args.rp_id])
|
cmd.extend(["--rp-id", args.rp_id])
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""Hatch build hook for building Vue frontend during package build."""
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
from sys import stderr
|
||||||
|
|
||||||
|
from hatchling.builders.hooks.plugin.interface import BuildHookInterface # type: ignore
|
||||||
|
|
||||||
|
exec(Path(__file__).with_name("util.py").read_text("UTF-8")) # noqa: S102
|
||||||
|
|
||||||
|
|
||||||
|
def run(cmd, **kwargs):
|
||||||
|
"""Run a command and display it."""
|
||||||
|
display_cmd = [Path(cmd[0]).name, *cmd[1:]]
|
||||||
|
stderr.write(f"### {' '.join(display_cmd)}\n")
|
||||||
|
subprocess.run(cmd, check=True, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
class CustomBuildHook(BuildHookInterface):
|
||||||
|
"""Build hook that compiles Vue frontend before packaging."""
|
||||||
|
|
||||||
|
def initialize(self, version, build_data):
|
||||||
|
super().initialize(version, build_data)
|
||||||
|
stderr.write(">>> Building the frontend\n")
|
||||||
|
|
||||||
|
install_cmd, build_cmd = find_build_tool() # noqa # type: ignore
|
||||||
|
|
||||||
|
try:
|
||||||
|
run(install_cmd, cwd="frontend")
|
||||||
|
stderr.write("\n")
|
||||||
|
run(build_cmd, cwd="frontend")
|
||||||
|
except Exception as e:
|
||||||
|
stderr.write(f"Error occurred while building frontend: {e}\n")
|
||||||
|
raise
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""Shared utilities for build and dev scripts."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
from sys import stderr
|
||||||
|
|
||||||
|
|
||||||
|
def find_js_runtime() -> tuple[str, str] | None:
|
||||||
|
"""Find a JavaScript runtime from JS_RUNTIME env or auto-detect.
|
||||||
|
|
||||||
|
Returns (tool_path, tool_name) where tool_name is "deno", "npm", or "bun".
|
||||||
|
Returns None if no runtime is found.
|
||||||
|
"""
|
||||||
|
options = ["deno", "npm", "bun"]
|
||||||
|
|
||||||
|
# Check for JS_RUNTIME environment variable
|
||||||
|
if js_runtime_env := os.environ.get("JS_RUNTIME"):
|
||||||
|
js_runtime = js_runtime_env
|
||||||
|
js_path = Path(js_runtime)
|
||||||
|
runtime_name = js_path.name
|
||||||
|
# Map node to npm
|
||||||
|
if runtime_name == "node":
|
||||||
|
runtime_name = "npm"
|
||||||
|
js_runtime = str(js_path.parent / "npm") if js_path.parent.name else "npm"
|
||||||
|
for option in options:
|
||||||
|
if option == runtime_name or runtime_name.startswith(option):
|
||||||
|
tool = shutil.which(js_runtime)
|
||||||
|
if tool is None:
|
||||||
|
stderr.write(f"┃ ⚠️ JS_RUNTIME={js_runtime_env} not found\n")
|
||||||
|
return None
|
||||||
|
return tool, option
|
||||||
|
stderr.write(f"┃ ⚠️ JS_RUNTIME={js_runtime_env} not recognized\n")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Auto-detect
|
||||||
|
for option in options:
|
||||||
|
if tool := shutil.which(option):
|
||||||
|
return tool, option
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def find_build_tool():
|
||||||
|
"""Find JavaScript runtime and construct install/build commands.
|
||||||
|
|
||||||
|
Returns (install_cmd, build_cmd) tuples of command lists.
|
||||||
|
Raises RuntimeError if no runtime is found.
|
||||||
|
"""
|
||||||
|
install = {
|
||||||
|
"deno": ("install", "--allow-scripts=npm:vue-demi"),
|
||||||
|
"npm": ("install",),
|
||||||
|
"bun": ("--bun", "install"),
|
||||||
|
}
|
||||||
|
# Run vite directly for deno to avoid npm-run-all2/run-p issues
|
||||||
|
build = {
|
||||||
|
"deno": ("run", "-A", "npm:vite", "build"),
|
||||||
|
"npm": ("run", "build"),
|
||||||
|
"bun": ("--bun", "run", "build"),
|
||||||
|
}
|
||||||
|
|
||||||
|
result = find_js_runtime()
|
||||||
|
if result is None:
|
||||||
|
raise RuntimeError(
|
||||||
|
"Deno, npm or Bun is required for building but none was found"
|
||||||
|
)
|
||||||
|
|
||||||
|
tool, name = result
|
||||||
|
return [tool, *install[name]], [tool, *build[name]]
|
||||||
|
|
||||||
|
|
||||||
|
def find_dev_tool():
|
||||||
|
"""Find JavaScript runtime and construct dev command.
|
||||||
|
|
||||||
|
Returns (dev_cmd, tool_name) or (None, None) if not found.
|
||||||
|
"""
|
||||||
|
dev_args = {
|
||||||
|
"deno": ("run", "dev", "--"),
|
||||||
|
"npm": ("--silent", "run", "dev", "--"),
|
||||||
|
"bun": ("run", "dev", "--"),
|
||||||
|
}
|
||||||
|
|
||||||
|
result = find_js_runtime()
|
||||||
|
if result is None:
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
tool, name = result
|
||||||
|
return [tool, *dev_args[name]], name
|
||||||
+86
-78
@@ -11,24 +11,38 @@ in the database to test authenticated endpoints.
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import os
|
import os
|
||||||
|
import tempfile
|
||||||
from collections.abc import AsyncGenerator
|
from collections.abc import AsyncGenerator
|
||||||
from datetime import datetime, timezone
|
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
import pytest_asyncio
|
import pytest_asyncio
|
||||||
import uuid7
|
|
||||||
|
|
||||||
from paskia import globals
|
import paskia.db.operations as ops_db
|
||||||
from paskia.db import Credential, Org, Permission, Role, User
|
from paskia import globals as paskia_globals
|
||||||
from paskia.db.sql import DB
|
from paskia.authsession import expires, reset_expires
|
||||||
|
from paskia.db import (
|
||||||
|
Credential,
|
||||||
|
Org,
|
||||||
|
Permission,
|
||||||
|
Role,
|
||||||
|
User,
|
||||||
|
add_permission_to_org,
|
||||||
|
create_credential,
|
||||||
|
create_org,
|
||||||
|
create_permission,
|
||||||
|
create_reset_token,
|
||||||
|
create_role,
|
||||||
|
create_session,
|
||||||
|
create_user,
|
||||||
|
)
|
||||||
|
from paskia.db.jsonl import JsonlStore
|
||||||
|
from paskia.db.operations import DB, _create_token
|
||||||
|
from paskia.fastapi.mainapp import app
|
||||||
from paskia.fastapi.session import AUTH_COOKIE_NAME
|
from paskia.fastapi.session import AUTH_COOKIE_NAME
|
||||||
from paskia.sansio import Passkey
|
from paskia.sansio import Passkey
|
||||||
from paskia.util.tokens import create_token, session_key
|
from paskia.util.passphrase import generate
|
||||||
|
|
||||||
# Use in-memory SQLite for tests
|
|
||||||
os.environ["PASKIA_DB"] = "sqlite+aiosqlite:///:memory:"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="session")
|
@pytest.fixture(scope="session")
|
||||||
@@ -41,16 +55,18 @@ def event_loop():
|
|||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def test_db() -> AsyncGenerator[DB, None]:
|
async def test_db() -> AsyncGenerator[DB, None]:
|
||||||
"""Create an in-memory SQLite database for testing.
|
"""Create an in-memory JSON database for testing."""
|
||||||
|
|
||||||
We use :memory: for speed - each test gets a fresh database.
|
with tempfile.NamedTemporaryFile(suffix=".jsonl", delete=True) as f:
|
||||||
"""
|
db = DB()
|
||||||
db = DB("sqlite+aiosqlite:///:memory:")
|
store = JsonlStore(db, f.name)
|
||||||
await db.init_db()
|
db._store = store
|
||||||
globals.db._instance = db
|
await store.load()
|
||||||
|
ops_db._db = db
|
||||||
|
ops_db._store = store
|
||||||
yield db
|
yield db
|
||||||
# Clean up
|
ops_db._db = None
|
||||||
globals.db._instance = None
|
ops_db._store = None
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
@@ -61,118 +77,114 @@ async def passkey_instance() -> Passkey:
|
|||||||
rp_name="Test RP",
|
rp_name="Test RP",
|
||||||
origins=["http://localhost:4401"],
|
origins=["http://localhost:4401"],
|
||||||
)
|
)
|
||||||
globals.passkey._instance = pk
|
paskia_globals.passkey._instance = pk
|
||||||
yield pk
|
yield pk
|
||||||
globals.passkey._instance = None
|
paskia_globals.passkey._instance = None
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def test_org(test_db: DB, admin_permission: Permission) -> Org:
|
async def test_org(test_db: DB, admin_permission: Permission) -> Org:
|
||||||
"""Create a test organization with admin permission."""
|
"""Create a test organization with admin permission."""
|
||||||
org = Org(
|
org = Org.create(display_name="Test Organization")
|
||||||
uuid=uuid7.create(),
|
create_org(org)
|
||||||
display_name="Test Organization",
|
# Grant admin permission to this org
|
||||||
permissions=["auth:admin"], # Org can grant this permission
|
add_permission_to_org(org.uuid, admin_permission.uuid)
|
||||||
)
|
|
||||||
await test_db.create_organization(org)
|
|
||||||
return org
|
return org
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def admin_permission(test_db: DB) -> Permission:
|
async def admin_permission(test_db: DB) -> Permission:
|
||||||
"""Create the auth:admin permission."""
|
"""Create the auth:admin permission."""
|
||||||
perm = Permission(id="auth:admin", display_name="Master Admin")
|
perm = Permission.create(scope="auth:admin", display_name="Master Admin")
|
||||||
await test_db.create_permission(perm)
|
create_permission(perm)
|
||||||
return perm
|
return perm
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def test_role(test_db: DB, test_org: Org, admin_permission: Permission) -> Role:
|
async def org_admin_permission(test_db: DB, test_org: Org) -> Permission:
|
||||||
|
"""Create the auth:org:admin permission."""
|
||||||
|
perm = Permission.create(scope="auth:org:admin", display_name="Organization Admin")
|
||||||
|
create_permission(perm)
|
||||||
|
# Make it grantable by the org
|
||||||
|
add_permission_to_org(test_org.uuid, perm.uuid)
|
||||||
|
return perm
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture(scope="function")
|
||||||
|
async def test_role(
|
||||||
|
test_db: DB,
|
||||||
|
test_org: Org,
|
||||||
|
admin_permission: Permission,
|
||||||
|
org_admin_permission: Permission,
|
||||||
|
) -> Role:
|
||||||
"""Create a test role with admin permission."""
|
"""Create a test role with admin permission."""
|
||||||
role = Role(
|
role = Role.create(
|
||||||
uuid=uuid7.create(),
|
org=test_org.uuid,
|
||||||
org_uuid=test_org.uuid,
|
|
||||||
display_name="Test Admin Role",
|
display_name="Test Admin Role",
|
||||||
permissions=["auth:admin", f"auth:org:{test_org.uuid}"],
|
permissions={admin_permission.uuid, org_admin_permission.uuid},
|
||||||
)
|
)
|
||||||
await test_db.create_role(role)
|
create_role(role)
|
||||||
return role
|
return role
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def user_role(test_db: DB, test_org: Org) -> Role:
|
async def user_role(test_db: DB, test_org: Org) -> Role:
|
||||||
"""Create a test role without admin permission (regular user)."""
|
"""Create a test role without admin permission (regular user)."""
|
||||||
role = Role(
|
role = Role.create(
|
||||||
uuid=uuid7.create(),
|
org=test_org.uuid,
|
||||||
org_uuid=test_org.uuid,
|
|
||||||
display_name="User Role",
|
display_name="User Role",
|
||||||
permissions=[],
|
|
||||||
)
|
)
|
||||||
await test_db.create_role(role)
|
create_role(role)
|
||||||
return role
|
return role
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def test_user(test_db: DB, test_role: Role) -> User:
|
async def test_user(test_db: DB, test_role: Role) -> User:
|
||||||
"""Create a test user with admin role."""
|
"""Create a test user with admin role."""
|
||||||
user = User(
|
user = User.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
display_name="Test Admin",
|
display_name="Test Admin",
|
||||||
role_uuid=test_role.uuid,
|
role=test_role.uuid,
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
visits=0,
|
|
||||||
)
|
)
|
||||||
await test_db.create_user(user)
|
create_user(user)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def regular_user(test_db: DB, user_role: Role) -> User:
|
async def regular_user(test_db: DB, user_role: Role) -> User:
|
||||||
"""Create a regular test user without admin permissions."""
|
"""Create a regular test user without admin permissions."""
|
||||||
user = User(
|
user = User.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
display_name="Regular User",
|
display_name="Regular User",
|
||||||
role_uuid=user_role.uuid,
|
role=user_role.uuid,
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
visits=0,
|
|
||||||
)
|
)
|
||||||
await test_db.create_user(user)
|
create_user(user)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def test_credential(test_db: DB, test_user: User) -> Credential:
|
async def test_credential(test_db: DB, test_user: User) -> Credential:
|
||||||
"""Create a test credential for the admin user."""
|
"""Create a test credential for the admin user."""
|
||||||
credential = Credential(
|
credential = Credential.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
credential_id=os.urandom(32),
|
credential_id=os.urandom(32),
|
||||||
user_uuid=test_user.uuid,
|
user=test_user.uuid,
|
||||||
aaguid=UUID("00000000-0000-0000-0000-000000000000"),
|
aaguid=UUID("00000000-0000-0000-0000-000000000000"),
|
||||||
public_key=os.urandom(64),
|
public_key=os.urandom(64),
|
||||||
sign_count=0,
|
sign_count=0,
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
last_used=None,
|
|
||||||
last_verified=None,
|
|
||||||
)
|
)
|
||||||
await test_db.create_credential(credential)
|
create_credential(credential)
|
||||||
return credential
|
return credential
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def regular_credential(test_db: DB, regular_user: User) -> Credential:
|
async def regular_credential(test_db: DB, regular_user: User) -> Credential:
|
||||||
"""Create a test credential for the regular user."""
|
"""Create a test credential for the regular user."""
|
||||||
credential = Credential(
|
credential = Credential.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
credential_id=os.urandom(32),
|
credential_id=os.urandom(32),
|
||||||
user_uuid=regular_user.uuid,
|
user=regular_user.uuid,
|
||||||
aaguid=UUID("00000000-0000-0000-0000-000000000000"),
|
aaguid=UUID("00000000-0000-0000-0000-000000000000"),
|
||||||
public_key=os.urandom(64),
|
public_key=os.urandom(64),
|
||||||
sign_count=0,
|
sign_count=0,
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
last_used=None,
|
|
||||||
last_verified=None,
|
|
||||||
)
|
)
|
||||||
await test_db.create_credential(credential)
|
create_credential(credential)
|
||||||
return credential
|
return credential
|
||||||
|
|
||||||
|
|
||||||
@@ -181,15 +193,15 @@ async def session_token(
|
|||||||
test_db: DB, test_user: User, test_credential: Credential
|
test_db: DB, test_user: User, test_credential: Credential
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Create a session for the admin user and return the token."""
|
"""Create a session for the admin user and return the token."""
|
||||||
token = create_token()
|
token = _create_token()
|
||||||
await test_db.create_session(
|
create_session(
|
||||||
user_uuid=test_user.uuid,
|
user_uuid=test_user.uuid,
|
||||||
credential_uuid=test_credential.uuid,
|
credential_uuid=test_credential.uuid,
|
||||||
key=session_key(token),
|
key=token,
|
||||||
host="localhost:4401",
|
host="localhost:4401",
|
||||||
ip="127.0.0.1",
|
ip="127.0.0.1",
|
||||||
user_agent="pytest",
|
user_agent="pytest",
|
||||||
renewed=datetime.now(timezone.utc),
|
expiry=expires(),
|
||||||
)
|
)
|
||||||
return token
|
return token
|
||||||
|
|
||||||
@@ -199,15 +211,15 @@ async def regular_session_token(
|
|||||||
test_db: DB, regular_user: User, regular_credential: Credential
|
test_db: DB, regular_user: User, regular_credential: Credential
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Create a session for a regular user and return the token."""
|
"""Create a session for a regular user and return the token."""
|
||||||
token = create_token()
|
token = _create_token()
|
||||||
await test_db.create_session(
|
create_session(
|
||||||
user_uuid=regular_user.uuid,
|
user_uuid=regular_user.uuid,
|
||||||
credential_uuid=regular_credential.uuid,
|
credential_uuid=regular_credential.uuid,
|
||||||
key=session_key(token),
|
key=token,
|
||||||
host="localhost:4401",
|
host="localhost:4401",
|
||||||
ip="127.0.0.1",
|
ip="127.0.0.1",
|
||||||
user_agent="pytest",
|
user_agent="pytest",
|
||||||
renewed=datetime.now(timezone.utc),
|
expiry=expires(),
|
||||||
)
|
)
|
||||||
return token
|
return token
|
||||||
|
|
||||||
@@ -215,14 +227,11 @@ async def regular_session_token(
|
|||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def reset_token(test_db: DB, test_user: User, test_credential: Credential) -> str:
|
async def reset_token(test_db: DB, test_user: User, test_credential: Credential) -> str:
|
||||||
"""Create a reset token for the test user."""
|
"""Create a reset token for the test user."""
|
||||||
from paskia.authsession import reset_expires
|
|
||||||
from paskia.util.passphrase import generate
|
|
||||||
from paskia.util.tokens import reset_key
|
|
||||||
|
|
||||||
token = generate()
|
token = generate()
|
||||||
await test_db.create_reset_token(
|
create_reset_token(
|
||||||
user_uuid=test_user.uuid,
|
user_uuid=test_user.uuid,
|
||||||
key=reset_key(token),
|
passphrase=token,
|
||||||
expiry=reset_expires(),
|
expiry=reset_expires(),
|
||||||
token_type="reset",
|
token_type="reset",
|
||||||
)
|
)
|
||||||
@@ -239,7 +248,6 @@ async def client(
|
|||||||
initialized first.
|
initialized first.
|
||||||
"""
|
"""
|
||||||
# Import app after globals are set
|
# Import app after globals are set
|
||||||
from paskia.fastapi.mainapp import app
|
|
||||||
|
|
||||||
transport = httpx.ASGITransport(app=app)
|
transport = httpx.ASGITransport(app=app)
|
||||||
async with httpx.AsyncClient(
|
async with httpx.AsyncClient(
|
||||||
|
|||||||
+276
-216
@@ -11,6 +11,7 @@ These tests cover:
|
|||||||
- Credential management
|
- Credential management
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
@@ -19,9 +20,23 @@ import pytest
|
|||||||
import pytest_asyncio
|
import pytest_asyncio
|
||||||
import uuid7
|
import uuid7
|
||||||
|
|
||||||
from paskia.db import Credential, Org, Permission, Role, User
|
from paskia import db
|
||||||
from paskia.db.sql import DB
|
from paskia.authsession import expires
|
||||||
from paskia.util.tokens import create_token, encode_session_key, session_key
|
from paskia.db import (
|
||||||
|
Credential,
|
||||||
|
Org,
|
||||||
|
Permission,
|
||||||
|
Role,
|
||||||
|
User,
|
||||||
|
add_permission_to_org,
|
||||||
|
create_credential,
|
||||||
|
create_org,
|
||||||
|
create_permission,
|
||||||
|
create_role,
|
||||||
|
create_session,
|
||||||
|
create_user,
|
||||||
|
)
|
||||||
|
from paskia.db.operations import DB, _create_token
|
||||||
from tests.conftest import auth_headers
|
from tests.conftest import auth_headers
|
||||||
|
|
||||||
# -------------------- Additional Fixtures --------------------
|
# -------------------- Additional Fixtures --------------------
|
||||||
@@ -30,12 +45,10 @@ from tests.conftest import auth_headers
|
|||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def second_org(test_db: DB) -> Org:
|
async def second_org(test_db: DB) -> Org:
|
||||||
"""Create a second organization for deletion tests."""
|
"""Create a second organization for deletion tests."""
|
||||||
org = Org(
|
org = Org.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
display_name="Second Organization",
|
display_name="Second Organization",
|
||||||
permissions=[],
|
|
||||||
)
|
)
|
||||||
await test_db.create_organization(org)
|
create_org(org)
|
||||||
return org
|
return org
|
||||||
|
|
||||||
|
|
||||||
@@ -44,47 +57,38 @@ async def second_org_role(
|
|||||||
test_db: DB, second_org: Org, admin_permission: Permission
|
test_db: DB, second_org: Org, admin_permission: Permission
|
||||||
) -> Role:
|
) -> Role:
|
||||||
"""Create a role in the second org with admin permission."""
|
"""Create a role in the second org with admin permission."""
|
||||||
role = Role(
|
role = Role.create(
|
||||||
uuid=uuid7.create(),
|
org=second_org.uuid,
|
||||||
org_uuid=second_org.uuid,
|
|
||||||
display_name="Second Org Admin Role",
|
display_name="Second Org Admin Role",
|
||||||
permissions=["auth:admin"],
|
permissions={admin_permission.uuid},
|
||||||
)
|
)
|
||||||
await test_db.create_role(role)
|
create_role(role)
|
||||||
return role
|
return role
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def second_org_user(test_db: DB, second_org_role: Role) -> User:
|
async def second_org_user(test_db: DB, second_org_role: Role) -> User:
|
||||||
"""Create a user in the second org."""
|
"""Create a user in the second org."""
|
||||||
user = User(
|
user = User.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
display_name="Second Org User",
|
display_name="Second Org User",
|
||||||
role_uuid=second_org_role.uuid,
|
role=second_org_role.uuid,
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
visits=0,
|
|
||||||
)
|
)
|
||||||
await test_db.create_user(user)
|
create_user(user)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def second_org_credential(test_db: DB, second_org_user: User) -> Credential:
|
async def second_org_credential(test_db: DB, second_org_user: User) -> Credential:
|
||||||
"""Create a credential for the second org user."""
|
"""Create a credential for the second org user."""
|
||||||
import os
|
|
||||||
|
|
||||||
credential = Credential(
|
credential = Credential.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
credential_id=os.urandom(32),
|
credential_id=os.urandom(32),
|
||||||
user_uuid=second_org_user.uuid,
|
user=second_org_user.uuid,
|
||||||
aaguid=UUID("00000000-0000-0000-0000-000000000000"),
|
aaguid=UUID("00000000-0000-0000-0000-000000000000"),
|
||||||
public_key=os.urandom(64),
|
public_key=os.urandom(64),
|
||||||
sign_count=0,
|
sign_count=0,
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
last_used=datetime.now(timezone.utc),
|
|
||||||
last_verified=datetime.now(timezone.utc),
|
|
||||||
)
|
)
|
||||||
await test_db.create_credential(credential)
|
create_credential(credential)
|
||||||
return credential
|
return credential
|
||||||
|
|
||||||
|
|
||||||
@@ -93,64 +97,58 @@ async def second_org_session_token(
|
|||||||
test_db: DB, second_org_user: User, second_org_credential: Credential
|
test_db: DB, second_org_user: User, second_org_credential: Credential
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Create a session for the second org admin user."""
|
"""Create a session for the second org admin user."""
|
||||||
token = create_token()
|
token = _create_token()
|
||||||
await test_db.create_session(
|
create_session(
|
||||||
user_uuid=second_org_user.uuid,
|
user_uuid=second_org_user.uuid,
|
||||||
credential_uuid=second_org_credential.uuid,
|
credential_uuid=second_org_credential.uuid,
|
||||||
key=session_key(token),
|
key=token,
|
||||||
host="localhost:4401",
|
host="localhost:4401",
|
||||||
ip="127.0.0.1",
|
ip="127.0.0.1",
|
||||||
user_agent="pytest",
|
user_agent="pytest",
|
||||||
renewed=datetime.now(timezone.utc),
|
expiry=expires(),
|
||||||
)
|
)
|
||||||
return token
|
return token
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def org_admin_role(test_db: DB, test_org: Org) -> Role:
|
async def org_admin_role(
|
||||||
|
test_db: DB, test_org: Org, org_admin_permission: Permission
|
||||||
|
) -> Role:
|
||||||
"""Create a role with org admin permission only (no global admin)."""
|
"""Create a role with org admin permission only (no global admin)."""
|
||||||
role = Role(
|
role = Role.create(
|
||||||
uuid=uuid7.create(),
|
org=test_org.uuid,
|
||||||
org_uuid=test_org.uuid,
|
|
||||||
display_name="Org Admin Role",
|
display_name="Org Admin Role",
|
||||||
permissions=[f"auth:org:{test_org.uuid}"],
|
permissions={org_admin_permission.uuid},
|
||||||
)
|
)
|
||||||
await test_db.create_role(role)
|
create_role(role)
|
||||||
return role
|
return role
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def org_admin_user(test_db: DB, org_admin_role: Role) -> User:
|
async def org_admin_user(test_db: DB, org_admin_role: Role) -> User:
|
||||||
"""Create a user with org admin permission only."""
|
"""Create a user with org admin permission only."""
|
||||||
user = User(
|
user = User.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
display_name="Org Admin User",
|
display_name="Org Admin User",
|
||||||
role_uuid=org_admin_role.uuid,
|
role=org_admin_role.uuid,
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
visits=5,
|
|
||||||
last_seen=datetime.now(timezone.utc),
|
|
||||||
)
|
)
|
||||||
await test_db.create_user(user)
|
user.visits = 5
|
||||||
|
user.last_seen = datetime.now(timezone.utc)
|
||||||
|
create_user(user)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def org_admin_credential(test_db: DB, org_admin_user: User) -> Credential:
|
async def org_admin_credential(test_db: DB, org_admin_user: User) -> Credential:
|
||||||
"""Create a credential for the org admin user."""
|
"""Create a credential for the org admin user."""
|
||||||
import os
|
|
||||||
|
|
||||||
credential = Credential(
|
credential = Credential.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
credential_id=os.urandom(32),
|
credential_id=os.urandom(32),
|
||||||
user_uuid=org_admin_user.uuid,
|
user=org_admin_user.uuid,
|
||||||
aaguid=UUID("00000000-0000-0000-0000-000000000000"),
|
aaguid=UUID("00000000-0000-0000-0000-000000000000"),
|
||||||
public_key=os.urandom(64),
|
public_key=os.urandom(64),
|
||||||
sign_count=0,
|
sign_count=0,
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
last_used=datetime.now(timezone.utc),
|
|
||||||
last_verified=None,
|
|
||||||
)
|
)
|
||||||
await test_db.create_credential(credential)
|
create_credential(credential)
|
||||||
return credential
|
return credential
|
||||||
|
|
||||||
|
|
||||||
@@ -159,15 +157,15 @@ async def org_admin_session_token(
|
|||||||
test_db: DB, org_admin_user: User, org_admin_credential: Credential
|
test_db: DB, org_admin_user: User, org_admin_credential: Credential
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Create a session for the org admin user."""
|
"""Create a session for the org admin user."""
|
||||||
token = create_token()
|
token = _create_token()
|
||||||
await test_db.create_session(
|
create_session(
|
||||||
user_uuid=org_admin_user.uuid,
|
user_uuid=org_admin_user.uuid,
|
||||||
credential_uuid=org_admin_credential.uuid,
|
credential_uuid=org_admin_credential.uuid,
|
||||||
key=session_key(token),
|
key=token,
|
||||||
host="localhost:4401",
|
host="localhost:4401",
|
||||||
ip="127.0.0.1",
|
ip="127.0.0.1",
|
||||||
user_agent="pytest",
|
user_agent="pytest",
|
||||||
renewed=datetime.now(timezone.utc),
|
expiry=expires(),
|
||||||
)
|
)
|
||||||
return token
|
return token
|
||||||
|
|
||||||
@@ -175,10 +173,10 @@ async def org_admin_session_token(
|
|||||||
@pytest_asyncio.fixture(scope="function")
|
@pytest_asyncio.fixture(scope="function")
|
||||||
async def grantable_permission(test_db: DB, test_org: Org) -> Permission:
|
async def grantable_permission(test_db: DB, test_org: Org) -> Permission:
|
||||||
"""Create a permission and add it to org's grantable permissions."""
|
"""Create a permission and add it to org's grantable permissions."""
|
||||||
perm = Permission(id="test:grantable:perm", display_name="Grantable Perm")
|
perm = Permission.create(scope="test:grantable:perm", display_name="Grantable Perm")
|
||||||
await test_db.create_permission(perm)
|
create_permission(perm)
|
||||||
# Add to org's grantable permissions
|
# Add to org's grantable permissions
|
||||||
await test_db.add_permission_to_organization(str(test_org.uuid), perm.id)
|
add_permission_to_org(test_org.uuid, perm.uuid)
|
||||||
return perm
|
return perm
|
||||||
|
|
||||||
|
|
||||||
@@ -333,7 +331,7 @@ class TestAdminOrganizations:
|
|||||||
self, client: httpx.AsyncClient, session_token: str, test_org
|
self, client: httpx.AsyncClient, session_token: str, test_org
|
||||||
):
|
):
|
||||||
"""Admin should be able to update an organization."""
|
"""Admin should be able to update an organization."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}",
|
f"/auth/api/admin/orgs/{test_org.uuid}",
|
||||||
json={"display_name": "Updated Org Name"},
|
json={"display_name": "Updated Org Name"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -350,11 +348,10 @@ class TestAdminOrganizations:
|
|||||||
test_org,
|
test_org,
|
||||||
):
|
):
|
||||||
"""Org admin should be able to update their organization."""
|
"""Org admin should be able to update their organization."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}",
|
f"/auth/api/admin/orgs/{test_org.uuid}",
|
||||||
json={
|
json={
|
||||||
"display_name": "Org Admin Updated Name",
|
"display_name": "Org Admin Updated Name",
|
||||||
"permissions": [f"auth:org:{test_org.uuid}"], # Keep org admin perm
|
|
||||||
},
|
},
|
||||||
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
@@ -371,31 +368,18 @@ class TestAdminOrganizations:
|
|||||||
test_db: DB,
|
test_db: DB,
|
||||||
):
|
):
|
||||||
"""Org admin cannot remove their org admin permission from org's permissions."""
|
"""Org admin cannot remove their org admin permission from org's permissions."""
|
||||||
# First create and add the org admin perm to the org's grantable perms
|
# The auth:org:admin perm is already created and added by org_admin_permission fixture
|
||||||
org_admin_perm_id = f"auth:org:{test_org.uuid}"
|
org_admin_perm = next(
|
||||||
perm = Permission(id=org_admin_perm_id, display_name="Org Admin")
|
p for p in db.data().permissions.values() if p.scope == "auth:org:admin"
|
||||||
try:
|
|
||||||
await test_db.create_permission(perm)
|
|
||||||
except Exception:
|
|
||||||
pass # Permission may already exist
|
|
||||||
|
|
||||||
# Add it to the org's permissions
|
|
||||||
await test_db.add_permission_to_organization(
|
|
||||||
str(test_org.uuid), org_admin_perm_id
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Try to remove all permissions including org admin perm
|
# Try to remove org admin perm (this is validated server-side in the remove endpoint)
|
||||||
response = await client.put(
|
response = await client.delete(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}",
|
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_uuid={org_admin_perm.uuid}",
|
||||||
json={
|
|
||||||
"display_name": "Try Remove Own Perm",
|
|
||||||
"permissions": [], # Remove org admin perm from org's permissions
|
|
||||||
},
|
|
||||||
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 400
|
# This should fail because only global admin can remove perms from org
|
||||||
data = response.json()
|
assert response.status_code == 403
|
||||||
assert "Cannot remove organization admin permission" in data["detail"]
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_delete_org_own_org_fails(
|
async def test_delete_org_own_org_fails(
|
||||||
@@ -419,18 +403,17 @@ class TestAdminOrganizations:
|
|||||||
):
|
):
|
||||||
"""Admin should be able to delete another organization."""
|
"""Admin should be able to delete another organization."""
|
||||||
# Create org to delete
|
# Create org to delete
|
||||||
org_to_delete = Org(
|
org_to_delete = Org.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
display_name="Org To Delete",
|
display_name="Org To Delete",
|
||||||
permissions=[],
|
|
||||||
)
|
)
|
||||||
await test_db.create_organization(org_to_delete)
|
create_org(org_to_delete)
|
||||||
|
|
||||||
# Create some org-specific permissions to test cleanup
|
# Create some org-specific permissions to test cleanup
|
||||||
org_perm = Permission(
|
org_perm = Permission.create(
|
||||||
id=f"test:org:{org_to_delete.uuid}:feature", display_name="Org Feature"
|
scope=f"test:org:{org_to_delete.uuid}:feature",
|
||||||
|
display_name="Org Feature",
|
||||||
)
|
)
|
||||||
await test_db.create_permission(org_perm)
|
create_permission(org_perm)
|
||||||
|
|
||||||
response = await client.delete(
|
response = await client.delete(
|
||||||
f"/auth/api/admin/orgs/{org_to_delete.uuid}",
|
f"/auth/api/admin/orgs/{org_to_delete.uuid}",
|
||||||
@@ -453,15 +436,12 @@ class TestAdminOrgPermissions:
|
|||||||
):
|
):
|
||||||
"""Admin should be able to add a permission to an org."""
|
"""Admin should be able to add a permission to an org."""
|
||||||
# First create a permission
|
# First create a permission
|
||||||
await client.post(
|
perm = Permission.create(scope="test:org:addable", display_name="Addable")
|
||||||
"/auth/api/admin/permissions",
|
create_permission(perm)
|
||||||
json={"id": "test:org:addable", "display_name": "Addable"},
|
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
|
||||||
)
|
|
||||||
|
|
||||||
# Add it to the org
|
# Add it to the org
|
||||||
response = await client.post(
|
response = await client.post(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_id=test:org:addable",
|
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_uuid={perm.uuid}",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -476,8 +456,11 @@ class TestAdminOrgPermissions:
|
|||||||
test_org,
|
test_org,
|
||||||
):
|
):
|
||||||
"""Org admin cannot add permissions to org (requires global admin)."""
|
"""Org admin cannot add permissions to org (requires global admin)."""
|
||||||
|
admin_perm = next(
|
||||||
|
p for p in db.data().permissions.values() if p.scope == "auth:admin"
|
||||||
|
)
|
||||||
response = await client.post(
|
response = await client.post(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_id=auth:admin",
|
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_uuid={admin_perm.uuid}",
|
||||||
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 403
|
assert response.status_code == 403
|
||||||
@@ -488,19 +471,16 @@ class TestAdminOrgPermissions:
|
|||||||
):
|
):
|
||||||
"""Admin should be able to remove a permission from an org."""
|
"""Admin should be able to remove a permission from an org."""
|
||||||
# First create and add a permission
|
# First create and add a permission
|
||||||
|
perm = Permission.create(scope="test:org:removable", display_name="Removable")
|
||||||
|
create_permission(perm)
|
||||||
await client.post(
|
await client.post(
|
||||||
"/auth/api/admin/permissions",
|
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_uuid={perm.uuid}",
|
||||||
json={"id": "test:org:removable", "display_name": "Removable"},
|
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
|
||||||
)
|
|
||||||
await client.post(
|
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_id=test:org:removable",
|
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
|
|
||||||
# Remove it
|
# Remove it
|
||||||
response = await client.delete(
|
response = await client.delete(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_id=test:org:removable",
|
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_uuid={perm.uuid}",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -515,8 +495,11 @@ class TestAdminOrgPermissions:
|
|||||||
test_org,
|
test_org,
|
||||||
):
|
):
|
||||||
"""Org admin cannot remove permissions from org (requires global admin)."""
|
"""Org admin cannot remove permissions from org (requires global admin)."""
|
||||||
|
admin_perm = next(
|
||||||
|
p for p in db.data().permissions.values() if p.scope == "auth:admin"
|
||||||
|
)
|
||||||
response = await client.delete(
|
response = await client.delete(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_id=auth:admin",
|
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_uuid={admin_perm.uuid}",
|
||||||
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 403
|
assert response.status_code == 403
|
||||||
@@ -584,7 +567,7 @@ class TestAdminRoles:
|
|||||||
f"/auth/api/admin/orgs/{test_org.uuid}/roles",
|
f"/auth/api/admin/orgs/{test_org.uuid}/roles",
|
||||||
json={
|
json={
|
||||||
"display_name": "Role With Perms",
|
"display_name": "Role With Perms",
|
||||||
"permissions": [grantable_permission.id],
|
"permissions": [str(grantable_permission.uuid)],
|
||||||
},
|
},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
@@ -602,14 +585,17 @@ class TestAdminRoles:
|
|||||||
):
|
):
|
||||||
"""Creating role with non-grantable permission should fail."""
|
"""Creating role with non-grantable permission should fail."""
|
||||||
# Create permission but don't add to org
|
# Create permission but don't add to org
|
||||||
perm = Permission(id="test:not:grantable", display_name="Not Grantable")
|
perm = Permission.create(
|
||||||
await test_db.create_permission(perm)
|
scope="test:not:grantable",
|
||||||
|
display_name="Not Grantable",
|
||||||
|
)
|
||||||
|
create_permission(perm)
|
||||||
|
|
||||||
response = await client.post(
|
response = await client.post(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/roles",
|
f"/auth/api/admin/orgs/{test_org.uuid}/roles",
|
||||||
json={
|
json={
|
||||||
"display_name": "Bad Role",
|
"display_name": "Bad Role",
|
||||||
"permissions": ["test:not:grantable"],
|
"permissions": [str(perm.uuid)],
|
||||||
},
|
},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
@@ -622,7 +608,7 @@ class TestAdminRoles:
|
|||||||
self, client: httpx.AsyncClient, session_token: str, test_org, test_role
|
self, client: httpx.AsyncClient, session_token: str, test_org, test_role
|
||||||
):
|
):
|
||||||
"""Admin should be able to update a role."""
|
"""Admin should be able to update a role."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{test_role.uuid}",
|
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{test_role.uuid}",
|
||||||
json={"display_name": "Updated Role Name"},
|
json={"display_name": "Updated Role Name"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -636,7 +622,7 @@ class TestAdminRoles:
|
|||||||
self, client: httpx.AsyncClient, session_token: str, test_org, second_org_role
|
self, client: httpx.AsyncClient, session_token: str, test_org, second_org_role
|
||||||
):
|
):
|
||||||
"""Cannot update role from another org."""
|
"""Cannot update role from another org."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{second_org_role.uuid}",
|
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{second_org_role.uuid}",
|
||||||
json={"display_name": "Try Update Wrong Org"},
|
json={"display_name": "Try Update Wrong Org"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -655,9 +641,8 @@ class TestAdminRoles:
|
|||||||
grantable_permission,
|
grantable_permission,
|
||||||
):
|
):
|
||||||
"""Admin should be able to add grantable permissions to role."""
|
"""Admin should be able to add grantable permissions to role."""
|
||||||
response = await client.put(
|
response = await client.post(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{user_role.uuid}",
|
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{user_role.uuid}/permissions/{grantable_permission.uuid}",
|
||||||
json={"permissions": [grantable_permission.id]},
|
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -672,12 +657,14 @@ class TestAdminRoles:
|
|||||||
test_db: DB,
|
test_db: DB,
|
||||||
):
|
):
|
||||||
"""Adding non-grantable permission to role should fail."""
|
"""Adding non-grantable permission to role should fail."""
|
||||||
perm = Permission(id="test:not:grantable:update", display_name="Not Grantable")
|
perm = Permission.create(
|
||||||
await test_db.create_permission(perm)
|
scope="test:not:grantable:update",
|
||||||
|
display_name="Not Grantable",
|
||||||
|
)
|
||||||
|
create_permission(perm)
|
||||||
|
|
||||||
response = await client.put(
|
response = await client.post(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{user_role.uuid}",
|
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{user_role.uuid}/permissions/{perm.uuid}",
|
||||||
json={"permissions": ["test:not:grantable:update"]},
|
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
@@ -686,17 +673,31 @@ class TestAdminRoles:
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_update_own_role_cannot_remove_admin(
|
async def test_update_own_role_cannot_remove_admin(
|
||||||
self, client: httpx.AsyncClient, session_token: str, test_org, test_role
|
self,
|
||||||
|
client: httpx.AsyncClient,
|
||||||
|
session_token: str,
|
||||||
|
test_org,
|
||||||
|
test_role,
|
||||||
|
admin_permission,
|
||||||
|
org_admin_permission,
|
||||||
):
|
):
|
||||||
"""Admin cannot remove their own admin permissions."""
|
"""Admin cannot remove their own admin permissions."""
|
||||||
response = await client.put(
|
# test_role has both auth:admin and auth:org:admin
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{test_role.uuid}",
|
# Remove auth:admin first (should succeed since org:admin remains)
|
||||||
json={"permissions": []}, # Remove all permissions
|
response = await client.delete(
|
||||||
|
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{test_role.uuid}/permissions/{admin_permission.uuid}",
|
||||||
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
# Now try to remove auth:org:admin (should fail - would leave no admin access)
|
||||||
|
response = await client.delete(
|
||||||
|
f"/auth/api/admin/orgs/{test_org.uuid}/roles/{test_role.uuid}/permissions/{org_admin_permission.uuid}",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert "Cannot update your own role" in data["detail"]
|
assert "Cannot remove your own admin permissions" in data["detail"]
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_delete_role(
|
async def test_delete_role(
|
||||||
@@ -853,7 +854,7 @@ class TestAdminUsersInOrg:
|
|||||||
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
||||||
):
|
):
|
||||||
"""Admin should be able to update user display name."""
|
"""Admin should be able to update user display name."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/display-name",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/display-name",
|
||||||
json={"display_name": "Updated Admin Name"},
|
json={"display_name": "Updated Admin Name"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -866,7 +867,7 @@ class TestAdminUsersInOrg:
|
|||||||
):
|
):
|
||||||
"""Updating non-existent user should return 404."""
|
"""Updating non-existent user should return 404."""
|
||||||
fake_uuid = uuid7.create()
|
fake_uuid = uuid7.create()
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{fake_uuid}/display-name",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{fake_uuid}/display-name",
|
||||||
json={"display_name": "New Name"},
|
json={"display_name": "New Name"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -880,7 +881,7 @@ class TestAdminUsersInOrg:
|
|||||||
self, client: httpx.AsyncClient, session_token: str, test_org, second_org_user
|
self, client: httpx.AsyncClient, session_token: str, test_org, second_org_user
|
||||||
):
|
):
|
||||||
"""Updating user from another org should return 404."""
|
"""Updating user from another org should return 404."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{second_org_user.uuid}/display-name",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{second_org_user.uuid}/display-name",
|
||||||
json={"display_name": "New Name"},
|
json={"display_name": "New Name"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -892,7 +893,7 @@ class TestAdminUsersInOrg:
|
|||||||
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
||||||
):
|
):
|
||||||
"""Updating user with empty display name should fail."""
|
"""Updating user with empty display name should fail."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/display-name",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/display-name",
|
||||||
json={"display_name": " "},
|
json={"display_name": " "},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -906,7 +907,7 @@ class TestAdminUsersInOrg:
|
|||||||
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
||||||
):
|
):
|
||||||
"""Updating user with too long display name should fail."""
|
"""Updating user with too long display name should fail."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/display-name",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/display-name",
|
||||||
json={"display_name": "x" * 100},
|
json={"display_name": "x" * 100},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -926,7 +927,7 @@ class TestAdminUsersInOrg:
|
|||||||
):
|
):
|
||||||
"""Admin should be able to change user's role within org."""
|
"""Admin should be able to change user's role within org."""
|
||||||
# Use regular_user who is in the same org but not the session owner
|
# Use regular_user who is in the same org but not the session owner
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{regular_user.uuid}/role",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{regular_user.uuid}/role",
|
||||||
json={"role": user_role.display_name},
|
json={"role": user_role.display_name},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -938,7 +939,7 @@ class TestAdminUsersInOrg:
|
|||||||
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
||||||
):
|
):
|
||||||
"""Updating user role without specifying role should fail."""
|
"""Updating user role without specifying role should fail."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/role",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/role",
|
||||||
json={},
|
json={},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -953,7 +954,7 @@ class TestAdminUsersInOrg:
|
|||||||
):
|
):
|
||||||
"""Updating role for non-existent user should fail."""
|
"""Updating role for non-existent user should fail."""
|
||||||
fake_uuid = uuid7.create()
|
fake_uuid = uuid7.create()
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{fake_uuid}/role",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{fake_uuid}/role",
|
||||||
json={"role": "User Role"},
|
json={"role": "User Role"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -967,7 +968,7 @@ class TestAdminUsersInOrg:
|
|||||||
self, client: httpx.AsyncClient, session_token: str, test_org, second_org_user
|
self, client: httpx.AsyncClient, session_token: str, test_org, second_org_user
|
||||||
):
|
):
|
||||||
"""Updating role for user in another org should fail."""
|
"""Updating role for user in another org should fail."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{second_org_user.uuid}/role",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{second_org_user.uuid}/role",
|
||||||
json={"role": "User Role"},
|
json={"role": "User Role"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -981,7 +982,7 @@ class TestAdminUsersInOrg:
|
|||||||
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
||||||
):
|
):
|
||||||
"""Updating user to non-existent role should fail."""
|
"""Updating user to non-existent role should fail."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/role",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/role",
|
||||||
json={"role": "Nonexistent Role"},
|
json={"role": "Nonexistent Role"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -1000,7 +1001,7 @@ class TestAdminUsersInOrg:
|
|||||||
user_role,
|
user_role,
|
||||||
):
|
):
|
||||||
"""Admin cannot change their own role to non-admin role."""
|
"""Admin cannot change their own role to non-admin role."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{org_admin_user.uuid}/role",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{org_admin_user.uuid}/role",
|
||||||
json={"role": user_role.display_name},
|
json={"role": user_role.display_name},
|
||||||
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
||||||
@@ -1021,7 +1022,7 @@ class TestAdminUsersInOrg:
|
|||||||
"""Admin can change their own role to another admin role."""
|
"""Admin can change their own role to another admin role."""
|
||||||
# test_user is already on test_role which has auth:admin
|
# test_user is already on test_role which has auth:admin
|
||||||
# Changing to the same role should succeed (no permission loss)
|
# Changing to the same role should succeed (no permission loss)
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/role",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/role",
|
||||||
json={"role": test_role.display_name},
|
json={"role": test_role.display_name},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -1080,14 +1081,11 @@ class TestAdminUsersInOrg:
|
|||||||
):
|
):
|
||||||
"""Creating link for user without credentials should return registration link."""
|
"""Creating link for user without credentials should return registration link."""
|
||||||
# Create user without credentials
|
# Create user without credentials
|
||||||
user_no_cred = User(
|
user_no_cred = User.create(
|
||||||
uuid=uuid7.create(),
|
|
||||||
display_name="User Without Creds",
|
display_name="User Without Creds",
|
||||||
role_uuid=user_role.uuid,
|
role=user_role.uuid,
|
||||||
created_at=datetime.now(timezone.utc),
|
|
||||||
visits=0,
|
|
||||||
)
|
)
|
||||||
await test_db.create_user(user_no_cred)
|
create_user(user_no_cred)
|
||||||
|
|
||||||
response = await client.post(
|
response = await client.post(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{user_no_cred.uuid}/create-link",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{user_no_cred.uuid}/create-link",
|
||||||
@@ -1172,21 +1170,19 @@ class TestAdminSessions:
|
|||||||
):
|
):
|
||||||
"""Admin should be able to delete a user's session."""
|
"""Admin should be able to delete a user's session."""
|
||||||
# Create an additional session to delete
|
# Create an additional session to delete
|
||||||
extra_token = create_token()
|
extra_token = _create_token()
|
||||||
extra_key = session_key(extra_token)
|
create_session(
|
||||||
await test_db.create_session(
|
|
||||||
user_uuid=test_user.uuid,
|
user_uuid=test_user.uuid,
|
||||||
credential_uuid=test_credential.uuid,
|
credential_uuid=test_credential.uuid,
|
||||||
key=extra_key,
|
key=extra_token,
|
||||||
host="other.host:4401",
|
host="other.host:4401",
|
||||||
ip="192.168.1.1",
|
ip="192.168.1.1",
|
||||||
user_agent="other-agent",
|
user_agent="other-agent",
|
||||||
renewed=datetime.now(timezone.utc),
|
expiry=expires(),
|
||||||
)
|
)
|
||||||
|
|
||||||
encoded_key = encode_session_key(extra_key)
|
|
||||||
response = await client.delete(
|
response = await client.delete(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/sessions/{encoded_key}",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/sessions/{extra_token}",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -1203,9 +1199,8 @@ class TestAdminSessions:
|
|||||||
test_user,
|
test_user,
|
||||||
):
|
):
|
||||||
"""Admin can delete their own current session."""
|
"""Admin can delete their own current session."""
|
||||||
encoded_key = encode_session_key(session_key(session_token))
|
|
||||||
response = await client.delete(
|
response = await client.delete(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/sessions/{encoded_key}",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/sessions/{session_token}",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -1245,14 +1240,14 @@ class TestAdminSessions:
|
|||||||
async def test_delete_session_invalid_id(
|
async def test_delete_session_invalid_id(
|
||||||
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
self, client: httpx.AsyncClient, session_token: str, test_org, test_user
|
||||||
):
|
):
|
||||||
"""Deleting session with invalid ID format should fail."""
|
"""Deleting session with invalid/non-existent ID should fail."""
|
||||||
response = await client.delete(
|
response = await client.delete(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/sessions/invalid!!id",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/sessions/invalid!!id",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 400
|
assert response.status_code == 404
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert "Invalid session identifier" in data["detail"]
|
assert "Session not found" in data["detail"]
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_delete_session_not_found(
|
async def test_delete_session_not_found(
|
||||||
@@ -1260,10 +1255,9 @@ class TestAdminSessions:
|
|||||||
):
|
):
|
||||||
"""Deleting non-existent session should fail."""
|
"""Deleting non-existent session should fail."""
|
||||||
# Use a valid format but non-existent key
|
# Use a valid format but non-existent key
|
||||||
fake_key = session_key(create_token())
|
fake_token = _create_token()
|
||||||
encoded_key = encode_session_key(fake_key)
|
|
||||||
response = await client.delete(
|
response = await client.delete(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/sessions/{encoded_key}",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/sessions/{fake_token}",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 404
|
assert response.status_code == 404
|
||||||
@@ -1290,8 +1284,8 @@ class TestAdminPermissions:
|
|||||||
data = response.json()
|
data = response.json()
|
||||||
assert isinstance(data, list)
|
assert isinstance(data, list)
|
||||||
# Should include at least auth:admin
|
# Should include at least auth:admin
|
||||||
perm_ids = [p["id"] for p in data]
|
perm_scopes = [p["scope"] for p in data]
|
||||||
assert "auth:admin" in perm_ids
|
assert "auth:admin" in perm_scopes
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_list_permissions_org_admin(
|
async def test_list_permissions_org_admin(
|
||||||
@@ -1301,7 +1295,7 @@ class TestAdminPermissions:
|
|||||||
test_org,
|
test_org,
|
||||||
grantable_permission,
|
grantable_permission,
|
||||||
):
|
):
|
||||||
"""Org admin should only see grantable permissions."""
|
"""Org admin should only see permissions their org can grant."""
|
||||||
response = await client.get(
|
response = await client.get(
|
||||||
"/auth/api/admin/permissions",
|
"/auth/api/admin/permissions",
|
||||||
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(org_admin_session_token), "Host": "localhost:4401"},
|
||||||
@@ -1309,10 +1303,12 @@ class TestAdminPermissions:
|
|||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
data = response.json()
|
data = response.json()
|
||||||
# Should only see permissions the org can grant
|
# Should only see permissions the org can grant
|
||||||
perm_ids = [p["id"] for p in data]
|
perm_scopes = [p["scope"] for p in data]
|
||||||
assert grantable_permission.id in perm_ids
|
assert grantable_permission.scope in perm_scopes
|
||||||
# Should NOT see auth:admin (not grantable by org)
|
# test_org CAN grant auth:admin (it's in org.permissions), so org admin sees it
|
||||||
assert "auth:admin" not in perm_ids
|
assert "auth:admin" in perm_scopes
|
||||||
|
# Should also see auto-created org admin permission
|
||||||
|
assert "auth:org:admin" in perm_scopes
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_create_permission(
|
async def test_create_permission(
|
||||||
@@ -1321,7 +1317,7 @@ class TestAdminPermissions:
|
|||||||
"""Admin should be able to create new permissions."""
|
"""Admin should be able to create new permissions."""
|
||||||
response = await client.post(
|
response = await client.post(
|
||||||
"/auth/api/admin/permissions",
|
"/auth/api/admin/permissions",
|
||||||
json={"id": "test:create:permission", "display_name": "Test Permission"},
|
json={"scope": "test:create:permission", "display_name": "Test Permission"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -1349,7 +1345,7 @@ class TestAdminPermissions:
|
|||||||
"""Creating permission without admin should fail."""
|
"""Creating permission without admin should fail."""
|
||||||
response = await client.post(
|
response = await client.post(
|
||||||
"/auth/api/admin/permissions",
|
"/auth/api/admin/permissions",
|
||||||
json={"id": "test:forbidden", "display_name": "Forbidden"},
|
json={"scope": "test:forbidden", "display_name": "Forbidden"},
|
||||||
headers={
|
headers={
|
||||||
**auth_headers(regular_session_token),
|
**auth_headers(regular_session_token),
|
||||||
"Host": "localhost:4401",
|
"Host": "localhost:4401",
|
||||||
@@ -1363,11 +1359,11 @@ class TestAdminPermissions:
|
|||||||
):
|
):
|
||||||
"""Admin should be able to update a permission."""
|
"""Admin should be able to update a permission."""
|
||||||
# Create permission first
|
# Create permission first
|
||||||
perm = Permission(id="test:updateable", display_name="Updateable")
|
perm = Permission.create(scope="test:updateable", display_name="Updateable")
|
||||||
await test_db.create_permission(perm)
|
create_permission(perm)
|
||||||
|
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
"/auth/api/admin/permission?permission_id=test:updateable&display_name=Updated%20Name",
|
f"/auth/api/admin/permission?permission_uuid={perm.uuid}&display_name=Updated%20Name",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -1376,11 +1372,15 @@ class TestAdminPermissions:
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_update_permission_empty_name(
|
async def test_update_permission_empty_name(
|
||||||
self, client: httpx.AsyncClient, session_token: str
|
self, client: httpx.AsyncClient, session_token: str, test_db: DB
|
||||||
):
|
):
|
||||||
"""Updating permission with empty name should fail."""
|
"""Updating permission with empty name should fail."""
|
||||||
response = await client.put(
|
# Create permission first
|
||||||
"/auth/api/admin/permission?permission_id=test:perm&display_name=",
|
perm = Permission.create(scope="test:perm", display_name="Test Perm")
|
||||||
|
create_permission(perm)
|
||||||
|
|
||||||
|
response = await client.patch(
|
||||||
|
f"/auth/api/admin/permission?permission_uuid={perm.uuid}&display_name=",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
@@ -1388,43 +1388,32 @@ class TestAdminPermissions:
|
|||||||
assert "display_name is required" in data["detail"]
|
assert "display_name is required" in data["detail"]
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_rename_permission(
|
async def test_update_permission_scope(
|
||||||
self, client: httpx.AsyncClient, session_token: str, test_db: DB
|
self, client: httpx.AsyncClient, session_token: str, test_db: DB
|
||||||
):
|
):
|
||||||
"""Admin should be able to rename a permission."""
|
"""Admin should be able to update a permission's scope via PATCH."""
|
||||||
# Create permission first
|
# Create permission first
|
||||||
perm = Permission(id="test:renameable2", display_name="Renameable")
|
perm = Permission.create(scope="test:renameable2", display_name="Renameable")
|
||||||
await test_db.create_permission(perm)
|
create_permission(perm)
|
||||||
|
|
||||||
response = await client.post(
|
response = await client.patch(
|
||||||
"/auth/api/admin/permission/rename",
|
f"/auth/api/admin/permission?permission_uuid={perm.uuid}&scope=test:renamed2",
|
||||||
json={"old_id": "test:renameable2", "new_id": "test:renamed2"},
|
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_rename_permission_missing_ids(
|
async def test_update_permission_auth_admin_scope_fails(
|
||||||
self, client: httpx.AsyncClient, session_token: str
|
self, client: httpx.AsyncClient, session_token: str
|
||||||
):
|
):
|
||||||
"""Renaming permission without IDs should fail."""
|
"""Cannot change the auth:admin permission scope."""
|
||||||
response = await client.post(
|
# Get the auth:admin permission
|
||||||
"/auth/api/admin/permission/rename",
|
|
||||||
json={},
|
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 400
|
|
||||||
data = response.json()
|
|
||||||
assert "required" in data["detail"]
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
perms = list(db.data().permissions.values())
|
||||||
async def test_rename_permission_auth_admin_fails(
|
admin_perm = next(p for p in perms if p.scope == "auth:admin")
|
||||||
self, client: httpx.AsyncClient, session_token: str
|
|
||||||
):
|
response = await client.patch(
|
||||||
"""Cannot rename the auth:admin permission."""
|
f"/auth/api/admin/permission?permission_uuid={admin_perm.uuid}&scope=auth:superadmin",
|
||||||
response = await client.post(
|
|
||||||
"/auth/api/admin/permission/rename",
|
|
||||||
json={"old_id": "auth:admin", "new_id": "auth:superadmin"},
|
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
@@ -1432,20 +1421,15 @@ class TestAdminPermissions:
|
|||||||
assert "Cannot rename the master admin" in data["detail"]
|
assert "Cannot rename the master admin" in data["detail"]
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_rename_permission_with_display_name(
|
async def test_update_permission_scope_and_display_name(
|
||||||
self, client: httpx.AsyncClient, session_token: str, test_db: DB
|
self, client: httpx.AsyncClient, session_token: str, test_db: DB
|
||||||
):
|
):
|
||||||
"""Renaming permission can also update display name."""
|
"""Updating permission can change scope and display name together."""
|
||||||
perm = Permission(id="test:rename:withname", display_name="Old Name")
|
perm = Permission.create(scope="test:rename:withname", display_name="Old Name")
|
||||||
await test_db.create_permission(perm)
|
create_permission(perm)
|
||||||
|
|
||||||
response = await client.post(
|
response = await client.patch(
|
||||||
"/auth/api/admin/permission/rename",
|
f"/auth/api/admin/permission?permission_uuid={perm.uuid}&scope=test:renamed:withname&display_name=New%20Display%20Name",
|
||||||
json={
|
|
||||||
"old_id": "test:rename:withname",
|
|
||||||
"new_id": "test:renamed:withname",
|
|
||||||
"display_name": "New Display Name",
|
|
||||||
},
|
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -1456,11 +1440,11 @@ class TestAdminPermissions:
|
|||||||
):
|
):
|
||||||
"""Admin should be able to delete a permission."""
|
"""Admin should be able to delete a permission."""
|
||||||
# Create permission first
|
# Create permission first
|
||||||
perm = Permission(id="test:deleteable", display_name="Deleteable")
|
perm = Permission.create(scope="test:deleteable", display_name="Deleteable")
|
||||||
await test_db.create_permission(perm)
|
create_permission(perm)
|
||||||
|
|
||||||
response = await client.delete(
|
response = await client.delete(
|
||||||
"/auth/api/admin/permission?permission_id=test:deleteable",
|
f"/auth/api/admin/permission?permission_uuid={perm.uuid}",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
@@ -1468,17 +1452,93 @@ class TestAdminPermissions:
|
|||||||
assert data["status"] == "ok"
|
assert data["status"] == "ok"
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_delete_permission_auth_admin_fails(
|
async def test_delete_permission_auth_admin_last_one_fails(
|
||||||
self, client: httpx.AsyncClient, session_token: str
|
self, client: httpx.AsyncClient, session_token: str
|
||||||
):
|
):
|
||||||
"""Cannot delete the auth:admin permission."""
|
"""Cannot delete the only auth:admin permission (would lock out admin)."""
|
||||||
|
# Get the auth:admin permission
|
||||||
|
|
||||||
|
perms = list(db.data().permissions.values())
|
||||||
|
admin_perm = next(p for p in perms if p.scope == "auth:admin")
|
||||||
|
|
||||||
response = await client.delete(
|
response = await client.delete(
|
||||||
"/auth/api/admin/permission?permission_id=auth:admin",
|
f"/auth/api/admin/permission?permission_uuid={admin_perm.uuid}",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert "Cannot delete the master admin" in data["detail"]
|
assert "lock you out of admin access" in data["detail"]
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_delete_permission_auth_admin_with_another_succeeds(
|
||||||
|
self, client: httpx.AsyncClient, session_token: str, test_db: DB
|
||||||
|
):
|
||||||
|
"""Can delete an auth:admin permission if another accessible one exists."""
|
||||||
|
|
||||||
|
# Create a second auth:admin permission (no domain restriction)
|
||||||
|
perm2 = Permission.create(scope="auth:admin", display_name="Secondary Admin")
|
||||||
|
create_permission(perm2)
|
||||||
|
|
||||||
|
# Get the original auth:admin permission (the one created in setup)
|
||||||
|
|
||||||
|
perms = list(db.data().permissions.values())
|
||||||
|
admin_perms = [p for p in perms if p.scope == "auth:admin"]
|
||||||
|
# Delete the first one (not the one we just created)
|
||||||
|
original_admin_perm = next(p for p in admin_perms if p.uuid != perm2.uuid)
|
||||||
|
|
||||||
|
# Now we can delete the original one
|
||||||
|
response = await client.delete(
|
||||||
|
f"/auth/api/admin/permission?permission_uuid={original_admin_perm.uuid}",
|
||||||
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
data = response.json()
|
||||||
|
assert data["status"] == "ok"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_delete_permission_auth_admin_domain_mismatch_fails(
|
||||||
|
self, client: httpx.AsyncClient, session_token: str, test_db: DB
|
||||||
|
):
|
||||||
|
"""Cannot delete auth:admin if remaining one has mismatched domain."""
|
||||||
|
|
||||||
|
# Create a second auth:admin permission with a different domain
|
||||||
|
perm2 = Permission.create(
|
||||||
|
scope="auth:admin",
|
||||||
|
display_name="Other Domain Admin",
|
||||||
|
domain="other.example.com",
|
||||||
|
)
|
||||||
|
create_permission(perm2)
|
||||||
|
|
||||||
|
# Cannot delete the original one because the remaining one is not accessible
|
||||||
|
# Get the original auth:admin permission
|
||||||
|
|
||||||
|
perms = list(db.data().permissions.values())
|
||||||
|
admin_perms = [p for p in perms if p.scope == "auth:admin" and p.domain is None]
|
||||||
|
original_admin_perm = admin_perms[0] # The one without domain
|
||||||
|
|
||||||
|
response = await client.delete(
|
||||||
|
f"/auth/api/admin/permission?permission_uuid={original_admin_perm.uuid}",
|
||||||
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
data = response.json()
|
||||||
|
assert "lock you out of admin access" in data["detail"]
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_remove_auth_admin_from_own_org_fails(
|
||||||
|
self, client: httpx.AsyncClient, session_token: str, test_org
|
||||||
|
):
|
||||||
|
"""Cannot remove auth:admin permission from your own organization."""
|
||||||
|
admin_perm = next(
|
||||||
|
p for p in db.data().permissions.values() if p.scope == "auth:admin"
|
||||||
|
)
|
||||||
|
response = await client.delete(
|
||||||
|
f"/auth/api/admin/orgs/{test_org.uuid}/permission?permission_uuid={admin_perm.uuid}",
|
||||||
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
data = response.json()
|
||||||
|
assert "lock you out of admin access" in data["detail"]
|
||||||
|
|
||||||
|
|
||||||
# -------------------- Edge Cases for AuthException in Org-Admin Checks --------------------
|
# -------------------- Edge Cases for AuthException in Org-Admin Checks --------------------
|
||||||
@@ -1526,7 +1586,7 @@ class TestOrgAdminAuthExceptions:
|
|||||||
test_user,
|
test_user,
|
||||||
):
|
):
|
||||||
"""Regular user trying to update display name should get 403."""
|
"""Regular user trying to update display name should get 403."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/display-name",
|
f"/auth/api/admin/orgs/{test_org.uuid}/users/{test_user.uuid}/display-name",
|
||||||
json={"display_name": "New Name"},
|
json={"display_name": "New Name"},
|
||||||
headers={**auth_headers(regular_session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(regular_session_token), "Host": "localhost:4401"},
|
||||||
|
|||||||
+52
-53
@@ -10,11 +10,15 @@ These tests cover:
|
|||||||
- /auth/api/set-session - Set session from bearer token
|
- /auth/api/set-session - Set session from bearer token
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from paskia.authsession import EXPIRES
|
||||||
|
from paskia.db import create_session, delete_session
|
||||||
|
from paskia.db.operations import _create_token
|
||||||
|
from paskia.util.passphrase import generate
|
||||||
from tests.conftest import auth_headers
|
from tests.conftest import auth_headers
|
||||||
|
|
||||||
|
|
||||||
@@ -75,7 +79,9 @@ class TestValidateEndpoint:
|
|||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert data["valid"] is True
|
assert data["valid"] is True
|
||||||
assert "user_uuid" in data
|
assert "ctx" in data
|
||||||
|
assert "user" in data["ctx"]
|
||||||
|
assert "uuid" in data["ctx"]["user"]
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_validate_with_permission_check(
|
async def test_validate_with_permission_check(
|
||||||
@@ -242,9 +248,9 @@ class TestUserInfoEndpoint:
|
|||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert "user" in data
|
assert "ctx" in data
|
||||||
assert data["user"]["user_uuid"] == str(test_user.uuid)
|
assert data["ctx"]["user"]["uuid"] == str(test_user.uuid)
|
||||||
assert data["user"]["user_name"] == test_user.display_name
|
assert data["ctx"]["user"]["display_name"] == test_user.display_name
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_user_info_includes_credentials(
|
async def test_user_info_includes_credentials(
|
||||||
@@ -285,19 +291,20 @@ class TestUserInfoEndpoint:
|
|||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert "permissions" in data
|
assert "ctx" in data
|
||||||
|
assert "permissions" in data["ctx"]
|
||||||
|
|
||||||
|
|
||||||
class TestSetSessionEndpoint:
|
class TestSetSessionEndpoint:
|
||||||
"""Tests for POST /auth/api/set-session"""
|
"""Tests for POST /auth/api/set-session"""
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_set_session_without_bearer_returns_403(
|
async def test_set_session_without_bearer_returns_401(
|
||||||
self, client: httpx.AsyncClient
|
self, client: httpx.AsyncClient
|
||||||
):
|
):
|
||||||
"""Set session without bearer token should return 403."""
|
"""Set session without bearer token should return 401."""
|
||||||
response = await client.post("/auth/api/set-session")
|
response = await client.post("/auth/api/set-session")
|
||||||
assert response.status_code == 403
|
assert response.status_code == 401
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_set_session_with_valid_bearer_token(
|
async def test_set_session_with_valid_bearer_token(
|
||||||
@@ -313,7 +320,7 @@ class TestSetSessionEndpoint:
|
|||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert "user_uuid" in data
|
assert "user" in data
|
||||||
# Check that Set-Cookie header is present
|
# Check that Set-Cookie header is present
|
||||||
assert "set-cookie" in response.headers
|
assert "set-cookie" in response.headers
|
||||||
|
|
||||||
@@ -391,47 +398,43 @@ class TestForwardAuthHtmlResponse:
|
|||||||
assert data["auth"]["mode"] == "login"
|
assert data["auth"]["mode"] == "login"
|
||||||
|
|
||||||
|
|
||||||
class TestUserInfoWithResetToken:
|
class TestTokenInfoEndpoint:
|
||||||
"""Tests for user-info endpoint with reset tokens"""
|
"""Tests for token-info endpoint with reset tokens"""
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_user_info_with_invalid_reset_token(self, client: httpx.AsyncClient):
|
async def test_token_info_with_invalid_token(self, client: httpx.AsyncClient):
|
||||||
"""User info with invalid reset token format should return 401."""
|
"""Token info with invalid token format should return 400."""
|
||||||
# Invalid format - not a well-formed passphrase (wrong separator)
|
response = await client.get(
|
||||||
response = await client.post(
|
"/auth/api/token-info",
|
||||||
"/auth/api/user-info?reset=invalid-token-format",
|
headers={"Authorization": "Bearer invalid-token-format"},
|
||||||
)
|
)
|
||||||
# Invalid format raises ValueError which gets converted to 401 HTTPException
|
assert response.status_code == 400
|
||||||
assert response.status_code == 401
|
|
||||||
data = response.json()
|
|
||||||
assert "Invalid reset token" in data["detail"]
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_user_info_with_nonexistent_reset_token(
|
async def test_token_info_with_nonexistent_token(self, client: httpx.AsyncClient):
|
||||||
self, client: httpx.AsyncClient
|
"""Token info with well-formed but non-existent token should return 401."""
|
||||||
):
|
|
||||||
"""User info with well-formed but non-existent reset token should return 401."""
|
|
||||||
# We need a well-formed passphrase that doesn't exist in DB
|
|
||||||
from paskia.util.passphrase import generate
|
|
||||||
|
|
||||||
fake_token = generate() # Generates a well-formed token
|
fake_token = generate()
|
||||||
response = await client.post(
|
response = await client.get(
|
||||||
f"/auth/api/user-info?reset={fake_token}",
|
"/auth/api/token-info",
|
||||||
|
headers={"Authorization": f"Bearer {fake_token}"},
|
||||||
)
|
)
|
||||||
# Should return 401 for non-existent token
|
|
||||||
assert response.status_code == 401
|
assert response.status_code == 401
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_user_info_with_valid_reset_token(
|
async def test_token_info_with_valid_token(
|
||||||
self, client: httpx.AsyncClient, reset_token: str, test_user
|
self, client: httpx.AsyncClient, reset_token: str, test_user
|
||||||
):
|
):
|
||||||
"""User info with valid reset token should return minimal user info."""
|
"""Token info with valid reset token should return token type and display name."""
|
||||||
response = await client.post(
|
response = await client.get(
|
||||||
f"/auth/api/user-info?reset={reset_token}",
|
"/auth/api/token-info",
|
||||||
|
headers={"Authorization": f"Bearer {reset_token}"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert "user" in data
|
assert "token_type" in data
|
||||||
|
assert "display_name" in data
|
||||||
|
assert data["display_name"] == test_user.display_name
|
||||||
|
|
||||||
|
|
||||||
class TestSetSessionErrors:
|
class TestSetSessionErrors:
|
||||||
@@ -441,7 +444,7 @@ class TestSetSessionErrors:
|
|||||||
async def test_set_session_with_invalid_bearer_token(
|
async def test_set_session_with_invalid_bearer_token(
|
||||||
self, client: httpx.AsyncClient
|
self, client: httpx.AsyncClient
|
||||||
):
|
):
|
||||||
"""Set session with invalid (malformed) bearer token should return 400."""
|
"""Set session with invalid (malformed) bearer token should return 401."""
|
||||||
response = await client.post(
|
response = await client.post(
|
||||||
"/auth/api/set-session",
|
"/auth/api/set-session",
|
||||||
headers={
|
headers={
|
||||||
@@ -449,8 +452,8 @@ class TestSetSessionErrors:
|
|||||||
"Host": "localhost:4401",
|
"Host": "localhost:4401",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
# Invalid token format returns 400
|
# Invalid token returns 401 (session not found)
|
||||||
assert response.status_code == 400
|
assert response.status_code == 401
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_set_session_with_nonexistent_token(self, client: httpx.AsyncClient):
|
async def test_set_session_with_nonexistent_token(self, client: httpx.AsyncClient):
|
||||||
@@ -464,8 +467,8 @@ class TestSetSessionErrors:
|
|||||||
"Host": "localhost:4401",
|
"Host": "localhost:4401",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
# Non-existent session returns 400 (ValueError -> 400)
|
# Non-existent session returns 401 (session expired)
|
||||||
assert response.status_code == 400
|
assert response.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
class TestValidateSessionRefresh:
|
class TestValidateSessionRefresh:
|
||||||
@@ -498,10 +501,9 @@ class TestValidateSessionRefresh:
|
|||||||
self, client: httpx.AsyncClient, test_db
|
self, client: httpx.AsyncClient, test_db
|
||||||
):
|
):
|
||||||
"""Validate should handle session expiry during refresh attempt."""
|
"""Validate should handle session expiry during refresh attempt."""
|
||||||
from paskia.util.tokens import create_token
|
|
||||||
|
|
||||||
# Create a token but don't create a session for it
|
# Create a token but don't create a session for it
|
||||||
token = create_token()
|
token = _create_token()
|
||||||
response = await client.post(
|
response = await client.post(
|
||||||
"/auth/api/validate",
|
"/auth/api/validate",
|
||||||
headers={**auth_headers(token), "Host": "localhost:4401"},
|
headers={**auth_headers(token), "Host": "localhost:4401"},
|
||||||
@@ -518,25 +520,22 @@ class TestValidateSessionRefresh:
|
|||||||
test_credential,
|
test_credential,
|
||||||
):
|
):
|
||||||
"""Validate should return 401 if session disappears during refresh."""
|
"""Validate should return 401 if session disappears during refresh."""
|
||||||
from datetime import timedelta
|
|
||||||
|
|
||||||
from paskia.util.tokens import create_token, session_key
|
# Create a session with an old expiry time to trigger refresh
|
||||||
|
token = _create_token()
|
||||||
# Create a session with an old renewed time to trigger refresh
|
old_expiry = datetime.now(timezone.utc) + EXPIRES - timedelta(minutes=10)
|
||||||
token = create_token()
|
create_session(
|
||||||
old_time = datetime.now(timezone.utc) - timedelta(minutes=10)
|
|
||||||
await test_db.create_session(
|
|
||||||
user_uuid=test_user.uuid,
|
user_uuid=test_user.uuid,
|
||||||
credential_uuid=test_credential.uuid,
|
credential_uuid=test_credential.uuid,
|
||||||
key=session_key(token),
|
key=token,
|
||||||
host="localhost:4401",
|
host="localhost:4401",
|
||||||
ip="127.0.0.1",
|
ip="127.0.0.1",
|
||||||
user_agent="pytest",
|
user_agent="pytest",
|
||||||
renewed=old_time,
|
expiry=old_expiry,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Delete the session right before validate tries to refresh
|
# Delete the session right before validate tries to refresh
|
||||||
await test_db.delete_session(session_key(token))
|
delete_session(token)
|
||||||
|
|
||||||
response = await client.post(
|
response = await client.post(
|
||||||
"/auth/api/validate",
|
"/auth/api/validate",
|
||||||
|
|||||||
+6
-6
@@ -16,12 +16,12 @@ from tests.conftest import auth_headers
|
|||||||
|
|
||||||
|
|
||||||
class TestUserDisplayName:
|
class TestUserDisplayName:
|
||||||
"""Tests for PUT /auth/api/user/display-name"""
|
"""Tests for PATCH /auth/api/user/display-name"""
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_update_display_name_requires_auth(self, client: httpx.AsyncClient):
|
async def test_update_display_name_requires_auth(self, client: httpx.AsyncClient):
|
||||||
"""Update display name without auth should return 401."""
|
"""Update display name without auth should return 401."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
"/auth/api/user/display-name",
|
"/auth/api/user/display-name",
|
||||||
json={"display_name": "New Name"},
|
json={"display_name": "New Name"},
|
||||||
)
|
)
|
||||||
@@ -32,7 +32,7 @@ class TestUserDisplayName:
|
|||||||
self, client: httpx.AsyncClient, session_token: str
|
self, client: httpx.AsyncClient, session_token: str
|
||||||
):
|
):
|
||||||
"""User should be able to update their display name."""
|
"""User should be able to update their display name."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
"/auth/api/user/display-name",
|
"/auth/api/user/display-name",
|
||||||
json={"display_name": "Updated Name"},
|
json={"display_name": "Updated Name"},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -46,7 +46,7 @@ class TestUserDisplayName:
|
|||||||
self, client: httpx.AsyncClient, session_token: str
|
self, client: httpx.AsyncClient, session_token: str
|
||||||
):
|
):
|
||||||
"""Empty display name should fail."""
|
"""Empty display name should fail."""
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
"/auth/api/user/display-name",
|
"/auth/api/user/display-name",
|
||||||
json={"display_name": ""},
|
json={"display_name": ""},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -59,7 +59,7 @@ class TestUserDisplayName:
|
|||||||
):
|
):
|
||||||
"""Display name over 64 chars should fail."""
|
"""Display name over 64 chars should fail."""
|
||||||
long_name = "x" * 100
|
long_name = "x" * 100
|
||||||
response = await client.put(
|
response = await client.patch(
|
||||||
"/auth/api/user/display-name",
|
"/auth/api/user/display-name",
|
||||||
json={"display_name": long_name},
|
json={"display_name": long_name},
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
@@ -117,7 +117,7 @@ class TestUserSessionManagement:
|
|||||||
"/auth/api/user/session/invalid-session-id",
|
"/auth/api/user/session/invalid-session-id",
|
||||||
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
headers={**auth_headers(session_token), "Host": "localhost:4401"},
|
||||||
)
|
)
|
||||||
assert response.status_code == 400
|
assert response.status_code == 404 # Not found (no format validation)
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_delete_nonexistent_session_returns_404(
|
async def test_delete_nonexistent_session_returns_404(
|
||||||
|
|||||||
Reference in New Issue
Block a user