Build phase 1 and the read-only repository browser
lore-forge now runs beside an unmodified loreserver as its token issuer, user directory and repository registry, with a server-rendered UI in the desktop client's pixel style. Accounts and sign-in: first-run setup, password sign-in with rate limiting, signup modes and invite links, GitHub, Discord and Google sign-in by explicit linking (tested against a fake provider), sessions and CLI logins with revocation, API tokens, and service accounts. Issuer: device code, refresh with rotation and reuse detection, token exchange to repository-scoped tokens, API-token login, the client credentials grant for service accounts, revocation, and signing key rotation from the admin page or the rotate-signing-key command. Access: user and organisation namespaces, members, teams, role presets with extra actions, per-repository grants, and the admin pages. Repository browser: FILES, GRAPH and TREE tabs and a revision page with diffs, read from loreserver as the viewer with a one-minute read-only token per page view. File diffs are computed here because Lore's ContentDiff is unimplemented. scripts/e2e-lore.sh checks all of this against the pinned Lore v0.14.0 release, including a branch and a merge. The design documents record what was verified in Lore's source and what is still assumed.
This commit is contained in:
parent
ea9cfc9f6a
commit
ab8555c65f
|
|
@ -1,6 +1,7 @@
|
||||||
# Accounts and sign-in
|
# Accounts and sign-in
|
||||||
|
|
||||||
Status: design, nothing built. Last updated 2026-11-25.
|
Status: built. Provider sign-in is tested against an in-process fake provider
|
||||||
|
only; no real GitHub, Discord or Google app has been used yet. Last updated 2026-11-25.
|
||||||
|
|
||||||
The account system follows **piki**, the owner's Go project (`../piki`). Piki's
|
The account system follows **piki**, the owner's Go project (`../piki`). Piki's
|
||||||
`agents/data-auth-services.md` maps its auth code; the schema is in
|
`agents/data-auth-services.md` maps its auth code; the schema is in
|
||||||
|
|
@ -21,18 +22,26 @@ As in piki:
|
||||||
|
|
||||||
- **First run:** `/setup` creates the instance owner with a username and password. It is only
|
- **First run:** `/setup` creates the instance owner with a username and password. It is only
|
||||||
available while no user exists.
|
available while no user exists.
|
||||||
- **Signup toggle:** the owner turns public signup on or off.
|
- **Signup mode:** an owner setting with three values. `closed` (the default): admins create
|
||||||
- **Invite keys:** the owner can require an invite key for signup. A key has a name, a maximum
|
accounts. `invite`: only invite links work. `open`: anyone who can reach the site signs up at
|
||||||
number of uses and an active flag, and records who used it. Signup with a key uses a path of
|
`/signup`.
|
||||||
the form `/signup/<key>`.
|
- **Invite keys:** admins create keys with a name, a maximum number of uses and an active
|
||||||
|
flag; each use is recorded. Signup with a key uses `/signup/<key>`. Invite links work in the
|
||||||
|
`invite` and `open` modes. The use is counted in the same transaction that creates the
|
||||||
|
account, so a key cannot be used more often than allowed by racing requests.
|
||||||
|
- **Admin-created accounts:** admins create an account with a password from `/admin`, or with
|
||||||
|
`lore-forge create-user` on the server.
|
||||||
|
|
||||||
## Signing in
|
## Signing in
|
||||||
|
|
||||||
Three methods, all ending in the same kind of session:
|
Two methods, both ending in the same kind of session:
|
||||||
|
|
||||||
1. **Username and password.**
|
1. **Username and password.**
|
||||||
2. **A linked provider:** GitHub, Discord or Google.
|
2. **A linked provider:** GitHub, Discord or Google.
|
||||||
3. **A passkey** (optional, registered from the profile).
|
Passkeys are not offered; see below.
|
||||||
|
|
||||||
|
Password sign-in is rate limited in memory per username: ten failures within 15 minutes block
|
||||||
|
further attempts for that username until the window passes. The limit resets on restart.
|
||||||
|
|
||||||
### Provider sign-in
|
### Provider sign-in
|
||||||
|
|
||||||
|
|
@ -57,6 +66,17 @@ Protocol notes:
|
||||||
- GitHub and Discord are plain OAuth 2.0 authorization-code flows followed by an identity
|
- GitHub and Discord are plain OAuth 2.0 authorization-code flows followed by an identity
|
||||||
request.
|
request.
|
||||||
- Google is OpenID Connect with PKCE and a per-flow nonce; identity comes from the ID token.
|
- Google is OpenID Connect with PKCE and a per-flow nonce; identity comes from the ID token.
|
||||||
|
The ID token's signature is not checked: it arrives directly from Google's token endpoint
|
||||||
|
over TLS, which OpenID Connect allows. Its issuer, audience, expiry and nonce are checked.
|
||||||
|
- Discord's flow uses no PKCE, as in piki.
|
||||||
|
- A flow expires after 10 minutes and is consumed with a single conditional update, so a
|
||||||
|
state value works once.
|
||||||
|
- Unlinking is refused when the provider is the account's last sign-in method and it has no
|
||||||
|
password.
|
||||||
|
|
||||||
|
**Assumed, not verified:** the providers' endpoints and response shapes are taken from piki
|
||||||
|
and the providers' documentation. Tests run the whole flow against a fake provider served
|
||||||
|
in-process; the first real sign-in will confirm them.
|
||||||
|
|
||||||
### Provider configuration
|
### Provider configuration
|
||||||
|
|
||||||
|
|
@ -66,14 +86,15 @@ As in piki:
|
||||||
- The settings page shows the exact callback URL to register with the provider.
|
- The settings page shows the exact callback URL to register with the provider.
|
||||||
- Secrets are stored encrypted (AES-GCM) with a 32-byte key supplied through the environment.
|
- Secrets are stored encrypted (AES-GCM) with a 32-byte key supplied through the environment.
|
||||||
The same key protects lore-forge's token signing keys (see [token-issuer.md](token-issuer.md)).
|
The same key protects lore-forge's token signing keys (see [token-issuer.md](token-issuer.md)).
|
||||||
- The owner sets the instance's canonical public URL. Callback URLs, passkey configuration and
|
- The owner sets the instance's canonical public URL. Callback URLs and
|
||||||
the issuer URL derive from it, never from request headers.
|
the issuer URL derive from it, never from request headers.
|
||||||
|
|
||||||
### Passkeys
|
### Passkeys
|
||||||
|
|
||||||
As in piki: optional, registered from the profile while signed in, usernameless sign-in with
|
**Dropped for now (owner, 2026-11-25).** Passwords and provider sign-in cover a self-hosted
|
||||||
user verification, only the public key stored. They are an additional sign-in method, not a
|
studio, and passkeys would bring WebAuthn code and the UI's first script. If they return, the
|
||||||
required second step.
|
design is piki's: optional, registered from the settings while signed in, usernameless sign-in
|
||||||
|
with user verification, only the public key stored.
|
||||||
|
|
||||||
## Sessions
|
## Sessions
|
||||||
|
|
||||||
|
|
@ -83,8 +104,10 @@ As in piki:
|
||||||
- Cookies are `HttpOnly`, `Secure` in production and `SameSite=Lax`. Unsafe methods require a
|
- Cookies are `HttpOnly`, `Secure` in production and `SameSite=Lax`. Unsafe methods require a
|
||||||
CSRF token.
|
CSRF token.
|
||||||
- "Stay signed in" keeps a session for 30 days after last use, up to 90 days in total.
|
- "Stay signed in" keeps a session for 30 days after last use, up to 90 days in total.
|
||||||
- Each session records how it was created (password, provider, passkey) and its user agent.
|
- Each session records how it was created (password or provider) and its user agent.
|
||||||
- Users see their active sessions in their profile and can revoke one or all others.
|
- Users see their active sessions in their settings and can revoke one or all others.
|
||||||
|
- Changing the password ends the account's other sessions. Disabling an account ends all its
|
||||||
|
sessions and CLI logins.
|
||||||
|
|
||||||
### What lore-forge adds
|
### What lore-forge adds
|
||||||
|
|
||||||
|
|
@ -117,25 +140,40 @@ Repository and organisation permissions are in
|
||||||
|
|
||||||
## API tokens
|
## API tokens
|
||||||
|
|
||||||
As in piki, a user can create named API tokens, stored hashed, with scopes and optional
|
As in piki, a user can create named API tokens, stored as SHA-256 hashes, with scopes and an
|
||||||
expiry. In lore-forge they serve two purposes:
|
optional expiry. The secret starts with `lf_` and is shown once. Two scopes:
|
||||||
|
|
||||||
- authenticating to lore-forge's JSON API;
|
- `api`: lore-forge's JSON API under `/api/v1` (`Authorization: Bearer`);
|
||||||
- logging the Lore CLI in without a browser, for CI. Lore defines API-key login as a token
|
- `lore`: logging the Lore CLI in without a browser, for CI. Lore sends it as a token exchange
|
||||||
exchange with the subject token type `urn:lore:params:oauth:token-type:api-key`.
|
with the subject token type `api-key` or `urn:lore:params:oauth:token-type:api-key`.
|
||||||
|
|
||||||
|
A CLI login started from a token records the token; revoking the token ends those logins.
|
||||||
|
Verified with `lore auth login --token-type api-key` by `scripts/e2e-lore.sh`.
|
||||||
|
|
||||||
|
## Service accounts
|
||||||
|
|
||||||
|
For CI and bots that should not act as a person. A service account belongs to a user or an
|
||||||
|
organisation namespace and is a `users` row with `kind = 'service'`. Its username is
|
||||||
|
`<owner>.<name>`; person usernames cannot contain dots, so the two never collide. It has no
|
||||||
|
password and cannot sign in to the web UI. It holds grants like any user.
|
||||||
|
|
||||||
|
Its secrets are API tokens with the `lore` scope. It logs in with the client credentials
|
||||||
|
grant: client ID is its username, client secret is a token. The login lasts an hour (or until
|
||||||
|
the token expires) and gets no refresh token. Owners of the namespace manage it under
|
||||||
|
`/settings/service-accounts` or `/orgs/<org>/service-accounts`. Verified with
|
||||||
|
`lore auth login --client-id` by `scripts/e2e-lore.sh`.
|
||||||
|
|
||||||
## Identity recorded by Lore
|
## Identity recorded by Lore
|
||||||
|
|
||||||
Lore writes the caller's identity into revision history permanently.
|
Lore writes the caller's identity into revision history permanently.
|
||||||
|
|
||||||
**Recommended, not yet confirmed:** put a stable internal user ID in the token, not the
|
**Decided (owner, 2026-11-25):** the token carries a stable internal user ID, not the
|
||||||
username, and have lore-forge answer Lore's name lookup service. Usernames can then change
|
username, and lore-forge answers Lore's name lookup service. Usernames can then change
|
||||||
without rewriting history, and the CLI still shows names. The alternative is to use the
|
without rewriting history, and the CLI still shows names.
|
||||||
username directly, which is simpler but makes usernames effectively permanent.
|
|
||||||
|
|
||||||
## Open questions
|
## Open questions
|
||||||
|
|
||||||
- Whether an invite may be redeemed directly with a provider, creating an account that never
|
- Whether an invite may be redeemed directly with a provider, creating an account that never
|
||||||
has a password. Piki does not allow this; the design currently matches piki.
|
has a password. Piki does not allow this; the design currently matches piki.
|
||||||
- Whether usernames can be changed, which depends on the identity decision above and on
|
- Whether usernames can be changed. The identity decision above allows it as far as Lore
|
||||||
namespace renames (see [namespaces-and-access.md](namespaces-and-access.md)).
|
history is concerned; it still depends on namespace renames (see [namespaces-and-access.md](namespaces-and-access.md)).
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
# Architecture overview
|
# Architecture overview
|
||||||
|
|
||||||
Status: design, nothing built. Last updated 2026-11-25.
|
Status: phase 1 walking skeleton built and verified against a real `loreserver`. Last updated
|
||||||
|
2026-11-25.
|
||||||
|
|
||||||
## What lore-forge is
|
## What lore-forge is
|
||||||
|
|
||||||
|
|
@ -68,11 +69,14 @@ repository creates and deletes, and user name lookups.
|
||||||
|
|
||||||
One cargo workspace, built as a modular monolith. Crate names are provisional.
|
One cargo workspace, built as a modular monolith. Crate names are provisional.
|
||||||
|
|
||||||
|
Built so far: `forge-store`, `forge-access`, `forge-id`, `forge-lore`, `forge-web` and the
|
||||||
|
`lore-forge` binary. `forge-core` and `forge-events` come with phases 2 and 3.
|
||||||
|
|
||||||
| Crate | Responsibility | Design document |
|
| Crate | Responsibility | Design document |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `forge-id` | Accounts, sessions, provider linking, the token issuer | [accounts-and-sign-in.md](accounts-and-sign-in.md), [token-issuer.md](token-issuer.md) |
|
| `forge-id` | Accounts, sessions, provider linking, the token issuer | [accounts-and-sign-in.md](accounts-and-sign-in.md), [token-issuer.md](token-issuer.md) |
|
||||||
| `forge-access` | Namespaces, orgs, teams, grants, role presets, the Lore registry service | [namespaces-and-access.md](namespaces-and-access.md) |
|
| `forge-access` | Namespaces, orgs, teams, grants, role presets, the Lore registry service | [namespaces-and-access.md](namespaces-and-access.md) |
|
||||||
| `forge-lore` | Typed client for `loreserver` (gRPC and HTTP), minting on-behalf tokens. The only crate that depends on Lore's protocol definitions | [lore-integration.md](lore-integration.md) |
|
| `forge-lore` | Lore's protocols: serves `UserService` and `RepositoryRegistryService`, generates the `loreserver` config; later a typed client for `loreserver`. The only crate that depends on Lore's protocol definitions | [lore-integration.md](lore-integration.md) |
|
||||||
| `forge-core` | Change requests, reviews, comments, landing | [forge-features.md](forge-features.md) |
|
| `forge-core` | Change requests, reviews, comments, landing | [forge-features.md](forge-features.md) |
|
||||||
| `forge-events` | Lore notification subscriber: activity feed, webhooks | [forge-features.md](forge-features.md) |
|
| `forge-events` | Lore notification subscriber: activity feed, webhooks | [forge-features.md](forge-features.md) |
|
||||||
| `forge-web` | HTTP server, templates, JSON API | [web-ui.md](web-ui.md) |
|
| `forge-web` | HTTP server, templates, JSON API | [web-ui.md](web-ui.md) |
|
||||||
|
|
@ -81,6 +85,14 @@ One cargo workspace, built as a modular monolith. Crate names are provisional.
|
||||||
There is no separate worker process. Landing a change is a single call to `loreserver`, so
|
There is no separate worker process. Landing a change is a single call to `loreserver`, so
|
||||||
background work runs as tasks inside the one binary.
|
background work runs as tasks inside the one binary.
|
||||||
|
|
||||||
|
### Desktop client
|
||||||
|
|
||||||
|
A separate tree, `desktop/`, holds the client side: `forge-service` (a per-user Rust service
|
||||||
|
that drives Lore through liblore and runs policies such as autosync), `forge-desktop` (a C++
|
||||||
|
tray application, Dear ImGui on vendored UHDK) and later `forge-tui`. The frontends talk to
|
||||||
|
the service over a local socket. It has its own Cargo workspace and `zig build`, so the server
|
||||||
|
never needs Zig. See [desktop-client.md](desktop-client.md).
|
||||||
|
|
||||||
## Decisions
|
## Decisions
|
||||||
|
|
||||||
| Topic | Decision | Source |
|
| Topic | Decision | Source |
|
||||||
|
|
@ -96,21 +108,55 @@ background work runs as tasks inside the one binary.
|
||||||
| Landing | Per-branch choice between review-gated and direct push | Owner |
|
| Landing | Per-branch choice between review-gated and direct push | Owner |
|
||||||
| Permission source | Grants managed in lore-forge, optional mapping from GitHub teams and Discord roles later | Recommended; owner had no preference |
|
| Permission source | Grants managed in lore-forge, optional mapping from GitHub teams and Discord roles later | Recommended; owner had no preference |
|
||||||
| Deployment | `loreserver` as a separate process; lore-forge generates its auth config | Recommended; owner had no preference |
|
| Deployment | `loreserver` as a separate process; lore-forge generates its auth config | Recommended; owner had no preference |
|
||||||
|
| Lore binaries | The official release pinned with SHA-256 in `lore.lock`, fetched into `.lore/`; `scripts/start.sh` runs a whole deployment from `run/` | Owner, 2026-11-25 |
|
||||||
|
| Desktop client | A per-user client service (Rust, liblore) with a C++ Dear ImGui tray GUI (pixel-art look) on vendored UHDK and a later Rust TUI as frontends, in `desktop/` | Owner, 2026-11-25; details in [desktop-client.md](desktop-client.md) |
|
||||||
| Audience | A self-hosted instance for one studio or community | Assumed; owner had no preference |
|
| Audience | A self-hosted instance for one studio or community | Assumed; owner had no preference |
|
||||||
| Per-repo tokens | Use Lore's per-repository token mode from the start | Recommended, not explicitly confirmed |
|
| Per-repo tokens | Use Lore's per-repository token mode from the start | Recommended, not explicitly confirmed |
|
||||||
| Identity in Lore history | A stable internal user ID, with names resolved through lore-forge | Recommended, not explicitly confirmed |
|
| Identity in Lore history | A stable internal user ID, with names resolved through lore-forge | Owner, 2026-11-25 |
|
||||||
|
| Database library | `sqlx` with its built-in migrations | Owner, 2026-11-25 |
|
||||||
|
| Templates and interactivity | maud and vendored htmx | Owner, 2026-11-25 |
|
||||||
|
| Phase 1 order | Walking skeleton first: store, keys, issuer grants and registry, tested against a real `loreserver`; full account UI after | Owner, 2026-11-25 |
|
||||||
| Who may create orgs | An owner setting, defaulting to instance admins only | Defaulted, not confirmed |
|
| Who may create orgs | An owner setting, defaulting to instance admins only | Defaulted, not confirmed |
|
||||||
|
| Web UI look | The desktop client's pixel style: VGA font, Sweetie 16 palette | Owner, 2026-11-25 |
|
||||||
|
| Passkeys | Dropped for now; possibly later | Owner, 2026-11-25 |
|
||||||
|
| Service accounts | `users` rows of kind `service`, named `<owner>.<name>`, logging in with client credentials | Implementation choice |
|
||||||
|
| Browser reads | As the viewer, with a one-minute read-only repository token per page view; file diffs computed in lore-forge because Lore's `ContentDiff` is unimplemented | Implementation choice |
|
||||||
|
| Browser layout | FILES, GRAPH and TREE, as in the desktop explorer | Owner, 2026-11-25 |
|
||||||
|
| Provider sign-in testing | Built and tested against an in-process fake; the owner registers real apps later | Owner, 2026-11-25 |
|
||||||
|
| Token lifetimes | Login token 1 h, scoped 5 min, CLI login 30 d idle / 90 d max | Defaulted, not confirmed |
|
||||||
|
| Ports | Pages, issuer and Lore's gRPC directory share one port, routed by content type | Implementation choice |
|
||||||
|
| Revocation speed | Token exchange checks the CLI login is live, so revoking a login ends repository access within five minutes | Implementation choice |
|
||||||
|
|
||||||
## Phases
|
## Phases
|
||||||
|
|
||||||
1. **Identity.** `lore auth login` works end to end: accounts, provider sign-in, the issuer,
|
1. **Identity.** `lore auth login` works end to end: accounts, provider sign-in, the issuer,
|
||||||
namespaces, grants, per-repository tokens. Everything else depends on this.
|
namespaces, grants, per-repository tokens. Everything else depends on this.
|
||||||
|
- **Done (walking skeleton):** store and migrations, ES256 keys, discovery, JWKS, device
|
||||||
|
grant, refresh with rotation, token exchange, revocation, the registry and user directory
|
||||||
|
over gRPC, setup, password sign-in and device approval pages. Verified by
|
||||||
|
`scripts/e2e-lore.sh` against the Lore v0.14.0 release. `scripts/start.sh` starts a
|
||||||
|
deployment from this repository alone.
|
||||||
|
- **Done (accounts, milestone A):** signup modes and invite keys; GitHub, Discord and Google
|
||||||
|
sign-in and linking (tested against a fake provider); session and CLI-login lists;
|
||||||
|
organisation, team, member and grant pages; service accounts with the client credentials
|
||||||
|
grant; API tokens, API-key login and a first JSON API; key rotation from the UI and the
|
||||||
|
`rotate-signing-key` command; sign-in rate limiting; the admin pages; the pixel restyle.
|
||||||
|
API-key and client credentials logins are in the e2e test.
|
||||||
|
- **Remaining:** a first sign-in against each real provider. Passkeys are dropped for now.
|
||||||
2. **Read-only forge.** Repository list, file browser, history, diffs, locks, activity feed.
|
2. **Read-only forge.** Repository list, file browser, history, diffs, locks, activity feed.
|
||||||
|
- **Done (browser, milestone B):** FILES, GRAPH and TREE tabs and a revision page with
|
||||||
|
diffs, read from `loreserver` as the viewer. Verified by unit tests against an in-process
|
||||||
|
fake and by `scripts/e2e-lore.sh` against the Lore v0.14.0 release, including a branch and
|
||||||
|
a merge.
|
||||||
|
- **Remaining:** history paging, downloads, locks, activity feed.
|
||||||
3. **Collaboration.** Branch-based change requests, reviews, comments, gated landing.
|
3. **Collaboration.** Branch-based change requests, reviews, comments, gated landing.
|
||||||
4. **Integrations.** Webhooks, Discord notifications, CI status checks, API tokens for CI.
|
4. **Integrations.** Webhooks, Discord notifications, CI status checks, API tokens for CI.
|
||||||
5. **Game-development specifics.** Asset previews (textures, `.uasset` thumbnails), lock
|
5. **Game-development specifics.** Asset previews (textures, `.uasset` thumbnails), lock
|
||||||
management.
|
management.
|
||||||
|
|
||||||
|
The desktop client has its own milestones, in [desktop-client.md](desktop-client.md). Milestone
|
||||||
|
1, the GUI and tray shell over a stub service, is done.
|
||||||
|
|
||||||
## Things to keep in mind
|
## Things to keep in mind
|
||||||
|
|
||||||
- **Epic plans its own web client.** Lore's roadmap lists an open-source web client with code
|
- **Epic plans its own web client.** Lore's roadmap lists an open-source web client with code
|
||||||
|
|
|
||||||
|
|
@ -1,24 +1,42 @@
|
||||||
# Forge features
|
# Forge features
|
||||||
|
|
||||||
Status: design, nothing built. Last updated 2026-11-25.
|
Status: the repository browser (phase 2) is built; locks and the rest are design only. Last
|
||||||
|
updated 2026-11-25.
|
||||||
|
|
||||||
These are phases 2 to 5 and are designed in less detail than identity. Each section says what
|
These are phases 2 to 5 and are designed in less detail than identity. Each section says what
|
||||||
Lore provides for it; see [lore-integration.md](lore-integration.md) for what was verified.
|
Lore provides for it; see [lore-integration.md](lore-integration.md) for what was verified.
|
||||||
|
|
||||||
## Repository browser (phase 2)
|
## Repository browser (phase 2)
|
||||||
|
|
||||||
|
Built, with the desktop explorer's three tabs (`crates/forge-web/src/pages/browse.rs`):
|
||||||
|
|
||||||
- **Repository list** per owner, and a dashboard of the repositories a user can reach.
|
- **Repository list** per owner, and a dashboard of the repositories a user can reach.
|
||||||
- **File browser:** directory listings and file views at any branch or revision.
|
- **FILES:** directory listings at a branch tip or any revision, each entry with the revision
|
||||||
- **History:** revisions on a branch, with author names resolved by lore-forge.
|
that last changed it; file views with line numbers. Text up to 512 KiB is shown; binary
|
||||||
- **Diffs:** between two revisions, and per file.
|
files are named as such.
|
||||||
- **Downloads** through presigned URLs.
|
- **GRAPH:** the revision DAG across branches (the newest 50 revisions of up to 12 branches),
|
||||||
|
drawn with the desktop's lane layout as one SVG per row. Branch heads are tagged; merges are
|
||||||
|
hollow. Revisions are ordered so a child always precedes its parents, newest first.
|
||||||
|
- **TREE:** branches, the open branch's newest 50 revisions, and the open revision's changes.
|
||||||
|
What is open is in the URL, so it needs no script.
|
||||||
|
- **One revision:** message, author, parents, the changed files, and unified diffs of up to
|
||||||
|
30 text files of up to 256 KiB each.
|
||||||
|
|
||||||
Backed by Lore's read-only `ThinClientService` (`RevisionTree`, `RevisionInfo`,
|
Not built yet: paging further back than the newest revisions, diffs between two arbitrary
|
||||||
`RevisionDiff`, `ContentDiff`) and its HTTP content routes. A deployment can run a second,
|
revisions, downloads, and entries inside linked repositories (shown, not opened).
|
||||||
read-only `loreserver` that mounts only that service, to keep browsing load off the main
|
|
||||||
server.
|
|
||||||
|
|
||||||
All reads are made as the browsing user; see [web-ui.md](web-ui.md).
|
**How it reads Lore.** Each page view gets a token from `Issuer::browse_token`: scoped to the
|
||||||
|
repository, carrying only `read`, valid one minute, refused if the viewer cannot read. With
|
||||||
|
it, lore-forge calls `loreserver`'s `RepositoryService.RepositoryGet` (default branch),
|
||||||
|
`RevisionService.BranchList` and `RevisionList`, `ThinClientService.RevisionInfo`,
|
||||||
|
`RevisionTree` and `RevisionDiff`, and fetches file content from loreserver's HTTP endpoint.
|
||||||
|
`ContentDiff` is unimplemented in Lore, so lore-forge diffs file content itself (`similar`).
|
||||||
|
`RevisionList` gives no messages or parents, so each listed revision costs one `RevisionInfo`
|
||||||
|
call, 16 at a time. See [lore-integration.md](lore-integration.md) for what was verified.
|
||||||
|
|
||||||
|
The endpoints are set with `LORE_FORGE_LORE_GRPC_URL` (default `http://127.0.0.1:41337`) and
|
||||||
|
`LORE_FORGE_LORE_HTTP_URL` (default `http://127.0.0.1:41339`). A deployment can point them at
|
||||||
|
a second, read-only `loreserver` to keep browsing load off the main server; that is untested.
|
||||||
|
|
||||||
## Locks (phase 2, extended in phase 5)
|
## Locks (phase 2, extended in phase 5)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,10 @@
|
||||||
# Lore integration
|
# Lore integration
|
||||||
|
|
||||||
Status: design, nothing built. Last updated 2026-11-25.
|
Status: phase 1 integration verified end to end. Last updated 2026-11-25.
|
||||||
|
|
||||||
Facts here were checked against Lore's `main` at commit `6b12f00` (2026-11-25), workspace
|
Facts here were checked against Lore's `main` at commit `6b12f00` (2026-11-25), workspace
|
||||||
version `0.14.1-nightly`. Lore is pre-1.0, so re-check before relying on them.
|
version `0.14.1-nightly`, and the release-specific facts against the v0.14.0 release, which
|
||||||
|
`lore.lock` pins. Lore is pre-1.0, so re-check before relying on them.
|
||||||
|
|
||||||
## Minimum Lore version
|
## Minimum Lore version
|
||||||
|
|
||||||
|
|
@ -78,7 +79,7 @@ cannot. lore-forge must be up first.
|
||||||
|
|
||||||
| Need | Lore surface | Verified |
|
| Need | Lore surface | Verified |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Browse trees, history, diffs | `lore.thin_client.v1.ThinClientService`: `RevisionTree`, `RevisionInfo`, `RevisionDiff`, `ContentDiff` | Proto read |
|
| Browse trees, history, diffs | `lore.thin_client.v1.ThinClientService`: `RevisionTree`, `RevisionInfo`, `RevisionDiff`; `RevisionService.BranchList`, `RevisionList`; `RepositoryService.RepositoryGet`; HTTP content | Verified end to end; see "Reading repositories" |
|
||||||
| Download file content | HTTP `/v1/repository/{id}/content/{address}`, plus presigned URLs | Routes read |
|
| Download file content | HTTP `/v1/repository/{id}/content/{address}`, plus presigned URLs | Routes read |
|
||||||
| Activity, webhooks, CI triggers | `NotificationService.Subscribe`. Events: branch created, pushed, deleted; resource locked, unlocked; obliterate | Proto read; `[notification] mode = "local"` is the default |
|
| Activity, webhooks, CI triggers | `NotificationService.Subscribe`. Events: branch created, pushed, deleted; resource locked, unlocked; obliterate | Proto read; `[notification] mode = "local"` is the default |
|
||||||
| Locks | `LockService`: `Lock`, `Query`, `Status`, `Unlock`, `AdminLock` | Proto read |
|
| Locks | `LockService`: `Lock`, `Query`, `Status`, `Unlock`, `AdminLock` | Proto read |
|
||||||
|
|
@ -102,6 +103,16 @@ token permissions instead (see [forge-features.md](forge-features.md)).
|
||||||
|
|
||||||
Both are defined in `lore-proto/proto/lore/user/v1/user.proto` and reached through `user_url`.
|
Both are defined in `lore-proto/proto/lore/user/v1/user.proto` and reached through `user_url`.
|
||||||
|
|
||||||
|
Verified in `docs/reference/lore-server-config.md`, `lore-server/src/authnz/auth.rs` and
|
||||||
|
`lore-transport/src/auth/ucs_auth.rs`:
|
||||||
|
|
||||||
|
- Both services are served at the **same** `user_url`.
|
||||||
|
- They are **gRPC**. `loreserver` dials `user_url` with tonic; accepted schemes are
|
||||||
|
`ucs-auth`, `https` and `http`, with TLS used for `https`. So lore-forge must serve gRPC
|
||||||
|
(HTTP/2) as well as its web pages, and a reverse proxy in front of it must pass gRPC through.
|
||||||
|
- **Lore clients call `UserService` at `user_url` too**, not only `loreserver`, so it must be
|
||||||
|
reachable from wherever the CLI runs. Without `user_url`, clients show raw user IDs as names.
|
||||||
|
|
||||||
### RepositoryRegistryService
|
### RepositoryRegistryService
|
||||||
|
|
||||||
- **`RepositoryRegister(id, name)`** — `loreserver` calls this before storing a new repository,
|
- **`RepositoryRegister(id, name)`** — `loreserver` calls this before storing a new repository,
|
||||||
|
|
@ -153,16 +164,96 @@ Both are defined in `lore-proto/proto/lore/user/v1/user.proto` and reached throu
|
||||||
- **Forks.** Lore's roadmap lists forks as "later, exploring", so change requests are
|
- **Forks.** Lore's roadmap lists forks as "later, exploring", so change requests are
|
||||||
branch-based.
|
branch-based.
|
||||||
|
|
||||||
|
## Verified end to end
|
||||||
|
|
||||||
|
`scripts/e2e-lore.sh` runs an unmodified `loreserver` and `lore` CLI against lore-forge, using
|
||||||
|
the configuration `lore-forge loreserver-config` generates. By default it uses the official
|
||||||
|
release pinned in `lore.lock`. As of 2026-11-25 it passes against the **v0.14.0 release**. An
|
||||||
|
earlier version of the test, which read claims with `--with-claims`, passed against a source
|
||||||
|
build of `6b12f00`. Whether `main` still has `--with-access-token` is unchecked. Together these
|
||||||
|
verify:
|
||||||
|
|
||||||
|
- `loreserver` starts against lore-forge's discovery document and ES256 JWKS.
|
||||||
|
- `lore auth login` completes the device grant through lore-forge's approval page, over plain
|
||||||
|
http on localhost (the client allows loopback http).
|
||||||
|
- `lore repository create`, `commit`, `push` and `clone` work with exchanged
|
||||||
|
repository-scoped tokens, and the token Lore stores carries the `resources` claim.
|
||||||
|
- `lore repository list` is answered by the registry's `RepositoryList`.
|
||||||
|
- `lore auth info` resolves the user's display name through `UserService`.
|
||||||
|
`--with-access-token` prints the stored repository token, whose payload the test checks.
|
||||||
|
(`--with-claims` exists on `main` but not in v0.14.0.)
|
||||||
|
- A second user is refused create in another's namespace, clone and listing.
|
||||||
|
- `lore auth login --token-type api-key` (token from `LORE_TOKEN`) logs in through token
|
||||||
|
exchange with a lore-forge API token; the CLI sends the type `api-key` verbatim.
|
||||||
|
- `lore auth login --client-id <service account>` (secret from `LORE_CLIENT_SECRET`) logs in
|
||||||
|
with the client credentials grant. A service account without a grant is refused clone; after
|
||||||
|
a grant it clones.
|
||||||
|
- `lore auth logout` reaches the revocation endpoint.
|
||||||
|
- `loreserver`'s ports can be moved with `[server.quic]`, `[server.grpc]` and `[server.http]`
|
||||||
|
`port` settings; the test uses this (`LORE_PORT`) to run beside a deployment from `run/`.
|
||||||
|
- How refusals surface: the registry's `INVALID_ARGUMENT` message reaches the CLI verbatim;
|
||||||
|
`NOT_FOUND` is reported by `loreserver` as `FAILED_PRECONDITION` "A required Auth entity was
|
||||||
|
not found"; `PERMISSION_DENIED` and an exchange `invalid_target` both show as "Not
|
||||||
|
authorized to access repository".
|
||||||
|
|
||||||
|
## Release binaries
|
||||||
|
|
||||||
|
Verified against the v0.14.0 GitHub release:
|
||||||
|
|
||||||
|
- Each release publishes `lore-<version>-<target>.tar.gz` and `loreserver-<version>-<target>.tar.gz`
|
||||||
|
for `aarch64-apple-darwin`, `x86_64-unknown-linux-gnu` and `aarch64-unknown-linux-gnu`, plus
|
||||||
|
Windows and `-debug` variants. There is no Intel macOS build.
|
||||||
|
- GitHub records a SHA-256 for every asset, which `scripts/fetch-lore.sh --pin` copies into
|
||||||
|
`lore.lock`.
|
||||||
|
- Binaries sit at the archive root. The `loreserver` archive also holds sample configuration
|
||||||
|
in `config/`, which the fetch script keeps as `config-examples/`.
|
||||||
|
- `loreserver` has its defaults compiled in. A config directory holding only the generated
|
||||||
|
`forge.toml` is enough. The public QUIC endpoint listens on `0.0.0.0:41337`. Without
|
||||||
|
`[server.quic.certificate]`, it generates a self-signed certificate on every start.
|
||||||
|
- On macOS the `lore` CLI stores the key for its token store in the keychain
|
||||||
|
(`tokenstore_encryption_key`). Each process asks for access until "Always Allow" is chosen.
|
||||||
|
- v0.14.0's `user.proto` differs from `6b12f00` only in comments, so the vendored proto matches.
|
||||||
|
|
||||||
|
## Reading repositories
|
||||||
|
|
||||||
|
Read in Lore's source at `6b12f00` (the protos are identical in v0.14.0 apart from comments)
|
||||||
|
and confirmed by `scripts/e2e-lore.sh` against the v0.14.0 release:
|
||||||
|
|
||||||
|
- The public gRPC endpoint (`[server.grpc]`, port 41337 over TCP) is plaintext HTTP/2 when it
|
||||||
|
has no certificate; there is no self-signed fallback as for QUIC. The CLI uses gRPC for
|
||||||
|
revision calls whatever the URL scheme.
|
||||||
|
- Partition-scoped calls (`RevisionService`, `ThinClientService`, `StorageService`) need
|
||||||
|
`authorization: Bearer <token>` and the repository ID as 16 raw bytes under
|
||||||
|
`lore-partition-bin` and `urc-repository-id-bin` (the CLI sends both). The token must be
|
||||||
|
repository-scoped: a login token matches no `resources` entry and is refused. Every read
|
||||||
|
call needs only `read`.
|
||||||
|
- `RepositoryGet` returns the default branch, fixed at creation (`main` is only the default
|
||||||
|
name).
|
||||||
|
- `BranchList` streams branches; `latest` is the tip's signature.
|
||||||
|
- `RevisionList` returns at most 100 revisions newest first, following first parents, with
|
||||||
|
paging signatures. Its items carry no message, author or parents; `RevisionInfo` does.
|
||||||
|
- `RevisionTree` takes a path prefix and a depth and can attribute each entry to the revision
|
||||||
|
that last changed it. `RevisionDiff` streams changes between two signatures.
|
||||||
|
- `ContentDiff` is unimplemented: it answers `UNIMPLEMENTED`.
|
||||||
|
- File content is served decoded on the HTTP port (41339) at
|
||||||
|
`GET /v1/repository/<id hex>/content/<hash hex>[-<context hex>]` with the same bearer token,
|
||||||
|
and honours `Range`. The HTTP endpoint is plaintext.
|
||||||
|
- `lore branch merge <branch>` commits the merge itself, with no message.
|
||||||
|
- Timestamps in `Revision` are milliseconds.
|
||||||
|
|
||||||
## Unverified
|
## Unverified
|
||||||
|
|
||||||
- How `BranchPush` with `fast_forward_merge` reports a conflict.
|
- How `BranchPush` with `fast_forward_merge` reports a conflict.
|
||||||
- Whether a repository can be renamed, which decides whether namespaces can be renamed.
|
- Whether a repository can be renamed, which decides whether namespaces can be renamed.
|
||||||
- Whether identical content is deduplicated across repositories or only within one.
|
- Whether identical content is deduplicated across repositories or only within one.
|
||||||
- The exact form of `user_url` and whether both services must share one endpoint.
|
|
||||||
- Whether `NotificationService.Subscribe` is reachable by an external subscriber in the default
|
- Whether `NotificationService.Subscribe` is reachable by an external subscriber in the default
|
||||||
`local` mode, and what permission it needs.
|
`local` mode, and what permission it needs.
|
||||||
- What `loreserver` itself checks on repository create beyond asking the registry.
|
- What `loreserver` itself checks on repository create beyond asking the registry, other than
|
||||||
|
the error mapping above.
|
||||||
- How stable `ThinClientService` is between releases.
|
- How stable `ThinClientService` is between releases.
|
||||||
|
- Whether a TreeNode in a linked repository can be read with a token for the parent
|
||||||
|
repository, or needs one for the linked repository.
|
||||||
|
- Paging `RevisionList` with `signature_backward`; the browser does not page yet.
|
||||||
|
|
||||||
## Upstream files worth reading
|
## Upstream files worth reading
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
# Namespaces and access
|
# Namespaces and access
|
||||||
|
|
||||||
Status: design, nothing built. Last updated 2026-11-25.
|
Status: built for phase 1: namespaces, organisations, members, teams, grants and their pages,
|
||||||
|
the registry rules, service accounts. GitHub and Discord mapping is not. Last updated
|
||||||
|
2026-11-25.
|
||||||
|
|
||||||
## Namespaces
|
## Namespaces
|
||||||
|
|
||||||
|
|
@ -51,14 +53,19 @@ same rules as creating a repository in the web UI.
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Create a repository in a personal namespace | That user |
|
| Create a repository in a personal namespace | That user |
|
||||||
| Create a repository in an organisation | Members the organisation allows (owners by default) |
|
| Create a repository in an organisation | Members the organisation allows (owners by default) |
|
||||||
| Create an organisation | An instance setting. Defaulted to instance admins only; not yet confirmed |
|
| Create an organisation | The owner's `orgs.create` setting: instance admins (the default) or everyone. The creator becomes its owner. The default is not yet confirmed |
|
||||||
|
|
||||||
## Organisations and teams
|
## Organisations and teams
|
||||||
|
|
||||||
- **Members** belong to an organisation with an organisation role: owner or member.
|
- **Members** belong to an organisation with an organisation role: owner or member.
|
||||||
- **Teams** are named groups of members within one organisation.
|
- **Teams** are named groups of members within one organisation.
|
||||||
- **Base permission:** an organisation may give all its members a default role on all its
|
- **Base permission:** an organisation may give all its members a default role on all its
|
||||||
repositories (for example Reader), or none.
|
repositories (for example Reader), or none. Owner cannot be a base permission.
|
||||||
|
- An organisation always keeps at least one owner: the last one cannot be demoted or removed.
|
||||||
|
- Only members can join a team; removing a member from the organisation removes them from
|
||||||
|
its teams. Deleting a team deletes its grants.
|
||||||
|
- Organisation owners manage members, teams, settings and service accounts at
|
||||||
|
`/orgs/<org>/...`. Members see the organisation's members and teams.
|
||||||
|
|
||||||
## Role presets
|
## Role presets
|
||||||
|
|
||||||
|
|
@ -70,15 +77,19 @@ Permissions are presented as presets that map onto Lore's actions.
|
||||||
| Writer | `write` | Push to unprotected branches, take locks |
|
| Writer | `write` | Push to unprotected branches, take locks |
|
||||||
| Maintainer | `write`, `set-protected` | Also protect and unprotect branches |
|
| Maintainer | `write`, `set-protected` | Also protect and unprotect branches |
|
||||||
| Admin | `write`, `admin` | Also release others' locks, manage the repository |
|
| Admin | `write`, `admin` | Also release others' locks, manage the repository |
|
||||||
| Owner | `owner` | Also delete the repository |
|
| Owner | `write`, `owner` | Also delete the repository |
|
||||||
|
|
||||||
Notes:
|
Verified in Lore's source at `6b12f00` (`lore-server/src/grpc/mod.rs`,
|
||||||
|
`lore-server/src/grpc/lock_service.rs`, `lore-server/src/authnz/resource_grants_authorizer.rs`):
|
||||||
|
|
||||||
- In Lore, any grant on a repository implies `read`.
|
- **Actions are checked literally; none implies another**, except that any grant implies
|
||||||
- The mapping of `admin` and `owner` to specific operations is taken from Lore's
|
`read`. So `owner` does not include `write`, which is why Owner lists both.
|
||||||
documentation: branch protection needs `owner`, `admin` or `set-protected`; repository delete
|
- Every "administer the repository" check accepts `owner` **or** `admin`: releasing others'
|
||||||
needs `owner` or `admin`. The table above should be re-checked against Lore's enforcement
|
locks, protecting branches (which `set-protected` also allows), and deleting the repository.
|
||||||
points before implementation.
|
- Pushes and branch changes need `write`; a push to a protected branch also needs
|
||||||
|
`push-protected`.
|
||||||
|
- Lore itself would let an Admin delete a repository. lore-forge's registry refuses the
|
||||||
|
unregister unless the caller has Owner, so in practice only Owner deletes.
|
||||||
|
|
||||||
### Advanced view
|
### Advanced view
|
||||||
|
|
||||||
|
|
@ -99,7 +110,10 @@ account can be given it explicitly. See [forge-features.md](forge-features.md).
|
||||||
|
|
||||||
A grant gives a subject a preset, plus optional extra actions, on a repository.
|
A grant gives a subject a preset, plus optional extra actions, on a repository.
|
||||||
|
|
||||||
- **Subjects:** a user, a team, or a service account.
|
- **Subjects:** a user, a team, or a service account (which is a user row, so it is granted
|
||||||
|
by its `<owner>.<name>` username).
|
||||||
|
- **Who manages them:** holders of the `admin` action on the repository (the Admin and Owner
|
||||||
|
presets) on its Access page. Only Owner holders can grant Owner. Every change is audited.
|
||||||
- **Sources of a user's access to a repository**, combined by union:
|
- **Sources of a user's access to a repository**, combined by union:
|
||||||
1. the repository is in their personal namespace (Owner);
|
1. the repository is in their personal namespace (Owner);
|
||||||
2. their organisation role and the organisation's base permission;
|
2. their organisation role and the organisation's base permission;
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
# Storage
|
# Storage
|
||||||
|
|
||||||
Status: design, nothing built. Last updated 2026-11-25.
|
Status: phase 1 schema built (`crates/forge-store/migrations/`: `0001_initial.sql`, and
|
||||||
|
`0002_accounts.sql` for invites, providers, API tokens and service accounts). Last updated 2026-11-25.
|
||||||
|
|
||||||
## What lore-forge stores
|
## What lore-forge stores
|
||||||
|
|
||||||
|
|
@ -27,8 +28,16 @@ written periodically, not per request. See [token-issuer.md](token-issuer.md).
|
||||||
|
|
||||||
### Library
|
### Library
|
||||||
|
|
||||||
Not yet decided. `sqlx` (async, compile-time-checked queries, built-in migrations) is the
|
**Decided (owner, 2026-11-25):** `sqlx`, with its built-in migrations embedded in the binary.
|
||||||
default candidate; `rusqlite` with a dedicated writer thread is the alternative.
|
|
||||||
|
Queries use sqlx's runtime-checked functions (`query`, `query_as` with `FromRow`), not its
|
||||||
|
compile-time `query!` macros, which need a live database or a committed `.sqlx` cache and
|
||||||
|
`sqlx-cli` on every schema change. sqlx 0.9 refuses SQL built at runtime, so every query is a
|
||||||
|
static string. Moving to the macros later is a mechanical change.
|
||||||
|
|
||||||
|
Before 0.1.0, migrations may be edited in place rather than followed by new ones, as piki does
|
||||||
|
before its first release. `0002_accounts.sql` was added as a new migration anyway, so
|
||||||
|
deployments already started from `run/` keep their data.
|
||||||
|
|
||||||
## Data directory
|
## Data directory
|
||||||
|
|
||||||
|
|
@ -45,36 +54,36 @@ One 32-byte key, supplied through the environment, encrypts:
|
||||||
- provider client secrets (GitHub, Discord, Google);
|
- provider client secrets (GitHub, Discord, Google);
|
||||||
- lore-forge's private token signing keys.
|
- lore-forge's private token signing keys.
|
||||||
|
|
||||||
The key is not stored in the data directory. As in piki, losing it means provider secrets must
|
The key is not stored in the data directory. `scripts/start.sh` keeps it in `run/secret.key`
|
||||||
|
(mode 600), next to the data directory `run/forge-data/` rather than inside it, and tells the
|
||||||
|
operator to back it up separately. As in piki, losing it means provider secrets must
|
||||||
be re-entered; here it also means new signing keys, which invalidates outstanding tokens and
|
be re-entered; here it also means new signing keys, which invalidates outstanding tokens and
|
||||||
requires `loreserver` to pick up the new keys.
|
requires `loreserver` to pick up the new keys.
|
||||||
|
|
||||||
Stored only as hashes, never recoverable: passwords, session tokens, refresh tokens, API
|
Stored only as hashes, never recoverable: passwords, session tokens, refresh tokens, API
|
||||||
tokens, device codes, invite-flow state.
|
tokens, device codes, invite-flow state.
|
||||||
|
|
||||||
## Tables (phase 1 sketch)
|
## Tables (phase 1)
|
||||||
|
|
||||||
Names are provisional.
|
|
||||||
|
|
||||||
### Accounts — following piki
|
### Accounts — following piki
|
||||||
|
|
||||||
| Table | Holds |
|
| Table | Holds |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `users` | Username, display name, password hash, instance role, disabled flag |
|
| `users` | Username, display name, password hash, instance role, disabled flag, kind (`person` or `service`), owning namespace for service accounts |
|
||||||
| `sessions` | Hashed token, user, method used, user agent, created, expires, revoked |
|
| `sessions` | Hashed token, user, method used, user agent, created, expires, revoked |
|
||||||
| `invite_keys`, `invite_key_uses` | Key, name, maximum uses, active flag; who used it |
|
| `invite_keys`, `invite_key_uses` | Key, name, maximum uses, active flag; who used it |
|
||||||
| `oauth_provider_configs` | Provider, client ID, encrypted secret, enabled |
|
| `oauth_provider_configs` | Provider, client ID, encrypted secret, enabled |
|
||||||
| `oauth_identities` | `(provider, subject id)` → user; unique per user and provider |
|
| `oauth_identities` | `(provider, subject id)` → user; unique per user and provider |
|
||||||
| `oauth_flows` | Hashed state, intent, PKCE verifier, nonce, expiry, used |
|
| `oauth_flows` | Hashed state, intent, PKCE verifier, nonce, expiry, used |
|
||||||
| `passkey_credentials`, `passkey_ceremonies` | Public keys; single-use ceremony state |
|
| `passkey_credentials`, `passkey_ceremonies` | Public keys; single-use ceremony state. Not created; passkeys are dropped for now |
|
||||||
| `settings` | Instance settings: signup toggle, canonical URL, who may create organisations |
|
| `settings` | Key-value instance settings: `signup.mode`, `orgs.create`. The canonical URLs come from the environment |
|
||||||
|
|
||||||
### Namespaces and access
|
### Namespaces and access
|
||||||
|
|
||||||
| Table | Holds |
|
| Table | Holds |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `namespaces` | Name, kind (user or organisation). The single name table |
|
| `namespaces` | Name, kind (user or organisation). The single name table |
|
||||||
| `orgs`, `org_members` | Organisation details; member and organisation role |
|
| `orgs`, `org_members` | Organisation details, base preset, whether members may create repositories; member and organisation role |
|
||||||
| `teams`, `team_members` | Teams within an organisation |
|
| `teams`, `team_members` | Teams within an organisation |
|
||||||
| `repos` | Lore repository ID, namespace, name, base permission, per-branch landing settings |
|
| `repos` | Lore repository ID, namespace, name, base permission, per-branch landing settings |
|
||||||
| `grants` | Repository, subject (user, team or service account), preset, extra actions |
|
| `grants` | Repository, subject (user, team or service account), preset, extra actions |
|
||||||
|
|
@ -84,10 +93,12 @@ Names are provisional.
|
||||||
| Table | Holds |
|
| Table | Holds |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `signing_keys` | Key ID, algorithm, encrypted private key, public key, state |
|
| `signing_keys` | Key ID, algorithm, encrypted private key, public key, state |
|
||||||
| `device_codes` | Hashed device code, user code, client, status, expiry |
|
| `device_codes` | Hashed device code, user code, client, status, polling interval, expiry |
|
||||||
| `refresh_tokens` | Hashed token, user, created, last used, revoked. Shown in the session list |
|
| `cli_logins` | One per `lore auth login`: user, client, created, last used, absolute expiry, revoked, the API token it started from. Shown in the session list |
|
||||||
| `service_accounts` | Non-human identities and their owner |
|
| `refresh_tokens` | Hashed token, its login, created, superseded (for rotation and reuse detection) |
|
||||||
| `api_tokens` | Hashed token, owner, name, scopes, expiry, last used |
|
| `api_tokens` | Hashed token, owner, name, scopes, expiry, last used, revoked |
|
||||||
|
|
||||||
|
Service accounts have no table of their own: they are `users` rows with `kind = 'service'`.
|
||||||
|
|
||||||
### Shared
|
### Shared
|
||||||
|
|
||||||
|
|
@ -108,6 +119,5 @@ statuses. Full-text search can use SQLite's FTS5.
|
||||||
|
|
||||||
## Open questions
|
## Open questions
|
||||||
|
|
||||||
- `sqlx` or `rusqlite`.
|
|
||||||
- How long to retain audit entries and activity events.
|
- How long to retain audit entries and activity events.
|
||||||
- Whether exchanged-token activity is audited at all.
|
- Whether exchanged-token activity is audited at all.
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
# Token issuer
|
# Token issuer
|
||||||
|
|
||||||
Status: design, nothing built. Last updated 2026-11-25.
|
Status: phase 1 built (`crates/forge-id/src/issuer/`); every grant below is exercised against
|
||||||
|
the Lore v0.14.0 release by `scripts/e2e-lore.sh`. Last updated 2026-11-25.
|
||||||
|
|
||||||
lore-forge is the OpenID Connect issuer that `loreserver` trusts. This document covers what it
|
lore-forge is the OpenID Connect issuer that `loreserver` trusts. This document covers what it
|
||||||
must serve. The requirements come from Lore; see [lore-integration.md](lore-integration.md).
|
must serve. The requirements come from Lore; see [lore-integration.md](lore-integration.md).
|
||||||
|
|
@ -16,14 +17,24 @@ other applications.
|
||||||
|
|
||||||
## Endpoints
|
## Endpoints
|
||||||
|
|
||||||
| Endpoint | Purpose |
|
| Endpoint | Path | Purpose |
|
||||||
| --- | --- |
|
| --- | --- | --- |
|
||||||
| `/.well-known/openid-configuration` | Discovery document |
|
| Discovery | `/.well-known/openid-configuration` | Discovery document |
|
||||||
| JWKS endpoint | Public signing keys, each with `alg` declared |
|
| JWKS | `/oauth/jwks` | Public signing keys, each with `alg` declared |
|
||||||
| Device authorization endpoint | Starts a CLI login |
|
| Device authorization | `/oauth/device_authorization` | Starts a CLI login |
|
||||||
| Token endpoint | All grants below |
|
| Token | `/oauth/token` | All grants below |
|
||||||
| Revocation endpoint | `lore auth logout` |
|
| Revocation | `/oauth/revoke` | `lore auth logout` |
|
||||||
| Device verification page | Browser page where the person approves a CLI login (part of the web UI) |
|
| Device verification | `/device` | Browser page where the person approves a CLI login (part of the web UI) |
|
||||||
|
|
||||||
|
The Lore CLI is a public client: it presents `client_id` (default `lore-cli`) and no secret.
|
||||||
|
Every grant checks the client ID. The one exception is the client credentials grant, where the
|
||||||
|
client is a service account authenticating with a secret, by HTTP Basic or in the form body;
|
||||||
|
discovery lists `none`, `client_secret_basic` and `client_secret_post`.
|
||||||
|
|
||||||
|
**Verified in Lore's source (6b12f00) and by the e2e test:** Lore's client uses Basic when
|
||||||
|
discovery lists `client_secret_basic` and the form body otherwise. For API-key login it sends
|
||||||
|
the token type it was given verbatim, so lore-forge accepts both `api-key` and
|
||||||
|
`urn:lore:params:oauth:token-type:api-key`.
|
||||||
|
|
||||||
## Grants on the token endpoint
|
## Grants on the token endpoint
|
||||||
|
|
||||||
|
|
@ -31,9 +42,9 @@ other applications.
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Device code (RFC 8628) | `lore auth login` | Login token and refresh token |
|
| Device code (RFC 8628) | `lore auth login` | Login token and refresh token |
|
||||||
| Refresh token | Lore client, automatically | New login token; refresh token rotated |
|
| Refresh token | Lore client, automatically | New login token; refresh token rotated |
|
||||||
| Client credentials | CI, `lore auth login --client-id` | Login token for a service account |
|
| Client credentials | CI, `lore auth login --client-id` | Login token for a service account; no refresh token. The login lasts one hour or until the secret expires |
|
||||||
| Token exchange (RFC 8693), login token in | Lore client, per repository | Repository-scoped token |
|
| Token exchange (RFC 8693), login token in | Lore client, per repository | Repository-scoped token |
|
||||||
| Token exchange (RFC 8693), API token in | CI without a browser | Login token for the token's user |
|
| Token exchange (RFC 8693), API token in | CI without a browser, `lore auth login --token-type api-key` | Login token and refresh token for the token's user; the token needs the `lore` scope |
|
||||||
|
|
||||||
The device grant must honour the polling rules Lore's client expects: `interval`,
|
The device grant must honour the polling rules Lore's client expects: `interval`,
|
||||||
`slow_down`, `expired_token` and `access_denied`.
|
`slow_down`, `expired_token` and `access_denied`.
|
||||||
|
|
@ -50,7 +61,9 @@ A JWT access token (`typ: at+jwt`) identifying the user.
|
||||||
| `sub` | Stable internal user ID |
|
| `sub` | Stable internal user ID |
|
||||||
| `aud` | The `loreserver` deployment URL |
|
| `aud` | The `loreserver` deployment URL |
|
||||||
| `identity` | The identity Lore records in history (see below) |
|
| `identity` | The identity Lore records in history (see below) |
|
||||||
| `root_domains` | Hosts the token may be sent to, if `aud` alone does not cover them |
|
| `root_domains` | Hosts the token may be sent to: the `loreserver` host and lore-forge's own. Always set, because the CLI sends tokens to lore-forge's user directory too |
|
||||||
|
| `sid` | The CLI login the token belongs to; lets exchange refuse tokens of an ended login |
|
||||||
|
| `client_id`, `jti`, `scope` | As RFC 9068 describes |
|
||||||
| `name`, `preferred_username` | For display |
|
| `name`, `preferred_username` | For display |
|
||||||
| `exp`, `iat` | Short lifetime; renewed by refresh |
|
| `exp`, `iat` | Short lifetime; renewed by refresh |
|
||||||
|
|
||||||
|
|
@ -86,7 +99,13 @@ Audit records for exchanges are batched or sampled. See [storage.md](storage.md)
|
||||||
### Refresh tokens
|
### Refresh tokens
|
||||||
|
|
||||||
- Opaque, stored hashed, rotated on use.
|
- Opaque, stored hashed, rotated on use.
|
||||||
- One per CLI login. Shown in the user's session list and revocable there.
|
- One CLI login (a `cli_logins` row) per `lore auth login`; its refresh tokens rotate within
|
||||||
|
it. Shown in the user's session list (`/settings/sessions`) and revocable there. A login
|
||||||
|
started from an API token or a service account secret ends when that token is revoked.
|
||||||
|
- **Reuse detection:** a rotated-out refresh token presented again ends the whole login, per
|
||||||
|
RFC 9700. A 60-second grace period lets a client retry a refresh whose response was lost.
|
||||||
|
- The login ends 30 days after its last refresh, or 90 days after it began, whichever is first,
|
||||||
|
matching "stay signed in" browser sessions.
|
||||||
- Lore's client requests `offline_access` on every login; lore-forge issues a refresh token
|
- Lore's client requests `offline_access` on every login; lore-forge issues a refresh token
|
||||||
for it.
|
for it.
|
||||||
- Revocation through the revocation endpoint ends the login.
|
- Revocation through the revocation endpoint ends the login.
|
||||||
|
|
@ -98,7 +117,10 @@ Audit records for exchanges are batched or sampled. See [storage.md](storage.md)
|
||||||
- **Storage:** private keys are stored encrypted with the same environment-supplied key that
|
- **Storage:** private keys are stored encrypted with the same environment-supplied key that
|
||||||
protects provider secrets.
|
protects provider secrets.
|
||||||
- **Rotation:** the JWKS publishes the current key and the previous one. `loreserver` re-fetches
|
- **Rotation:** the JWKS publishes the current key and the previous one. `loreserver` re-fetches
|
||||||
keys when it sees an unknown key ID, so rotation needs no server restart.
|
keys when it sees an unknown key ID, so rotation needs no server restart. The owner rotates
|
||||||
|
from `/admin/settings` or with `lore-forge rotate-signing-key` on the server; a running
|
||||||
|
lore-forge re-reads its keys every minute, so a rotation made by the command reaches it
|
||||||
|
within that time. Rotating twice retires the oldest key, ending tokens it signed.
|
||||||
- **Stability:** keys persist across restarts. Lore's sample service regenerates its key on
|
- **Stability:** keys persist across restarts. Lore's sample service regenerates its key on
|
||||||
every start, which invalidates all outstanding tokens; lore-forge must not.
|
every start, which invalidates all outstanding tokens; lore-forge must not.
|
||||||
|
|
||||||
|
|
@ -106,13 +128,22 @@ Audit records for exchanges are batched or sampled. See [storage.md](storage.md)
|
||||||
|
|
||||||
Lore records `identity` (or `sub` when absent) as the creator and committer of revisions.
|
Lore records `identity` (or `sub` when absent) as the creator and committer of revisions.
|
||||||
|
|
||||||
**Recommended, not yet confirmed:** set it to the stable internal user ID and serve names
|
**Decided (owner, 2026-11-25):** set it to the stable internal user ID and serve names
|
||||||
through Lore's `UserService`. See [accounts-and-sign-in.md](accounts-and-sign-in.md).
|
through Lore's `UserService`. See [accounts-and-sign-in.md](accounts-and-sign-in.md).
|
||||||
|
|
||||||
|
## Tokens for the web UI
|
||||||
|
|
||||||
|
`Issuer::browse_token` mints a token for lore-forge's own pages to read a repository from
|
||||||
|
`loreserver` as the viewer: the viewer's identity, one `resources` entry for that repository
|
||||||
|
with only `read`, a one-minute lifetime, no `sid`. It is never handed to the browser. It is
|
||||||
|
refused when the viewer's grants do not include `read`.
|
||||||
|
|
||||||
## Service accounts and CI
|
## Service accounts and CI
|
||||||
|
|
||||||
- A service account is a non-human identity owned by a user or organisation.
|
- A service account is a non-human identity owned by a user or organisation.
|
||||||
- It logs in with client credentials, or with an API token through token exchange.
|
- It logs in with client credentials; its secrets are API tokens with the `lore` scope.
|
||||||
|
A person's own API token logs in through token exchange instead.
|
||||||
|
- Details are in [accounts-and-sign-in.md](accounts-and-sign-in.md).
|
||||||
- It receives grants like any user. The `push-protected` action is how a CI account is allowed
|
- It receives grants like any user. The `push-protected` action is how a CI account is allowed
|
||||||
to push to a protected branch.
|
to push to a protected branch.
|
||||||
|
|
||||||
|
|
@ -121,11 +152,22 @@ through Lore's `UserService`. See [accounts-and-sign-in.md](accounts-and-sign-in
|
||||||
| Change | Takes effect |
|
| Change | Takes effect |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Grant added or removed | Within five minutes, when the client's scoped token expires |
|
| Grant added or removed | Within five minutes, when the client's scoped token expires |
|
||||||
| CLI login revoked | When the current login token expires; no new tokens after that |
|
| CLI login revoked | Exchange refuses at once (it checks the login is live), so repository access ends within five minutes. The login token itself stays valid until it expires, at most an hour, for calls that name no repository |
|
||||||
| User disabled | Same as a revoked login, for all of that user's logins |
|
| User disabled | Same as a revoked login, for all of that user's logins |
|
||||||
| Signing key rotated out | When removed from the JWKS |
|
| Signing key rotated out | When removed from the JWKS |
|
||||||
|
|
||||||
Lifetimes for the login token and refresh token are not yet decided.
|
The exchange's liveness check is one indexed read. It keeps the exchange path free of writes.
|
||||||
|
|
||||||
|
### Lifetimes
|
||||||
|
|
||||||
|
Defaulted, not confirmed by the owner (`forge_id::issuer::Lifetimes`):
|
||||||
|
|
||||||
|
| Item | Lifetime |
|
||||||
|
| --- | --- |
|
||||||
|
| Login token | 1 hour |
|
||||||
|
| Repository-scoped token | 5 minutes, never past the login token |
|
||||||
|
| CLI login (refresh) | 30 days idle, 90 days at most |
|
||||||
|
| Device code | 10 minutes, polled every 5 seconds |
|
||||||
|
|
||||||
## Security notes
|
## Security notes
|
||||||
|
|
||||||
|
|
@ -138,7 +180,5 @@ Lifetimes for the login token and refresh token are not yet decided.
|
||||||
|
|
||||||
## Open questions
|
## Open questions
|
||||||
|
|
||||||
- Login token and refresh token lifetimes.
|
- Confirm the lifetimes above.
|
||||||
- Whether the audience alone covers every host a token must reach, or a `root_domains` claim
|
|
||||||
is needed (relevant if `loreserver` and lore-forge are on unrelated domains).
|
|
||||||
- Whether to keep an audit trail of token exchanges, and at what granularity.
|
- Whether to keep an audit trail of token exchanges, and at what granularity.
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# Web UI
|
# Web UI
|
||||||
|
|
||||||
Status: design, nothing built. Last updated 2026-11-25.
|
Status: phase 1 pages and the phase 2 repository browser are built. Last updated 2026-11-25.
|
||||||
|
|
||||||
## Approach
|
## Approach
|
||||||
|
|
||||||
|
|
@ -13,13 +13,25 @@ no separate frontend application and no Node build step.
|
||||||
| Templates | maud | Components are plain Rust functions, so a handler can return a whole page or one fragment. Askama is the alternative if HTML should live in template files |
|
| Templates | maud | Components are plain Rust functions, so a handler can return a whole page or one fragment. Askama is the alternative if HTML should live in template files |
|
||||||
| Interactivity | htmx | Vendored, not fetched from a CDN |
|
| Interactivity | htmx | Vendored, not fetched from a CDN |
|
||||||
| Scripts | A few small hand-written ones | Only where HTML is not enough: diff viewer, image comparison, later 3D previews |
|
| Scripts | A few small hand-written ones | Only where HTML is not enough: diff viewer, image comparison, later 3D previews |
|
||||||
| Styles | Plain CSS with custom properties | |
|
| Styles | Plain CSS with custom properties | One stylesheet, `crates/forge-web/assets/app.css` |
|
||||||
|
| Look | The desktop client's pixel style: IBM VGA 8x16 font, Sweetie 16 palette, bevelled buttons, square panels | Owner, 2026-11-25 ("a similar facelift"). The font is self-hosted under `/static/`; its CC BY-SA licence is at `/licenses`, linked from every footer |
|
||||||
| Assets | Embedded in the binary | One file to deploy |
|
| Assets | Embedded in the binary | One file to deploy |
|
||||||
| Live updates | Server-sent events | Fed by Lore's notification stream: activity, lock state, CI status |
|
| Live updates | Server-sent events | Fed by Lore's notification stream: activity, lock state, CI status |
|
||||||
| API | JSON under `/api/v1` | Calls the same core services as the pages; authenticated by API tokens |
|
| API | JSON under `/api/v1` | Calls the same core services as the pages; authenticated by API tokens |
|
||||||
|
|
||||||
The template and interactivity choices are recommendations that have not been explicitly
|
All of these are confirmed by the owner; maud and htmx were confirmed on 2026-11-25.
|
||||||
confirmed; "server-rendered" has.
|
|
||||||
|
### One port for pages and gRPC
|
||||||
|
|
||||||
|
Lore reaches the user directory and repository registry over gRPC at `user_url`. lore-forge
|
||||||
|
serves them on the same port as its pages and issuer, routing requests whose content type is
|
||||||
|
`application/grpc*` to the gRPC services and everything else to the web routes. So one public
|
||||||
|
URL is both the issuer and `user_url`. A reverse proxy in front must speak HTTP/2 to
|
||||||
|
lore-forge and pass gRPC through.
|
||||||
|
|
||||||
|
htmx is not vendored yet: no phase 1 page needs it. Every phase 1 page works as plain forms:
|
||||||
|
a successful POST redirects with `?ok=<code>` for its notice; a refused one re-renders the
|
||||||
|
form with the error and status 422.
|
||||||
|
|
||||||
## Why server rendering suits Lore
|
## Why server rendering suits Lore
|
||||||
|
|
||||||
|
|
@ -47,8 +59,15 @@ Repository content is untrusted: Markdown, SVG and HTML files can carry script.
|
||||||
- **Raw content on a separate origin.** Raw files and previews are served from a different
|
- **Raw content on a separate origin.** Raw files and previews are served from a different
|
||||||
hostname than the UI and issuer, so a malicious file cannot read session cookies or call the
|
hostname than the UI and issuer, so a malicious file cannot read session cookies or call the
|
||||||
UI as the user.
|
UI as the user.
|
||||||
- **Strict content security policy** on the main origin, with no inline script. Server
|
- **Strict content security policy** on the main origin, with no inline script or style:
|
||||||
rendering makes this straightforward; htmx is configured to work without inline handlers.
|
`default-src 'none'` with `'self'` for scripts, styles, fonts and images (`data:` images
|
||||||
|
too), `form-action 'self'`, `frame-ancestors 'none'`. A test renders every page and fails
|
||||||
|
on any `<script>` or `style=`. htmx is to be configured to work without inline handlers.
|
||||||
|
- **Repository content is shown as escaped text only.** The browser renders files as text in
|
||||||
|
a table or says they are binary; it serves no raw file, so the separate raw-content origin
|
||||||
|
is not needed yet. It will be when downloads or rendered previews come.
|
||||||
|
- **One-time secrets** (API tokens, service account secrets) appear only in the response to
|
||||||
|
the POST that made them, never in a URL or a redirect.
|
||||||
- **Rendered Markdown is sanitised** before it is placed in a page on the main origin.
|
- **Rendered Markdown is sanitised** before it is placed in a page on the main origin.
|
||||||
- **Server-side sessions** with CSRF tokens on unsafe methods; see
|
- **Server-side sessions** with CSRF tokens on unsafe methods; see
|
||||||
[accounts-and-sign-in.md](accounts-and-sign-in.md).
|
[accounts-and-sign-in.md](accounts-and-sign-in.md).
|
||||||
|
|
@ -58,39 +77,51 @@ Repository content is untrusted: Markdown, SVG and HTML files can carry script.
|
||||||
## Acting as the user
|
## Acting as the user
|
||||||
|
|
||||||
When a page needs data from `loreserver`, lore-forge mints a short-lived repository-scoped
|
When a page needs data from `loreserver`, lore-forge mints a short-lived repository-scoped
|
||||||
token carrying the browsing user's identity and their actual grants, and calls `loreserver`
|
token carrying the browsing user's identity, and calls `loreserver` with it. Built for the
|
||||||
with it.
|
repository browser: the token carries only `read` (pages only read) and lasts one minute;
|
||||||
|
each page view mints its own.
|
||||||
|
|
||||||
- The web UI and the CLI are authorised by the same rule, enforced in the same place.
|
- The web UI and the CLI are authorised by the same rule, enforced in the same place.
|
||||||
- lore-forge holds no standing super-user credential for reading repositories.
|
- lore-forge holds no standing super-user credential for reading repositories.
|
||||||
- The one exception is landing a change on a review-gated branch, where lore-forge uses its own
|
- The one exception is landing a change on a review-gated branch, where lore-forge uses its own
|
||||||
landing identity; see [forge-features.md](forge-features.md).
|
landing identity; see [forge-features.md](forge-features.md).
|
||||||
|
|
||||||
## Routes (sketch)
|
## Routes
|
||||||
|
|
||||||
|
Built in phase 1:
|
||||||
|
|
||||||
| Path | Page |
|
| Path | Page |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `/` | Dashboard: your repositories and recent activity |
|
| `/` | Dashboard: your repositories, your namespaces, CLI instructions |
|
||||||
| `/setup`, `/login`, `/signup/<key>` | Account entry points |
|
| `/setup`, `/login`, `/signup`, `/signup/<key>` | Account entry points |
|
||||||
|
| `/oauth/<provider>/start`, `/oauth/<provider>/callback` | Provider sign-in and linking |
|
||||||
| `/device` | Approve a CLI login |
|
| `/device` | Approve a CLI login |
|
||||||
| `/settings/...` | Profile, linked providers, sessions, API tokens; instance settings for the owner |
|
| `/settings`, `/settings/sessions`, `/settings/providers`, `/settings/tokens`, `/settings/service-accounts` | Profile and password, sessions and CLI logins, linked providers, API tokens, personal service accounts |
|
||||||
|
| `/admin`, `/admin/invites`, `/admin/repos`, `/admin/audit` | Users, invites, all repositories, audit log (admins) |
|
||||||
|
| `/admin/settings`, `/admin/providers` | Signup mode, who creates organisations, key rotation; provider apps (owner) |
|
||||||
|
| `/orgs`, `/orgs/<org>/members`, `/teams`, `/settings`, `/service-accounts` | Organisations |
|
||||||
| `/<owner>` | A user's or organisation's repositories |
|
| `/<owner>` | A user's or organisation's repositories |
|
||||||
| `/<owner>/<repo>` | Repository home |
|
| `/<owner>/<repo>` | FILES: listing or file view; `?b=<branch>&rev=<signature>&path=<path>` |
|
||||||
| `/<owner>/<repo>/tree/<ref>/<path>` | File browser |
|
| `/<owner>/<repo>/graph`, `/<owner>/<repo>/tree` | GRAPH and TREE |
|
||||||
| `/<owner>/<repo>/history/<ref>` | Revision history |
|
| `/<owner>/<repo>/revision/<signature>` | One revision and its diffs |
|
||||||
| `/<owner>/<repo>/revision/<id>` | One revision and its diff |
|
| `/<owner>/<repo>/access` | Grants, for holders of the `admin` action |
|
||||||
|
| `/licenses` | Third-party licences |
|
||||||
|
| `/api/v1/user`, `/api/v1/repos` | JSON API, API tokens with the `api` scope |
|
||||||
|
|
||||||
|
Planned:
|
||||||
|
|
||||||
|
| Path | Page |
|
||||||
|
| --- | --- |
|
||||||
| `/<owner>/<repo>/changes`, `/changes/<n>` | Change requests |
|
| `/<owner>/<repo>/changes`, `/changes/<n>` | Change requests |
|
||||||
| `/<owner>/<repo>/locks` | Lock dashboard |
|
| `/<owner>/<repo>/locks` | Lock dashboard |
|
||||||
| `/<owner>/<repo>/settings` | Access, branch rules |
|
| `/<owner>/<repo>/settings` | Branch rules |
|
||||||
| `/.well-known/openid-configuration`, token and device endpoints | The issuer |
|
| `/api/v1/...` | More of the JSON API |
|
||||||
| `/api/v1/...` | JSON API |
|
|
||||||
|
|
||||||
Because owners occupy the top level of the path, reserved words such as `login`, `settings`
|
Because owners occupy the top level of the path, reserved words such as `login`, `settings`
|
||||||
and `api` cannot be used as usernames or organisation names.
|
and `api` cannot be used as usernames or organisation names.
|
||||||
|
|
||||||
## Open questions
|
## Open questions
|
||||||
|
|
||||||
- Confirm maud and htmx.
|
|
||||||
- Hostname scheme for the raw-content origin, and how it is configured for small self-hosted
|
- Hostname scheme for the raw-content origin, and how it is configured for small self-hosted
|
||||||
installs that have only one hostname.
|
installs that have only one hostname.
|
||||||
- Whether anonymous visitors can see anything.
|
- Whether anonymous visitors can see anything.
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
/target
|
||||||
|
/data
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite-wal
|
||||||
|
*.sqlite-shm
|
||||||
|
/.lore
|
||||||
|
/run
|
||||||
|
/desktop/target
|
||||||
|
/desktop/zig-out
|
||||||
|
/desktop/.zig-cache
|
||||||
|
.zig-cache
|
||||||
43
AGENTS.md
43
AGENTS.md
|
|
@ -4,7 +4,8 @@ lore-forge is a Rust web server that sits beside Epic's [Lore](https://github.co
|
||||||
version control server. It provides accounts, sign-in through GitHub, Discord and Google, the
|
version control server. It provides accounts, sign-in through GitHub, Discord and Google, the
|
||||||
tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on top.
|
tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on top.
|
||||||
|
|
||||||
**Status:** design only. No code has been written yet.
|
**Status:** phase 1 in progress. The walking skeleton works end to end against a real
|
||||||
|
`loreserver`; see the phases in [architecture-overview.md](.ai/designs/architecture-overview.md).
|
||||||
|
|
||||||
## Git commits
|
## Git commits
|
||||||
|
|
||||||
|
|
@ -13,8 +14,44 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on
|
||||||
messages and to pull request descriptions.
|
messages and to pull request descriptions.
|
||||||
- Commit only when asked.
|
- Commit only when asked.
|
||||||
|
|
||||||
|
## Building and testing
|
||||||
|
|
||||||
|
- `cargo test --workspace` runs the unit and in-process HTTP tests. `protoc` must be on `PATH`
|
||||||
|
(Lore's `user.proto` is compiled at build time).
|
||||||
|
- `cargo clippy --workspace --all-targets` should stay clean.
|
||||||
|
- `scripts/e2e-lore.sh` runs lore-forge against an unmodified `loreserver` and `lore` CLI: by
|
||||||
|
default the release pinned in `lore.lock`, fetched into `.lore/` by `scripts/fetch-lore.sh`.
|
||||||
|
Set `LORE_BIN_DIR` to test another build, and `LORE_PORT`/`FORGE_PORT` to run it beside a
|
||||||
|
deployment started by `scripts/start.sh`. Run it after any change to the issuer, registry or
|
||||||
|
directory, and whenever the Lore version moves. `SMOKE=1` stops after one login and push.
|
||||||
|
On macOS each `lore` process asks for keychain access until "Always Allow" is chosen, so do a
|
||||||
|
smoke run first and tell the owner a prompt is coming.
|
||||||
|
- To move Lore: `scripts/fetch-lore.sh --pin vX.Y.Z`, then the e2e test, then update the version
|
||||||
|
recorded in [lore-integration.md](.ai/designs/lore-integration.md).
|
||||||
|
|
||||||
|
- The desktop client in `desktop/` builds separately with Zig 0.17.1 and Cargo:
|
||||||
|
- `cd desktop && zig build test` runs its Rust tests and the GUI's self-test against a
|
||||||
|
private service;
|
||||||
|
- `zig build check -Dtarget=x86_64-windows-gnu` cross-compiles the GUI;
|
||||||
|
- `cargo clippy --all-targets` in `desktop/` should stay clean;
|
||||||
|
- `forge-desktop --test --config-from <toml> --screenshot <png>` captures the window, for
|
||||||
|
checking UI changes without screen-recording permission.
|
||||||
|
|
||||||
## Where things are
|
## Where things are
|
||||||
|
|
||||||
|
| Path | Contents |
|
||||||
|
| --- | --- |
|
||||||
|
| `crates/forge-store` | SQLite pool, migrations (`migrations/`), audit helper |
|
||||||
|
| `crates/forge-access` | Actions, presets, name rules, grant resolution, registry rules, organisations |
|
||||||
|
| `crates/forge-id` | Secret key, passwords, signing keys and JWTs, users, sessions, the issuer (`src/issuer/`) |
|
||||||
|
| `crates/forge-lore` | Vendored Lore protos (`proto/`), the gRPC directory and registry, generated `loreserver` config |
|
||||||
|
| `crates/forge-web` | axum routes: issuer endpoints, pages (maud), CSRF and security headers |
|
||||||
|
| `crates/lore-forge` | The binary: `serve`, `loreserver-config`, `generate-secret-key`, `create-user` |
|
||||||
|
| `scripts/start.sh` | Starts a deployment from `run/` (git-ignored): settings, secret key, both servers |
|
||||||
|
| `scripts/fetch-lore.sh`, `lore.lock` | Downloads the pinned Lore release into `.lore/` (git-ignored), checking SHA-256 |
|
||||||
|
| `scripts/e2e-lore.sh` | End-to-end test against real Lore |
|
||||||
|
| `desktop/` | The desktop client: `gui/` (C++ tray app), `service/` and `protocol/` (Rust), `vendor/` (UHDK, Dear ImGui) |
|
||||||
|
|
||||||
- [.ai/designs/](.ai/designs/) holds the design documents. Start with
|
- [.ai/designs/](.ai/designs/) holds the design documents. Start with
|
||||||
[architecture-overview.md](.ai/designs/architecture-overview.md), which links to the rest.
|
[architecture-overview.md](.ai/designs/architecture-overview.md), which links to the rest.
|
||||||
|
|
||||||
|
|
@ -28,6 +65,7 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on
|
||||||
| [web-ui.md](.ai/designs/web-ui.md) | Server-rendered UI stack and its security constraints |
|
| [web-ui.md](.ai/designs/web-ui.md) | Server-rendered UI stack and its security constraints |
|
||||||
| [forge-features.md](.ai/designs/forge-features.md) | Repo browser, change requests, landing, activity |
|
| [forge-features.md](.ai/designs/forge-features.md) | Repo browser, change requests, landing, activity |
|
||||||
| [storage.md](.ai/designs/storage.md) | SQLite, the data directory, tables |
|
| [storage.md](.ai/designs/storage.md) | SQLite, the data directory, tables |
|
||||||
|
| [desktop-client.md](.ai/designs/desktop-client.md) | The desktop client: service, GUI, TUI, their protocol, liblore, UHDK |
|
||||||
|
|
||||||
## Working on the design
|
## Working on the design
|
||||||
|
|
||||||
|
|
@ -47,5 +85,8 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on
|
||||||
- **Lore:** <https://github.com/EpicGames/lore>. Minimum version for this design is v0.14.0.
|
- **Lore:** <https://github.com/EpicGames/lore>. Minimum version for this design is v0.14.0.
|
||||||
The most relevant upstream files are listed in
|
The most relevant upstream files are listed in
|
||||||
[lore-integration.md](.ai/designs/lore-integration.md).
|
[lore-integration.md](.ai/designs/lore-integration.md).
|
||||||
|
- **UHDK:** the owner's desktop library (a sibling checkout, `../uhdk-internal`), vendored into
|
||||||
|
`desktop/vendor/`. Update it only as [desktop/vendor/README.md](desktop/vendor/README.md)
|
||||||
|
describes; never edit the vendored copy.
|
||||||
- **piki:** the owner's Go project (a sibling checkout, `../piki`) is the reference for the
|
- **piki:** the owner's Go project (a sibling checkout, `../piki`) is the reference for the
|
||||||
account system. Its `agents/data-auth-services.md` maps the auth code.
|
account system. Its `agents/data-auth-services.md` maps the auth code.
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,55 @@
|
||||||
|
[workspace]
|
||||||
|
resolver = "3"
|
||||||
|
members = ["crates/*"]
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
license = "MIT"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[workspace.lints.rust]
|
||||||
|
unsafe_code = "forbid"
|
||||||
|
|
||||||
|
[workspace.lints.clippy]
|
||||||
|
dbg_macro = "warn"
|
||||||
|
todo = "warn"
|
||||||
|
|
||||||
|
[workspace.dependencies]
|
||||||
|
forge-store = { path = "crates/forge-store" }
|
||||||
|
forge-id = { path = "crates/forge-id" }
|
||||||
|
forge-access = { path = "crates/forge-access" }
|
||||||
|
forge-lore = { path = "crates/forge-lore" }
|
||||||
|
forge-web = { path = "crates/forge-web" }
|
||||||
|
|
||||||
|
aes-gcm = "0.11"
|
||||||
|
anyhow = "1"
|
||||||
|
argon2 = "0.6"
|
||||||
|
axum = { version = "0.8", features = ["http2", "macros"] }
|
||||||
|
base64 = "0.23"
|
||||||
|
clap = { version = "4", features = ["derive", "env"] }
|
||||||
|
getrandom = "0.4"
|
||||||
|
maud = { version = "0.27", features = ["axum"] }
|
||||||
|
p256 = { version = "0.14", features = ["ecdsa"] }
|
||||||
|
prost = "0.14"
|
||||||
|
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
sha2 = "0.11"
|
||||||
|
similar = "2"
|
||||||
|
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite", "migrate", "macros"] }
|
||||||
|
subtle = "2"
|
||||||
|
tempfile = "3"
|
||||||
|
thiserror = "2"
|
||||||
|
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal", "time", "sync"] }
|
||||||
|
tokio-stream = "0.1"
|
||||||
|
tonic = { version = "0.14", default-features = false, features = ["codegen", "router", "server"] }
|
||||||
|
tonic-prost = "0.14"
|
||||||
|
tonic-prost-build = "0.14"
|
||||||
|
tonic-types = "0.14"
|
||||||
|
tower = { version = "0.5", features = ["util"] }
|
||||||
|
tower-http = { version = "0.7", features = ["trace"] }
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
|
url = "2"
|
||||||
|
uuid = { version = "1", features = ["v4"] }
|
||||||
|
|
@ -0,0 +1,95 @@
|
||||||
|
# lore-forge
|
||||||
|
|
||||||
|
Accounts, sign-in, per-repository tokens and a self-hosted forge for Epic's
|
||||||
|
[Lore](https://github.com/EpicGames/lore) version control system.
|
||||||
|
|
||||||
|
lore-forge runs beside an unmodified `loreserver` as the OpenID Connect issuer it trusts. Lore
|
||||||
|
clients log in through lore-forge, which signs tokens scoped to one repository at a time from the
|
||||||
|
permissions it manages. Repository data still flows directly between Lore clients and
|
||||||
|
`loreserver`.
|
||||||
|
|
||||||
|
**Status:** early. `lore auth login`, repository create, push, clone and listing work end to end
|
||||||
|
against Lore 0.14. Provider sign-in, invites and the forge UI are still to come. The design is in
|
||||||
|
[.ai/designs/](.ai/designs/architecture-overview.md).
|
||||||
|
|
||||||
|
## Starting a deployment
|
||||||
|
|
||||||
|
This repository is all a deployment needs. You need Rust, `protoc`, `curl` and `tar`.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
scripts/start.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
On the first run it:
|
||||||
|
|
||||||
|
1. writes `run/deployment.env` with local defaults;
|
||||||
|
2. generates `run/secret.key`;
|
||||||
|
3. builds lore-forge;
|
||||||
|
4. downloads the Lore release pinned in `lore.lock` into `.lore/` and checks its SHA-256;
|
||||||
|
5. starts lore-forge and then `loreserver`, which it configures to trust lore-forge.
|
||||||
|
|
||||||
|
Then:
|
||||||
|
|
||||||
|
- Open <http://localhost:8080> and create the owner account.
|
||||||
|
- Sign in with the CLI, using the path the script prints:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
.lore/v0.14.0/lore auth login lore://localhost:41337
|
||||||
|
.lore/v0.14.0/lore repository create lore://localhost:41337/<your-username>/my-game
|
||||||
|
```
|
||||||
|
|
||||||
|
Ctrl-C stops both servers. Later runs reuse everything in `run/`, which is git-ignored. Set
|
||||||
|
`LORE_FORGE_RUN_DIR` to keep it somewhere else.
|
||||||
|
|
||||||
|
| In `run/` | |
|
||||||
|
| --- | --- |
|
||||||
|
| `deployment.env` | Public URLs, listen address, TLS certificate for `loreserver`. Edit it before going beyond localhost |
|
||||||
|
| `secret.key` | Encrypts the token signing keys. Back it up **apart from** the rest; losing it invalidates every outstanding token |
|
||||||
|
| `forge-data/` | lore-forge's SQLite database |
|
||||||
|
| `lore-store/` | `loreserver`'s repository storage |
|
||||||
|
| `lore-config/` | The `loreserver` configuration, regenerated on every start |
|
||||||
|
| `logs/` | Both servers' logs |
|
||||||
|
|
||||||
|
To serve other machines, set `PUBLIC_URL` to lore-forge's https URL. Behind a reverse proxy, the
|
||||||
|
proxy must pass HTTP/2 through so gRPC works. Also set `LORE_URL` and `LORE_REMOTE` to the host
|
||||||
|
clients use for Lore, and `LORE_TLS_CERT`/`LORE_TLS_KEY` to a real certificate. Without one,
|
||||||
|
`loreserver` makes a self-signed certificate on every start.
|
||||||
|
|
||||||
|
`PUBLIC_URL` is the token issuer, so do not change it once people have logged in.
|
||||||
|
|
||||||
|
### Lore releases
|
||||||
|
|
||||||
|
`lore.lock` pins the Lore release and the SHA-256 of each archive. To fetch it on its own:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
scripts/fetch-lore.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
It prints the directory holding the binaries. Lore publishes binaries for macOS on Apple
|
||||||
|
silicon and for Linux on x86-64 and arm64. Elsewhere, build Lore from source and set
|
||||||
|
`LORE_BIN_DIR`.
|
||||||
|
|
||||||
|
To move to another release, run the e2e test before committing the new lock:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
scripts/fetch-lore.sh --pin vX.Y.Z
|
||||||
|
```
|
||||||
|
|
||||||
|
On macOS the `lore` CLI keeps the key for its stored logins in the keychain. Each `lore` process
|
||||||
|
asks for it until you choose **Always Allow**.
|
||||||
|
|
||||||
|
## Desktop client
|
||||||
|
|
||||||
|
[desktop/](desktop/README.md) holds a tray application and the per-user service it talks to.
|
||||||
|
They are early: the service simulates sync for now. It builds with Zig and Cargo, separately
|
||||||
|
from the server.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo test --workspace
|
||||||
|
scripts/e2e-lore.sh # against the pinned Lore release
|
||||||
|
SMOKE=1 scripts/e2e-lore.sh # one login, create and push only
|
||||||
|
```
|
||||||
|
|
||||||
|
Set `LORE_BIN_DIR` to test against another Lore build.
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
[package]
|
||||||
|
name = "forge-access"
|
||||||
|
description = "Namespaces, organisations, teams, grants and role presets"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
forge-store.workspace = true
|
||||||
|
sqlx.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
uuid.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
forge-store = { workspace = true, features = ["testing"] }
|
||||||
|
tokio.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
@ -0,0 +1,220 @@
|
||||||
|
//! Lore's actions and the role presets lore-forge presents on top of them.
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
/// An action Lore checks on a repository. Lore checks each one literally: none implies
|
||||||
|
/// another, except that any grant implies [`Action::Read`].
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
|
pub enum Action {
|
||||||
|
Read,
|
||||||
|
Write,
|
||||||
|
Owner,
|
||||||
|
Admin,
|
||||||
|
Migrate,
|
||||||
|
PushProtected,
|
||||||
|
SetProtected,
|
||||||
|
Obliterate,
|
||||||
|
Presign,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Action {
|
||||||
|
pub const ALL: [Action; 9] = [
|
||||||
|
Action::Read,
|
||||||
|
Action::Write,
|
||||||
|
Action::Owner,
|
||||||
|
Action::Admin,
|
||||||
|
Action::Migrate,
|
||||||
|
Action::PushProtected,
|
||||||
|
Action::SetProtected,
|
||||||
|
Action::Obliterate,
|
||||||
|
Action::Presign,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The name Lore uses in tokens.
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Action::Read => "read",
|
||||||
|
Action::Write => "write",
|
||||||
|
Action::Owner => "owner",
|
||||||
|
Action::Admin => "admin",
|
||||||
|
Action::Migrate => "migrate",
|
||||||
|
Action::PushProtected => "push-protected",
|
||||||
|
Action::SetProtected => "set-protected",
|
||||||
|
Action::Obliterate => "obliterate",
|
||||||
|
Action::Presign => "presign",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bit(self) -> u16 {
|
||||||
|
1 << (self as u16)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Action {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str(self.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
#[error("unknown Lore action '{0}'")]
|
||||||
|
pub struct UnknownAction(pub String);
|
||||||
|
|
||||||
|
impl FromStr for Action {
|
||||||
|
type Err = UnknownAction;
|
||||||
|
fn from_str(name: &str) -> Result<Self, Self::Err> {
|
||||||
|
Action::ALL
|
||||||
|
.into_iter()
|
||||||
|
.find(|action| action.as_str() == name)
|
||||||
|
.ok_or_else(|| UnknownAction(name.to_owned()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A set of actions held on one repository. A non-empty set always contains
|
||||||
|
/// [`Action::Read`], since any grant implies it, so sets compare by what they allow.
|
||||||
|
#[derive(Clone, Copy, Default, PartialEq, Eq)]
|
||||||
|
pub struct ActionSet(u16);
|
||||||
|
|
||||||
|
impl ActionSet {
|
||||||
|
pub const EMPTY: ActionSet = ActionSet(0);
|
||||||
|
|
||||||
|
pub fn of(actions: &[Action]) -> Self {
|
||||||
|
actions.iter().fold(Self::EMPTY, |set, action| set.with(*action))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with(self, action: Action) -> Self {
|
||||||
|
ActionSet(self.0 | action.bit() | Action::Read.bit())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn union(self, other: ActionSet) -> Self {
|
||||||
|
ActionSet(self.0 | other.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(self, action: Action) -> bool {
|
||||||
|
self.0 & action.bit() != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(self) -> bool {
|
||||||
|
self.0 == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The actions in a stable order.
|
||||||
|
pub fn to_vec(self) -> Vec<Action> {
|
||||||
|
Action::ALL.into_iter().filter(|action| self.contains(*action)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn names(self) -> Vec<&'static str> {
|
||||||
|
self.to_vec().into_iter().map(Action::as_str).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses a space-separated list, as stored in `grants.extra_actions`. Unknown names are
|
||||||
|
/// skipped and logged, so a stored value from a newer version never widens access.
|
||||||
|
pub fn parse_lenient(list: &str) -> Self {
|
||||||
|
list.split_ascii_whitespace()
|
||||||
|
.filter_map(|name| match name.parse::<Action>() {
|
||||||
|
Ok(action) => Some(action),
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!("ignoring stored grant: {error}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.fold(Self::EMPTY, ActionSet::with)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The space-separated form stored in `grants.extra_actions`. `read` is left out, being
|
||||||
|
/// implied.
|
||||||
|
pub fn to_stored(self) -> String {
|
||||||
|
Action::ALL
|
||||||
|
.into_iter()
|
||||||
|
.filter(|action| *action != Action::Read && self.contains(*action))
|
||||||
|
.map(Action::as_str)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for ActionSet {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_set().entries(self.names()).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A named bundle of actions, the way permissions are shown to people.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub enum Preset {
|
||||||
|
Reader,
|
||||||
|
Writer,
|
||||||
|
Maintainer,
|
||||||
|
Admin,
|
||||||
|
Owner,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Preset {
|
||||||
|
pub const ALL: [Preset; 5] = [
|
||||||
|
Preset::Reader,
|
||||||
|
Preset::Writer,
|
||||||
|
Preset::Maintainer,
|
||||||
|
Preset::Admin,
|
||||||
|
Preset::Owner,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The Lore actions a preset grants. No preset includes `push-protected`: on a
|
||||||
|
/// review-gated branch lore-forge's landing identity is the only holder.
|
||||||
|
pub fn actions(self) -> ActionSet {
|
||||||
|
use Action::*;
|
||||||
|
match self {
|
||||||
|
Preset::Reader => ActionSet::of(&[Read]),
|
||||||
|
Preset::Writer => ActionSet::of(&[Write]),
|
||||||
|
Preset::Maintainer => ActionSet::of(&[Write, SetProtected]),
|
||||||
|
Preset::Admin => ActionSet::of(&[Write, Admin]),
|
||||||
|
Preset::Owner => ActionSet::of(&[Write, Owner]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The name stored in the database.
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Preset::Reader => "reader",
|
||||||
|
Preset::Writer => "writer",
|
||||||
|
Preset::Maintainer => "maintainer",
|
||||||
|
Preset::Admin => "admin",
|
||||||
|
Preset::Owner => "owner",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(name: &str) -> Option<Preset> {
|
||||||
|
Preset::ALL.into_iter().find(|preset| preset.as_str() == name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn owner_includes_write_because_lore_does_not_imply_it() {
|
||||||
|
assert!(Preset::Owner.actions().contains(Action::Write));
|
||||||
|
assert!(Preset::Owner.actions().contains(Action::Owner));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_preset_holds_push_protected() {
|
||||||
|
for preset in Preset::ALL {
|
||||||
|
assert!(!preset.actions().contains(Action::PushProtected), "{preset:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn any_grant_lists_read() {
|
||||||
|
assert_eq!(Preset::Writer.actions().names(), ["read", "write"]);
|
||||||
|
assert!(ActionSet::EMPTY.names().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stored_form_round_trips_and_ignores_unknown_names() {
|
||||||
|
let set = ActionSet::of(&[Action::Obliterate, Action::Presign]);
|
||||||
|
assert_eq!(ActionSet::parse_lenient(&set.to_stored()), set);
|
||||||
|
assert_eq!(ActionSet::parse_lenient("presign fly"), ActionSet::of(&[Action::Presign]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,137 @@
|
||||||
|
//! Namespaces, organisations, teams, grants and their resolution into Lore actions.
|
||||||
|
//!
|
||||||
|
//! Resolution runs on every token exchange, so [`resolve`] answers from a few indexed reads
|
||||||
|
//! and never writes.
|
||||||
|
|
||||||
|
pub mod actions;
|
||||||
|
pub mod names;
|
||||||
|
pub mod orgs;
|
||||||
|
pub mod repos;
|
||||||
|
|
||||||
|
pub use actions::Action;
|
||||||
|
pub use actions::ActionSet;
|
||||||
|
pub use actions::Preset;
|
||||||
|
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
|
||||||
|
/// The actions `user_id` holds on the repository `repo_id`: the union of their personal
|
||||||
|
/// namespace, organisation role and base permission, team grants and direct grants.
|
||||||
|
/// Empty when they hold nothing, including when the repository is unknown.
|
||||||
|
pub async fn resolve(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
user_id: &str,
|
||||||
|
repo_id: &str,
|
||||||
|
) -> Result<ActionSet, sqlx::Error> {
|
||||||
|
let rows: Vec<(Option<String>, String)> = sqlx::query_as(
|
||||||
|
"SELECT 'owner', ''
|
||||||
|
FROM repos r JOIN namespaces n ON n.name = r.namespace
|
||||||
|
WHERE r.id = ?1 AND n.kind = 'user' AND n.user_id = ?2
|
||||||
|
UNION ALL
|
||||||
|
SELECT CASE WHEN m.role = 'owner' THEN 'owner' ELSE o.base_preset END, ''
|
||||||
|
FROM repos r
|
||||||
|
JOIN namespaces n ON n.name = r.namespace
|
||||||
|
JOIN orgs o ON o.id = n.org_id
|
||||||
|
JOIN org_members m ON m.org_id = o.id AND m.user_id = ?2
|
||||||
|
WHERE r.id = ?1
|
||||||
|
UNION ALL
|
||||||
|
SELECT g.preset, g.extra_actions
|
||||||
|
FROM grants g
|
||||||
|
JOIN team_members t ON g.subject_kind = 'team' AND g.subject_id = t.team_id
|
||||||
|
WHERE g.repo_id = ?1 AND t.user_id = ?2
|
||||||
|
UNION ALL
|
||||||
|
SELECT g.preset, g.extra_actions
|
||||||
|
FROM grants g
|
||||||
|
WHERE g.repo_id = ?1 AND g.subject_kind = 'user' AND g.subject_id = ?2",
|
||||||
|
)
|
||||||
|
.bind(repo_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(rows.into_iter().fold(ActionSet::EMPTY, |set, (preset, extra)| {
|
||||||
|
let preset = preset
|
||||||
|
.as_deref()
|
||||||
|
.and_then(Preset::parse)
|
||||||
|
.map_or(ActionSet::EMPTY, Preset::actions);
|
||||||
|
set.union(preset).union(ActionSet::parse_lenient(&extra))
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates the personal namespace for a new user, inside the caller's transaction.
|
||||||
|
pub async fn create_user_namespace(
|
||||||
|
conn: &mut sqlx::SqliteConnection,
|
||||||
|
username: &str,
|
||||||
|
user_id: &str,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query("INSERT INTO namespaces (name, kind, user_id) VALUES (?, 'user', ?)")
|
||||||
|
.bind(username)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(conn)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a top-level name refers to.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Namespace {
|
||||||
|
User { name: String, user_id: String },
|
||||||
|
Org { name: String, org_id: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Namespace {
|
||||||
|
pub fn name(&self) -> &str {
|
||||||
|
match self {
|
||||||
|
Namespace::User { name, .. } | Namespace::Org { name, .. } => name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn namespace(pool: &SqlitePool, name: &str) -> Result<Option<Namespace>, sqlx::Error> {
|
||||||
|
let row: Option<(String, String, Option<String>, Option<String>)> =
|
||||||
|
sqlx::query_as("SELECT name, kind, user_id, org_id FROM namespaces WHERE name = ?")
|
||||||
|
.bind(name)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(row.and_then(|(name, kind, user_id, org_id)| match (kind.as_str(), user_id, org_id) {
|
||||||
|
("user", Some(user_id), _) => Some(Namespace::User { name, user_id }),
|
||||||
|
("org", _, Some(org_id)) => Some(Namespace::Org { name, org_id }),
|
||||||
|
_ => None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a user or organisation already holds `name`.
|
||||||
|
pub async fn namespace_taken(pool: &SqlitePool, name: &str) -> Result<bool, sqlx::Error> {
|
||||||
|
let found: Option<(String,)> = sqlx::query_as("SELECT name FROM namespaces WHERE name = ?")
|
||||||
|
.bind(name)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(found.is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test fixtures shared by this crate's tests.
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) mod fixtures {
|
||||||
|
use forge_store::sqlx;
|
||||||
|
|
||||||
|
pub async fn user(pool: &forge_store::SqlitePool, name: &str) -> String {
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let mut tx = pool.begin().await.unwrap();
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO users (id, username, display_name, instance_role, created_at)
|
||||||
|
VALUES (?, ?, ?, 'member', 0)",
|
||||||
|
)
|
||||||
|
.bind(&id)
|
||||||
|
.bind(name)
|
||||||
|
.bind(name)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
super::create_user_namespace(&mut tx, name, &id).await.unwrap();
|
||||||
|
tx.commit().await.unwrap();
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn repo_id(n: u8) -> String {
|
||||||
|
format!("{n:02x}").repeat(16)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,91 @@
|
||||||
|
//! Rules for namespace and repository names.
|
||||||
|
|
||||||
|
/// Words that occupy the top level of the web UI's paths, so no user or organisation may be
|
||||||
|
/// named after them.
|
||||||
|
const RESERVED: &[&str] = &[
|
||||||
|
".well-known", "about", "admin", "api", "assets", "device", "explore", "favicon.ico",
|
||||||
|
"health", "help", "licenses", "login", "logout", "new", "oauth", "org", "orgs", "raw", "robots.txt",
|
||||||
|
"settings", "setup", "signup", "static", "user", "users",
|
||||||
|
];
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum NameError {
|
||||||
|
#[error("names must be 1 to 39 characters")]
|
||||||
|
Length,
|
||||||
|
#[error("names may contain only lowercase letters, digits and single hyphens, and may not start or end with a hyphen")]
|
||||||
|
Characters,
|
||||||
|
#[error("'{0}' is reserved")]
|
||||||
|
Reserved(String),
|
||||||
|
#[error("repository names have the form owner/name")]
|
||||||
|
NotOwnerSlashName,
|
||||||
|
#[error("repository names may contain only letters, digits, '-', '_' and '.', and may not start with '.'")]
|
||||||
|
RepositoryCharacters,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks a username or organisation name. They share one table and the top level of the
|
||||||
|
/// URL space, so the rule is the same for both: lowercase ASCII letters and digits with
|
||||||
|
/// single interior hyphens, as on GitHub.
|
||||||
|
pub fn check_namespace(name: &str) -> Result<(), NameError> {
|
||||||
|
if name.is_empty() || name.len() > 39 {
|
||||||
|
return Err(NameError::Length);
|
||||||
|
}
|
||||||
|
let valid_chars = name
|
||||||
|
.bytes()
|
||||||
|
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-');
|
||||||
|
if !valid_chars || name.starts_with('-') || name.ends_with('-') || name.contains("--") {
|
||||||
|
return Err(NameError::Characters);
|
||||||
|
}
|
||||||
|
if RESERVED.contains(&name) {
|
||||||
|
return Err(NameError::Reserved(name.to_owned()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks one segment of a Lore repository name: ASCII alphanumerics, `-`, `_` and `.`,
|
||||||
|
/// not empty and not starting with `.`. This is Lore's own rule.
|
||||||
|
fn check_repository_segment(segment: &str) -> Result<(), NameError> {
|
||||||
|
let valid = !segment.is_empty()
|
||||||
|
&& segment.len() <= 100
|
||||||
|
&& !segment.starts_with('.')
|
||||||
|
&& segment
|
||||||
|
.bytes()
|
||||||
|
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'));
|
||||||
|
if valid { Ok(()) } else { Err(NameError::RepositoryCharacters) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits a Lore repository name into its owner and repository parts, checking both.
|
||||||
|
pub fn split_repository_name(full: &str) -> Result<(&str, &str), NameError> {
|
||||||
|
let mut parts = full.split('/');
|
||||||
|
let (Some(owner), Some(name), None) = (parts.next(), parts.next(), parts.next()) else {
|
||||||
|
return Err(NameError::NotOwnerSlashName);
|
||||||
|
};
|
||||||
|
check_namespace(owner)?;
|
||||||
|
check_repository_segment(name)?;
|
||||||
|
Ok((owner, name))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn namespace_names() {
|
||||||
|
assert!(check_namespace("studio").is_ok());
|
||||||
|
assert!(check_namespace("a-b-1").is_ok());
|
||||||
|
assert_eq!(check_namespace(""), Err(NameError::Length));
|
||||||
|
assert_eq!(check_namespace("Studio"), Err(NameError::Characters));
|
||||||
|
assert_eq!(check_namespace("-a"), Err(NameError::Characters));
|
||||||
|
assert_eq!(check_namespace("a--b"), Err(NameError::Characters));
|
||||||
|
assert!(matches!(check_namespace("settings"), Err(NameError::Reserved(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repository_names() {
|
||||||
|
assert_eq!(split_repository_name("studio/game"), Ok(("studio", "game")));
|
||||||
|
assert_eq!(split_repository_name("studio/Game_v2.x"), Ok(("studio", "Game_v2.x")));
|
||||||
|
assert_eq!(split_repository_name("game"), Err(NameError::NotOwnerSlashName));
|
||||||
|
assert_eq!(split_repository_name("a/b/c"), Err(NameError::NotOwnerSlashName));
|
||||||
|
assert_eq!(split_repository_name("studio/.git"), Err(NameError::RepositoryCharacters));
|
||||||
|
assert_eq!(split_repository_name("studio/"), Err(NameError::RepositoryCharacters));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,498 @@
|
||||||
|
//! Organisations, their members and teams, and repository grants.
|
||||||
|
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
|
||||||
|
use crate::ActionSet;
|
||||||
|
use crate::Preset;
|
||||||
|
use crate::names;
|
||||||
|
use crate::names::NameError;
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum OrgError {
|
||||||
|
#[error(transparent)]
|
||||||
|
InvalidName(#[from] NameError),
|
||||||
|
#[error("the name '{0}' is taken")]
|
||||||
|
NameTaken(String),
|
||||||
|
#[error("a team can only be granted access to its own organisation's repositories")]
|
||||||
|
TeamOutsideOrg,
|
||||||
|
#[error("no such repository, team or organisation")]
|
||||||
|
NotFound,
|
||||||
|
#[error("an organisation must keep at least one owner")]
|
||||||
|
LastOwner,
|
||||||
|
#[error("display names must be 1 to 100 characters")]
|
||||||
|
InvalidDisplayName,
|
||||||
|
#[error("the base permission cannot be Owner")]
|
||||||
|
OwnerBase,
|
||||||
|
#[error("only members of the organisation can join its teams")]
|
||||||
|
NotAMember,
|
||||||
|
#[error(transparent)]
|
||||||
|
Database(#[from] sqlx::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum OrgRole {
|
||||||
|
Owner,
|
||||||
|
Member,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OrgRole {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
OrgRole::Owner => "owner",
|
||||||
|
OrgRole::Member => "member",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(text: &str) -> Option<OrgRole> {
|
||||||
|
match text {
|
||||||
|
"owner" => Some(OrgRole::Owner),
|
||||||
|
"member" => Some(OrgRole::Member),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Org {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub display_name: String,
|
||||||
|
pub base_preset: Option<Preset>,
|
||||||
|
pub members_can_create_repos: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct OrgRow {
|
||||||
|
id: String,
|
||||||
|
name: String,
|
||||||
|
display_name: String,
|
||||||
|
base_preset: Option<String>,
|
||||||
|
members_can_create_repos: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<OrgRow> for Org {
|
||||||
|
fn from(row: OrgRow) -> Self {
|
||||||
|
Org {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
display_name: row.display_name,
|
||||||
|
base_preset: row.base_preset.as_deref().and_then(Preset::parse),
|
||||||
|
members_can_create_repos: row.members_can_create_repos,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! select_org {
|
||||||
|
($tail:literal) => {
|
||||||
|
concat!(
|
||||||
|
"SELECT o.id, n.name, o.display_name, o.base_preset, o.members_can_create_repos
|
||||||
|
FROM orgs o JOIN namespaces n ON n.org_id = o.id ",
|
||||||
|
$tail
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, sqlx::FromRow)]
|
||||||
|
pub struct Member {
|
||||||
|
pub user_id: String,
|
||||||
|
pub username: String,
|
||||||
|
pub display_name: String,
|
||||||
|
pub role: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, sqlx::FromRow)]
|
||||||
|
pub struct Team {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub members: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct GrantRow {
|
||||||
|
pub subject: GrantSubject,
|
||||||
|
pub preset: Option<Preset>,
|
||||||
|
pub extra: ActionSet,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum GrantSubject {
|
||||||
|
User { id: String, username: String },
|
||||||
|
Team { id: String, name: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find(pool: &SqlitePool, name: &str) -> Result<Option<Org>, sqlx::Error> {
|
||||||
|
let row: Option<OrgRow> = sqlx::query_as(select_org!("WHERE n.name = ?"))
|
||||||
|
.bind(name)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(row.map(Org::from))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list_all(pool: &SqlitePool) -> Result<Vec<Org>, sqlx::Error> {
|
||||||
|
let rows: Vec<OrgRow> = sqlx::query_as(select_org!("ORDER BY n.name")).fetch_all(pool).await?;
|
||||||
|
Ok(rows.into_iter().map(Org::from).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The organisations `user_id` belongs to, with their role in each.
|
||||||
|
pub async fn list_for_user(pool: &SqlitePool, user_id: &str) -> Result<Vec<(Org, OrgRole)>, sqlx::Error> {
|
||||||
|
let rows: Vec<OrgRow> = sqlx::query_as(select_org!(
|
||||||
|
"JOIN org_members m ON m.org_id = o.id WHERE m.user_id = ? ORDER BY n.name"
|
||||||
|
))
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
let mut listed = Vec::with_capacity(rows.len());
|
||||||
|
for row in rows {
|
||||||
|
let org = Org::from(row);
|
||||||
|
if let Some(role) = role_of(pool, &org.id, user_id).await? {
|
||||||
|
listed.push((org, role));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(listed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn role_of(pool: &SqlitePool, org_id: &str, user_id: &str) -> Result<Option<OrgRole>, sqlx::Error> {
|
||||||
|
let row: Option<(String,)> = sqlx::query_as("SELECT role FROM org_members WHERE org_id = ? AND user_id = ?")
|
||||||
|
.bind(org_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(row.and_then(|(role,)| OrgRole::parse(&role)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn members(pool: &SqlitePool, org_id: &str) -> Result<Vec<Member>, sqlx::Error> {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT u.id AS user_id, u.username, u.display_name, m.role
|
||||||
|
FROM org_members m JOIN users u ON u.id = m.user_id
|
||||||
|
WHERE m.org_id = ? ORDER BY m.role DESC, u.username",
|
||||||
|
)
|
||||||
|
.bind(org_id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn other_owners(pool: &SqlitePool, org_id: &str, user_id: &str) -> Result<i64, sqlx::Error> {
|
||||||
|
let (count,): (i64,) = sqlx::query_as(
|
||||||
|
"SELECT count(*) FROM org_members WHERE org_id = ? AND role = 'owner' AND user_id != ?",
|
||||||
|
)
|
||||||
|
.bind(org_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(count)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes a member's role. An organisation always keeps one owner.
|
||||||
|
pub async fn set_member_role(pool: &SqlitePool, org_id: &str, user_id: &str, role: OrgRole) -> Result<(), OrgError> {
|
||||||
|
if role != OrgRole::Owner && other_owners(pool, org_id, user_id).await? == 0 {
|
||||||
|
return Err(OrgError::LastOwner);
|
||||||
|
}
|
||||||
|
sqlx::query("UPDATE org_members SET role = ? WHERE org_id = ? AND user_id = ?")
|
||||||
|
.bind(role.as_str())
|
||||||
|
.bind(org_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes a member from the organisation and its teams. An organisation always keeps one
|
||||||
|
/// owner.
|
||||||
|
pub async fn remove_member(pool: &SqlitePool, org_id: &str, user_id: &str) -> Result<(), OrgError> {
|
||||||
|
if other_owners(pool, org_id, user_id).await? == 0 {
|
||||||
|
return Err(OrgError::LastOwner);
|
||||||
|
}
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query(
|
||||||
|
"DELETE FROM team_members WHERE user_id = ? AND team_id IN (SELECT id FROM teams WHERE org_id = ?)",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(org_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("DELETE FROM org_members WHERE org_id = ? AND user_id = ?")
|
||||||
|
.bind(org_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
org_id: &str,
|
||||||
|
display_name: &str,
|
||||||
|
base_preset: Option<Preset>,
|
||||||
|
members_can_create_repos: bool,
|
||||||
|
) -> Result<(), OrgError> {
|
||||||
|
let display_name = display_name.trim();
|
||||||
|
if display_name.is_empty() || display_name.chars().count() > 100 {
|
||||||
|
return Err(OrgError::InvalidDisplayName);
|
||||||
|
}
|
||||||
|
if base_preset == Some(Preset::Owner) {
|
||||||
|
return Err(OrgError::OwnerBase);
|
||||||
|
}
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE orgs SET display_name = ?, base_preset = ?, members_can_create_repos = ? WHERE id = ?",
|
||||||
|
)
|
||||||
|
.bind(display_name)
|
||||||
|
.bind(base_preset.map(Preset::as_str))
|
||||||
|
.bind(members_can_create_repos)
|
||||||
|
.bind(org_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn teams(pool: &SqlitePool, org_id: &str) -> Result<Vec<Team>, sqlx::Error> {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT t.id, t.name, (SELECT count(*) FROM team_members m WHERE m.team_id = t.id) AS members
|
||||||
|
FROM teams t WHERE t.org_id = ? ORDER BY t.name",
|
||||||
|
)
|
||||||
|
.bind(org_id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find_team(pool: &SqlitePool, org_id: &str, name: &str) -> Result<Option<Team>, sqlx::Error> {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT t.id, t.name, (SELECT count(*) FROM team_members m WHERE m.team_id = t.id) AS members
|
||||||
|
FROM teams t WHERE t.org_id = ? AND t.name = ?",
|
||||||
|
)
|
||||||
|
.bind(org_id)
|
||||||
|
.bind(name)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn team_members(pool: &SqlitePool, team_id: &str) -> Result<Vec<Member>, sqlx::Error> {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT u.id AS user_id, u.username, u.display_name, '' AS role
|
||||||
|
FROM team_members m JOIN users u ON u.id = m.user_id
|
||||||
|
WHERE m.team_id = ? ORDER BY u.username",
|
||||||
|
)
|
||||||
|
.bind(team_id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn remove_team_member(pool: &SqlitePool, team_id: &str, user_id: &str) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query("DELETE FROM team_members WHERE team_id = ? AND user_id = ?")
|
||||||
|
.bind(team_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes a team and its grants.
|
||||||
|
pub async fn delete_team(pool: &SqlitePool, team_id: &str) -> Result<(), sqlx::Error> {
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query("DELETE FROM grants WHERE subject_kind = 'team' AND subject_id = ?")
|
||||||
|
.bind(team_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("DELETE FROM teams WHERE id = ?").bind(team_id).execute(&mut *tx).await?;
|
||||||
|
tx.commit().await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every grant on a repository, users first.
|
||||||
|
pub async fn grants(pool: &SqlitePool, repo_id: &str) -> Result<Vec<GrantRow>, sqlx::Error> {
|
||||||
|
let rows: Vec<(String, String, String, Option<String>, String)> = sqlx::query_as(
|
||||||
|
"SELECT g.subject_kind, g.subject_id, coalesce(u.username, t.name, '?'), g.preset, g.extra_actions
|
||||||
|
FROM grants g
|
||||||
|
LEFT JOIN users u ON g.subject_kind = 'user' AND u.id = g.subject_id
|
||||||
|
LEFT JOIN teams t ON g.subject_kind = 'team' AND t.id = g.subject_id
|
||||||
|
WHERE g.repo_id = ?
|
||||||
|
ORDER BY g.subject_kind DESC, 3",
|
||||||
|
)
|
||||||
|
.bind(repo_id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|(kind, id, label, preset, extra)| GrantRow {
|
||||||
|
subject: if kind == "team" {
|
||||||
|
GrantSubject::Team { id, name: label }
|
||||||
|
} else {
|
||||||
|
GrantSubject::User { id, username: label }
|
||||||
|
},
|
||||||
|
preset: preset.as_deref().and_then(Preset::parse),
|
||||||
|
extra: ActionSet::parse_lenient(&extra),
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Who a grant is for.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub enum Subject<'a> {
|
||||||
|
User(&'a str),
|
||||||
|
Team(&'a str),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an organisation named `name` with `creator_id` as its first owner. Returns the
|
||||||
|
/// organisation ID.
|
||||||
|
pub async fn create(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
name: &str,
|
||||||
|
display_name: &str,
|
||||||
|
creator_id: &str,
|
||||||
|
) -> Result<String, OrgError> {
|
||||||
|
names::check_namespace(name)?;
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query("INSERT INTO orgs (id, display_name, created_at) VALUES (?, ?, ?)")
|
||||||
|
.bind(&id)
|
||||||
|
.bind(display_name)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
let named = sqlx::query("INSERT INTO namespaces (name, kind, org_id) VALUES (?, 'org', ?)")
|
||||||
|
.bind(name)
|
||||||
|
.bind(&id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await;
|
||||||
|
match named {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(error) if forge_store::is_unique_violation(&error) => {
|
||||||
|
return Err(OrgError::NameTaken(name.to_owned()));
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
}
|
||||||
|
sqlx::query("INSERT INTO org_members (org_id, user_id, role) VALUES (?, ?, 'owner')")
|
||||||
|
.bind(&id)
|
||||||
|
.bind(creator_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
forge_store::audit(&mut *tx, Some(creator_id), "org.create", name, &id).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds `user_id` to the organisation, or changes their role if already a member.
|
||||||
|
pub async fn add_member(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
org_id: &str,
|
||||||
|
user_id: &str,
|
||||||
|
role: OrgRole,
|
||||||
|
) -> Result<(), OrgError> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO org_members (org_id, user_id, role) VALUES (?, ?, ?)
|
||||||
|
ON CONFLICT (org_id, user_id) DO UPDATE SET role = excluded.role",
|
||||||
|
)
|
||||||
|
.bind(org_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(role.as_str())
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_base_preset(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
org_id: &str,
|
||||||
|
preset: Option<Preset>,
|
||||||
|
) -> Result<(), OrgError> {
|
||||||
|
if preset == Some(Preset::Owner) {
|
||||||
|
// Owner on every repository would let every member delete them.
|
||||||
|
return Err(OrgError::OwnerBase);
|
||||||
|
}
|
||||||
|
sqlx::query("UPDATE orgs SET base_preset = ? WHERE id = ?")
|
||||||
|
.bind(preset.map(Preset::as_str))
|
||||||
|
.bind(org_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_team(pool: &SqlitePool, org_id: &str, name: &str) -> Result<String, OrgError> {
|
||||||
|
names::check_namespace(name)?;
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let created = sqlx::query("INSERT INTO teams (id, org_id, name) VALUES (?, ?, ?)")
|
||||||
|
.bind(&id)
|
||||||
|
.bind(org_id)
|
||||||
|
.bind(name)
|
||||||
|
.execute(pool)
|
||||||
|
.await;
|
||||||
|
match created {
|
||||||
|
Ok(_) => Ok(id),
|
||||||
|
Err(error) if forge_store::is_unique_violation(&error) => {
|
||||||
|
Err(OrgError::NameTaken(name.to_owned()))
|
||||||
|
}
|
||||||
|
Err(error) => Err(error.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn add_team_member(pool: &SqlitePool, team_id: &str, user_id: &str) -> Result<(), OrgError> {
|
||||||
|
let member: Option<(i64,)> = sqlx::query_as(
|
||||||
|
"SELECT 1 FROM teams t JOIN org_members m ON m.org_id = t.org_id WHERE t.id = ? AND m.user_id = ?",
|
||||||
|
)
|
||||||
|
.bind(team_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
if member.is_none() {
|
||||||
|
return Err(OrgError::NotAMember);
|
||||||
|
}
|
||||||
|
sqlx::query("INSERT OR IGNORE INTO team_members (team_id, user_id) VALUES (?, ?)")
|
||||||
|
.bind(team_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets a subject's grant on a repository, replacing any earlier one. A grant with no preset
|
||||||
|
/// and no extra actions removes it.
|
||||||
|
pub async fn set_grant(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
repo_id: &str,
|
||||||
|
subject: Subject<'_>,
|
||||||
|
preset: Option<Preset>,
|
||||||
|
extra: ActionSet,
|
||||||
|
) -> Result<(), OrgError> {
|
||||||
|
let (kind, subject_id) = match subject {
|
||||||
|
Subject::User(id) => ("user", id),
|
||||||
|
Subject::Team(id) => ("team", id),
|
||||||
|
};
|
||||||
|
if let Subject::Team(team_id) = subject {
|
||||||
|
let same_org: Option<(i64,)> = sqlx::query_as(
|
||||||
|
"SELECT 1 FROM teams t
|
||||||
|
JOIN namespaces n ON n.org_id = t.org_id
|
||||||
|
JOIN repos r ON r.namespace = n.name
|
||||||
|
WHERE t.id = ? AND r.id = ?",
|
||||||
|
)
|
||||||
|
.bind(team_id)
|
||||||
|
.bind(repo_id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
if same_org.is_none() {
|
||||||
|
return Err(OrgError::TeamOutsideOrg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if preset.is_none() && extra.is_empty() {
|
||||||
|
sqlx::query("DELETE FROM grants WHERE repo_id = ? AND subject_kind = ? AND subject_id = ?")
|
||||||
|
.bind(repo_id)
|
||||||
|
.bind(kind)
|
||||||
|
.bind(subject_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO grants (repo_id, subject_kind, subject_id, preset, extra_actions)
|
||||||
|
VALUES (?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT (repo_id, subject_kind, subject_id)
|
||||||
|
DO UPDATE SET preset = excluded.preset, extra_actions = excluded.extra_actions",
|
||||||
|
)
|
||||||
|
.bind(repo_id)
|
||||||
|
.bind(kind)
|
||||||
|
.bind(subject_id)
|
||||||
|
.bind(preset.map(Preset::as_str))
|
||||||
|
.bind(extra.to_stored())
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,377 @@
|
||||||
|
//! Repositories as the registry sees them: registering, unregistering and listing.
|
||||||
|
//!
|
||||||
|
//! `loreserver` calls these through `lore.user.v1.RepositoryRegistryService` before it
|
||||||
|
//! creates or deletes a repository, so they are where namespaces are enforced.
|
||||||
|
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
|
||||||
|
use crate::Action;
|
||||||
|
use crate::ActionSet;
|
||||||
|
use crate::names;
|
||||||
|
use crate::names::NameError;
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum RegistryError {
|
||||||
|
#[error(transparent)]
|
||||||
|
InvalidName(#[from] NameError),
|
||||||
|
#[error("repository IDs are 16 bytes")]
|
||||||
|
InvalidId,
|
||||||
|
#[error("no user or organisation is named '{0}'")]
|
||||||
|
NamespaceNotFound(String),
|
||||||
|
#[error("you may not do this in '{0}'")]
|
||||||
|
PermissionDenied(String),
|
||||||
|
#[error("the repository ID or name is already registered")]
|
||||||
|
AlreadyExists,
|
||||||
|
#[error(transparent)]
|
||||||
|
Database(#[from] sqlx::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, sqlx::FromRow)]
|
||||||
|
pub struct Repo {
|
||||||
|
pub id: String,
|
||||||
|
pub namespace: String,
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Repo {
|
||||||
|
pub fn full_name(&self) -> String {
|
||||||
|
format!("{}/{}", self.namespace, self.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Lore repository ID in the form lore-forge stores and tokens carry: 32 lowercase hex
|
||||||
|
/// digits. `None` unless `bytes` is exactly 16 bytes.
|
||||||
|
pub fn id_from_bytes(bytes: &[u8]) -> Option<String> {
|
||||||
|
(bytes.len() == 16).then(|| bytes.iter().map(|byte| format!("{byte:02x}")).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `id` is a stored-form repository ID.
|
||||||
|
pub fn is_valid_id(id: &str) -> bool {
|
||||||
|
id.len() == 32 && id.bytes().all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct NamespaceRow {
|
||||||
|
name: String,
|
||||||
|
kind: String,
|
||||||
|
user_id: Option<String>,
|
||||||
|
org_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `user_id` may create repositories in `namespace`.
|
||||||
|
async fn may_create_in(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
user_id: &str,
|
||||||
|
namespace: &NamespaceRow,
|
||||||
|
) -> Result<bool, sqlx::Error> {
|
||||||
|
match namespace.kind.as_str() {
|
||||||
|
"user" => Ok(namespace.user_id.as_deref() == Some(user_id)),
|
||||||
|
"org" => {
|
||||||
|
let row: Option<(String, bool)> = sqlx::query_as(
|
||||||
|
"SELECT m.role, o.members_can_create_repos
|
||||||
|
FROM org_members m JOIN orgs o ON o.id = m.org_id
|
||||||
|
WHERE m.org_id = ? AND m.user_id = ?",
|
||||||
|
)
|
||||||
|
.bind(&namespace.org_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(matches!(row, Some((role, members_may)) if role == "owner" || members_may))
|
||||||
|
}
|
||||||
|
_ => Ok(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Registers the repository `loreserver` is about to create. Registering the same ID under
|
||||||
|
/// the same name again succeeds, so a retried create does too.
|
||||||
|
pub async fn register(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
user_id: &str,
|
||||||
|
id: &[u8],
|
||||||
|
full_name: &str,
|
||||||
|
) -> Result<Repo, RegistryError> {
|
||||||
|
let id = id_from_bytes(id).ok_or(RegistryError::InvalidId)?;
|
||||||
|
let (owner, name) = names::split_repository_name(full_name)?;
|
||||||
|
let namespace: NamespaceRow =
|
||||||
|
sqlx::query_as("SELECT name, kind, user_id, org_id FROM namespaces WHERE name = ?")
|
||||||
|
.bind(owner)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| RegistryError::NamespaceNotFound(owner.to_owned()))?;
|
||||||
|
if !may_create_in(pool, user_id, &namespace).await? {
|
||||||
|
return Err(RegistryError::PermissionDenied(namespace.name));
|
||||||
|
}
|
||||||
|
let existing: Option<Repo> =
|
||||||
|
sqlx::query_as("SELECT id, namespace, name FROM repos WHERE id = ?")
|
||||||
|
.bind(&id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
if let Some(existing) = existing {
|
||||||
|
let same = existing.namespace.eq_ignore_ascii_case(&namespace.name)
|
||||||
|
&& existing.name.eq_ignore_ascii_case(name);
|
||||||
|
return if same { Ok(existing) } else { Err(RegistryError::AlreadyExists) };
|
||||||
|
}
|
||||||
|
let repo = Repo { id, namespace: namespace.name, name: name.to_owned() };
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
let inserted = sqlx::query(
|
||||||
|
"INSERT INTO repos (id, namespace, name, created_by, created_at) VALUES (?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(&repo.id)
|
||||||
|
.bind(&repo.namespace)
|
||||||
|
.bind(&repo.name)
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await;
|
||||||
|
match inserted {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(error) if forge_store::is_unique_violation(&error) => {
|
||||||
|
return Err(RegistryError::AlreadyExists);
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
}
|
||||||
|
forge_store::audit(&mut *tx, Some(user_id), "repo.create", &repo.full_name(), &repo.id).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(repo)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unregisters a repository `loreserver` is about to delete. Only an Owner may. A
|
||||||
|
/// repository that is not registered unregisters successfully.
|
||||||
|
pub async fn unregister(pool: &SqlitePool, user_id: &str, id: &[u8]) -> Result<(), RegistryError> {
|
||||||
|
let id = id_from_bytes(id).ok_or(RegistryError::InvalidId)?;
|
||||||
|
let Some(repo) = get(pool, &id).await? else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
if !crate::resolve(pool, user_id, &id).await?.contains(Action::Owner) {
|
||||||
|
return Err(RegistryError::PermissionDenied(repo.full_name()));
|
||||||
|
}
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query("DELETE FROM repos WHERE id = ?").bind(&id).execute(&mut *tx).await?;
|
||||||
|
forge_store::audit(&mut *tx, Some(user_id), "repo.delete", &repo.full_name(), &id).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get(pool: &SqlitePool, id: &str) -> Result<Option<Repo>, sqlx::Error> {
|
||||||
|
sqlx::query_as("SELECT id, namespace, name FROM repos WHERE id = ?")
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find_by_name(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
namespace: &str,
|
||||||
|
name: &str,
|
||||||
|
) -> Result<Option<Repo>, sqlx::Error> {
|
||||||
|
sqlx::query_as("SELECT id, namespace, name FROM repos WHERE namespace = ? AND name = ?")
|
||||||
|
.bind(namespace)
|
||||||
|
.bind(name)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every repository `user_id` holds any action on, with those actions, ordered by name.
|
||||||
|
pub async fn list_for_user(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
user_id: &str,
|
||||||
|
) -> Result<Vec<(Repo, ActionSet)>, sqlx::Error> {
|
||||||
|
let candidates: Vec<Repo> = sqlx::query_as(
|
||||||
|
"SELECT r.id, r.namespace, r.name FROM repos r WHERE r.id IN (
|
||||||
|
SELECT r.id FROM repos r JOIN namespaces n ON n.name = r.namespace
|
||||||
|
WHERE n.kind = 'user' AND n.user_id = ?1
|
||||||
|
UNION
|
||||||
|
SELECT r.id FROM repos r
|
||||||
|
JOIN namespaces n ON n.name = r.namespace
|
||||||
|
JOIN orgs o ON o.id = n.org_id
|
||||||
|
JOIN org_members m ON m.org_id = o.id AND m.user_id = ?1
|
||||||
|
WHERE m.role = 'owner' OR o.base_preset IS NOT NULL
|
||||||
|
UNION
|
||||||
|
SELECT g.repo_id FROM grants g
|
||||||
|
JOIN team_members t ON g.subject_kind = 'team' AND g.subject_id = t.team_id
|
||||||
|
WHERE t.user_id = ?1
|
||||||
|
UNION
|
||||||
|
SELECT g.repo_id FROM grants g WHERE g.subject_kind = 'user' AND g.subject_id = ?1
|
||||||
|
) ORDER BY r.namespace, r.name",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
let mut listed = Vec::with_capacity(candidates.len());
|
||||||
|
for repo in candidates {
|
||||||
|
let actions = crate::resolve(pool, user_id, &repo.id).await?;
|
||||||
|
if !actions.is_empty() {
|
||||||
|
listed.push((repo, actions));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(listed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The repositories of one namespace that `viewer_id` holds any action on, with those actions.
|
||||||
|
pub async fn list_in_namespace(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
namespace: &str,
|
||||||
|
viewer_id: &str,
|
||||||
|
) -> Result<Vec<(Repo, ActionSet)>, sqlx::Error> {
|
||||||
|
let repos: Vec<Repo> =
|
||||||
|
sqlx::query_as("SELECT id, namespace, name FROM repos WHERE namespace = ? ORDER BY name")
|
||||||
|
.bind(namespace)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
let mut listed = Vec::with_capacity(repos.len());
|
||||||
|
for repo in repos {
|
||||||
|
let actions = crate::resolve(pool, viewer_id, &repo.id).await?;
|
||||||
|
if !actions.is_empty() {
|
||||||
|
listed.push((repo, actions));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(listed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every registered repository, for instance admins.
|
||||||
|
pub async fn list_all(pool: &SqlitePool) -> Result<Vec<Repo>, sqlx::Error> {
|
||||||
|
sqlx::query_as("SELECT id, namespace, name FROM repos ORDER BY namespace, name").fetch_all(pool).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::fixtures;
|
||||||
|
use crate::orgs;
|
||||||
|
use crate::Preset;
|
||||||
|
|
||||||
|
fn id(n: u8) -> Vec<u8> {
|
||||||
|
vec![n; 16]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn personal_namespace_is_owned_by_its_user_only() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let alice = fixtures::user(pool, "alice").await;
|
||||||
|
let bob = fixtures::user(pool, "bob").await;
|
||||||
|
|
||||||
|
let repo = register(pool, &alice, &id(1), "alice/game").await.unwrap();
|
||||||
|
assert_eq!(repo.full_name(), "alice/game");
|
||||||
|
assert_eq!(crate::resolve(pool, &alice, &repo.id).await.unwrap(), Preset::Owner.actions());
|
||||||
|
assert!(crate::resolve(pool, &bob, &repo.id).await.unwrap().is_empty());
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
register(pool, &bob, &id(2), "alice/other").await,
|
||||||
|
Err(RegistryError::PermissionDenied(_))
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
unregister(pool, &bob, &id(1)).await,
|
||||||
|
Err(RegistryError::PermissionDenied(_))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn register_is_idempotent_but_rejects_conflicts() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let alice = fixtures::user(pool, "alice").await;
|
||||||
|
register(pool, &alice, &id(1), "alice/game").await.unwrap();
|
||||||
|
register(pool, &alice, &id(1), "alice/game").await.unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
register(pool, &alice, &id(1), "alice/renamed").await,
|
||||||
|
Err(RegistryError::AlreadyExists)
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
register(pool, &alice, &id(2), "alice/GAME").await,
|
||||||
|
Err(RegistryError::AlreadyExists)
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
register(pool, &alice, &id(3), "nobody/game").await,
|
||||||
|
Err(RegistryError::NamespaceNotFound(_))
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
register(pool, &alice, &id(3), "game").await,
|
||||||
|
Err(RegistryError::InvalidName(_))
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
register(pool, &alice, &[1, 2], "alice/x").await,
|
||||||
|
Err(RegistryError::InvalidId)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn unregister_removes_and_tolerates_unknown() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let alice = fixtures::user(pool, "alice").await;
|
||||||
|
register(pool, &alice, &id(1), "alice/game").await.unwrap();
|
||||||
|
unregister(pool, &alice, &id(1)).await.unwrap();
|
||||||
|
assert!(get(pool, &fixtures::repo_id(1)).await.unwrap().is_none());
|
||||||
|
unregister(pool, &alice, &id(1)).await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn organisation_access_combines_sources() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let owner = fixtures::user(pool, "owner").await;
|
||||||
|
let member = fixtures::user(pool, "member").await;
|
||||||
|
let outsider = fixtures::user(pool, "outsider").await;
|
||||||
|
let org = orgs::create(pool, "studio", "Studio", &owner).await.unwrap();
|
||||||
|
orgs::add_member(pool, &org, &member, orgs::OrgRole::Member).await.unwrap();
|
||||||
|
|
||||||
|
// Members may not create repositories by default; owners may.
|
||||||
|
assert!(matches!(
|
||||||
|
register(pool, &member, &id(1), "studio/game").await,
|
||||||
|
Err(RegistryError::PermissionDenied(_))
|
||||||
|
));
|
||||||
|
let repo = register(pool, &owner, &id(1), "studio/game").await.unwrap();
|
||||||
|
assert_eq!(crate::resolve(pool, &owner, &repo.id).await.unwrap(), Preset::Owner.actions());
|
||||||
|
assert!(crate::resolve(pool, &member, &repo.id).await.unwrap().is_empty());
|
||||||
|
assert!(list_for_user(pool, &member).await.unwrap().is_empty());
|
||||||
|
|
||||||
|
// Base permission.
|
||||||
|
orgs::set_base_preset(pool, &org, Some(Preset::Reader)).await.unwrap();
|
||||||
|
assert_eq!(crate::resolve(pool, &member, &repo.id).await.unwrap(), Preset::Reader.actions());
|
||||||
|
|
||||||
|
// Team grant adds on top.
|
||||||
|
let team = orgs::create_team(pool, &org, "artists").await.unwrap();
|
||||||
|
orgs::add_team_member(pool, &team, &member).await.unwrap();
|
||||||
|
orgs::set_grant(pool, &repo.id, orgs::Subject::Team(&team), Some(Preset::Writer), ActionSet::EMPTY)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(crate::resolve(pool, &member, &repo.id).await.unwrap(), Preset::Writer.actions());
|
||||||
|
|
||||||
|
// Direct grant with an extra action.
|
||||||
|
orgs::set_grant(
|
||||||
|
pool,
|
||||||
|
&repo.id,
|
||||||
|
orgs::Subject::User(&outsider),
|
||||||
|
Some(Preset::Reader),
|
||||||
|
ActionSet::of(&[Action::Presign]),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let outsider_actions = crate::resolve(pool, &outsider, &repo.id).await.unwrap();
|
||||||
|
assert_eq!(outsider_actions.names(), ["read", "presign"]);
|
||||||
|
let listed = list_for_user(pool, &outsider).await.unwrap();
|
||||||
|
assert_eq!(listed.len(), 1);
|
||||||
|
assert_eq!(listed[0].0.full_name(), "studio/game");
|
||||||
|
|
||||||
|
// Only the owner may delete.
|
||||||
|
assert!(unregister(pool, &member, &id(1)).await.is_err());
|
||||||
|
unregister(pool, &owner, &id(1)).await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn team_grants_stay_inside_their_organisation() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let alice = fixtures::user(pool, "alice").await;
|
||||||
|
let org = orgs::create(pool, "studio", "Studio", &alice).await.unwrap();
|
||||||
|
let team = orgs::create_team(pool, &org, "artists").await.unwrap();
|
||||||
|
let personal = register(pool, &alice, &id(9), "alice/own").await.unwrap();
|
||||||
|
assert!(
|
||||||
|
orgs::set_grant(pool, &personal.id, orgs::Subject::Team(&team), Some(Preset::Reader), ActionSet::EMPTY)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,33 @@
|
||||||
|
[package]
|
||||||
|
name = "forge-id"
|
||||||
|
description = "Accounts, sessions and the OpenID Connect issuer Lore trusts"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
aes-gcm.workspace = true
|
||||||
|
argon2.workspace = true
|
||||||
|
base64.workspace = true
|
||||||
|
forge-access.workspace = true
|
||||||
|
forge-store.workspace = true
|
||||||
|
getrandom.workspace = true
|
||||||
|
p256.workspace = true
|
||||||
|
reqwest.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
sha2.workspace = true
|
||||||
|
sqlx.workspace = true
|
||||||
|
subtle.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
url.workspace = true
|
||||||
|
uuid.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
forge-store = { workspace = true, features = ["testing"] }
|
||||||
|
tokio.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
@ -0,0 +1,222 @@
|
||||||
|
//! API tokens, as in piki: named, stored hashed, with scopes and an optional expiry.
|
||||||
|
//!
|
||||||
|
//! A token with the `lore` scope signs the Lore CLI in without a browser: through token
|
||||||
|
//! exchange with the API-key subject type, or as a service account's client secret. One
|
||||||
|
//! with `api` reads lore-forge's JSON API.
|
||||||
|
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
|
||||||
|
use crate::crypto;
|
||||||
|
use crate::users;
|
||||||
|
use crate::users::User;
|
||||||
|
|
||||||
|
/// Every token starts with this, so secret scanners can recognise one.
|
||||||
|
pub const PREFIX: &str = "lf_";
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Scope {
|
||||||
|
Lore,
|
||||||
|
Api,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Scope {
|
||||||
|
pub const ALL: [Scope; 2] = [Scope::Lore, Scope::Api];
|
||||||
|
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Scope::Lore => "lore",
|
||||||
|
Scope::Api => "api",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(text: &str) -> Option<Scope> {
|
||||||
|
Scope::ALL.into_iter().find(|scope| scope.as_str() == text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, sqlx::FromRow)]
|
||||||
|
pub struct ApiToken {
|
||||||
|
pub id: String,
|
||||||
|
pub user_id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub scopes: String,
|
||||||
|
pub created_at: i64,
|
||||||
|
pub expires_at: Option<i64>,
|
||||||
|
pub last_used_at: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApiToken {
|
||||||
|
pub fn has(&self, scope: Scope) -> bool {
|
||||||
|
self.scopes.split(' ').any(|s| s == scope.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum TokenError {
|
||||||
|
#[error("names must be 1 to 100 characters")]
|
||||||
|
InvalidName,
|
||||||
|
#[error("choose at least one scope")]
|
||||||
|
NoScopes,
|
||||||
|
#[error(transparent)]
|
||||||
|
Database(#[from] sqlx::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A token as created: the secret is shown once and never again.
|
||||||
|
pub struct NewToken {
|
||||||
|
pub token: ApiToken,
|
||||||
|
pub secret: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
user_id: &str,
|
||||||
|
name: &str,
|
||||||
|
scopes: &[Scope],
|
||||||
|
lifetime_days: Option<i64>,
|
||||||
|
actor_id: &str,
|
||||||
|
) -> Result<NewToken, TokenError> {
|
||||||
|
let name = name.trim();
|
||||||
|
if name.is_empty() || name.chars().count() > 100 {
|
||||||
|
return Err(TokenError::InvalidName);
|
||||||
|
}
|
||||||
|
if scopes.is_empty() {
|
||||||
|
return Err(TokenError::NoScopes);
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
let secret = format!("{PREFIX}{}", crypto::random_token());
|
||||||
|
let scopes: Vec<&str> = Scope::ALL.iter().filter(|s| scopes.contains(s)).map(|s| s.as_str()).collect();
|
||||||
|
let token = ApiToken {
|
||||||
|
id: uuid::Uuid::new_v4().to_string(),
|
||||||
|
user_id: user_id.to_owned(),
|
||||||
|
name: name.to_owned(),
|
||||||
|
scopes: scopes.join(" "),
|
||||||
|
created_at: now,
|
||||||
|
expires_at: lifetime_days.map(|days| now + days * 24 * 3600),
|
||||||
|
last_used_at: None,
|
||||||
|
};
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO api_tokens (id, token_hash, user_id, name, scopes, created_by, created_at,
|
||||||
|
expires_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(&token.id)
|
||||||
|
.bind(crypto::hash_token(&secret))
|
||||||
|
.bind(&token.user_id)
|
||||||
|
.bind(&token.name)
|
||||||
|
.bind(&token.scopes)
|
||||||
|
.bind(actor_id)
|
||||||
|
.bind(now)
|
||||||
|
.bind(token.expires_at)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
forge_store::audit(&mut *tx, Some(actor_id), "api_token.create", &token.id, &token.name).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(NewToken { token, secret })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The live tokens of a user or service account, newest first.
|
||||||
|
pub async fn list(pool: &SqlitePool, user_id: &str) -> Result<Vec<ApiToken>, sqlx::Error> {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, user_id, name, scopes, created_at, expires_at, last_used_at FROM api_tokens
|
||||||
|
WHERE user_id = ? AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > ?)
|
||||||
|
ORDER BY created_at DESC",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Revokes a token of `user_id`, ending the CLI logins it started. Returns whether one was
|
||||||
|
/// revoked.
|
||||||
|
pub async fn revoke(pool: &SqlitePool, user_id: &str, id: &str, actor_id: &str) -> Result<bool, sqlx::Error> {
|
||||||
|
let now = forge_store::now();
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
let revoked = sqlx::query(
|
||||||
|
"UPDATE api_tokens SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(now)
|
||||||
|
.bind(id)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if revoked.rows_affected() == 0 {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
sqlx::query("UPDATE cli_logins SET revoked_at = ? WHERE api_token_id = ? AND revoked_at IS NULL")
|
||||||
|
.bind(now)
|
||||||
|
.bind(id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
forge_store::audit(&mut *tx, Some(actor_id), "api_token.revoke", id, "").await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The token and its enabled owner for a presented secret holding `scope`. Records the use.
|
||||||
|
pub async fn authenticate(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
secret: &str,
|
||||||
|
scope: Scope,
|
||||||
|
) -> Result<Option<(ApiToken, User)>, sqlx::Error> {
|
||||||
|
if !secret.starts_with(PREFIX) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
let token: Option<ApiToken> = sqlx::query_as(
|
||||||
|
"SELECT id, user_id, name, scopes, created_at, expires_at, last_used_at FROM api_tokens
|
||||||
|
WHERE token_hash = ? AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > ?)",
|
||||||
|
)
|
||||||
|
.bind(crypto::hash_token(secret))
|
||||||
|
.bind(now)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
let Some(token) = token.filter(|token| token.has(scope)) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let Some(user) = users::get(pool, &token.user_id).await?.filter(|user| !user.disabled) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
// At most one write a minute per token, so a busy API client does not hammer the writer.
|
||||||
|
if token.last_used_at.is_none_or(|at| now - at >= 60) {
|
||||||
|
sqlx::query("UPDATE api_tokens SET last_used_at = ? WHERE id = ?")
|
||||||
|
.bind(now)
|
||||||
|
.bind(&token.id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Ok(Some((token, user)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::users::InstanceRole;
|
||||||
|
use crate::users::NewUser;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn create_authenticate_revoke() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let user = users::create(
|
||||||
|
pool,
|
||||||
|
NewUser { username: "ci", display_name: "CI", password: None, role: InstanceRole::Member },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let new = create(pool, &user.id, "build", &[Scope::Lore], Some(30), &user.id).await.unwrap();
|
||||||
|
assert!(new.secret.starts_with(PREFIX));
|
||||||
|
let (token, owner) = authenticate(pool, &new.secret, Scope::Lore).await.unwrap().unwrap();
|
||||||
|
assert_eq!(token.id, new.token.id);
|
||||||
|
assert_eq!(owner.id, user.id);
|
||||||
|
assert!(authenticate(pool, &new.secret, Scope::Api).await.unwrap().is_none());
|
||||||
|
assert!(authenticate(pool, "lf_nope", Scope::Lore).await.unwrap().is_none());
|
||||||
|
assert_eq!(list(pool, &user.id).await.unwrap().len(), 1);
|
||||||
|
assert!(revoke(pool, &user.id, &new.token.id, &user.id).await.unwrap());
|
||||||
|
assert!(authenticate(pool, &new.secret, Scope::Lore).await.unwrap().is_none());
|
||||||
|
assert!(list(pool, &user.id).await.unwrap().is_empty());
|
||||||
|
assert!(matches!(create(pool, &user.id, "x", &[], None, &user.id).await, Err(TokenError::NoScopes)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,133 @@
|
||||||
|
//! Randomness, hashing and the environment-supplied secret key.
|
||||||
|
|
||||||
|
use aes_gcm::Aes256Gcm;
|
||||||
|
use aes_gcm::KeyInit;
|
||||||
|
use aes_gcm::aead::Aead;
|
||||||
|
use aes_gcm::aead::Payload;
|
||||||
|
use base64::Engine;
|
||||||
|
use base64::engine::general_purpose::STANDARD;
|
||||||
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||||
|
use sha2::Digest;
|
||||||
|
use sha2::Sha256;
|
||||||
|
|
||||||
|
/// Fills an array from the operating system's random source.
|
||||||
|
pub fn random_bytes<const N: usize>() -> [u8; N] {
|
||||||
|
let mut bytes = [0u8; N];
|
||||||
|
getrandom::fill(&mut bytes).expect("the operating system's random source failed");
|
||||||
|
bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A random 256-bit token in base64url, for session, refresh and device codes.
|
||||||
|
pub fn random_token() -> String {
|
||||||
|
b64url(random_bytes::<32>())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SHA-256 of a high-entropy token, the form tokens are stored in. Tokens are random, so an
|
||||||
|
/// unsalted fast hash is enough to make a database leak useless.
|
||||||
|
pub fn hash_token(token: &str) -> Vec<u8> {
|
||||||
|
Sha256::digest(token.as_bytes()).to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn b64url(bytes: impl AsRef<[u8]>) -> String {
|
||||||
|
URL_SAFE_NO_PAD.encode(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn b64url_decode(text: &str) -> Option<Vec<u8>> {
|
||||||
|
URL_SAFE_NO_PAD.decode(text).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compares two byte strings in constant time.
|
||||||
|
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
||||||
|
use subtle::ConstantTimeEq;
|
||||||
|
a.len() == b.len() && bool::from(a.ct_eq(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum SecretKeyError {
|
||||||
|
#[error("the secret key must be 32 bytes, base64-encoded")]
|
||||||
|
Malformed,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
#[error("decrypting a stored secret failed; the secret key may have changed")]
|
||||||
|
pub struct DecryptError;
|
||||||
|
|
||||||
|
/// The 32-byte key, supplied through the environment, that encrypts provider secrets and
|
||||||
|
/// token signing keys at rest. It is never written to the data directory.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct SecretKey {
|
||||||
|
cipher: Aes256Gcm,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for SecretKey {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("SecretKey(..)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SecretKey {
|
||||||
|
pub fn from_base64(text: &str) -> Result<Self, SecretKeyError> {
|
||||||
|
let bytes = STANDARD
|
||||||
|
.decode(text.trim())
|
||||||
|
.or_else(|_| URL_SAFE_NO_PAD.decode(text.trim()))
|
||||||
|
.map_err(|_| SecretKeyError::Malformed)?;
|
||||||
|
Self::from_bytes(&bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self, SecretKeyError> {
|
||||||
|
if bytes.len() != 32 {
|
||||||
|
return Err(SecretKeyError::Malformed);
|
||||||
|
}
|
||||||
|
let cipher = Aes256Gcm::new_from_slice(bytes).map_err(|_| SecretKeyError::Malformed)?;
|
||||||
|
Ok(Self { cipher })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new random key in the form [`SecretKey::from_base64`] reads.
|
||||||
|
pub fn generate_base64() -> String {
|
||||||
|
STANDARD.encode(random_bytes::<32>())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encrypts `plaintext`, binding it to `context` so a ciphertext cannot be moved to
|
||||||
|
/// another row or purpose. The result is the 12-byte nonce followed by the ciphertext.
|
||||||
|
pub fn seal(&self, context: &str, plaintext: &[u8]) -> Vec<u8> {
|
||||||
|
let nonce = random_bytes::<12>();
|
||||||
|
let payload = Payload { msg: plaintext, aad: context.as_bytes() };
|
||||||
|
let ciphertext = self
|
||||||
|
.cipher
|
||||||
|
.encrypt(&nonce.into(), payload)
|
||||||
|
.expect("AES-GCM encryption of a short message cannot fail");
|
||||||
|
let mut sealed = nonce.to_vec();
|
||||||
|
sealed.extend_from_slice(&ciphertext);
|
||||||
|
sealed
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open(&self, context: &str, sealed: &[u8]) -> Result<Vec<u8>, DecryptError> {
|
||||||
|
if sealed.len() < 12 {
|
||||||
|
return Err(DecryptError);
|
||||||
|
}
|
||||||
|
let (nonce, ciphertext) = sealed.split_at(12);
|
||||||
|
let nonce: [u8; 12] = nonce.try_into().map_err(|_| DecryptError)?;
|
||||||
|
let payload = Payload { msg: ciphertext, aad: context.as_bytes() };
|
||||||
|
self.cipher.decrypt(&nonce.into(), payload).map_err(|_| DecryptError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn seal_round_trips_and_binds_context() {
|
||||||
|
let key = SecretKey::from_base64(&SecretKey::generate_base64()).unwrap();
|
||||||
|
let sealed = key.seal("a", b"secret");
|
||||||
|
assert_eq!(key.open("a", &sealed).unwrap(), b"secret");
|
||||||
|
assert!(key.open("b", &sealed).is_err());
|
||||||
|
let other = SecretKey::from_base64(&SecretKey::generate_base64()).unwrap();
|
||||||
|
assert!(other.open("a", &sealed).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_short_keys() {
|
||||||
|
assert!(SecretKey::from_base64("c2hvcnQ=").is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,94 @@
|
||||||
|
//! Instance settings the owner controls: who may sign up and who may create organisations.
|
||||||
|
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
|
||||||
|
const SIGNUP: &str = "signup.mode";
|
||||||
|
const ORG_CREATION: &str = "orgs.create";
|
||||||
|
|
||||||
|
/// Who may create an account without an admin.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum SignupMode {
|
||||||
|
/// Only admins create accounts.
|
||||||
|
Closed,
|
||||||
|
/// Anyone with a valid invite key.
|
||||||
|
Invite,
|
||||||
|
/// Anyone.
|
||||||
|
Open,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SignupMode {
|
||||||
|
pub const ALL: [SignupMode; 3] = [SignupMode::Closed, SignupMode::Invite, SignupMode::Open];
|
||||||
|
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
SignupMode::Closed => "closed",
|
||||||
|
SignupMode::Invite => "invite",
|
||||||
|
SignupMode::Open => "open",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(text: &str) -> Option<SignupMode> {
|
||||||
|
SignupMode::ALL.into_iter().find(|mode| mode.as_str() == text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Who may create organisations.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum OrgCreation {
|
||||||
|
Admins,
|
||||||
|
Everyone,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OrgCreation {
|
||||||
|
pub const ALL: [OrgCreation; 2] = [OrgCreation::Admins, OrgCreation::Everyone];
|
||||||
|
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
OrgCreation::Admins => "admins",
|
||||||
|
OrgCreation::Everyone => "everyone",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(text: &str) -> Option<OrgCreation> {
|
||||||
|
OrgCreation::ALL.into_iter().find(|policy| policy.as_str() == text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn signup_mode(pool: &SqlitePool) -> Result<SignupMode, sqlx::Error> {
|
||||||
|
let stored = forge_store::setting(pool, SIGNUP).await?;
|
||||||
|
Ok(stored.as_deref().and_then(SignupMode::parse).unwrap_or(SignupMode::Closed))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn org_creation(pool: &SqlitePool) -> Result<OrgCreation, sqlx::Error> {
|
||||||
|
let stored = forge_store::setting(pool, ORG_CREATION).await?;
|
||||||
|
Ok(stored.as_deref().and_then(OrgCreation::parse).unwrap_or(OrgCreation::Admins))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
signup: SignupMode,
|
||||||
|
orgs: OrgCreation,
|
||||||
|
actor_id: &str,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
forge_store::set_setting(pool, SIGNUP, signup.as_str()).await?;
|
||||||
|
forge_store::set_setting(pool, ORG_CREATION, orgs.as_str()).await?;
|
||||||
|
let detail = format!("signup={} orgs={}", signup.as_str(), orgs.as_str());
|
||||||
|
forge_store::audit(pool, Some(actor_id), "instance.settings", "", &detail).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn defaults_and_round_trip() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
assert_eq!(signup_mode(pool).await.unwrap(), SignupMode::Closed);
|
||||||
|
assert_eq!(org_creation(pool).await.unwrap(), OrgCreation::Admins);
|
||||||
|
set(pool, SignupMode::Invite, OrgCreation::Everyone, "x").await.unwrap();
|
||||||
|
assert_eq!(signup_mode(pool).await.unwrap(), SignupMode::Invite);
|
||||||
|
assert_eq!(org_creation(pool).await.unwrap(), OrgCreation::Everyone);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,183 @@
|
||||||
|
//! Signup invite keys, as in piki: a named key with a maximum number of uses and an active
|
||||||
|
//! flag, recording who used it.
|
||||||
|
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
|
||||||
|
use crate::crypto;
|
||||||
|
use crate::users;
|
||||||
|
use crate::users::CreateUserError;
|
||||||
|
use crate::users::NewUser;
|
||||||
|
use crate::users::User;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, sqlx::FromRow)]
|
||||||
|
pub struct Invite {
|
||||||
|
pub id: String,
|
||||||
|
pub invite_key: String,
|
||||||
|
pub name: String,
|
||||||
|
pub max_uses: i64,
|
||||||
|
pub active: bool,
|
||||||
|
pub created_at: i64,
|
||||||
|
pub uses: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Invite {
|
||||||
|
pub fn usable(&self) -> bool {
|
||||||
|
self.active && self.uses < self.max_uses
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum InviteError {
|
||||||
|
#[error("names must be 1 to 100 characters")]
|
||||||
|
InvalidName,
|
||||||
|
#[error("an invite needs between 1 and 10000 uses")]
|
||||||
|
InvalidUses,
|
||||||
|
#[error("this invite is not valid any more")]
|
||||||
|
Unusable,
|
||||||
|
#[error(transparent)]
|
||||||
|
User(#[from] CreateUserError),
|
||||||
|
#[error(transparent)]
|
||||||
|
Database(#[from] sqlx::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! select_invite {
|
||||||
|
($tail:literal) => {
|
||||||
|
concat!(
|
||||||
|
"SELECT k.id, k.invite_key, k.name, k.max_uses, k.active, k.created_at,
|
||||||
|
(SELECT count(*) FROM invite_key_uses u WHERE u.invite_key_id = k.id) AS uses
|
||||||
|
FROM invite_keys k ",
|
||||||
|
$tail
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create(pool: &SqlitePool, name: &str, max_uses: i64, actor_id: &str) -> Result<Invite, InviteError> {
|
||||||
|
let name = name.trim();
|
||||||
|
if name.is_empty() || name.chars().count() > 100 {
|
||||||
|
return Err(InviteError::InvalidName);
|
||||||
|
}
|
||||||
|
if !(1..=10_000).contains(&max_uses) {
|
||||||
|
return Err(InviteError::InvalidUses);
|
||||||
|
}
|
||||||
|
let invite = Invite {
|
||||||
|
id: uuid::Uuid::new_v4().to_string(),
|
||||||
|
invite_key: crypto::random_token(),
|
||||||
|
name: name.to_owned(),
|
||||||
|
max_uses,
|
||||||
|
active: true,
|
||||||
|
created_at: forge_store::now(),
|
||||||
|
uses: 0,
|
||||||
|
};
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO invite_keys (id, invite_key, name, max_uses, created_by, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(&invite.id)
|
||||||
|
.bind(&invite.invite_key)
|
||||||
|
.bind(&invite.name)
|
||||||
|
.bind(invite.max_uses)
|
||||||
|
.bind(actor_id)
|
||||||
|
.bind(invite.created_at)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
forge_store::audit(&mut *tx, Some(actor_id), "invite.create", &invite.id, &invite.name).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(invite)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list(pool: &SqlitePool) -> Result<Vec<Invite>, sqlx::Error> {
|
||||||
|
sqlx::query_as(select_invite!("ORDER BY k.created_at DESC")).fetch_all(pool).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find(pool: &SqlitePool, key: &str) -> Result<Option<Invite>, sqlx::Error> {
|
||||||
|
sqlx::query_as(select_invite!("WHERE k.invite_key = ?")).bind(key).fetch_optional(pool).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Who used an invite: usernames and when.
|
||||||
|
pub async fn uses(pool: &SqlitePool, id: &str) -> Result<Vec<(String, i64)>, sqlx::Error> {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT u.username, x.used_at FROM invite_key_uses x JOIN users u ON u.id = x.user_id
|
||||||
|
WHERE x.invite_key_id = ? ORDER BY x.used_at",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_active(pool: &SqlitePool, id: &str, active: bool, actor_id: &str) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query("UPDATE invite_keys SET active = ? WHERE id = ?")
|
||||||
|
.bind(active)
|
||||||
|
.bind(id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
let action = if active { "invite.enable" } else { "invite.disable" };
|
||||||
|
forge_store::audit(pool, Some(actor_id), action, id, "").await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an account with an invite key, in one transaction: the account exists only if the
|
||||||
|
/// key was usable, and a key is never used more often than it allows.
|
||||||
|
pub async fn sign_up(pool: &SqlitePool, key: &str, new: NewUser<'_>) -> Result<User, InviteError> {
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
let user = users::create_in(&mut tx, new).await?;
|
||||||
|
let used = sqlx::query(
|
||||||
|
"INSERT INTO invite_key_uses (invite_key_id, user_id, used_at)
|
||||||
|
SELECT k.id, ?, ? FROM invite_keys k
|
||||||
|
WHERE k.invite_key = ? AND k.active = 1
|
||||||
|
AND (SELECT count(*) FROM invite_key_uses u WHERE u.invite_key_id = k.id) < k.max_uses",
|
||||||
|
)
|
||||||
|
.bind(&user.id)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.bind(key)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if used.rows_affected() != 1 {
|
||||||
|
return Err(InviteError::Unusable);
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::users::InstanceRole;
|
||||||
|
|
||||||
|
fn person(username: &str) -> NewUser<'_> {
|
||||||
|
NewUser { username, display_name: username, password: Some("long enough password"), role: InstanceRole::Member }
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn admin(pool: &SqlitePool) -> String {
|
||||||
|
users::create(pool, NewUser { role: InstanceRole::Owner, ..person("boss") }).await.unwrap().id
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn uses_are_capped_and_recorded() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let admin = admin(pool).await;
|
||||||
|
let invite = create(pool, "artists", 1, &admin).await.unwrap();
|
||||||
|
let user = sign_up(pool, &invite.invite_key, person("dana")).await.unwrap();
|
||||||
|
assert!(matches!(sign_up(pool, &invite.invite_key, person("erin")).await, Err(InviteError::Unusable)));
|
||||||
|
// The refused signup left no account behind.
|
||||||
|
assert!(users::find_by_username(pool, "erin").await.unwrap().is_none());
|
||||||
|
let found = find(pool, &invite.invite_key).await.unwrap().unwrap();
|
||||||
|
assert_eq!(found.uses, 1);
|
||||||
|
assert!(!found.usable());
|
||||||
|
assert_eq!(uses(pool, &invite.id).await.unwrap()[0].0, user.username);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn disabled_and_unknown_keys_are_refused() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let admin = admin(pool).await;
|
||||||
|
let invite = create(pool, "team", 5, &admin).await.unwrap();
|
||||||
|
set_active(pool, &invite.id, false, &admin).await.unwrap();
|
||||||
|
assert!(matches!(sign_up(pool, &invite.invite_key, person("dana")).await, Err(InviteError::Unusable)));
|
||||||
|
assert!(matches!(sign_up(pool, "nope", person("dana")).await, Err(InviteError::Unusable)));
|
||||||
|
assert!(matches!(create(pool, "", 1, &admin).await, Err(InviteError::InvalidName)));
|
||||||
|
assert!(matches!(create(pool, "x", 0, &admin).await, Err(InviteError::InvalidUses)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,275 @@
|
||||||
|
//! The device authorization grant (RFC 8628), which `lore auth login` uses.
|
||||||
|
|
||||||
|
use forge_store::sqlx;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use super::Issuer;
|
||||||
|
use super::OAuthError;
|
||||||
|
use super::paths;
|
||||||
|
use crate::crypto;
|
||||||
|
use crate::users;
|
||||||
|
|
||||||
|
/// Letters that cannot be mistaken for one another or spell much, per RFC 8628 section 6.1.
|
||||||
|
const USER_CODE_ALPHABET: &[u8; 20] = b"BCDFGHJKLMNPQRSTVWXZ";
|
||||||
|
|
||||||
|
/// The device authorization response.
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct DeviceAuthorization {
|
||||||
|
pub device_code: String,
|
||||||
|
pub user_code: String,
|
||||||
|
pub verification_uri: String,
|
||||||
|
pub verification_uri_complete: String,
|
||||||
|
pub expires_in: i64,
|
||||||
|
pub interval: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct PollRow {
|
||||||
|
id: String,
|
||||||
|
status: String,
|
||||||
|
user_id: Option<String>,
|
||||||
|
scope: String,
|
||||||
|
interval_secs: i64,
|
||||||
|
expires_at: i64,
|
||||||
|
last_polled_at: Option<i64>,
|
||||||
|
requested_by: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A pending request, as the approval page shows it.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DeviceRequest {
|
||||||
|
pub user_code: String,
|
||||||
|
pub requested_by: String,
|
||||||
|
pub created_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn user_code() -> String {
|
||||||
|
let mut code = String::with_capacity(9);
|
||||||
|
while code.len() < 9 {
|
||||||
|
for byte in crypto::random_bytes::<16>() {
|
||||||
|
// Rejection sampling keeps the distribution uniform: 240 is a multiple of 20.
|
||||||
|
if byte < 240 && code.len() < 9 {
|
||||||
|
if code.len() == 4 {
|
||||||
|
code.push('-');
|
||||||
|
}
|
||||||
|
code.push(USER_CODE_ALPHABET[(byte % 20) as usize] as char);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
code
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts a code as a person typed it into canonical `XXXX-XXXX` form, or `None` if it cannot
|
||||||
|
/// be one.
|
||||||
|
pub fn normalize_user_code(input: &str) -> Option<String> {
|
||||||
|
let letters: String = input
|
||||||
|
.chars()
|
||||||
|
.filter(|c| c.is_ascii_alphanumeric())
|
||||||
|
.map(|c| c.to_ascii_uppercase())
|
||||||
|
.collect();
|
||||||
|
if letters.len() != 8 || !letters.bytes().all(|b| USER_CODE_ALPHABET.contains(&b)) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(format!("{}-{}", &letters[..4], &letters[4..]))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Issuer {
|
||||||
|
/// Starts a CLI login. `requested_by` describes the device, for the approval page.
|
||||||
|
pub async fn device_authorize(
|
||||||
|
&self,
|
||||||
|
client_id: Option<&str>,
|
||||||
|
scope: Option<&str>,
|
||||||
|
requested_by: &str,
|
||||||
|
) -> Result<DeviceAuthorization, OAuthError> {
|
||||||
|
if client_id != Some(self.config.client_id.as_str()) {
|
||||||
|
return Err(OAuthError { status: 401, ..OAuthError::new("invalid_client") });
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
let lifetimes = self.config.lifetimes;
|
||||||
|
// Housekeeping: expired requests are no use to anyone.
|
||||||
|
sqlx::query("DELETE FROM device_codes WHERE expires_at < ?")
|
||||||
|
.bind(now - 3600)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
let device_code = crypto::random_token();
|
||||||
|
let mut code = user_code();
|
||||||
|
for attempt in 0.. {
|
||||||
|
let inserted = sqlx::query(
|
||||||
|
"INSERT INTO device_codes (id, device_code_hash, user_code, client_id, scope,
|
||||||
|
requested_by, status, interval_secs, created_at, expires_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(uuid::Uuid::new_v4().to_string())
|
||||||
|
.bind(crypto::hash_token(&device_code))
|
||||||
|
.bind(&code)
|
||||||
|
.bind(&self.config.client_id)
|
||||||
|
.bind(scope.unwrap_or(""))
|
||||||
|
.bind(requested_by.chars().take(200).collect::<String>())
|
||||||
|
.bind(lifetimes.device_interval_secs)
|
||||||
|
.bind(now)
|
||||||
|
.bind(now + lifetimes.device_code_secs)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await;
|
||||||
|
match inserted {
|
||||||
|
Ok(_) => break,
|
||||||
|
Err(error) if forge_store::is_unique_violation(&error) && attempt < 5 => {
|
||||||
|
code = user_code();
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let verification_uri = self.config.url(paths::DEVICE_VERIFICATION);
|
||||||
|
Ok(DeviceAuthorization {
|
||||||
|
verification_uri_complete: format!("{verification_uri}?user_code={code}"),
|
||||||
|
verification_uri,
|
||||||
|
device_code,
|
||||||
|
user_code: code,
|
||||||
|
expires_in: lifetimes.device_code_secs,
|
||||||
|
interval: lifetimes.device_interval_secs,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pending request with this user code, if it has not expired.
|
||||||
|
pub async fn pending_device_request(
|
||||||
|
&self,
|
||||||
|
user_code: &str,
|
||||||
|
) -> Result<Option<DeviceRequest>, sqlx::Error> {
|
||||||
|
let Some(code) = normalize_user_code(user_code) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let row: Option<(String, String, i64)> = sqlx::query_as(
|
||||||
|
"SELECT user_code, requested_by, created_at FROM device_codes
|
||||||
|
WHERE user_code = ? AND status = 'pending' AND expires_at > ?",
|
||||||
|
)
|
||||||
|
.bind(code)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(row.map(|(user_code, requested_by, created_at)| DeviceRequest {
|
||||||
|
user_code,
|
||||||
|
requested_by,
|
||||||
|
created_at,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Approves or denies a pending request on behalf of `user_id`. False if there was no
|
||||||
|
/// such pending request.
|
||||||
|
pub async fn decide_device_request(
|
||||||
|
&self,
|
||||||
|
user_code: &str,
|
||||||
|
user_id: &str,
|
||||||
|
approve: bool,
|
||||||
|
) -> Result<bool, sqlx::Error> {
|
||||||
|
let Some(code) = normalize_user_code(user_code) else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
let mut tx = self.pool.begin().await?;
|
||||||
|
let updated = sqlx::query(
|
||||||
|
"UPDATE device_codes SET status = ?, user_id = ?
|
||||||
|
WHERE user_code = ? AND status = 'pending' AND expires_at > ?",
|
||||||
|
)
|
||||||
|
.bind(if approve { "approved" } else { "denied" })
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(&code)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
let decided = updated.rows_affected() == 1;
|
||||||
|
if decided {
|
||||||
|
let action = if approve { "device.approve" } else { "device.deny" };
|
||||||
|
forge_store::audit(&mut *tx, Some(user_id), action, &code, "").await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(decided)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The token request with `grant_type=urn:ietf:params:oauth:grant-type:device_code`.
|
||||||
|
pub(super) async fn device_code_grant(
|
||||||
|
&self,
|
||||||
|
form: &super::Form,
|
||||||
|
) -> Result<serde_json::Value, OAuthError> {
|
||||||
|
let device_code = form.require("device_code")?;
|
||||||
|
if form.get("client_id")? != Some(self.config.client_id.as_str()) {
|
||||||
|
return Err(OAuthError::new("invalid_client"));
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
let row: Option<PollRow> = sqlx::query_as(
|
||||||
|
"SELECT id, status, user_id, scope, interval_secs, expires_at, last_polled_at,
|
||||||
|
requested_by
|
||||||
|
FROM device_codes WHERE device_code_hash = ?",
|
||||||
|
)
|
||||||
|
.bind(crypto::hash_token(device_code))
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
let Some(PollRow {
|
||||||
|
id,
|
||||||
|
status,
|
||||||
|
user_id,
|
||||||
|
scope,
|
||||||
|
interval_secs: interval,
|
||||||
|
expires_at,
|
||||||
|
last_polled_at: last_polled,
|
||||||
|
requested_by,
|
||||||
|
}) = row
|
||||||
|
else {
|
||||||
|
return Err(OAuthError::new("invalid_grant"));
|
||||||
|
};
|
||||||
|
if expires_at <= now {
|
||||||
|
return Err(OAuthError::new("expired_token"));
|
||||||
|
}
|
||||||
|
match status.as_str() {
|
||||||
|
"pending" => {
|
||||||
|
let too_fast = last_polled.is_some_and(|last| now - last < interval);
|
||||||
|
// Each slow_down widens the interval by five seconds, per RFC 8628 3.5.
|
||||||
|
let next_interval = if too_fast { interval + 5 } else { interval };
|
||||||
|
sqlx::query("UPDATE device_codes SET last_polled_at = ?, interval_secs = ? WHERE id = ?")
|
||||||
|
.bind(now)
|
||||||
|
.bind(next_interval)
|
||||||
|
.bind(&id)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Err(OAuthError::new(if too_fast { "slow_down" } else { "authorization_pending" }))
|
||||||
|
}
|
||||||
|
"denied" => Err(OAuthError::new("access_denied")),
|
||||||
|
"consumed" => Err(OAuthError::new("invalid_grant")),
|
||||||
|
"approved" => {
|
||||||
|
// Consume first, so two polls racing cannot both get tokens.
|
||||||
|
let consumed = sqlx::query(
|
||||||
|
"UPDATE device_codes SET status = 'consumed' WHERE id = ? AND status = 'approved'",
|
||||||
|
)
|
||||||
|
.bind(&id)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
if consumed.rows_affected() != 1 {
|
||||||
|
return Err(OAuthError::new("invalid_grant"));
|
||||||
|
}
|
||||||
|
let user = match user_id {
|
||||||
|
Some(user_id) => users::get(&self.pool, &user_id).await?,
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
let Some(user) = user.filter(|user| !user.disabled) else {
|
||||||
|
return Err(OAuthError::new("access_denied"));
|
||||||
|
};
|
||||||
|
self.start_login(&user, &scope, &requested_by, None).await
|
||||||
|
}
|
||||||
|
_ => Err(OAuthError::server_error()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn user_codes_are_well_formed_and_normalize() {
|
||||||
|
for _ in 0..100 {
|
||||||
|
let code = user_code();
|
||||||
|
assert_eq!(code.len(), 9);
|
||||||
|
assert_eq!(normalize_user_code(&code).as_deref(), Some(code.as_str()));
|
||||||
|
}
|
||||||
|
assert_eq!(normalize_user_code("bcdf ghjk").as_deref(), Some("BCDF-GHJK"));
|
||||||
|
assert_eq!(normalize_user_code("BCDF-GHJA"), None);
|
||||||
|
assert_eq!(normalize_user_code("BCDF"), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,404 @@
|
||||||
|
//! The token endpoint's grants and the revocation endpoint.
|
||||||
|
|
||||||
|
use forge_access::repos;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use super::ACCESS_TOKEN_TYPE;
|
||||||
|
use super::API_KEY_TOKEN_TYPE;
|
||||||
|
use super::DEVICE_CODE;
|
||||||
|
use super::Form;
|
||||||
|
use super::Issuer;
|
||||||
|
use super::LiveError;
|
||||||
|
use super::OAuthError;
|
||||||
|
use super::ResourceGrant;
|
||||||
|
use super::TOKEN_EXCHANGE;
|
||||||
|
use crate::api_tokens;
|
||||||
|
use crate::api_tokens::Scope;
|
||||||
|
use crate::crypto;
|
||||||
|
use crate::users;
|
||||||
|
use crate::users::User;
|
||||||
|
|
||||||
|
/// Lifetime of [`Issuer::browse_token`] tokens. Each page view mints its own.
|
||||||
|
const BROWSE_TOKEN_SECS: i64 = 60;
|
||||||
|
|
||||||
|
const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt";
|
||||||
|
const CLIENT_CREDENTIALS: &str = "client_credentials";
|
||||||
|
|
||||||
|
/// The client ID and secret of an HTTP Basic `Authorization` header, each form-urlencoded
|
||||||
|
/// as RFC 6749 section 2.3.1 requires.
|
||||||
|
fn basic_credentials(header: &str) -> Option<(String, String)> {
|
||||||
|
use base64::Engine;
|
||||||
|
let encoded = header.strip_prefix("Basic ").or_else(|| header.strip_prefix("basic "))?;
|
||||||
|
let decoded = base64::engine::general_purpose::STANDARD.decode(encoded.trim()).ok()?;
|
||||||
|
let text = String::from_utf8(decoded).ok()?;
|
||||||
|
let (id, secret) = text.split_once(':')?;
|
||||||
|
let unescape = |part: &str| -> String {
|
||||||
|
url::form_urlencoded::parse(format!("x={part}").as_bytes()).next().map(|(_, v)| v.into_owned()).unwrap_or_default()
|
||||||
|
};
|
||||||
|
Some((unescape(id), unescape(secret)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct RefreshRow {
|
||||||
|
login_id: String,
|
||||||
|
superseded_at: Option<i64>,
|
||||||
|
user_id: String,
|
||||||
|
scope: String,
|
||||||
|
last_used_at: i64,
|
||||||
|
expires_at: i64,
|
||||||
|
revoked_at: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Issuer {
|
||||||
|
/// Answers a request to the token endpoint. `authorization` is the request's
|
||||||
|
/// `Authorization` header, which carries a confidential client's credentials.
|
||||||
|
pub async fn token(&self, form: &Form, authorization: Option<&str>) -> Result<serde_json::Value, OAuthError> {
|
||||||
|
match form.require("grant_type")? {
|
||||||
|
DEVICE_CODE => self.device_code_grant(form).await,
|
||||||
|
"refresh_token" => self.refresh_grant(form).await,
|
||||||
|
TOKEN_EXCHANGE => self.exchange_grant(form).await,
|
||||||
|
CLIENT_CREDENTIALS => self.client_credentials_grant(form, authorization).await,
|
||||||
|
_ => Err(OAuthError::new("unsupported_grant_type")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `grant_type=client_credentials`: a service account logs in with its name as the client
|
||||||
|
/// ID and one of its `lore` API tokens as the secret, sent as HTTP Basic or in the form.
|
||||||
|
/// The answer has no refresh token; the client logs in again when it expires.
|
||||||
|
async fn client_credentials_grant(
|
||||||
|
&self,
|
||||||
|
form: &Form,
|
||||||
|
authorization: Option<&str>,
|
||||||
|
) -> Result<serde_json::Value, OAuthError> {
|
||||||
|
let unauthorised = || OAuthError { status: 401, ..OAuthError::new("invalid_client") };
|
||||||
|
let (client_id, secret) = match authorization {
|
||||||
|
Some(header) => basic_credentials(header).ok_or_else(unauthorised)?,
|
||||||
|
None => match (form.get("client_id")?, form.get("client_secret")?) {
|
||||||
|
(Some(id), Some(secret)) => (id.to_owned(), secret.to_owned()),
|
||||||
|
_ => return Err(unauthorised()),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let Some((token, user)) = api_tokens::authenticate(&self.pool, &secret, Scope::Lore).await? else {
|
||||||
|
return Err(unauthorised());
|
||||||
|
};
|
||||||
|
if !user.service || !user.username.eq_ignore_ascii_case(&client_id) {
|
||||||
|
return Err(unauthorised());
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
let lifetime = self.config.lifetimes.login_token_secs;
|
||||||
|
let expires = token.expires_at.map_or(now + lifetime, |end| end.min(now + lifetime));
|
||||||
|
let login_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let mut tx = self.pool.begin().await?;
|
||||||
|
// Logins of earlier runs that have long expired.
|
||||||
|
sqlx::query("DELETE FROM cli_logins WHERE api_token_id = ? AND expires_at < ?")
|
||||||
|
.bind(&token.id)
|
||||||
|
.bind(now - 24 * 3600)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO cli_logins (id, user_id, client_id, description, created_at, last_used_at,
|
||||||
|
expires_at, api_token_id)
|
||||||
|
VALUES (?, ?, ?, 'client credentials', ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(&login_id)
|
||||||
|
.bind(&user.id)
|
||||||
|
.bind(&client_id)
|
||||||
|
.bind(now)
|
||||||
|
.bind(now)
|
||||||
|
.bind(expires)
|
||||||
|
.bind(&token.id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
let scope = form.get("scope")?.unwrap_or_default();
|
||||||
|
let access_token = self.mint(&user, &login_id, scope, expires, None);
|
||||||
|
Ok(json!({
|
||||||
|
"access_token": access_token,
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"expires_in": expires - now,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Token exchange with an API token as the subject: a CLI login for the token's owner,
|
||||||
|
/// answered like the device grant. Revoking the token ends the login.
|
||||||
|
async fn api_key_login(&self, form: &Form) -> Result<serde_json::Value, OAuthError> {
|
||||||
|
let secret = form.require("subject_token")?;
|
||||||
|
let Some((token, user)) = api_tokens::authenticate(&self.pool, secret, Scope::Lore).await? else {
|
||||||
|
return Err(OAuthError::new("invalid_grant"));
|
||||||
|
};
|
||||||
|
let description = format!("API token {}", token.name);
|
||||||
|
self.start_login(&user, "", &description, Some(&token.id)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a CLI login for `user` and answers with its first tokens.
|
||||||
|
pub(super) async fn start_login(
|
||||||
|
&self,
|
||||||
|
user: &User,
|
||||||
|
scope: &str,
|
||||||
|
description: &str,
|
||||||
|
api_token_id: Option<&str>,
|
||||||
|
) -> Result<serde_json::Value, OAuthError> {
|
||||||
|
let now = forge_store::now();
|
||||||
|
let lifetimes = self.config.lifetimes;
|
||||||
|
let login_id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let refresh_token = crypto::random_token();
|
||||||
|
let mut tx = self.pool.begin().await?;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO cli_logins (id, user_id, client_id, scope, description, created_at,
|
||||||
|
last_used_at, expires_at, api_token_id)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(&login_id)
|
||||||
|
.bind(&user.id)
|
||||||
|
.bind(&self.config.client_id)
|
||||||
|
.bind(scope)
|
||||||
|
.bind(description)
|
||||||
|
.bind(now)
|
||||||
|
.bind(now)
|
||||||
|
.bind(now + lifetimes.refresh_max_secs)
|
||||||
|
.bind(api_token_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("INSERT INTO refresh_tokens (token_hash, login_id, created_at) VALUES (?, ?, ?)")
|
||||||
|
.bind(crypto::hash_token(&refresh_token))
|
||||||
|
.bind(&login_id)
|
||||||
|
.bind(now)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
forge_store::audit(&mut *tx, Some(&user.id), "cli_login.create", &login_id, description)
|
||||||
|
.await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
let refresh_expires = (now + lifetimes.refresh_idle_secs).min(now + lifetimes.refresh_max_secs);
|
||||||
|
Ok(self.login_response(user, &login_id, scope, &refresh_token, refresh_expires))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn login_response(
|
||||||
|
&self,
|
||||||
|
user: &User,
|
||||||
|
login_id: &str,
|
||||||
|
scope: &str,
|
||||||
|
refresh_token: &str,
|
||||||
|
refresh_expires_at: i64,
|
||||||
|
) -> serde_json::Value {
|
||||||
|
let now = forge_store::now();
|
||||||
|
let lifetime = self.config.lifetimes.login_token_secs;
|
||||||
|
let access_token = self.mint(user, login_id, scope, now + lifetime, None);
|
||||||
|
let mut response = json!({
|
||||||
|
"access_token": access_token,
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"expires_in": lifetime,
|
||||||
|
"refresh_token": refresh_token,
|
||||||
|
"refresh_token_expires_in": refresh_expires_at - now,
|
||||||
|
});
|
||||||
|
if !scope.is_empty() {
|
||||||
|
response["scope"] = json!(scope);
|
||||||
|
}
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `grant_type=refresh_token`: a new login token, and the refresh token rotated.
|
||||||
|
async fn refresh_grant(&self, form: &Form) -> Result<serde_json::Value, OAuthError> {
|
||||||
|
let presented = form.require("refresh_token")?;
|
||||||
|
if form.get("client_id")? != Some(self.config.client_id.as_str()) {
|
||||||
|
return Err(OAuthError::new("invalid_client"));
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
let lifetimes = self.config.lifetimes;
|
||||||
|
let mut tx = self.pool.begin().await?;
|
||||||
|
let row: Option<RefreshRow> = sqlx::query_as(
|
||||||
|
"SELECT l.id AS login_id, t.superseded_at, l.user_id, l.scope, l.last_used_at,
|
||||||
|
l.expires_at, l.revoked_at
|
||||||
|
FROM refresh_tokens t JOIN cli_logins l ON l.id = t.login_id
|
||||||
|
WHERE t.token_hash = ?",
|
||||||
|
)
|
||||||
|
.bind(crypto::hash_token(presented))
|
||||||
|
.fetch_optional(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
let Some(RefreshRow {
|
||||||
|
login_id,
|
||||||
|
superseded_at,
|
||||||
|
user_id,
|
||||||
|
scope,
|
||||||
|
last_used_at: last_used,
|
||||||
|
expires_at,
|
||||||
|
revoked_at: revoked,
|
||||||
|
}) = row
|
||||||
|
else {
|
||||||
|
return Err(OAuthError::new("invalid_grant"));
|
||||||
|
};
|
||||||
|
let ended = revoked.is_some()
|
||||||
|
|| expires_at <= now
|
||||||
|
|| last_used + lifetimes.refresh_idle_secs <= now;
|
||||||
|
if ended {
|
||||||
|
return Err(OAuthError::new("invalid_grant"));
|
||||||
|
}
|
||||||
|
if let Some(superseded_at) = superseded_at
|
||||||
|
&& now - superseded_at > lifetimes.refresh_reuse_grace_secs
|
||||||
|
{
|
||||||
|
// A refresh token used after it was rotated out was most likely copied. End the
|
||||||
|
// login, so neither copy works any more (RFC 9700 section 4.14.2).
|
||||||
|
sqlx::query("UPDATE cli_logins SET revoked_at = ? WHERE id = ?")
|
||||||
|
.bind(now)
|
||||||
|
.bind(&login_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
forge_store::audit(&mut *tx, Some(&user_id), "cli_login.refresh_reuse", &login_id, "")
|
||||||
|
.await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
tracing::warn!(login = %login_id, "rotated-out refresh token reused; login ended");
|
||||||
|
return Err(OAuthError::new("invalid_grant"));
|
||||||
|
}
|
||||||
|
let Some(user) = users::get(&self.pool, &user_id).await?.filter(|user| !user.disabled)
|
||||||
|
else {
|
||||||
|
return Err(OAuthError::new("invalid_grant"));
|
||||||
|
};
|
||||||
|
let next = crypto::random_token();
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE refresh_tokens SET superseded_at = ? WHERE login_id = ? AND superseded_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(now)
|
||||||
|
.bind(&login_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("INSERT INTO refresh_tokens (token_hash, login_id, created_at) VALUES (?, ?, ?)")
|
||||||
|
.bind(crypto::hash_token(&next))
|
||||||
|
.bind(&login_id)
|
||||||
|
.bind(now)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("DELETE FROM refresh_tokens WHERE login_id = ? AND superseded_at < ?")
|
||||||
|
.bind(&login_id)
|
||||||
|
.bind(now - lifetimes.refresh_reuse_grace_secs.max(3600))
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("UPDATE cli_logins SET last_used_at = ? WHERE id = ?")
|
||||||
|
.bind(now)
|
||||||
|
.bind(&login_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
let refresh_expires = (now + lifetimes.refresh_idle_secs).min(expires_at);
|
||||||
|
Ok(self.login_response(&user, &login_id, &scope, &next, refresh_expires))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `grant_type=urn:ietf:params:oauth:grant-type:token-exchange`.
|
||||||
|
///
|
||||||
|
/// With an access token as the subject and one `resource` naming a repository, answers a
|
||||||
|
/// token scoped to that repository carrying the caller's actions on it. This runs for
|
||||||
|
/// every repository every active client uses, about every five minutes, so it only reads.
|
||||||
|
async fn exchange_grant(&self, form: &Form) -> Result<serde_json::Value, OAuthError> {
|
||||||
|
if form.get("client_id")? != Some(self.config.client_id.as_str()) {
|
||||||
|
return Err(OAuthError::new("invalid_client"));
|
||||||
|
}
|
||||||
|
if let Some(requested) = form.get("requested_token_type")?
|
||||||
|
&& requested != ACCESS_TOKEN_TYPE
|
||||||
|
&& requested != JWT_TOKEN_TYPE
|
||||||
|
{
|
||||||
|
return Err(OAuthError::described("invalid_request", "requested_token_type"));
|
||||||
|
}
|
||||||
|
match form.require("subject_token_type")? {
|
||||||
|
ACCESS_TOKEN_TYPE => {}
|
||||||
|
// `lore auth login --token-type` sends its argument verbatim.
|
||||||
|
API_KEY_TOKEN_TYPE | "api-key" => return self.api_key_login(form).await,
|
||||||
|
_ => return Err(OAuthError::described("invalid_request", "subject_token_type")),
|
||||||
|
}
|
||||||
|
let subject = match self.verify_live(form.require("subject_token")?).await {
|
||||||
|
Ok(claims) if !claims.is_scoped() => claims,
|
||||||
|
Ok(_) => return Err(OAuthError::described("invalid_grant", "subject is already scoped")),
|
||||||
|
Err(LiveError::Invalid(error)) => {
|
||||||
|
tracing::debug!("exchange refused the subject token: {error}");
|
||||||
|
return Err(OAuthError::new("invalid_grant"));
|
||||||
|
}
|
||||||
|
Err(LiveError::Database(error)) => return Err(error.into()),
|
||||||
|
};
|
||||||
|
let resources = form.get_all("resource");
|
||||||
|
let prefix = self.config.resource_prefix();
|
||||||
|
let repo_id = match resources.as_slice() {
|
||||||
|
[resource] => resource.strip_prefix(prefix.as_str()).filter(|id| repos::is_valid_id(id)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let Some(repo_id) = repo_id else {
|
||||||
|
return Err(OAuthError::described("invalid_target", "one repository resource"));
|
||||||
|
};
|
||||||
|
let actions = forge_access::resolve(&self.pool, &subject.sub, repo_id).await?;
|
||||||
|
if actions.is_empty() {
|
||||||
|
return Err(OAuthError::described("invalid_target", "no access to the repository"));
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
// Lore reads `exp` as whole seconds, and a scoped token never outlives its login token.
|
||||||
|
let expires = subject.exp.min(now + self.config.lifetimes.scoped_token_secs);
|
||||||
|
let user = User {
|
||||||
|
id: subject.sub.clone(),
|
||||||
|
username: subject.preferred_username.clone().unwrap_or_default(),
|
||||||
|
display_name: subject.name.clone().unwrap_or_default(),
|
||||||
|
role: users::InstanceRole::Member,
|
||||||
|
disabled: false,
|
||||||
|
service: false,
|
||||||
|
};
|
||||||
|
let resources = vec![ResourceGrant {
|
||||||
|
resource_id: format!("urc-{repo_id}"),
|
||||||
|
permission: actions.names().into_iter().map(str::to_owned).collect(),
|
||||||
|
}];
|
||||||
|
let sid = subject.sid.as_deref().unwrap_or_default();
|
||||||
|
let scope = subject.scope.as_deref().unwrap_or_default();
|
||||||
|
let token = self.mint(&user, sid, scope, expires, Some(resources));
|
||||||
|
Ok(json!({
|
||||||
|
"access_token": token,
|
||||||
|
"issued_token_type": ACCESS_TOKEN_TYPE,
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"expires_in": expires - now,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A token for lore-forge's own pages to read repository `repo_id` from `loreserver` as
|
||||||
|
/// `user`: scoped to that repository, carrying only `read`, and valid for a minute. `None`
|
||||||
|
/// when the user cannot read it. No CLI login backs it, so it cannot be refreshed or
|
||||||
|
/// exchanged.
|
||||||
|
pub async fn browse_token(&self, user: &User, repo_id: &str) -> Result<Option<String>, sqlx::Error> {
|
||||||
|
if !forge_access::resolve(&self.pool, &user.id, repo_id).await?.contains(forge_access::Action::Read) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let resources = vec![ResourceGrant { resource_id: format!("urc-{repo_id}"), permission: vec!["read".to_owned()] }];
|
||||||
|
Ok(Some(self.mint(user, "", "", forge_store::now() + BROWSE_TOKEN_SECS, Some(resources))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The revocation endpoint (RFC 7009). Revoking a refresh token, or any token of a login,
|
||||||
|
/// ends that login. Answers success for unknown tokens, as the RFC requires.
|
||||||
|
pub async fn revoke(&self, form: &Form) -> Result<(), OAuthError> {
|
||||||
|
let token = form.require("token")?;
|
||||||
|
if form.get("client_id")? != Some(self.config.client_id.as_str()) {
|
||||||
|
return Err(OAuthError { status: 401, ..OAuthError::new("invalid_client") });
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
let login_id: Option<String> = if token.matches('.').count() == 2 {
|
||||||
|
// An access token: end its login even if the token itself has expired.
|
||||||
|
self.keys
|
||||||
|
.verify::<super::Claims>(token)
|
||||||
|
.ok()
|
||||||
|
.filter(|claims| claims.iss == self.config.issuer)
|
||||||
|
.and_then(|claims| claims.sid)
|
||||||
|
} else {
|
||||||
|
sqlx::query_as::<_, (String,)>("SELECT login_id FROM refresh_tokens WHERE token_hash = ?")
|
||||||
|
.bind(crypto::hash_token(token))
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?
|
||||||
|
.map(|(id,)| id)
|
||||||
|
};
|
||||||
|
if let Some(login_id) = login_id {
|
||||||
|
let mut tx = self.pool.begin().await?;
|
||||||
|
let ended = sqlx::query(
|
||||||
|
"UPDATE cli_logins SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(now)
|
||||||
|
.bind(&login_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if ended.rows_affected() == 1 {
|
||||||
|
forge_store::audit(&mut *tx, None, "cli_login.revoke", &login_id, "").await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,358 @@
|
||||||
|
//! The OpenID Connect issuer `loreserver` trusts.
|
||||||
|
//!
|
||||||
|
//! Implements the capability profile Lore requires of an issuer: discovery and JWKS, the
|
||||||
|
//! device authorization grant, refresh with rotation, token exchange for repository-scoped
|
||||||
|
//! tokens, and revocation. See `.ai/designs/token-issuer.md`.
|
||||||
|
|
||||||
|
mod device;
|
||||||
|
mod grants;
|
||||||
|
|
||||||
|
pub use device::DeviceAuthorization;
|
||||||
|
pub use device::DeviceRequest;
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use crate::keys::JwtError;
|
||||||
|
use crate::keys::Keys;
|
||||||
|
use crate::users::User;
|
||||||
|
|
||||||
|
pub const TOKEN_EXCHANGE: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
|
||||||
|
pub const DEVICE_CODE: &str = "urn:ietf:params:oauth:grant-type:device_code";
|
||||||
|
pub const ACCESS_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token";
|
||||||
|
pub const API_KEY_TOKEN_TYPE: &str = "urn:lore:params:oauth:token-type:api-key";
|
||||||
|
|
||||||
|
/// Paths of the issuer's endpoints under the issuer URL.
|
||||||
|
pub mod paths {
|
||||||
|
pub const DISCOVERY: &str = "/.well-known/openid-configuration";
|
||||||
|
pub const JWKS: &str = "/oauth/jwks";
|
||||||
|
pub const DEVICE_AUTHORIZATION: &str = "/oauth/device_authorization";
|
||||||
|
pub const TOKEN: &str = "/oauth/token";
|
||||||
|
pub const REVOCATION: &str = "/oauth/revoke";
|
||||||
|
pub const DEVICE_VERIFICATION: &str = "/device";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the issuer needs to know about the deployment.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct IssuerConfig {
|
||||||
|
/// The issuer URL, lore-forge's canonical public URL without a trailing slash. This exact
|
||||||
|
/// string is `loreserver`'s `jwt_issuer`.
|
||||||
|
pub issuer: String,
|
||||||
|
/// The `loreserver` deployment URL, without a trailing slash. It is the tokens' audience
|
||||||
|
/// and the base of the resource template.
|
||||||
|
pub lore_url: String,
|
||||||
|
/// The public client ID the Lore CLI presents.
|
||||||
|
pub client_id: String,
|
||||||
|
/// Hosts tokens may be sent to: the `loreserver` host and lore-forge's own, which serves
|
||||||
|
/// Lore's user directory.
|
||||||
|
pub root_domains: Vec<String>,
|
||||||
|
pub lifetimes: Lifetimes,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct Lifetimes {
|
||||||
|
pub login_token_secs: i64,
|
||||||
|
pub scoped_token_secs: i64,
|
||||||
|
pub refresh_idle_secs: i64,
|
||||||
|
pub refresh_max_secs: i64,
|
||||||
|
pub device_code_secs: i64,
|
||||||
|
pub device_interval_secs: i64,
|
||||||
|
/// How long a rotated-out refresh token is still accepted, for a client whose refresh
|
||||||
|
/// response was lost in transit.
|
||||||
|
pub refresh_reuse_grace_secs: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Lifetimes {
|
||||||
|
fn default() -> Self {
|
||||||
|
Lifetimes {
|
||||||
|
login_token_secs: 3600,
|
||||||
|
scoped_token_secs: 300,
|
||||||
|
refresh_idle_secs: 30 * 24 * 3600,
|
||||||
|
refresh_max_secs: 90 * 24 * 3600,
|
||||||
|
device_code_secs: 600,
|
||||||
|
device_interval_secs: 5,
|
||||||
|
refresh_reuse_grace_secs: 60,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IssuerConfig {
|
||||||
|
/// Builds the configuration from the two public URLs.
|
||||||
|
pub fn new(public_url: &url::Url, lore_url: &url::Url, client_id: &str) -> Self {
|
||||||
|
let trim = |url: &url::Url| url.as_str().trim_end_matches('/').to_owned();
|
||||||
|
let mut root_domains = Vec::new();
|
||||||
|
for url in [lore_url, public_url] {
|
||||||
|
if let Some(host) = url.host_str()
|
||||||
|
&& !root_domains.iter().any(|known| known == host)
|
||||||
|
{
|
||||||
|
root_domains.push(host.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
IssuerConfig {
|
||||||
|
issuer: trim(public_url),
|
||||||
|
lore_url: trim(lore_url),
|
||||||
|
client_id: client_id.to_owned(),
|
||||||
|
root_domains,
|
||||||
|
lifetimes: Lifetimes::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `loreserver`'s `resource_template`: how the CLI names a repository on exchange.
|
||||||
|
pub fn resource_template(&self) -> String {
|
||||||
|
format!("{}/partitions/{{id}}", self.lore_url)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resource_prefix(&self) -> String {
|
||||||
|
format!("{}/partitions/", self.lore_url)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn url(&self, path: &str) -> String {
|
||||||
|
format!("{}{path}", self.issuer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One entry of the `resources` claim.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ResourceGrant {
|
||||||
|
pub resource_id: String,
|
||||||
|
pub permission: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The claims of every token this issuer signs.
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Claims {
|
||||||
|
pub iss: String,
|
||||||
|
pub sub: String,
|
||||||
|
pub aud: Vec<String>,
|
||||||
|
pub exp: i64,
|
||||||
|
pub iat: i64,
|
||||||
|
pub jti: String,
|
||||||
|
pub client_id: String,
|
||||||
|
/// The identity Lore records: the stable user ID.
|
||||||
|
pub identity: String,
|
||||||
|
/// The CLI login this token belongs to. Absent on tokens no login backs.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub sid: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub scope: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub name: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub preferred_username: Option<String>,
|
||||||
|
pub root_domains: Vec<String>,
|
||||||
|
/// Present only on repository-scoped tokens.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub resources: Option<Vec<ResourceGrant>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Claims {
|
||||||
|
pub fn is_scoped(&self) -> bool {
|
||||||
|
self.resources.is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An error answered from the token, device authorization or revocation endpoint, in the
|
||||||
|
/// RFC 6749 section 5.2 form.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct OAuthError {
|
||||||
|
pub status: u16,
|
||||||
|
pub error: &'static str,
|
||||||
|
pub description: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OAuthError {
|
||||||
|
pub fn new(error: &'static str) -> Self {
|
||||||
|
OAuthError { status: 400, error, description: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn described(error: &'static str, description: impl Into<String>) -> Self {
|
||||||
|
OAuthError { status: 400, error, description: Some(description.into()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn server_error() -> Self {
|
||||||
|
OAuthError { status: 500, error: "server_error", description: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn body(&self) -> serde_json::Value {
|
||||||
|
match &self.description {
|
||||||
|
Some(description) => json!({ "error": self.error, "error_description": description }),
|
||||||
|
None => json!({ "error": self.error }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<sqlx::Error> for OAuthError {
|
||||||
|
fn from(error: sqlx::Error) -> Self {
|
||||||
|
tracing::error!("issuer database error: {error}");
|
||||||
|
OAuthError::server_error()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The form parameters of a request to an issuer endpoint. RFC 6749 forbids repeating a
|
||||||
|
/// parameter, except where an extension allows it, as RFC 8707 does for `resource`.
|
||||||
|
pub struct Form {
|
||||||
|
pairs: Vec<(String, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Form {
|
||||||
|
pub fn parse(body: &[u8]) -> Self {
|
||||||
|
Form { pairs: url::form_urlencoded::parse(body).into_owned().collect() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The single value of `name`. A repeated parameter is an `invalid_request`.
|
||||||
|
pub fn get(&self, name: &str) -> Result<Option<&str>, OAuthError> {
|
||||||
|
let mut values = self.pairs.iter().filter(|(key, _)| key == name).map(|(_, v)| v.as_str());
|
||||||
|
let first = values.next();
|
||||||
|
if values.next().is_some() {
|
||||||
|
return Err(OAuthError::described("invalid_request", format!("{name} is repeated")));
|
||||||
|
}
|
||||||
|
Ok(first)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn require(&self, name: &str) -> Result<&str, OAuthError> {
|
||||||
|
self.get(name)?
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.ok_or_else(|| OAuthError::described("invalid_request", format!("{name} is missing")))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_all(&self, name: &str) -> Vec<&str> {
|
||||||
|
self.pairs.iter().filter(|(key, _)| key == name).map(|(_, v)| v.as_str()).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum VerifyError {
|
||||||
|
#[error(transparent)]
|
||||||
|
Jwt(#[from] JwtError),
|
||||||
|
#[error("issued by another issuer")]
|
||||||
|
Issuer,
|
||||||
|
#[error("meant for another audience")]
|
||||||
|
Audience,
|
||||||
|
#[error("expired")]
|
||||||
|
Expired,
|
||||||
|
#[error("the login has ended or the account is disabled")]
|
||||||
|
LoginEnded,
|
||||||
|
#[error("a repository-scoped token where a login token is needed")]
|
||||||
|
Scoped,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The issuer: signing keys, configuration and the database.
|
||||||
|
pub struct Issuer {
|
||||||
|
pool: SqlitePool,
|
||||||
|
keys: Arc<Keys>,
|
||||||
|
config: IssuerConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Issuer {
|
||||||
|
pub fn new(pool: SqlitePool, keys: Arc<Keys>, config: IssuerConfig) -> Self {
|
||||||
|
Issuer { pool, keys, config }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn config(&self) -> &IssuerConfig {
|
||||||
|
&self.config
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn keys(&self) -> &Keys {
|
||||||
|
&self.keys
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The OpenID Connect discovery document.
|
||||||
|
pub fn discovery(&self) -> serde_json::Value {
|
||||||
|
let url = |path| self.config.url(path);
|
||||||
|
json!({
|
||||||
|
"issuer": self.config.issuer,
|
||||||
|
"jwks_uri": url(paths::JWKS),
|
||||||
|
"token_endpoint": url(paths::TOKEN),
|
||||||
|
"device_authorization_endpoint": url(paths::DEVICE_AUTHORIZATION),
|
||||||
|
"revocation_endpoint": url(paths::REVOCATION),
|
||||||
|
"grant_types_supported": [DEVICE_CODE, "refresh_token", TOKEN_EXCHANGE, "client_credentials"],
|
||||||
|
// Public clients (the Lore CLI) send none; service accounts send their secret.
|
||||||
|
"token_endpoint_auth_methods_supported": ["none", "client_secret_basic", "client_secret_post"],
|
||||||
|
"revocation_endpoint_auth_methods_supported": ["none"],
|
||||||
|
"response_types_supported": [],
|
||||||
|
"subject_types_supported": ["public"],
|
||||||
|
"id_token_signing_alg_values_supported": [crate::keys::ALG],
|
||||||
|
"scopes_supported": ["openid", "profile", "offline_access"],
|
||||||
|
"claims_supported": ["sub", "identity", "name", "preferred_username", "resources"],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verifies a token this issuer signed for `loreserver`: signature, issuer, audience and
|
||||||
|
/// expiry. Does not consult the database.
|
||||||
|
pub fn verify_token(&self, token: &str) -> Result<Claims, VerifyError> {
|
||||||
|
let claims: Claims = self.keys.verify(token)?;
|
||||||
|
if claims.iss != self.config.issuer {
|
||||||
|
return Err(VerifyError::Issuer);
|
||||||
|
}
|
||||||
|
if !claims.aud.contains(&self.config.lore_url) {
|
||||||
|
return Err(VerifyError::Audience);
|
||||||
|
}
|
||||||
|
if claims.exp <= forge_store::now() {
|
||||||
|
return Err(VerifyError::Expired);
|
||||||
|
}
|
||||||
|
Ok(claims)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verifies a token and checks that the login behind it is live and the account
|
||||||
|
/// enabled. Reads, never writes, so it is safe on the exchange path.
|
||||||
|
pub async fn verify_live(&self, token: &str) -> Result<Claims, LiveError> {
|
||||||
|
let claims = self.verify_token(token)?;
|
||||||
|
let live: Option<(i64,)> = match &claims.sid {
|
||||||
|
Some(sid) => {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT 1 FROM cli_logins l JOIN users u ON u.id = l.user_id
|
||||||
|
WHERE l.id = ? AND l.user_id = ? AND l.revoked_at IS NULL
|
||||||
|
AND l.expires_at > ? AND u.disabled = 0",
|
||||||
|
)
|
||||||
|
.bind(sid)
|
||||||
|
.bind(&claims.sub)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
if live.is_none() {
|
||||||
|
return Err(VerifyError::LoginEnded.into());
|
||||||
|
}
|
||||||
|
Ok(claims)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mint(&self, user: &User, sid: &str, scope: &str, exp: i64, resources: Option<Vec<ResourceGrant>>) -> String {
|
||||||
|
let now = forge_store::now();
|
||||||
|
let claims = Claims {
|
||||||
|
iss: self.config.issuer.clone(),
|
||||||
|
sub: user.id.clone(),
|
||||||
|
aud: vec![self.config.lore_url.clone()],
|
||||||
|
exp,
|
||||||
|
iat: now,
|
||||||
|
jti: crate::crypto::b64url(crate::crypto::random_bytes::<16>()),
|
||||||
|
client_id: self.config.client_id.clone(),
|
||||||
|
identity: user.id.clone(),
|
||||||
|
sid: Some(sid.to_owned()),
|
||||||
|
scope: (!scope.is_empty()).then(|| scope.to_owned()),
|
||||||
|
name: Some(user.display_name.clone()),
|
||||||
|
preferred_username: Some(user.username.clone()),
|
||||||
|
root_domains: self.config.root_domains.clone(),
|
||||||
|
resources,
|
||||||
|
};
|
||||||
|
self.keys.sign(&claims)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A failure of [`Issuer::verify_live`].
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum LiveError {
|
||||||
|
#[error(transparent)]
|
||||||
|
Invalid(#[from] VerifyError),
|
||||||
|
#[error(transparent)]
|
||||||
|
Database(#[from] sqlx::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) mod tests;
|
||||||
|
|
@ -0,0 +1,389 @@
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use forge_store::sqlx;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::crypto::SecretKey;
|
||||||
|
use crate::users;
|
||||||
|
use crate::users::InstanceRole;
|
||||||
|
use crate::users::NewUser;
|
||||||
|
|
||||||
|
pub(crate) struct Fixture {
|
||||||
|
pub issuer: Issuer,
|
||||||
|
pub alice: User,
|
||||||
|
pub _store: forge_store::testing::TestStore,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn fixture() -> Fixture {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool().clone();
|
||||||
|
let secret = SecretKey::from_base64(&SecretKey::generate_base64()).unwrap();
|
||||||
|
let keys = Arc::new(Keys::load_or_create(pool.clone(), secret).await.unwrap());
|
||||||
|
let config = IssuerConfig::new(
|
||||||
|
&"https://forge.example.com/".parse().unwrap(),
|
||||||
|
&"https://lore.example.com".parse().unwrap(),
|
||||||
|
"lore-cli",
|
||||||
|
);
|
||||||
|
let alice = users::create(
|
||||||
|
&pool,
|
||||||
|
NewUser { username: "alice", display_name: "Alice", password: None, role: InstanceRole::Owner },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
Fixture { issuer: Issuer::new(pool, keys, config), alice, _store: store }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn form(pairs: &[(&str, &str)]) -> Form {
|
||||||
|
let body = url::form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish();
|
||||||
|
Form::parse(body.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fixture {
|
||||||
|
/// Runs a device login for alice through to its tokens.
|
||||||
|
pub(crate) async fn login(&self) -> serde_json::Value {
|
||||||
|
let auth = self
|
||||||
|
.issuer
|
||||||
|
.device_authorize(Some("lore-cli"), Some("openid offline_access"), "lore/test")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(self.issuer.decide_device_request(&auth.user_code, &self.alice.id, true).await.unwrap());
|
||||||
|
self.issuer
|
||||||
|
.token(&form(&[
|
||||||
|
("grant_type", DEVICE_CODE),
|
||||||
|
("device_code", &auth.device_code),
|
||||||
|
("client_id", "lore-cli"),
|
||||||
|
]), None)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn exchange(&self, token: &str, resources: &[&str]) -> Result<serde_json::Value, OAuthError> {
|
||||||
|
let mut pairs = vec![
|
||||||
|
("grant_type", TOKEN_EXCHANGE),
|
||||||
|
("client_id", "lore-cli"),
|
||||||
|
("subject_token", token),
|
||||||
|
("subject_token_type", ACCESS_TOKEN_TYPE),
|
||||||
|
("requested_token_type", ACCESS_TOKEN_TYPE),
|
||||||
|
];
|
||||||
|
pairs.extend(resources.iter().map(|resource| ("resource", *resource)));
|
||||||
|
self.issuer.token(&form(&pairs), None).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn refresh(&self, refresh_token: &str) -> Result<serde_json::Value, OAuthError> {
|
||||||
|
self.issuer
|
||||||
|
.token(&form(&[
|
||||||
|
("grant_type", "refresh_token"),
|
||||||
|
("refresh_token", refresh_token),
|
||||||
|
("client_id", "lore-cli"),
|
||||||
|
]), None)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pool(&self) -> &forge_store::SqlitePool {
|
||||||
|
&self.issuer.pool
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resource(id: &str) -> String {
|
||||||
|
format!("https://lore.example.com/partitions/{id}")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_derives_urls_and_domains() {
|
||||||
|
let config = IssuerConfig::new(
|
||||||
|
&"https://forge.example.com/".parse().unwrap(),
|
||||||
|
&"https://lore.example.com:8443/".parse().unwrap(),
|
||||||
|
"lore-cli",
|
||||||
|
);
|
||||||
|
assert_eq!(config.issuer, "https://forge.example.com");
|
||||||
|
assert_eq!(config.lore_url, "https://lore.example.com:8443");
|
||||||
|
assert_eq!(config.root_domains, ["lore.example.com", "forge.example.com"]);
|
||||||
|
assert_eq!(config.resource_template(), "https://lore.example.com:8443/partitions/{id}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn device_login_issues_a_login_token_lore_accepts() {
|
||||||
|
let fx = fixture().await;
|
||||||
|
let tokens = fx.login().await;
|
||||||
|
assert_eq!(tokens["token_type"], "Bearer");
|
||||||
|
assert!(tokens["refresh_token"].as_str().is_some());
|
||||||
|
let claims = fx.issuer.verify_live(tokens["access_token"].as_str().unwrap()).await.unwrap();
|
||||||
|
assert_eq!(claims.sub, fx.alice.id);
|
||||||
|
assert_eq!(claims.identity, fx.alice.id);
|
||||||
|
assert_eq!(claims.aud, ["https://lore.example.com"]);
|
||||||
|
assert_eq!(claims.root_domains, ["lore.example.com", "forge.example.com"]);
|
||||||
|
assert_eq!(claims.preferred_username.as_deref(), Some("alice"));
|
||||||
|
assert!(!claims.is_scoped());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn device_polling_follows_rfc_8628() {
|
||||||
|
let fx = fixture().await;
|
||||||
|
let auth = fx.issuer.device_authorize(Some("lore-cli"), None, "").await.unwrap();
|
||||||
|
assert!(auth.verification_uri_complete.starts_with("https://forge.example.com/device?user_code="));
|
||||||
|
let grant = form(&[
|
||||||
|
("grant_type", DEVICE_CODE),
|
||||||
|
("device_code", &auth.device_code),
|
||||||
|
("client_id", "lore-cli"),
|
||||||
|
]);
|
||||||
|
let poll = || fx.issuer.token(&grant, None);
|
||||||
|
assert_eq!(poll().await.unwrap_err().error, "authorization_pending");
|
||||||
|
assert_eq!(poll().await.unwrap_err().error, "slow_down");
|
||||||
|
|
||||||
|
assert!(fx.issuer.pending_device_request(&auth.user_code).await.unwrap().is_some());
|
||||||
|
fx.issuer.decide_device_request(&auth.user_code, &fx.alice.id, false).await.unwrap();
|
||||||
|
assert_eq!(poll().await.unwrap_err().error, "access_denied");
|
||||||
|
|
||||||
|
let unknown = fx
|
||||||
|
.issuer
|
||||||
|
.token(&form(&[("grant_type", DEVICE_CODE), ("device_code", "nope"), ("client_id", "lore-cli")]), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(unknown.unwrap_err().error, "invalid_grant");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn device_codes_are_single_use_and_expire() {
|
||||||
|
let fx = fixture().await;
|
||||||
|
let auth = fx.issuer.device_authorize(Some("lore-cli"), None, "").await.unwrap();
|
||||||
|
fx.issuer.decide_device_request(&auth.user_code, &fx.alice.id, true).await.unwrap();
|
||||||
|
let grant = form(&[("grant_type", DEVICE_CODE), ("device_code", &auth.device_code), ("client_id", "lore-cli")]);
|
||||||
|
fx.issuer.token(&grant, None).await.unwrap();
|
||||||
|
assert_eq!(fx.issuer.token(&grant, None).await.unwrap_err().error, "invalid_grant");
|
||||||
|
|
||||||
|
let late = fx.issuer.device_authorize(Some("lore-cli"), None, "").await.unwrap();
|
||||||
|
sqlx::query("UPDATE device_codes SET expires_at = 0 WHERE user_code = ?")
|
||||||
|
.bind(&late.user_code)
|
||||||
|
.execute(fx.pool())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(!fx.issuer.decide_device_request(&late.user_code, &fx.alice.id, true).await.unwrap());
|
||||||
|
let poll = form(&[("grant_type", DEVICE_CODE), ("device_code", &late.device_code), ("client_id", "lore-cli")]);
|
||||||
|
assert_eq!(fx.issuer.token(&poll, None).await.unwrap_err().error, "expired_token");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn device_authorization_requires_the_lore_client() {
|
||||||
|
let fx = fixture().await;
|
||||||
|
assert_eq!(fx.issuer.device_authorize(Some("other"), None, "").await.unwrap_err().error, "invalid_client");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn refresh_rotates_and_detects_reuse() {
|
||||||
|
let fx = fixture().await;
|
||||||
|
let first = fx.login().await;
|
||||||
|
let first_refresh = first["refresh_token"].as_str().unwrap();
|
||||||
|
|
||||||
|
let second = fx.refresh(first_refresh).await.unwrap();
|
||||||
|
let second_refresh = second["refresh_token"].as_str().unwrap();
|
||||||
|
assert_ne!(first_refresh, second_refresh);
|
||||||
|
fx.issuer.verify_live(second["access_token"].as_str().unwrap()).await.unwrap();
|
||||||
|
|
||||||
|
// Within the grace period the old token still works (a lost response is retried).
|
||||||
|
let third = fx.refresh(first_refresh).await.unwrap();
|
||||||
|
|
||||||
|
// Past it, reusing a rotated-out token ends the whole login.
|
||||||
|
sqlx::query("UPDATE refresh_tokens SET superseded_at = superseded_at - 3600 WHERE superseded_at IS NOT NULL")
|
||||||
|
.execute(fx.pool())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(fx.refresh(second_refresh).await.unwrap_err().error, "invalid_grant");
|
||||||
|
assert_eq!(fx.refresh(third["refresh_token"].as_str().unwrap()).await.unwrap_err().error, "invalid_grant");
|
||||||
|
assert!(fx.issuer.verify_live(third["access_token"].as_str().unwrap()).await.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn exchange_scopes_a_token_to_one_repository() {
|
||||||
|
let fx = fixture().await;
|
||||||
|
let repo = forge_access::repos::register(fx.pool(), &fx.alice.id, &[7; 16], "alice/game").await.unwrap();
|
||||||
|
let login = fx.login().await;
|
||||||
|
let login_token = login["access_token"].as_str().unwrap();
|
||||||
|
|
||||||
|
let scoped = fx.exchange(login_token, &[&resource(&repo.id)]).await.unwrap();
|
||||||
|
assert_eq!(scoped["issued_token_type"], ACCESS_TOKEN_TYPE);
|
||||||
|
assert!(scoped["expires_in"].as_i64().unwrap() <= 300);
|
||||||
|
let claims = fx.issuer.verify_token(scoped["access_token"].as_str().unwrap()).unwrap();
|
||||||
|
assert_eq!(claims.identity, fx.alice.id);
|
||||||
|
let grants = claims.resources.unwrap();
|
||||||
|
assert_eq!(grants.len(), 1);
|
||||||
|
assert_eq!(grants[0].resource_id, format!("urc-{}", repo.id));
|
||||||
|
assert_eq!(grants[0].permission, ["read", "write", "owner"]);
|
||||||
|
|
||||||
|
// A scoped token cannot be exchanged again.
|
||||||
|
let again = fx.exchange(scoped["access_token"].as_str().unwrap(), &[&resource(&repo.id)]).await;
|
||||||
|
assert_eq!(again.unwrap_err().error, "invalid_grant");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn exchange_refuses_what_it_should() {
|
||||||
|
let fx = fixture().await;
|
||||||
|
let bob = users::create(
|
||||||
|
fx.pool(),
|
||||||
|
NewUser { username: "bob", display_name: "Bob", password: None, role: InstanceRole::Member },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let repo = forge_access::repos::register(fx.pool(), &bob.id, &[8; 16], "bob/secret").await.unwrap();
|
||||||
|
let login = fx.login().await;
|
||||||
|
let token = login["access_token"].as_str().unwrap();
|
||||||
|
|
||||||
|
let error = |result: Result<serde_json::Value, OAuthError>| result.unwrap_err().error;
|
||||||
|
assert_eq!(error(fx.exchange(token, &[&resource(&repo.id)]).await), "invalid_target");
|
||||||
|
assert_eq!(error(fx.exchange(token, &[]).await), "invalid_target");
|
||||||
|
assert_eq!(error(fx.exchange(token, &[&resource("zz")]).await), "invalid_target");
|
||||||
|
assert_eq!(
|
||||||
|
error(fx.exchange(token, &[&format!("https://elsewhere/partitions/{}", repo.id)]).await),
|
||||||
|
"invalid_target"
|
||||||
|
);
|
||||||
|
assert_eq!(error(fx.exchange(token, &[&resource(&repo.id), &resource(&repo.id)]).await), "invalid_target");
|
||||||
|
assert_eq!(error(fx.exchange("not.a.token", &[&resource(&repo.id)]).await), "invalid_grant");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn revocation_and_disabling_stop_new_tokens() {
|
||||||
|
let fx = fixture().await;
|
||||||
|
let repo = forge_access::repos::register(fx.pool(), &fx.alice.id, &[9; 16], "alice/game").await.unwrap();
|
||||||
|
|
||||||
|
let login = fx.login().await;
|
||||||
|
let token = login["access_token"].as_str().unwrap().to_owned();
|
||||||
|
fx.issuer
|
||||||
|
.revoke(&form(&[
|
||||||
|
("token", login["refresh_token"].as_str().unwrap()),
|
||||||
|
("token_type_hint", "refresh_token"),
|
||||||
|
("client_id", "lore-cli"),
|
||||||
|
]))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(fx.exchange(&token, &[&resource(&repo.id)]).await.unwrap_err().error, "invalid_grant");
|
||||||
|
assert_eq!(
|
||||||
|
fx.refresh(login["refresh_token"].as_str().unwrap()).await.unwrap_err().error,
|
||||||
|
"invalid_grant"
|
||||||
|
);
|
||||||
|
// Unknown tokens revoke successfully.
|
||||||
|
fx.issuer.revoke(&form(&[("token", "unknown"), ("client_id", "lore-cli")])).await.unwrap();
|
||||||
|
|
||||||
|
let other = fx.login().await;
|
||||||
|
sqlx::query("UPDATE users SET disabled = 1 WHERE id = ?").bind(&fx.alice.id).execute(fx.pool()).await.unwrap();
|
||||||
|
let other_token = other["access_token"].as_str().unwrap();
|
||||||
|
assert_eq!(fx.exchange(other_token, &[&resource(&repo.id)]).await.unwrap_err().error, "invalid_grant");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tokens_for_another_audience_or_issuer_do_not_verify() {
|
||||||
|
let fx = fixture().await;
|
||||||
|
let login = fx.login().await;
|
||||||
|
let token = login["access_token"].as_str().unwrap();
|
||||||
|
let mut claims = fx.issuer.verify_token(token).unwrap();
|
||||||
|
claims.aud = vec!["https://other.example.com".into()];
|
||||||
|
let foreign = fx.issuer.keys.sign(&claims);
|
||||||
|
assert_eq!(fx.issuer.verify_token(&foreign).unwrap_err(), VerifyError::Audience);
|
||||||
|
claims.aud = vec!["https://lore.example.com".into()];
|
||||||
|
claims.exp = 1;
|
||||||
|
assert_eq!(fx.issuer.verify_token(&fx.issuer.keys.sign(&claims)).unwrap_err(), VerifyError::Expired);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn repeated_parameters_are_invalid() {
|
||||||
|
let fx = fixture().await;
|
||||||
|
let result = fx
|
||||||
|
.issuer
|
||||||
|
.token(&form(&[("grant_type", "refresh_token"), ("grant_type", "refresh_token")]), None)
|
||||||
|
.await;
|
||||||
|
assert_eq!(result.unwrap_err().error, "invalid_request");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_api_token_logs_the_cli_in_until_revoked() {
|
||||||
|
use crate::api_tokens;
|
||||||
|
let fx = fixture().await;
|
||||||
|
let repo = forge_access::repos::register(fx.pool(), &fx.alice.id, &[8; 16], "alice/ci").await.unwrap();
|
||||||
|
let new = api_tokens::create(fx.pool(), &fx.alice.id, "ci", &[api_tokens::Scope::Lore], None, &fx.alice.id)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
// `lore auth login --token-type api-key` sends the type verbatim; the URN works too.
|
||||||
|
for token_type in ["api-key", API_KEY_TOKEN_TYPE] {
|
||||||
|
let login = fx
|
||||||
|
.issuer
|
||||||
|
.token(&form(&[
|
||||||
|
("grant_type", TOKEN_EXCHANGE),
|
||||||
|
("client_id", "lore-cli"),
|
||||||
|
("subject_token", &new.secret),
|
||||||
|
("subject_token_type", token_type),
|
||||||
|
("requested_token_type", ACCESS_TOKEN_TYPE),
|
||||||
|
]), None)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(login["refresh_token"].is_string());
|
||||||
|
let access = login["access_token"].as_str().unwrap();
|
||||||
|
fx.exchange(access, &[&resource(&repo.id)]).await.unwrap();
|
||||||
|
}
|
||||||
|
let wrong = form(&[
|
||||||
|
("grant_type", TOKEN_EXCHANGE),
|
||||||
|
("client_id", "lore-cli"),
|
||||||
|
("subject_token", "lf_wrong"),
|
||||||
|
("subject_token_type", "api-key"),
|
||||||
|
]);
|
||||||
|
assert_eq!(fx.issuer.token(&wrong, None).await.unwrap_err().error, "invalid_grant");
|
||||||
|
|
||||||
|
let login = fx
|
||||||
|
.issuer
|
||||||
|
.token(&form(&[
|
||||||
|
("grant_type", TOKEN_EXCHANGE),
|
||||||
|
("client_id", "lore-cli"),
|
||||||
|
("subject_token", &new.secret),
|
||||||
|
("subject_token_type", "api-key"),
|
||||||
|
]), None)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
api_tokens::revoke(fx.pool(), &fx.alice.id, &new.token.id, &fx.alice.id).await.unwrap();
|
||||||
|
let access = login["access_token"].as_str().unwrap();
|
||||||
|
assert_eq!(fx.exchange(access, &[&resource(&repo.id)]).await.unwrap_err().error, "invalid_grant");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_service_account_logs_in_with_client_credentials() {
|
||||||
|
use base64::Engine;
|
||||||
|
use crate::api_tokens;
|
||||||
|
let fx = fixture().await;
|
||||||
|
let repo = forge_access::repos::register(fx.pool(), &fx.alice.id, &[9; 16], "alice/game").await.unwrap();
|
||||||
|
let ci = users::create_service_account(fx.pool(), "alice", "ci", "CI", &fx.alice.id).await.unwrap();
|
||||||
|
assert_eq!(ci.username, "alice.ci");
|
||||||
|
forge_access::orgs::set_grant(
|
||||||
|
fx.pool(),
|
||||||
|
&repo.id,
|
||||||
|
forge_access::orgs::Subject::User(&ci.id),
|
||||||
|
Some(forge_access::Preset::Writer),
|
||||||
|
forge_access::ActionSet::of(&[forge_access::Action::PushProtected]),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let new = api_tokens::create(fx.pool(), &ci.id, "build", &[api_tokens::Scope::Lore], None, &fx.alice.id)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let basic = format!(
|
||||||
|
"Basic {}",
|
||||||
|
base64::engine::general_purpose::STANDARD.encode(format!("alice.ci:{}", new.secret))
|
||||||
|
);
|
||||||
|
let grant = form(&[("grant_type", "client_credentials")]);
|
||||||
|
let login = fx.issuer.token(&grant, Some(&basic)).await.unwrap();
|
||||||
|
assert!(login.get("refresh_token").is_none());
|
||||||
|
let access = login["access_token"].as_str().unwrap();
|
||||||
|
let scoped = fx.exchange(access, &[&resource(&repo.id)]).await.unwrap();
|
||||||
|
let claims = fx.issuer.verify_token(scoped["access_token"].as_str().unwrap()).unwrap();
|
||||||
|
assert_eq!(claims.identity, ci.id);
|
||||||
|
assert_eq!(claims.resources.unwrap()[0].permission, ["read", "write", "push-protected"]);
|
||||||
|
|
||||||
|
// client_secret_post works too; a wrong name or a person's token does not.
|
||||||
|
let post = form(&[("grant_type", "client_credentials"), ("client_id", "alice.ci"), ("client_secret", &new.secret)]);
|
||||||
|
fx.issuer.token(&post, None).await.unwrap();
|
||||||
|
let wrong = format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(format!("alice.cd:{}", new.secret)));
|
||||||
|
assert_eq!(fx.issuer.token(&grant, Some(&wrong)).await.unwrap_err().error, "invalid_client");
|
||||||
|
let personal = api_tokens::create(fx.pool(), &fx.alice.id, "me", &[api_tokens::Scope::Lore], None, &fx.alice.id)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let person = form(&[("grant_type", "client_credentials"), ("client_id", "alice"), ("client_secret", &personal.secret)]);
|
||||||
|
assert_eq!(fx.issuer.token(&person, None).await.unwrap_err().error, "invalid_client");
|
||||||
|
|
||||||
|
// Revoking the secret ends the login.
|
||||||
|
api_tokens::revoke(fx.pool(), &ci.id, &new.token.id, &fx.alice.id).await.unwrap();
|
||||||
|
assert_eq!(fx.exchange(access, &[&resource(&repo.id)]).await.unwrap_err().error, "invalid_grant");
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,310 @@
|
||||||
|
//! Token signing keys and the JWTs signed with them.
|
||||||
|
//!
|
||||||
|
//! Keys are ES256 (P-256), persisted encrypted under the [`SecretKey`] so they survive
|
||||||
|
//! restarts. The JWKS lists the current key and the previous one, so tokens signed just
|
||||||
|
//! before a rotation keep verifying, and `loreserver` re-fetches keys when it meets an
|
||||||
|
//! unknown key ID.
|
||||||
|
//!
|
||||||
|
//! Only tokens this issuer signed are ever verified here, so verification accepts exactly the
|
||||||
|
//! form this module produces: `alg` ES256, `typ` `at+jwt` and a known `kid`.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::RwLock;
|
||||||
|
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
use p256::ecdsa::Signature;
|
||||||
|
use p256::ecdsa::SigningKey;
|
||||||
|
use p256::ecdsa::VerifyingKey;
|
||||||
|
use p256::ecdsa::signature::Signer;
|
||||||
|
use p256::ecdsa::signature::Verifier;
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use crate::crypto::SecretKey;
|
||||||
|
use crate::crypto::b64url;
|
||||||
|
use crate::crypto::b64url_decode;
|
||||||
|
use crate::crypto::random_bytes;
|
||||||
|
|
||||||
|
pub const ALG: &str = "ES256";
|
||||||
|
pub const TYP: &str = "at+jwt";
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum KeyError {
|
||||||
|
#[error(transparent)]
|
||||||
|
Database(#[from] sqlx::Error),
|
||||||
|
#[error("signing key {0} cannot be decrypted with the configured secret key")]
|
||||||
|
Undecryptable(String),
|
||||||
|
#[error("signing key {0} is corrupt")]
|
||||||
|
Corrupt(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum JwtError {
|
||||||
|
#[error("not a JWT")]
|
||||||
|
Malformed,
|
||||||
|
#[error("not signed the way this issuer signs")]
|
||||||
|
UnexpectedHeader,
|
||||||
|
#[error("signed with an unknown key")]
|
||||||
|
UnknownKey,
|
||||||
|
#[error("bad signature")]
|
||||||
|
BadSignature,
|
||||||
|
#[error("claims are not the expected shape")]
|
||||||
|
Claims,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Ring {
|
||||||
|
kid: String,
|
||||||
|
signing: SigningKey,
|
||||||
|
verifying: HashMap<String, VerifyingKey>,
|
||||||
|
jwks: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The issuer's signing keys, loaded into memory.
|
||||||
|
pub struct Keys {
|
||||||
|
pool: SqlitePool,
|
||||||
|
secret: SecretKey,
|
||||||
|
ring: RwLock<Arc<Ring>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn jwk(kid: &str, key: &VerifyingKey) -> serde_json::Value {
|
||||||
|
let point = key.to_sec1_point(false);
|
||||||
|
json!({
|
||||||
|
"kty": "EC",
|
||||||
|
"crv": "P-256",
|
||||||
|
"x": b64url(point.x().expect("uncompressed point has x")),
|
||||||
|
"y": b64url(point.y().expect("uncompressed point has y")),
|
||||||
|
"kid": kid,
|
||||||
|
"alg": ALG,
|
||||||
|
"use": "sig",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate() -> SigningKey {
|
||||||
|
loop {
|
||||||
|
if let Ok(key) = SigningKey::from_slice(&random_bytes::<32>()) {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn context(kid: &str) -> String {
|
||||||
|
format!("lore-forge signing key {kid}")
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Keys {
|
||||||
|
/// Loads the stored keys, creating the first one on a new instance.
|
||||||
|
pub async fn load_or_create(pool: SqlitePool, secret: SecretKey) -> Result<Self, KeyError> {
|
||||||
|
let has_current: Option<(String,)> =
|
||||||
|
sqlx::query_as("SELECT kid FROM signing_keys WHERE state = 'current'")
|
||||||
|
.fetch_optional(&pool)
|
||||||
|
.await?;
|
||||||
|
if has_current.is_none() {
|
||||||
|
insert_new(&pool, &secret).await?;
|
||||||
|
tracing::info!("created the first token signing key");
|
||||||
|
}
|
||||||
|
let ring = load(&pool, &secret).await?;
|
||||||
|
Ok(Self { pool, secret, ring: RwLock::new(Arc::new(ring)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Makes a new key current. The old current key stays in the JWKS as the previous key;
|
||||||
|
/// the key before it is retired and its tokens stop verifying.
|
||||||
|
pub async fn rotate(&self) -> Result<(), KeyError> {
|
||||||
|
let mut tx = self.pool.begin().await?;
|
||||||
|
sqlx::query("UPDATE signing_keys SET state = 'retired' WHERE state = 'previous'")
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("UPDATE signing_keys SET state = 'previous' WHERE state = 'current'")
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
insert_new(&mut *tx, &self.secret).await?;
|
||||||
|
forge_store::audit(&mut *tx, None, "keys.rotate", "", "").await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
let ring = load(&self.pool, &self.secret).await?;
|
||||||
|
*self.ring.write().expect("key ring lock") = Arc::new(ring);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-reads the keys from the database, so a rotation made by another process (the
|
||||||
|
/// `rotate-signing-key` command) reaches this one.
|
||||||
|
pub async fn reload(&self) -> Result<(), KeyError> {
|
||||||
|
let ring = load(&self.pool, &self.secret).await?;
|
||||||
|
*self.ring.write().expect("key ring lock") = Arc::new(ring);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current key's ID and when it was created.
|
||||||
|
pub async fn current(&self) -> Result<Option<(String, i64)>, sqlx::Error> {
|
||||||
|
sqlx::query_as("SELECT kid, created_at FROM signing_keys WHERE state = 'current'")
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ring(&self) -> Arc<Ring> {
|
||||||
|
self.ring.read().expect("key ring lock").clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The public keys for the JWKS endpoint.
|
||||||
|
pub fn jwks(&self) -> serde_json::Value {
|
||||||
|
self.ring().jwks.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signs `claims` as an `at+jwt` with the current key.
|
||||||
|
pub fn sign<C: Serialize>(&self, claims: &C) -> String {
|
||||||
|
let ring = self.ring();
|
||||||
|
let header = json!({ "alg": ALG, "typ": TYP, "kid": ring.kid });
|
||||||
|
let input = format!(
|
||||||
|
"{}.{}",
|
||||||
|
b64url(serde_json::to_vec(&header).expect("header serialises")),
|
||||||
|
b64url(serde_json::to_vec(claims).expect("claims serialise")),
|
||||||
|
);
|
||||||
|
let signature: Signature = ring.signing.sign(input.as_bytes());
|
||||||
|
format!("{input}.{}", b64url(signature.to_bytes()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks the signature of a token this issuer signed and decodes its claims. Says
|
||||||
|
/// nothing about expiry or audience; callers check those.
|
||||||
|
pub fn verify<C: DeserializeOwned>(&self, token: &str) -> Result<C, JwtError> {
|
||||||
|
let mut parts = token.split('.');
|
||||||
|
let (Some(header), Some(payload), Some(signature), None) =
|
||||||
|
(parts.next(), parts.next(), parts.next(), parts.next())
|
||||||
|
else {
|
||||||
|
return Err(JwtError::Malformed);
|
||||||
|
};
|
||||||
|
let header_json: serde_json::Value =
|
||||||
|
serde_json::from_slice(&b64url_decode(header).ok_or(JwtError::Malformed)?)
|
||||||
|
.map_err(|_| JwtError::Malformed)?;
|
||||||
|
if header_json.get("alg").and_then(|v| v.as_str()) != Some(ALG)
|
||||||
|
|| header_json.get("typ").and_then(|v| v.as_str()) != Some(TYP)
|
||||||
|
{
|
||||||
|
return Err(JwtError::UnexpectedHeader);
|
||||||
|
}
|
||||||
|
let kid = header_json.get("kid").and_then(|v| v.as_str()).ok_or(JwtError::UnexpectedHeader)?;
|
||||||
|
let ring = self.ring();
|
||||||
|
let key = ring.verifying.get(kid).ok_or(JwtError::UnknownKey)?;
|
||||||
|
let signature = b64url_decode(signature).ok_or(JwtError::Malformed)?;
|
||||||
|
let signature = Signature::from_slice(&signature).map_err(|_| JwtError::BadSignature)?;
|
||||||
|
let signed = &token[..header.len() + 1 + payload.len()];
|
||||||
|
key.verify(signed.as_bytes(), &signature).map_err(|_| JwtError::BadSignature)?;
|
||||||
|
serde_json::from_slice(&b64url_decode(payload).ok_or(JwtError::Malformed)?)
|
||||||
|
.map_err(|_| JwtError::Claims)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn insert_new<'e, E>(executor: E, secret: &SecretKey) -> Result<(), KeyError>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Sqlite>,
|
||||||
|
{
|
||||||
|
let key = generate();
|
||||||
|
let kid = b64url(random_bytes::<12>());
|
||||||
|
let public = jwk(&kid, key.verifying_key());
|
||||||
|
let sealed = secret.seal(&context(&kid), &key.to_bytes());
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO signing_keys (kid, alg, private_key, public_jwk, state, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, 'current', ?)",
|
||||||
|
)
|
||||||
|
.bind(&kid)
|
||||||
|
.bind(ALG)
|
||||||
|
.bind(sealed)
|
||||||
|
.bind(public.to_string())
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.execute(executor)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn load(pool: &SqlitePool, secret: &SecretKey) -> Result<Ring, KeyError> {
|
||||||
|
let rows: Vec<(String, Vec<u8>, String)> = sqlx::query_as(
|
||||||
|
"SELECT kid, private_key, state FROM signing_keys
|
||||||
|
WHERE state IN ('current', 'previous') ORDER BY state = 'current' DESC",
|
||||||
|
)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
let mut current = None;
|
||||||
|
let mut verifying = HashMap::new();
|
||||||
|
let mut public = Vec::new();
|
||||||
|
for (kid, sealed, state) in rows {
|
||||||
|
let bytes = secret
|
||||||
|
.open(&context(&kid), &sealed)
|
||||||
|
.map_err(|_| KeyError::Undecryptable(kid.clone()))?;
|
||||||
|
let signing =
|
||||||
|
SigningKey::from_slice(&bytes).map_err(|_| KeyError::Corrupt(kid.clone()))?;
|
||||||
|
let verifying_key = *signing.verifying_key();
|
||||||
|
public.push(jwk(&kid, &verifying_key));
|
||||||
|
verifying.insert(kid.clone(), verifying_key);
|
||||||
|
if state == "current" {
|
||||||
|
current = Some((kid, signing));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (kid, signing) = current.ok_or_else(|| KeyError::Corrupt("current".into()))?;
|
||||||
|
Ok(Ring { kid, signing, verifying, jwks: json!({ "keys": public }) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
async fn keys(store: &forge_store::Store, secret: &SecretKey) -> Keys {
|
||||||
|
Keys::load_or_create(store.pool().clone(), secret.clone()).await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn signs_verifies_and_survives_restart() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let secret = SecretKey::from_base64(&SecretKey::generate_base64()).unwrap();
|
||||||
|
let first = keys(&store, &secret).await;
|
||||||
|
let token = first.sign(&json!({ "sub": "u1" }));
|
||||||
|
let claims: serde_json::Value = first.verify(&token).unwrap();
|
||||||
|
assert_eq!(claims["sub"], "u1");
|
||||||
|
|
||||||
|
let reloaded = keys(&store, &secret).await;
|
||||||
|
assert_eq!(reloaded.jwks(), first.jwks());
|
||||||
|
let _: serde_json::Value = reloaded.verify(&token).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rejects_tampering_and_foreign_headers() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let secret = SecretKey::from_base64(&SecretKey::generate_base64()).unwrap();
|
||||||
|
let keys = keys(&store, &secret).await;
|
||||||
|
let token = keys.sign(&json!({ "sub": "u1" }));
|
||||||
|
let (signed, signature) = token.rsplit_once('.').unwrap();
|
||||||
|
let (header, _) = signed.split_once('.').unwrap();
|
||||||
|
|
||||||
|
let forged_payload = format!("{header}.{}.{signature}", b64url(br#"{"sub":"admin"}"#));
|
||||||
|
assert_eq!(keys.verify::<serde_json::Value>(&forged_payload), Err(JwtError::BadSignature));
|
||||||
|
|
||||||
|
let none_header = b64url(br#"{"alg":"none","typ":"at+jwt"}"#);
|
||||||
|
let unsigned = format!("{none_header}.{}.", b64url(br#"{"sub":"admin"}"#));
|
||||||
|
assert_eq!(keys.verify::<serde_json::Value>(&unsigned), Err(JwtError::UnexpectedHeader));
|
||||||
|
|
||||||
|
assert_eq!(keys.verify::<serde_json::Value>("a.b"), Err(JwtError::Malformed));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rotation_keeps_the_previous_key_for_one_generation() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let secret = SecretKey::from_base64(&SecretKey::generate_base64()).unwrap();
|
||||||
|
let keys = keys(&store, &secret).await;
|
||||||
|
let old = keys.sign(&json!({ "n": 1 }));
|
||||||
|
keys.rotate().await.unwrap();
|
||||||
|
assert_eq!(keys.jwks()["keys"].as_array().unwrap().len(), 2);
|
||||||
|
let _: serde_json::Value = keys.verify(&old).unwrap();
|
||||||
|
keys.rotate().await.unwrap();
|
||||||
|
assert_eq!(keys.verify::<serde_json::Value>(&old), Err(JwtError::UnknownKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_different_secret_key_cannot_load_the_keys() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let secret = SecretKey::from_base64(&SecretKey::generate_base64()).unwrap();
|
||||||
|
keys(&store, &secret).await;
|
||||||
|
let other = SecretKey::from_base64(&SecretKey::generate_base64()).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
Keys::load_or_create(store.pool().clone(), other).await,
|
||||||
|
Err(KeyError::Undecryptable(_))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
//! Accounts, sessions and the OpenID Connect issuer that `loreserver` trusts.
|
||||||
|
|
||||||
|
pub mod api_tokens;
|
||||||
|
pub mod crypto;
|
||||||
|
pub mod instance;
|
||||||
|
pub mod invites;
|
||||||
|
pub mod issuer;
|
||||||
|
pub mod keys;
|
||||||
|
pub mod oauth;
|
||||||
|
pub mod password;
|
||||||
|
pub mod sessions;
|
||||||
|
pub mod users;
|
||||||
|
|
||||||
|
pub use issuer::Issuer;
|
||||||
|
pub use issuer::IssuerConfig;
|
||||||
|
pub use users::User;
|
||||||
|
|
@ -0,0 +1,750 @@
|
||||||
|
//! Sign-in through GitHub, Discord and Google, as in piki.
|
||||||
|
//!
|
||||||
|
//! - A provider signs a person in only to an account that linked it while signed in. Links
|
||||||
|
//! are keyed by `(provider, subject id)` and never matched by email or username.
|
||||||
|
//! - Each attempt is a single-use flow row with a hashed state, a PKCE verifier and, for
|
||||||
|
//! Google, a nonce. Flows expire after ten minutes.
|
||||||
|
//! - Provider tokens are used once to read the identity, then revoked (GitHub, Discord) or
|
||||||
|
//! discarded (Google, whose revocation would end the whole grant).
|
||||||
|
//! - Client secrets are stored sealed under the [`SecretKey`].
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use sha2::Digest;
|
||||||
|
|
||||||
|
use crate::crypto;
|
||||||
|
use crate::crypto::SecretKey;
|
||||||
|
|
||||||
|
const FLOW_SECS: i64 = 600;
|
||||||
|
const MAX_RESPONSE_BYTES: usize = 1 << 20;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Provider {
|
||||||
|
GitHub,
|
||||||
|
Discord,
|
||||||
|
Google,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Provider {
|
||||||
|
pub const ALL: [Provider; 3] = [Provider::GitHub, Provider::Discord, Provider::Google];
|
||||||
|
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Provider::GitHub => "github",
|
||||||
|
Provider::Discord => "discord",
|
||||||
|
Provider::Google => "google",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Provider::GitHub => "GitHub",
|
||||||
|
Provider::Discord => "Discord",
|
||||||
|
Provider::Google => "Google",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(text: &str) -> Option<Provider> {
|
||||||
|
Provider::ALL.into_iter().find(|p| p.as_str() == text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the provider's developer settings are, for the settings page.
|
||||||
|
pub fn console_url(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Provider::GitHub => "https://github.com/settings/developers",
|
||||||
|
Provider::Discord => "https://discord.com/developers/applications",
|
||||||
|
Provider::Google => "https://console.cloud.google.com/apis/credentials",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A provider's endpoints. Real ones in production; tests point them at a fake provider.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Endpoints {
|
||||||
|
pub authorize: String,
|
||||||
|
pub token: String,
|
||||||
|
/// GitHub and Discord: the current-user endpoint.
|
||||||
|
pub identity: String,
|
||||||
|
/// GitHub: the base under which `/applications/{client_id}/token` revokes. Discord: the
|
||||||
|
/// revocation endpoint. Google: unused.
|
||||||
|
pub revoke: String,
|
||||||
|
/// Google: the accepted `iss` values of ID tokens.
|
||||||
|
pub issuers: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Endpoints {
|
||||||
|
pub fn real(provider: Provider) -> Endpoints {
|
||||||
|
let s = str::to_owned;
|
||||||
|
match provider {
|
||||||
|
Provider::GitHub => Endpoints {
|
||||||
|
authorize: s("https://github.com/login/oauth/authorize"),
|
||||||
|
token: s("https://github.com/login/oauth/access_token"),
|
||||||
|
identity: s("https://api.github.com/user"),
|
||||||
|
revoke: s("https://api.github.com"),
|
||||||
|
issuers: vec![],
|
||||||
|
},
|
||||||
|
Provider::Discord => Endpoints {
|
||||||
|
authorize: s("https://discord.com/oauth2/authorize"),
|
||||||
|
token: s("https://discord.com/api/oauth2/token"),
|
||||||
|
identity: s("https://discord.com/api/v10/users/@me"),
|
||||||
|
revoke: s("https://discord.com/api/oauth2/token/revoke"),
|
||||||
|
issuers: vec![],
|
||||||
|
},
|
||||||
|
Provider::Google => Endpoints {
|
||||||
|
authorize: s("https://accounts.google.com/o/oauth2/v2/auth"),
|
||||||
|
token: s("https://oauth2.googleapis.com/token"),
|
||||||
|
identity: String::new(),
|
||||||
|
revoke: String::new(),
|
||||||
|
issuers: vec![s("https://accounts.google.com"), s("accounts.google.com")],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Endpoints under `base`, for a fake provider in tests: `{base}/{provider}/authorize`
|
||||||
|
/// and so on.
|
||||||
|
pub fn under(base: &str, provider: Provider) -> Endpoints {
|
||||||
|
let at = |path: &str| format!("{base}/{}/{path}", provider.as_str());
|
||||||
|
Endpoints {
|
||||||
|
authorize: at("authorize"),
|
||||||
|
token: at("token"),
|
||||||
|
identity: at("user"),
|
||||||
|
revoke: if provider == Provider::Discord { at("revoke") } else { format!("{base}/github") },
|
||||||
|
issuers: vec![base.to_owned()],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the settings page shows of a provider's configuration. Never the secret.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ConfigSummary {
|
||||||
|
pub provider: Provider,
|
||||||
|
pub client_id: String,
|
||||||
|
pub has_secret: bool,
|
||||||
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Config {
|
||||||
|
client_id: String,
|
||||||
|
client_secret: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A provider account as the provider describes it.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Identity {
|
||||||
|
pub provider: Provider,
|
||||||
|
pub subject_id: String,
|
||||||
|
pub username: String,
|
||||||
|
pub display_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A provider account linked to a lore-forge account.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Linked {
|
||||||
|
pub provider: Provider,
|
||||||
|
pub username: String,
|
||||||
|
pub created_at: i64,
|
||||||
|
pub last_used_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Intent {
|
||||||
|
SignIn,
|
||||||
|
Link,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Intent {
|
||||||
|
fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Intent::SignIn => "signin",
|
||||||
|
Intent::Link => "link",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A completed flow, for the web layer to act on.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Finished {
|
||||||
|
pub intent: Intent,
|
||||||
|
pub user_id: Option<String>,
|
||||||
|
pub session_id: Option<String>,
|
||||||
|
pub next: String,
|
||||||
|
pub persistent: bool,
|
||||||
|
pub identity: Identity,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum OAuthError {
|
||||||
|
#[error("{0} sign-in is not set up")]
|
||||||
|
NotConfigured(&'static str),
|
||||||
|
#[error("this sign-in attempt expired or was already used; start again")]
|
||||||
|
BadState,
|
||||||
|
#[error("the provider refused: {0}")]
|
||||||
|
Provider(String),
|
||||||
|
#[error("that {0} account is already linked to another account")]
|
||||||
|
LinkedElsewhere(&'static str),
|
||||||
|
#[error("this account already has a {0} account linked")]
|
||||||
|
AlreadyLinked(&'static str),
|
||||||
|
#[error("this is the account's only way to sign in; set a password first")]
|
||||||
|
LastMethod,
|
||||||
|
#[error("the stored client secret cannot be decrypted with the configured secret key")]
|
||||||
|
Undecryptable,
|
||||||
|
#[error(transparent)]
|
||||||
|
Database(#[from] sqlx::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Provider configuration, flows and links.
|
||||||
|
pub struct OAuth {
|
||||||
|
pool: SqlitePool,
|
||||||
|
secret: SecretKey,
|
||||||
|
http: reqwest::Client,
|
||||||
|
test_base: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OAuth {
|
||||||
|
pub fn new(pool: SqlitePool, secret: SecretKey) -> OAuth {
|
||||||
|
let http = reqwest::Client::builder()
|
||||||
|
.timeout(Duration::from_secs(15))
|
||||||
|
.redirect(reqwest::redirect::Policy::none())
|
||||||
|
.user_agent("lore-forge")
|
||||||
|
.build()
|
||||||
|
.expect("HTTP client");
|
||||||
|
OAuth { pool, secret, http, test_base: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends every provider request under `base` instead, for tests.
|
||||||
|
pub fn with_test_base(mut self, base: &str) -> OAuth {
|
||||||
|
self.test_base = Some(base.trim_end_matches('/').to_owned());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn endpoints(&self, provider: Provider) -> Endpoints {
|
||||||
|
match &self.test_base {
|
||||||
|
Some(base) => Endpoints::under(base, provider),
|
||||||
|
None => Endpoints::real(provider),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn context(provider: Provider) -> String {
|
||||||
|
format!("oauth.{}", provider.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn summaries(&self) -> Result<Vec<ConfigSummary>, sqlx::Error> {
|
||||||
|
let rows: Vec<(String, String, Option<Vec<u8>>, bool)> =
|
||||||
|
sqlx::query_as("SELECT provider, client_id, client_secret, enabled FROM oauth_provider_configs")
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(Provider::ALL
|
||||||
|
.into_iter()
|
||||||
|
.map(|provider| {
|
||||||
|
let row = rows.iter().find(|row| row.0 == provider.as_str());
|
||||||
|
ConfigSummary {
|
||||||
|
provider,
|
||||||
|
client_id: row.map(|row| row.1.clone()).unwrap_or_default(),
|
||||||
|
has_secret: row.is_some_and(|row| row.2.is_some()),
|
||||||
|
enabled: row.is_some_and(|row| row.3),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The providers people can sign in with.
|
||||||
|
pub async fn enabled(&self) -> Result<Vec<Provider>, sqlx::Error> {
|
||||||
|
Ok(self
|
||||||
|
.summaries()
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|s| s.enabled && s.has_secret && !s.client_id.is_empty())
|
||||||
|
.map(|s| s.provider)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves a provider's configuration. An empty `client_secret` keeps the stored one.
|
||||||
|
pub async fn save(
|
||||||
|
&self,
|
||||||
|
provider: Provider,
|
||||||
|
client_id: &str,
|
||||||
|
client_secret: &str,
|
||||||
|
enabled: bool,
|
||||||
|
actor_id: &str,
|
||||||
|
) -> Result<(), sqlx::Error> {
|
||||||
|
let client_id = client_id.trim();
|
||||||
|
let sealed = (!client_secret.trim().is_empty())
|
||||||
|
.then(|| self.secret.seal(&Self::context(provider), client_secret.trim().as_bytes()));
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO oauth_provider_configs (provider, client_id, client_secret, enabled, updated_by,
|
||||||
|
updated_at)
|
||||||
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
|
||||||
|
ON CONFLICT (provider) DO UPDATE SET
|
||||||
|
client_id = excluded.client_id,
|
||||||
|
client_secret = coalesce(?3, oauth_provider_configs.client_secret),
|
||||||
|
enabled = excluded.enabled, updated_by = excluded.updated_by,
|
||||||
|
updated_at = excluded.updated_at",
|
||||||
|
)
|
||||||
|
.bind(provider.as_str())
|
||||||
|
.bind(client_id)
|
||||||
|
.bind(sealed)
|
||||||
|
.bind(enabled)
|
||||||
|
.bind(actor_id)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
let detail = format!("enabled={enabled}");
|
||||||
|
forge_store::audit(&self.pool, Some(actor_id), "oauth.configure", provider.as_str(), &detail).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn config(&self, provider: Provider) -> Result<Config, OAuthError> {
|
||||||
|
let row: Option<(String, Option<Vec<u8>>, bool)> = sqlx::query_as(
|
||||||
|
"SELECT client_id, client_secret, enabled FROM oauth_provider_configs WHERE provider = ?",
|
||||||
|
)
|
||||||
|
.bind(provider.as_str())
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
let Some((client_id, Some(sealed), true)) = row.filter(|row| !row.0.is_empty()) else {
|
||||||
|
return Err(OAuthError::NotConfigured(provider.label()));
|
||||||
|
};
|
||||||
|
let secret = self.secret.open(&Self::context(provider), &sealed).map_err(|_| OAuthError::Undecryptable)?;
|
||||||
|
let client_secret = String::from_utf8(secret).map_err(|_| OAuthError::Undecryptable)?;
|
||||||
|
Ok(Config { client_id, client_secret })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts a flow and answers the provider URL to send the browser to.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub async fn start(
|
||||||
|
&self,
|
||||||
|
provider: Provider,
|
||||||
|
intent: Intent,
|
||||||
|
user_id: Option<&str>,
|
||||||
|
session_id: Option<&str>,
|
||||||
|
next: &str,
|
||||||
|
persistent: bool,
|
||||||
|
redirect_uri: &str,
|
||||||
|
) -> Result<String, OAuthError> {
|
||||||
|
let config = self.config(provider).await?;
|
||||||
|
let now = forge_store::now();
|
||||||
|
let state = crypto::random_token();
|
||||||
|
let verifier = crypto::random_token();
|
||||||
|
let nonce = if provider == Provider::Google { crypto::random_token() } else { String::new() };
|
||||||
|
// Expired flows are cleared here rather than by a background task.
|
||||||
|
sqlx::query("DELETE FROM oauth_flows WHERE expires_at < ?").bind(now).execute(&self.pool).await?;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO oauth_flows (state_hash, provider, intent, user_id, session_id, next_path,
|
||||||
|
pkce_verifier, nonce, persistent, created_at, expires_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(crypto::hash_token(&state))
|
||||||
|
.bind(provider.as_str())
|
||||||
|
.bind(intent.as_str())
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(session_id)
|
||||||
|
.bind(next)
|
||||||
|
.bind(&verifier)
|
||||||
|
.bind(&nonce)
|
||||||
|
.bind(persistent)
|
||||||
|
.bind(now)
|
||||||
|
.bind(now + FLOW_SECS)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
let challenge = crypto::b64url(sha2::Sha256::digest(verifier.as_bytes()));
|
||||||
|
let mut pairs: Vec<(&str, &str)> = vec![
|
||||||
|
("client_id", &config.client_id),
|
||||||
|
("redirect_uri", redirect_uri),
|
||||||
|
("state", &state),
|
||||||
|
];
|
||||||
|
match provider {
|
||||||
|
Provider::GitHub => pairs.extend([
|
||||||
|
("scope", "read:user"),
|
||||||
|
("allow_signup", "false"),
|
||||||
|
("code_challenge", &challenge),
|
||||||
|
("code_challenge_method", "S256"),
|
||||||
|
]),
|
||||||
|
// As in piki, Discord's flow uses no PKCE.
|
||||||
|
Provider::Discord => pairs.extend([("response_type", "code"), ("scope", "identify")]),
|
||||||
|
Provider::Google => pairs.extend([
|
||||||
|
("response_type", "code"),
|
||||||
|
("scope", "openid email profile"),
|
||||||
|
("nonce", &nonce),
|
||||||
|
("code_challenge", &challenge),
|
||||||
|
("code_challenge_method", "S256"),
|
||||||
|
("prompt", "select_account"),
|
||||||
|
]),
|
||||||
|
}
|
||||||
|
let query = url::form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish();
|
||||||
|
Ok(format!("{}?{query}", self.endpoints(provider).authorize))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Completes a flow: consumes its state, exchanges the code and reads the identity.
|
||||||
|
pub async fn finish(
|
||||||
|
&self,
|
||||||
|
provider: Provider,
|
||||||
|
state: &str,
|
||||||
|
code: &str,
|
||||||
|
redirect_uri: &str,
|
||||||
|
) -> Result<Finished, OAuthError> {
|
||||||
|
let now = forge_store::now();
|
||||||
|
let row: Option<FlowRow> = sqlx::query_as(
|
||||||
|
"UPDATE oauth_flows SET used_at = ?1
|
||||||
|
WHERE state_hash = ?2 AND provider = ?3 AND used_at IS NULL AND expires_at > ?1
|
||||||
|
RETURNING intent, user_id, session_id, next_path, pkce_verifier, nonce, persistent",
|
||||||
|
)
|
||||||
|
.bind(now)
|
||||||
|
.bind(crypto::hash_token(state))
|
||||||
|
.bind(provider.as_str())
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
let Some((intent, user_id, session_id, next, verifier, nonce, persistent)) = row else {
|
||||||
|
return Err(OAuthError::BadState);
|
||||||
|
};
|
||||||
|
let config = self.config(provider).await?;
|
||||||
|
let identity = self.identify(provider, &config, code, redirect_uri, &verifier, &nonce).await?;
|
||||||
|
Ok(Finished {
|
||||||
|
intent: if intent == "link" { Intent::Link } else { Intent::SignIn },
|
||||||
|
user_id,
|
||||||
|
session_id,
|
||||||
|
next,
|
||||||
|
persistent,
|
||||||
|
identity,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn identify(
|
||||||
|
&self,
|
||||||
|
provider: Provider,
|
||||||
|
config: &Config,
|
||||||
|
code: &str,
|
||||||
|
redirect_uri: &str,
|
||||||
|
verifier: &str,
|
||||||
|
nonce: &str,
|
||||||
|
) -> Result<Identity, OAuthError> {
|
||||||
|
let endpoints = self.endpoints(provider);
|
||||||
|
let mut form = vec![("grant_type", "authorization_code"), ("code", code), ("redirect_uri", redirect_uri)];
|
||||||
|
if provider != Provider::Discord {
|
||||||
|
form.push(("code_verifier", verifier));
|
||||||
|
}
|
||||||
|
let request = self.http.post(&endpoints.token).header("Accept", "application/json");
|
||||||
|
let request = match provider {
|
||||||
|
// Discord takes client authentication only as HTTP Basic.
|
||||||
|
Provider::Discord => request.basic_auth(&config.client_id, Some(&config.client_secret)),
|
||||||
|
_ => {
|
||||||
|
form.push(("client_id", &config.client_id));
|
||||||
|
form.push(("client_secret", &config.client_secret));
|
||||||
|
request
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let token: TokenResponse = read_json(request.form(&form)).await?;
|
||||||
|
if let Some(error) = token.error {
|
||||||
|
return Err(OAuthError::Provider(error));
|
||||||
|
}
|
||||||
|
match provider {
|
||||||
|
Provider::Google => {
|
||||||
|
let id_token = token.id_token.ok_or_else(|| OAuthError::Provider("no ID token".into()))?;
|
||||||
|
google_identity(&id_token, &config.client_id, nonce, &endpoints.issuers)
|
||||||
|
}
|
||||||
|
Provider::GitHub | Provider::Discord => {
|
||||||
|
let access = token.access_token.ok_or_else(|| OAuthError::Provider("no access token".into()))?;
|
||||||
|
let identity = self.user_identity(provider, &endpoints, &access).await;
|
||||||
|
self.revoke(provider, &endpoints, config, &access).await;
|
||||||
|
identity
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn user_identity(&self, provider: Provider, endpoints: &Endpoints, access: &str) -> Result<Identity, OAuthError> {
|
||||||
|
let request = self.http.get(&endpoints.identity).bearer_auth(access);
|
||||||
|
if provider == Provider::GitHub {
|
||||||
|
let request = request
|
||||||
|
.header("Accept", "application/vnd.github+json")
|
||||||
|
.header("X-GitHub-Api-Version", "2022-11-28");
|
||||||
|
let user: GitHubUser = read_json(request).await?;
|
||||||
|
if user.login.is_empty() {
|
||||||
|
return Err(OAuthError::Provider("incomplete identity".into()));
|
||||||
|
}
|
||||||
|
Ok(Identity {
|
||||||
|
provider,
|
||||||
|
subject_id: user.id.to_string(),
|
||||||
|
username: user.login,
|
||||||
|
display_name: user.name.unwrap_or_default(),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
let user: DiscordUser = read_json(request).await?;
|
||||||
|
if user.id.is_empty() || user.username.is_empty() {
|
||||||
|
return Err(OAuthError::Provider("incomplete identity".into()));
|
||||||
|
}
|
||||||
|
Ok(Identity {
|
||||||
|
provider,
|
||||||
|
subject_id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
display_name: user.global_name.unwrap_or_default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Revokes a provider access token once the identity is read. Failure is logged, not
|
||||||
|
/// fatal: the token was only ever good for reading the identity.
|
||||||
|
async fn revoke(&self, provider: Provider, endpoints: &Endpoints, config: &Config, access: &str) {
|
||||||
|
let request = match provider {
|
||||||
|
Provider::GitHub => self
|
||||||
|
.http
|
||||||
|
.delete(format!("{}/applications/{}/token", endpoints.revoke, config.client_id))
|
||||||
|
.basic_auth(&config.client_id, Some(&config.client_secret))
|
||||||
|
.header("Accept", "application/vnd.github+json")
|
||||||
|
.json(&serde_json::json!({ "access_token": access })),
|
||||||
|
Provider::Discord => self
|
||||||
|
.http
|
||||||
|
.post(&endpoints.revoke)
|
||||||
|
.basic_auth(&config.client_id, Some(&config.client_secret))
|
||||||
|
.form(&[("token", access), ("token_type_hint", "access_token")]),
|
||||||
|
Provider::Google => return,
|
||||||
|
};
|
||||||
|
match request.send().await {
|
||||||
|
Ok(response) if response.status().is_success() => {}
|
||||||
|
Ok(response) => tracing::warn!(provider = provider.as_str(), status = %response.status(), "token revocation refused"),
|
||||||
|
Err(error) => tracing::warn!(provider = provider.as_str(), "token revocation failed: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The account a provider identity is linked to, recording the sign-in.
|
||||||
|
pub async fn linked_user(&self, identity: &Identity) -> Result<Option<String>, sqlx::Error> {
|
||||||
|
let row: Option<(String,)> = sqlx::query_as(
|
||||||
|
"UPDATE oauth_identities SET last_used_at = ?, provider_username = ?, provider_display_name = ?
|
||||||
|
WHERE provider = ? AND subject_id = ? RETURNING user_id",
|
||||||
|
)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.bind(&identity.username)
|
||||||
|
.bind(&identity.display_name)
|
||||||
|
.bind(identity.provider.as_str())
|
||||||
|
.bind(&identity.subject_id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(row.map(|(id,)| id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn link(&self, user_id: &str, identity: &Identity) -> Result<(), OAuthError> {
|
||||||
|
let label = identity.provider.label();
|
||||||
|
let elsewhere: Option<(String,)> =
|
||||||
|
sqlx::query_as("SELECT user_id FROM oauth_identities WHERE provider = ? AND subject_id = ?")
|
||||||
|
.bind(identity.provider.as_str())
|
||||||
|
.bind(&identity.subject_id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
match elsewhere {
|
||||||
|
Some((owner,)) if owner == user_id => return Ok(()),
|
||||||
|
Some(_) => return Err(OAuthError::LinkedElsewhere(label)),
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
let inserted = sqlx::query(
|
||||||
|
"INSERT INTO oauth_identities (provider, subject_id, user_id, provider_username,
|
||||||
|
provider_display_name, created_at, last_used_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(identity.provider.as_str())
|
||||||
|
.bind(&identity.subject_id)
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(&identity.username)
|
||||||
|
.bind(&identity.display_name)
|
||||||
|
.bind(now)
|
||||||
|
.bind(now)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await;
|
||||||
|
match inserted {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(error) if forge_store::is_unique_violation(&error) => {
|
||||||
|
return Err(OAuthError::AlreadyLinked(label));
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
}
|
||||||
|
let detail = format!("{} {}", identity.username, identity.subject_id);
|
||||||
|
forge_store::audit(&self.pool, Some(user_id), "oauth.link", identity.provider.as_str(), &detail).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn linked(&self, user_id: &str) -> Result<Vec<Linked>, sqlx::Error> {
|
||||||
|
let rows: Vec<(String, String, i64, i64)> = sqlx::query_as(
|
||||||
|
"SELECT provider, provider_username, created_at, last_used_at FROM oauth_identities
|
||||||
|
WHERE user_id = ? ORDER BY provider",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(provider, username, created_at, last_used_at)| {
|
||||||
|
Some(Linked { provider: Provider::parse(&provider)?, username, created_at, last_used_at })
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unlinks a provider, unless it is the account's only way to sign in.
|
||||||
|
pub async fn unlink(&self, user_id: &str, provider: Provider) -> Result<(), OAuthError> {
|
||||||
|
let linked = self.linked(user_id).await?;
|
||||||
|
if linked.len() <= 1 && !crate::users::has_password(&self.pool, user_id).await? {
|
||||||
|
return Err(OAuthError::LastMethod);
|
||||||
|
}
|
||||||
|
sqlx::query("DELETE FROM oauth_identities WHERE user_id = ? AND provider = ?")
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(provider.as_str())
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
forge_store::audit(&self.pool, Some(user_id), "oauth.unlink", provider.as_str(), "").await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A consumed flow: intent, user, session, next path, PKCE verifier, nonce, persistent.
|
||||||
|
type FlowRow = (String, Option<String>, Option<String>, String, String, String, bool);
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct TokenResponse {
|
||||||
|
access_token: Option<String>,
|
||||||
|
id_token: Option<String>,
|
||||||
|
error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct GitHubUser {
|
||||||
|
id: u64,
|
||||||
|
#[serde(default)]
|
||||||
|
login: String,
|
||||||
|
name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct DiscordUser {
|
||||||
|
#[serde(default)]
|
||||||
|
id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
username: String,
|
||||||
|
global_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_json<T: serde::de::DeserializeOwned>(request: reqwest::RequestBuilder) -> Result<T, OAuthError> {
|
||||||
|
let response = request.send().await.map_err(|error| OAuthError::Provider(error.without_url().to_string()))?;
|
||||||
|
let status = response.status();
|
||||||
|
let bytes = response.bytes().await.map_err(|error| OAuthError::Provider(error.to_string()))?;
|
||||||
|
if bytes.len() > MAX_RESPONSE_BYTES {
|
||||||
|
return Err(OAuthError::Provider("response too large".into()));
|
||||||
|
}
|
||||||
|
if !status.is_success() {
|
||||||
|
// A token endpoint answers OAuth errors with 400 and a JSON body.
|
||||||
|
if let Ok(body) = serde_json::from_slice::<serde_json::Value>(&bytes)
|
||||||
|
&& let Some(error) = body.get("error").and_then(|e| e.as_str())
|
||||||
|
{
|
||||||
|
return Err(OAuthError::Provider(error.to_owned()));
|
||||||
|
}
|
||||||
|
return Err(OAuthError::Provider(format!("status {status}")));
|
||||||
|
}
|
||||||
|
serde_json::from_slice(&bytes).map_err(|error| OAuthError::Provider(format!("unreadable response: {error}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct GoogleClaims {
|
||||||
|
iss: String,
|
||||||
|
aud: Audience,
|
||||||
|
azp: Option<String>,
|
||||||
|
sub: String,
|
||||||
|
exp: i64,
|
||||||
|
iat: Option<i64>,
|
||||||
|
nonce: Option<String>,
|
||||||
|
email: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
email_verified: serde_json::Value,
|
||||||
|
name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
enum Audience {
|
||||||
|
One(String),
|
||||||
|
Many(Vec<String>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The identity in a Google ID token. Its claims are checked without a signature check,
|
||||||
|
/// which OIDC Core 3.1.3.7 (6) allows only because the token came straight from Google's
|
||||||
|
/// token endpoint over TLS, in answer to this client's authenticated request. Never call
|
||||||
|
/// this with a token from anywhere else.
|
||||||
|
fn google_identity(id_token: &str, client_id: &str, nonce: &str, issuers: &[String]) -> Result<Identity, OAuthError> {
|
||||||
|
let bad = |what: &str| OAuthError::Provider(format!("ID token {what}"));
|
||||||
|
let payload = id_token.split('.').nth(1).ok_or_else(|| bad("is malformed"))?;
|
||||||
|
let payload = crypto::b64url_decode(payload.trim_end_matches('=')).ok_or_else(|| bad("is malformed"))?;
|
||||||
|
let claims: GoogleClaims = serde_json::from_slice(&payload).map_err(|_| bad("is malformed"))?;
|
||||||
|
if !issuers.contains(&claims.iss) {
|
||||||
|
return Err(bad("has the wrong issuer"));
|
||||||
|
}
|
||||||
|
let audiences = match &claims.aud {
|
||||||
|
Audience::One(one) => vec![one.as_str()],
|
||||||
|
Audience::Many(many) => many.iter().map(String::as_str).collect(),
|
||||||
|
};
|
||||||
|
if !audiences.contains(&client_id) {
|
||||||
|
return Err(bad("is for another client"));
|
||||||
|
}
|
||||||
|
if (audiences.len() > 1 || claims.azp.is_some()) && claims.azp.as_deref() != Some(client_id) {
|
||||||
|
return Err(bad("is for another client"));
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
if claims.exp + 60 <= now {
|
||||||
|
return Err(bad("expired"));
|
||||||
|
}
|
||||||
|
if claims.iat.is_some_and(|iat| iat > now + 300) {
|
||||||
|
return Err(bad("was issued in the future"));
|
||||||
|
}
|
||||||
|
let nonce_ok = !nonce.is_empty()
|
||||||
|
&& claims.nonce.as_deref().is_some_and(|got| crypto::constant_time_eq(got.as_bytes(), nonce.as_bytes()));
|
||||||
|
if !nonce_ok {
|
||||||
|
return Err(bad("nonce does not match"));
|
||||||
|
}
|
||||||
|
let subject = claims.sub.trim();
|
||||||
|
if subject.is_empty() {
|
||||||
|
return Err(bad("has no subject"));
|
||||||
|
}
|
||||||
|
let verified = matches!(claims.email_verified, serde_json::Value::Bool(true))
|
||||||
|
|| claims.email_verified.as_str() == Some("true");
|
||||||
|
let name = claims.name.unwrap_or_default().trim().to_owned();
|
||||||
|
// The email is only a label for the settings page, never used to match accounts.
|
||||||
|
let username = match claims.email {
|
||||||
|
Some(email) if verified && !email.trim().is_empty() => email.trim().to_owned(),
|
||||||
|
_ if !name.is_empty() => name.clone(),
|
||||||
|
_ => subject.to_owned(),
|
||||||
|
};
|
||||||
|
Ok(Identity { provider: Provider::Google, subject_id: subject.to_owned(), username, display_name: name })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn token(claims: serde_json::Value) -> String {
|
||||||
|
format!("e30.{}.sig", crypto::b64url(claims.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn claims() -> serde_json::Value {
|
||||||
|
serde_json::json!({
|
||||||
|
"iss": "https://accounts.google.com", "aud": "client", "sub": "123",
|
||||||
|
"exp": forge_store::now() + 600, "iat": forge_store::now(), "nonce": "n",
|
||||||
|
"email": "a@example.com", "email_verified": true, "name": "A",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn google_claims_are_checked() {
|
||||||
|
let issuers = Endpoints::real(Provider::Google).issuers;
|
||||||
|
let identity = google_identity(&token(claims()), "client", "n", &issuers).unwrap();
|
||||||
|
assert_eq!(identity.subject_id, "123");
|
||||||
|
assert_eq!(identity.username, "a@example.com");
|
||||||
|
let mut wrong = claims();
|
||||||
|
wrong["nonce"] = "m".into();
|
||||||
|
assert!(google_identity(&token(wrong), "client", "n", &issuers).is_err());
|
||||||
|
let mut wrong = claims();
|
||||||
|
wrong["aud"] = "other".into();
|
||||||
|
assert!(google_identity(&token(wrong), "client", "n", &issuers).is_err());
|
||||||
|
let mut wrong = claims();
|
||||||
|
wrong["iss"] = "https://evil.example".into();
|
||||||
|
assert!(google_identity(&token(wrong), "client", "n", &issuers).is_err());
|
||||||
|
let mut wrong = claims();
|
||||||
|
wrong["exp"] = (forge_store::now() - 120).into();
|
||||||
|
assert!(google_identity(&token(wrong), "client", "n", &issuers).is_err());
|
||||||
|
assert!(google_identity(&token(claims()), "client", "", &issuers).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,46 @@
|
||||||
|
//! Password hashing with Argon2id.
|
||||||
|
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
|
use argon2::Argon2;
|
||||||
|
use argon2::PasswordHash;
|
||||||
|
use argon2::PasswordHasher;
|
||||||
|
use argon2::PasswordVerifier;
|
||||||
|
|
||||||
|
pub const MIN_LENGTH: usize = 10;
|
||||||
|
pub const MAX_LENGTH: usize = 1024;
|
||||||
|
|
||||||
|
/// A hash to verify against when the account does not exist, so a missing account takes as
|
||||||
|
/// long to reject as a wrong password.
|
||||||
|
static DUMMY_HASH: LazyLock<String> = LazyLock::new(|| hash("not a real password"));
|
||||||
|
|
||||||
|
pub fn hash(password: &str) -> String {
|
||||||
|
let salt = crate::crypto::random_bytes::<16>();
|
||||||
|
Argon2::default()
|
||||||
|
.hash_password_with_salt(password.as_bytes(), &salt)
|
||||||
|
.expect("Argon2 hashing with default parameters cannot fail")
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify(stored: &str, password: &str) -> bool {
|
||||||
|
match PasswordHash::new(stored) {
|
||||||
|
Ok(parsed) => Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok(),
|
||||||
|
Err(_) => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spends the time a verification would, for a sign-in with an unknown username.
|
||||||
|
pub fn verify_dummy(password: &str) {
|
||||||
|
let _ = verify(&DUMMY_HASH, password);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#[test]
|
||||||
|
fn round_trip() {
|
||||||
|
let stored = super::hash("correct horse");
|
||||||
|
assert!(super::verify(&stored, "correct horse"));
|
||||||
|
assert!(!super::verify(&stored, "wrong horse"));
|
||||||
|
assert!(!super::verify("garbage", "correct horse"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,244 @@
|
||||||
|
//! Browser sessions, as in piki: a random token in an `HttpOnly` cookie, stored only as a
|
||||||
|
//! hash.
|
||||||
|
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
|
||||||
|
use crate::crypto;
|
||||||
|
use crate::users;
|
||||||
|
use crate::users::User;
|
||||||
|
|
||||||
|
/// A "stay signed in" session lasts this long after its last use...
|
||||||
|
pub const PERSISTENT_IDLE_SECS: i64 = 30 * 24 * 3600;
|
||||||
|
/// ...and never longer than this after it was created.
|
||||||
|
pub const PERSISTENT_MAX_SECS: i64 = 90 * 24 * 3600;
|
||||||
|
/// A session without "stay signed in" lasts this long, and its cookie ends with the browser.
|
||||||
|
pub const TRANSIENT_SECS: i64 = 12 * 3600;
|
||||||
|
/// Sliding expiry is written at most this often per session.
|
||||||
|
const TOUCH_INTERVAL_SECS: i64 = 60;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum AuthMethod {
|
||||||
|
Password,
|
||||||
|
Provider,
|
||||||
|
Passkey,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthMethod {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
AuthMethod::Password => "password",
|
||||||
|
AuthMethod::Provider => "provider",
|
||||||
|
AuthMethod::Passkey => "passkey",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Session {
|
||||||
|
pub id: String,
|
||||||
|
pub user: User,
|
||||||
|
pub persistent: bool,
|
||||||
|
pub expires_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct NewSession {
|
||||||
|
/// The cookie value. Only its hash is stored.
|
||||||
|
pub token: String,
|
||||||
|
pub session: Session,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
user: &User,
|
||||||
|
method: AuthMethod,
|
||||||
|
user_agent: &str,
|
||||||
|
persistent: bool,
|
||||||
|
) -> Result<NewSession, sqlx::Error> {
|
||||||
|
let now = forge_store::now();
|
||||||
|
let token = crypto::random_token();
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let expires_at = now + if persistent { PERSISTENT_IDLE_SECS } else { TRANSIENT_SECS };
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO sessions (id, token_hash, user_id, auth_method, user_agent, persistent,
|
||||||
|
created_at, last_seen_at, expires_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(&id)
|
||||||
|
.bind(crypto::hash_token(&token))
|
||||||
|
.bind(&user.id)
|
||||||
|
.bind(method.as_str())
|
||||||
|
.bind(truncate(user_agent, 300))
|
||||||
|
.bind(persistent)
|
||||||
|
.bind(now)
|
||||||
|
.bind(now)
|
||||||
|
.bind(expires_at)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
forge_store::audit(&mut *tx, Some(&user.id), "session.create", &id, method.as_str()).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(NewSession {
|
||||||
|
token,
|
||||||
|
session: Session { id, user: user.clone(), persistent, expires_at },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The live session for a cookie value, sliding a persistent session's expiry forward.
|
||||||
|
pub async fn lookup(pool: &SqlitePool, token: &str) -> Result<Option<Session>, sqlx::Error> {
|
||||||
|
let now = forge_store::now();
|
||||||
|
let row: Option<(String, String, bool, i64, i64, i64)> = sqlx::query_as(
|
||||||
|
"SELECT id, user_id, persistent, created_at, last_seen_at, expires_at FROM sessions
|
||||||
|
WHERE token_hash = ? AND revoked_at IS NULL AND expires_at > ?",
|
||||||
|
)
|
||||||
|
.bind(crypto::hash_token(token))
|
||||||
|
.bind(now)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
let Some((id, user_id, persistent, created_at, last_seen_at, mut expires_at)) = row else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let Some(user) = users::get(pool, &user_id).await?.filter(|user| !user.disabled) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
if persistent && now - last_seen_at >= TOUCH_INTERVAL_SECS {
|
||||||
|
expires_at = (now + PERSISTENT_IDLE_SECS).min(created_at + PERSISTENT_MAX_SECS);
|
||||||
|
sqlx::query("UPDATE sessions SET last_seen_at = ?, expires_at = ? WHERE id = ?")
|
||||||
|
.bind(now)
|
||||||
|
.bind(expires_at)
|
||||||
|
.bind(&id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Ok(Some(Session { id, user, persistent, expires_at }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends the session a cookie value belongs to.
|
||||||
|
pub async fn revoke_token(pool: &SqlitePool, token: &str) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query("UPDATE sessions SET revoked_at = ? WHERE token_hash = ? AND revoked_at IS NULL")
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.bind(crypto::hash_token(token))
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A live browser session, as the session list shows it.
|
||||||
|
#[derive(Clone, Debug, sqlx::FromRow)]
|
||||||
|
pub struct SessionInfo {
|
||||||
|
pub id: String,
|
||||||
|
pub auth_method: String,
|
||||||
|
pub user_agent: String,
|
||||||
|
pub created_at: i64,
|
||||||
|
pub last_seen_at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A live Lore CLI login, as the session list shows it.
|
||||||
|
#[derive(Clone, Debug, sqlx::FromRow)]
|
||||||
|
pub struct CliLogin {
|
||||||
|
pub id: String,
|
||||||
|
pub description: String,
|
||||||
|
pub created_at: i64,
|
||||||
|
pub last_used_at: i64,
|
||||||
|
pub expires_at: i64,
|
||||||
|
/// The API token it was started with, if any.
|
||||||
|
pub token_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list(pool: &SqlitePool, user_id: &str) -> Result<Vec<SessionInfo>, sqlx::Error> {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT id, auth_method, user_agent, created_at, last_seen_at FROM sessions
|
||||||
|
WHERE user_id = ? AND revoked_at IS NULL AND expires_at > ?
|
||||||
|
ORDER BY last_seen_at DESC",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends one of `user_id`'s sessions.
|
||||||
|
pub async fn revoke(pool: &SqlitePool, user_id: &str, id: &str) -> Result<bool, sqlx::Error> {
|
||||||
|
let ended = sqlx::query(
|
||||||
|
"UPDATE sessions SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.bind(id)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(ended.rows_affected() == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends every session of `user_id` except `keep`.
|
||||||
|
pub async fn revoke_others(pool: &SqlitePool, user_id: &str, keep: &str) -> Result<u64, sqlx::Error> {
|
||||||
|
let ended = sqlx::query(
|
||||||
|
"UPDATE sessions SET revoked_at = ? WHERE user_id = ? AND id != ? AND revoked_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(keep)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(ended.rows_affected())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn cli_logins(pool: &SqlitePool, user_id: &str) -> Result<Vec<CliLogin>, sqlx::Error> {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT l.id, l.description, l.created_at, l.last_used_at, l.expires_at,
|
||||||
|
t.name AS token_name
|
||||||
|
FROM cli_logins l LEFT JOIN api_tokens t ON t.id = l.api_token_id
|
||||||
|
WHERE l.user_id = ? AND l.revoked_at IS NULL AND l.expires_at > ?
|
||||||
|
ORDER BY l.last_used_at DESC",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ends one of `user_id`'s CLI logins. Its tokens stop working within five minutes, when
|
||||||
|
/// the current repository token expires.
|
||||||
|
pub async fn revoke_cli_login(pool: &SqlitePool, user_id: &str, id: &str) -> Result<bool, sqlx::Error> {
|
||||||
|
let ended = sqlx::query(
|
||||||
|
"UPDATE cli_logins SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL",
|
||||||
|
)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.bind(id)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
if ended.rows_affected() == 1 {
|
||||||
|
forge_store::audit(pool, Some(user_id), "cli_login.revoke", id, "").await?;
|
||||||
|
}
|
||||||
|
Ok(ended.rows_affected() == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn truncate(text: &str, max_chars: usize) -> String {
|
||||||
|
text.chars().take(max_chars).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::users::InstanceRole;
|
||||||
|
use crate::users::NewUser;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn create_lookup_revoke() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let user = users::create(
|
||||||
|
pool,
|
||||||
|
NewUser { username: "alice", display_name: "Alice", password: None, role: InstanceRole::Member },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let new = create(pool, &user, AuthMethod::Password, "test", true).await.unwrap();
|
||||||
|
let found = lookup(pool, &new.token).await.unwrap().unwrap();
|
||||||
|
assert_eq!(found.user, user);
|
||||||
|
assert!(lookup(pool, "not a token").await.unwrap().is_none());
|
||||||
|
revoke_token(pool, &new.token).await.unwrap();
|
||||||
|
assert!(lookup(pool, &new.token).await.unwrap().is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,500 @@
|
||||||
|
//! Local accounts.
|
||||||
|
|
||||||
|
use forge_access::names;
|
||||||
|
use forge_access::names::NameError;
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
|
||||||
|
use crate::password;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum InstanceRole {
|
||||||
|
Owner,
|
||||||
|
Admin,
|
||||||
|
Member,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InstanceRole {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
InstanceRole::Owner => "owner",
|
||||||
|
InstanceRole::Admin => "admin",
|
||||||
|
InstanceRole::Member => "member",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(text: &str) -> InstanceRole {
|
||||||
|
match text {
|
||||||
|
"owner" => InstanceRole::Owner,
|
||||||
|
"admin" => InstanceRole::Admin,
|
||||||
|
_ => InstanceRole::Member,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct User {
|
||||||
|
/// Stable internal ID, and the identity Lore records.
|
||||||
|
pub id: String,
|
||||||
|
pub username: String,
|
||||||
|
pub display_name: String,
|
||||||
|
pub role: InstanceRole,
|
||||||
|
pub disabled: bool,
|
||||||
|
/// A service account: no password, no namespace, signs in only with client credentials.
|
||||||
|
pub service: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct UserRow {
|
||||||
|
id: String,
|
||||||
|
username: String,
|
||||||
|
display_name: String,
|
||||||
|
instance_role: String,
|
||||||
|
disabled: bool,
|
||||||
|
kind: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<UserRow> for User {
|
||||||
|
fn from(row: UserRow) -> Self {
|
||||||
|
User {
|
||||||
|
id: row.id,
|
||||||
|
username: row.username,
|
||||||
|
display_name: row.display_name,
|
||||||
|
role: InstanceRole::parse(&row.instance_role),
|
||||||
|
disabled: row.disabled,
|
||||||
|
service: row.kind == "service",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A static query selecting a [`UserRow`], followed by `$tail`.
|
||||||
|
macro_rules! select_user {
|
||||||
|
($tail:literal) => {
|
||||||
|
concat!("SELECT id, username, display_name, instance_role, disabled, kind FROM users ", $tail)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum CreateUserError {
|
||||||
|
#[error("username: {0}")]
|
||||||
|
InvalidUsername(#[from] NameError),
|
||||||
|
#[error("that username is taken")]
|
||||||
|
UsernameTaken,
|
||||||
|
#[error("display names must be 1 to 100 characters")]
|
||||||
|
InvalidDisplayName,
|
||||||
|
#[error("passwords must be {} to {} characters", password::MIN_LENGTH, password::MAX_LENGTH)]
|
||||||
|
InvalidPassword,
|
||||||
|
#[error(transparent)]
|
||||||
|
Database(#[from] sqlx::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct NewUser<'a> {
|
||||||
|
pub username: &'a str,
|
||||||
|
pub display_name: &'a str,
|
||||||
|
pub password: Option<&'a str>,
|
||||||
|
pub role: InstanceRole,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an account and its personal namespace.
|
||||||
|
pub async fn create(pool: &SqlitePool, new: NewUser<'_>) -> Result<User, CreateUserError> {
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
let user = create_in(&mut tx, new).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_display_name(display_name: &str) -> Result<String, CreateUserError> {
|
||||||
|
let display_name = display_name.trim();
|
||||||
|
if display_name.is_empty() || display_name.chars().count() > 100 {
|
||||||
|
return Err(CreateUserError::InvalidDisplayName);
|
||||||
|
}
|
||||||
|
Ok(display_name.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_password(password: &str) -> Result<String, CreateUserError> {
|
||||||
|
let length = password.chars().count();
|
||||||
|
if !(password::MIN_LENGTH..=password::MAX_LENGTH).contains(&length) {
|
||||||
|
return Err(CreateUserError::InvalidPassword);
|
||||||
|
}
|
||||||
|
Ok(password::hash(password))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`create`] inside the caller's transaction, so signup can redeem an invite atomically.
|
||||||
|
pub async fn create_in(
|
||||||
|
tx: &mut sqlx::SqliteConnection,
|
||||||
|
new: NewUser<'_>,
|
||||||
|
) -> Result<User, CreateUserError> {
|
||||||
|
names::check_namespace(new.username)?;
|
||||||
|
let display_name = check_display_name(new.display_name)?;
|
||||||
|
let password_hash = new.password.map(check_password).transpose()?;
|
||||||
|
let user = User {
|
||||||
|
id: uuid::Uuid::new_v4().to_string(),
|
||||||
|
username: new.username.to_owned(),
|
||||||
|
display_name,
|
||||||
|
role: new.role,
|
||||||
|
disabled: false,
|
||||||
|
service: false,
|
||||||
|
};
|
||||||
|
let inserted = sqlx::query(
|
||||||
|
"INSERT INTO users (id, username, display_name, password_hash, instance_role, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(&user.id)
|
||||||
|
.bind(&user.username)
|
||||||
|
.bind(&user.display_name)
|
||||||
|
.bind(password_hash)
|
||||||
|
.bind(user.role.as_str())
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await;
|
||||||
|
let taken = |error: &sqlx::Error| forge_store::is_unique_violation(error);
|
||||||
|
match inserted {
|
||||||
|
Err(error) if taken(&error) => return Err(CreateUserError::UsernameTaken),
|
||||||
|
other => other?,
|
||||||
|
};
|
||||||
|
match forge_access::create_user_namespace(&mut *tx, &user.username, &user.id).await {
|
||||||
|
// An organisation holds the name.
|
||||||
|
Err(error) if taken(&error) => return Err(CreateUserError::UsernameTaken),
|
||||||
|
other => other?,
|
||||||
|
}
|
||||||
|
forge_store::audit(&mut *tx, Some(&user.id), "user.create", &user.username, user.role.as_str())
|
||||||
|
.await?;
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a service account named `<owner>.<name>` under the namespace `owner`.
|
||||||
|
pub async fn create_service_account(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
owner: &str,
|
||||||
|
name: &str,
|
||||||
|
display_name: &str,
|
||||||
|
actor_id: &str,
|
||||||
|
) -> Result<User, CreateUserError> {
|
||||||
|
names::check_namespace(name)?;
|
||||||
|
let display_name = check_display_name(display_name)?;
|
||||||
|
let user = User {
|
||||||
|
id: uuid::Uuid::new_v4().to_string(),
|
||||||
|
username: format!("{owner}.{name}"),
|
||||||
|
display_name,
|
||||||
|
role: InstanceRole::Member,
|
||||||
|
disabled: false,
|
||||||
|
service: true,
|
||||||
|
};
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
let inserted = sqlx::query(
|
||||||
|
"INSERT INTO users (id, username, display_name, instance_role, kind, owner_namespace,
|
||||||
|
created_at)
|
||||||
|
VALUES (?, ?, ?, 'member', 'service', ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(&user.id)
|
||||||
|
.bind(&user.username)
|
||||||
|
.bind(&user.display_name)
|
||||||
|
.bind(owner)
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await;
|
||||||
|
match inserted {
|
||||||
|
Err(error) if forge_store::is_unique_violation(&error) => {
|
||||||
|
return Err(CreateUserError::UsernameTaken);
|
||||||
|
}
|
||||||
|
other => other?,
|
||||||
|
};
|
||||||
|
forge_store::audit(&mut *tx, Some(actor_id), "service_account.create", &user.username, "").await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The service accounts owned by a namespace.
|
||||||
|
pub async fn service_accounts(pool: &SqlitePool, owner: &str) -> Result<Vec<User>, sqlx::Error> {
|
||||||
|
let rows: Vec<UserRow> =
|
||||||
|
sqlx::query_as(select_user!("WHERE kind = 'service' AND owner_namespace = ? ORDER BY username"))
|
||||||
|
.bind(owner)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(rows.into_iter().map(User::from).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The namespace that owns a service account.
|
||||||
|
pub async fn service_account_owner(pool: &SqlitePool, id: &str) -> Result<Option<String>, sqlx::Error> {
|
||||||
|
let row: Option<(Option<String>,)> =
|
||||||
|
sqlx::query_as("SELECT owner_namespace FROM users WHERE id = ? AND kind = 'service'")
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(row.and_then(|(owner,)| owner))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes a service account, its tokens, logins and grants.
|
||||||
|
pub async fn delete_service_account(pool: &SqlitePool, id: &str, actor_id: &str) -> Result<(), sqlx::Error> {
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query("DELETE FROM grants WHERE subject_kind = 'user' AND subject_id = ?")
|
||||||
|
.bind(id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
let deleted = sqlx::query("DELETE FROM users WHERE id = ? AND kind = 'service'")
|
||||||
|
.bind(id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if deleted.rows_affected() == 1 {
|
||||||
|
forge_store::audit(&mut *tx, Some(actor_id), "service_account.delete", id, "").await?;
|
||||||
|
}
|
||||||
|
tx.commit().await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many people have accounts. Service accounts are not counted.
|
||||||
|
pub async fn count(pool: &SqlitePool) -> Result<i64, sqlx::Error> {
|
||||||
|
let (count,): (i64,) =
|
||||||
|
sqlx::query_as("SELECT count(*) FROM users WHERE kind = 'person'").fetch_one(pool).await?;
|
||||||
|
Ok(count)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every person's account, by username.
|
||||||
|
pub async fn list(pool: &SqlitePool) -> Result<Vec<User>, sqlx::Error> {
|
||||||
|
let rows: Vec<UserRow> = sqlx::query_as(select_user!("WHERE kind = 'person' ORDER BY username"))
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(rows.into_iter().map(User::from).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum AccountError {
|
||||||
|
#[error("the instance must keep at least one enabled owner")]
|
||||||
|
LastOwner,
|
||||||
|
#[error("the current password is wrong")]
|
||||||
|
WrongPassword,
|
||||||
|
#[error(transparent)]
|
||||||
|
Invalid(#[from] CreateUserError),
|
||||||
|
#[error(transparent)]
|
||||||
|
Database(#[from] sqlx::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether changing `user_id` would leave no enabled owner.
|
||||||
|
async fn is_last_owner(pool: &SqlitePool, user_id: &str) -> Result<bool, sqlx::Error> {
|
||||||
|
let (others,): (i64,) = sqlx::query_as(
|
||||||
|
"SELECT count(*) FROM users
|
||||||
|
WHERE instance_role = 'owner' AND disabled = 0 AND kind = 'person' AND id != ?",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(others == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_role(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
user_id: &str,
|
||||||
|
role: InstanceRole,
|
||||||
|
actor_id: &str,
|
||||||
|
) -> Result<(), AccountError> {
|
||||||
|
if role != InstanceRole::Owner && is_last_owner(pool, user_id).await? {
|
||||||
|
return Err(AccountError::LastOwner);
|
||||||
|
}
|
||||||
|
sqlx::query("UPDATE users SET instance_role = ? WHERE id = ? AND kind = 'person'")
|
||||||
|
.bind(role.as_str())
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
forge_store::audit(pool, Some(actor_id), "user.role", user_id, role.as_str()).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Disables or enables an account. Disabling ends its sessions and CLI logins.
|
||||||
|
pub async fn set_disabled(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
user_id: &str,
|
||||||
|
disabled: bool,
|
||||||
|
actor_id: &str,
|
||||||
|
) -> Result<(), AccountError> {
|
||||||
|
if disabled && is_last_owner(pool, user_id).await? {
|
||||||
|
return Err(AccountError::LastOwner);
|
||||||
|
}
|
||||||
|
let now = forge_store::now();
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query("UPDATE users SET disabled = ? WHERE id = ?")
|
||||||
|
.bind(disabled)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
if disabled {
|
||||||
|
sqlx::query("UPDATE sessions SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL")
|
||||||
|
.bind(now)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("UPDATE cli_logins SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL")
|
||||||
|
.bind(now)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
let action = if disabled { "user.disable" } else { "user.enable" };
|
||||||
|
forge_store::audit(&mut *tx, Some(actor_id), action, user_id, "").await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_display_name(pool: &SqlitePool, user_id: &str, display_name: &str) -> Result<(), AccountError> {
|
||||||
|
let display_name = check_display_name(display_name)?;
|
||||||
|
sqlx::query("UPDATE users SET display_name = ? WHERE id = ?")
|
||||||
|
.bind(display_name)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the account has a password it can sign in with.
|
||||||
|
pub async fn has_password(pool: &SqlitePool, user_id: &str) -> Result<bool, sqlx::Error> {
|
||||||
|
let row: Option<(Option<String>,)> = sqlx::query_as("SELECT password_hash FROM users WHERE id = ?")
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(matches!(row, Some((Some(_),))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes a password. `current` must match when the account has one. Other sessions of the
|
||||||
|
/// account are ended; `keep_session` is the one the change was made from.
|
||||||
|
pub async fn change_password(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
user_id: &str,
|
||||||
|
current: &str,
|
||||||
|
new: &str,
|
||||||
|
keep_session: &str,
|
||||||
|
) -> Result<(), AccountError> {
|
||||||
|
let row: Option<(Option<String>,)> = sqlx::query_as("SELECT password_hash FROM users WHERE id = ?")
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
if let Some((Some(stored),)) = &row
|
||||||
|
&& !password::verify(stored, current)
|
||||||
|
{
|
||||||
|
return Err(AccountError::WrongPassword);
|
||||||
|
}
|
||||||
|
let hash = check_password(new)?;
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query("UPDATE users SET password_hash = ? WHERE id = ?")
|
||||||
|
.bind(hash)
|
||||||
|
.bind(user_id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("UPDATE sessions SET revoked_at = ? WHERE user_id = ? AND id != ? AND revoked_at IS NULL")
|
||||||
|
.bind(forge_store::now())
|
||||||
|
.bind(user_id)
|
||||||
|
.bind(keep_session)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
forge_store::audit(&mut *tx, Some(user_id), "user.password", user_id, "").await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get(pool: &SqlitePool, id: &str) -> Result<Option<User>, sqlx::Error> {
|
||||||
|
let row: Option<UserRow> = sqlx::query_as(select_user!("WHERE id = ?"))
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(row.map(User::from))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find_by_username(pool: &SqlitePool, username: &str) -> Result<Option<User>, sqlx::Error> {
|
||||||
|
let row: Option<UserRow> =
|
||||||
|
sqlx::query_as(select_user!("WHERE username = ?"))
|
||||||
|
.bind(username)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(row.map(User::from))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find_by_display_name(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
display_name: &str,
|
||||||
|
) -> Result<Vec<User>, sqlx::Error> {
|
||||||
|
let rows: Vec<UserRow> =
|
||||||
|
sqlx::query_as(select_user!("WHERE display_name = ? LIMIT 100"))
|
||||||
|
.bind(display_name)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(rows.into_iter().map(User::from).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The users with the given IDs, skipping unknown ones.
|
||||||
|
pub async fn get_many(pool: &SqlitePool, ids: &[String]) -> Result<Vec<User>, sqlx::Error> {
|
||||||
|
let mut users = Vec::with_capacity(ids.len());
|
||||||
|
for id in ids.iter().take(1000) {
|
||||||
|
if let Some(user) = get(pool, id).await? {
|
||||||
|
users.push(user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(users)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks a username and password. `None` for an unknown user, a wrong password, an account
|
||||||
|
/// without a password, or a disabled account; the caller cannot tell which.
|
||||||
|
pub async fn authenticate(
|
||||||
|
pool: &SqlitePool,
|
||||||
|
username: &str,
|
||||||
|
password: &str,
|
||||||
|
) -> Result<Option<User>, sqlx::Error> {
|
||||||
|
let row: Option<(String, Option<String>)> =
|
||||||
|
sqlx::query_as("SELECT id, password_hash FROM users WHERE username = ? AND kind = 'person'")
|
||||||
|
.bind(username)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
let Some((id, Some(stored))) = row else {
|
||||||
|
password::verify_dummy(password);
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
if !password::verify(&stored, password) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
Ok(get(pool, &id).await?.filter(|user| !user.disabled))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn alice<'a>() -> NewUser<'a> {
|
||||||
|
NewUser {
|
||||||
|
username: "alice",
|
||||||
|
display_name: "Alice",
|
||||||
|
password: Some("long enough password"),
|
||||||
|
role: InstanceRole::Owner,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn create_and_authenticate() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let user = create(pool, alice()).await.unwrap();
|
||||||
|
assert!(forge_access::namespace_taken(pool, "alice").await.unwrap());
|
||||||
|
assert_eq!(authenticate(pool, "alice", "long enough password").await.unwrap(), Some(user.clone()));
|
||||||
|
assert_eq!(authenticate(pool, "ALICE", "long enough password").await.unwrap(), Some(user));
|
||||||
|
assert_eq!(authenticate(pool, "alice", "wrong").await.unwrap(), None);
|
||||||
|
assert_eq!(authenticate(pool, "nobody", "x").await.unwrap(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rejects_bad_input_and_duplicates() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
create(pool, alice()).await.unwrap();
|
||||||
|
assert!(matches!(create(pool, alice()).await, Err(CreateUserError::UsernameTaken)));
|
||||||
|
let short = NewUser { username: "bob", password: Some("short"), ..alice() };
|
||||||
|
assert!(matches!(create(pool, short).await, Err(CreateUserError::InvalidPassword)));
|
||||||
|
let reserved = NewUser { username: "settings", ..alice() };
|
||||||
|
assert!(matches!(create(pool, reserved).await, Err(CreateUserError::InvalidUsername(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn usernames_cannot_take_an_organisation_name() {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool();
|
||||||
|
let owner = create(pool, alice()).await.unwrap();
|
||||||
|
forge_access::orgs::create(pool, "studio", "Studio", &owner.id).await.unwrap();
|
||||||
|
let clash = NewUser { username: "studio", ..alice() };
|
||||||
|
assert!(matches!(create(pool, clash).await, Err(CreateUserError::UsernameTaken)));
|
||||||
|
assert!(find_by_username(pool, "studio").await.unwrap().is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
[package]
|
||||||
|
name = "forge-lore"
|
||||||
|
description = "lore-forge's side of Lore's protocols: the user directory and repository registry"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
forge-access.workspace = true
|
||||||
|
forge-id.workspace = true
|
||||||
|
forge-store.workspace = true
|
||||||
|
prost.workspace = true
|
||||||
|
reqwest.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
tokio-stream.workspace = true
|
||||||
|
tonic = { workspace = true, features = ["channel"] }
|
||||||
|
tonic-prost.workspace = true
|
||||||
|
tonic-types.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
tonic-prost-build.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
forge-store = { workspace = true, features = ["testing"] }
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
// Servers for the services lore-forge provides (and fakes of loreserver's, in tests);
|
||||||
|
// clients for the loreserver services the repository browser reads.
|
||||||
|
tonic_prost_build::configure().build_client(true).build_server(true).compile_protos(
|
||||||
|
&[
|
||||||
|
"proto/lore/user/v1/user.proto",
|
||||||
|
"proto/lore/revision/v1/revision.proto",
|
||||||
|
"proto/lore/repository/v1/repository.proto",
|
||||||
|
"proto/lore/thin_client/v1/thin_client.proto",
|
||||||
|
],
|
||||||
|
&["proto"],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
# Vendored Lore protocol definitions
|
||||||
|
|
||||||
|
Copied unchanged from [Lore](https://github.com/EpicGames/lore) (MIT licence), `lore-proto/proto/`,
|
||||||
|
at commit `6b12f00` (2026-11-25, workspace version `0.14.1-nightly`).
|
||||||
|
|
||||||
|
| File | Used for |
|
||||||
|
| --- | --- |
|
||||||
|
| `lore/user/v1/user.proto` | `UserService` and `RepositoryRegistryService`, which lore-forge serves at `user_url` |
|
||||||
|
| `lore/model/v1/model.proto` | Shared messages |
|
||||||
|
| `lore/revision/v1/revision.proto` | `RevisionService`: branches and revision lists, for the browser |
|
||||||
|
| `lore/repository/v1/repository.proto` | `RepositoryService`: the default branch, for the browser |
|
||||||
|
| `lore/thin_client/v1/thin_client.proto`, `model.proto` | `ThinClientService`: revisions, trees, diffs, for the browser |
|
||||||
|
|
||||||
|
Lore is pre-1.0. When upgrading the Lore version lore-forge targets, re-copy these files from the
|
||||||
|
matching Lore commit, update the commit above, and re-run the end-to-end test.
|
||||||
|
|
@ -0,0 +1,152 @@
|
||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package lore.model.v1;
|
||||||
|
|
||||||
|
// Storage fragment header — describes a unit of content-addressed payload
|
||||||
|
// returned from the storage layer.
|
||||||
|
message Fragment {
|
||||||
|
// Implementation-defined fragment flags (compression, encryption, etc.).
|
||||||
|
uint32 flags = 1;
|
||||||
|
// Wire size of the fragment payload after any encoding (compressed bytes).
|
||||||
|
uint32 size_payload = 2;
|
||||||
|
// Logical size of the underlying content before encoding.
|
||||||
|
uint64 size_content = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Content-addressed handle for a stored object.
|
||||||
|
message Address {
|
||||||
|
// Content hash uniquely identifying the object.
|
||||||
|
bytes hash = 1;
|
||||||
|
// Optional addressing context (e.g. partition / namespace tag).
|
||||||
|
bytes context = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Outcome of a single item within a streaming storage operation.
|
||||||
|
//
|
||||||
|
// Streaming RPCs report a per-item failure in-band, as a field on the response
|
||||||
|
// message, rather than as a gRPC `Status`. A `Status` yielded from a server
|
||||||
|
// response stream is written as HTTP/2 trailers and ends the stream, which would
|
||||||
|
// take down every other request multiplexed onto it — and for `Get`/`GetMetadata`
|
||||||
|
// a missing fragment is routine control flow, not a fault. A terminal `Status` is
|
||||||
|
// reserved for stream-fatal conditions, where no per-item attribution is possible
|
||||||
|
// (e.g. a corrupt request stream).
|
||||||
|
// A code other than `OK` decides the item on its own: the rest of the response carries no
|
||||||
|
// meaning in that case and a reader must not consult it. A response that omits the status
|
||||||
|
// entirely predates the field and is read as `OK`.
|
||||||
|
message ItemStatus {
|
||||||
|
// gRPC status code, as the numeric `google.rpc.Code` value. `OK` on a successful item,
|
||||||
|
// so every streaming response reports its outcome the same way.
|
||||||
|
uint32 code = 1;
|
||||||
|
// Human-readable detail, used for log lines and surfaced error text.
|
||||||
|
string message = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Result of a fragment lookup against the storage layer.
|
||||||
|
enum FragmentState {
|
||||||
|
// Found in the caller-supplied addressing context.
|
||||||
|
FOUND_IN_CONTEXT = 0;
|
||||||
|
// Found, but in a different context than the caller supplied.
|
||||||
|
FOUND = 1;
|
||||||
|
// No fragment exists at this address in any reachable context.
|
||||||
|
NOT_FOUND = 2;
|
||||||
|
// Lookup failed for an indeterminate reason.
|
||||||
|
UNKNOWN = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Anchor identifying a specific revision on a specific branch by content
|
||||||
|
// signature. Used in Branch.stack (ancestry chain) and in any context where
|
||||||
|
// the revision must be concrete (e.g. BranchCreate's caller-supplied stack).
|
||||||
|
// Carries the signature only; callers needing the per-branch revision number
|
||||||
|
// look it up via RevisionInfo.
|
||||||
|
message BranchPoint {
|
||||||
|
// Branch the parent revision lives on.
|
||||||
|
bytes branch_id = 1;
|
||||||
|
// Content signature of the parent revision.
|
||||||
|
bytes revision_signature = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request-time specifier for a revision. RevisionIdentifier is paired with
|
||||||
|
// `bytes signature` in oneof `query` / `query_<side>` / `start` fields per
|
||||||
|
// the unified revision-specifier convention.
|
||||||
|
message RevisionIdentifier {
|
||||||
|
// Branch the revision lives on.
|
||||||
|
bytes branch_id = 1;
|
||||||
|
// Per-branch revision number. In any v1 *request*, value 0 resolves to
|
||||||
|
// the current tip of the branch; the server resolves 0 to a concrete
|
||||||
|
// number at request time. Valid Storage and response state always carry
|
||||||
|
// concrete numbers; 0 never appears there.
|
||||||
|
// Exception: BranchCreate requires fully-resolved concrete signatures via BranchPoint stack.
|
||||||
|
// Exception: In responses, zeroed revision signatures resolve to a zeroed revision number
|
||||||
|
uint64 number = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lean projection of a revision used in list responses (e.g.
|
||||||
|
// RevisionListResponse.items). Carries enough to identify the revision
|
||||||
|
// and present a list-row entry without the full Revision payload.
|
||||||
|
message RevisionItem {
|
||||||
|
// Revision number on its branch.
|
||||||
|
uint64 number = 1;
|
||||||
|
// Content signature of the revision.
|
||||||
|
bytes signature = 2;
|
||||||
|
// Metadata hash associated with this revision.
|
||||||
|
bytes metadata = 3;
|
||||||
|
// Serialized state header.
|
||||||
|
bytes state = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A repository — the top-level container for a revision graph. Repositories
|
||||||
|
// are hard-deleted (no `deleted` flag): a deleted repository disappears
|
||||||
|
// from RepositoryGet / RepositoryList entirely and its name becomes free
|
||||||
|
// for reuse.
|
||||||
|
message Repository {
|
||||||
|
// Server-assigned unique identifier; stable across renames.
|
||||||
|
bytes id = 1;
|
||||||
|
// Human-readable name. Unique among live repositories. Validation rules
|
||||||
|
// are defined by lore-revision (see `repository::is_valid_name`).
|
||||||
|
string name = 2;
|
||||||
|
// Free-form caller-supplied description.
|
||||||
|
string description = 3;
|
||||||
|
// Default branch id, fixed at create time and stored in the repository
|
||||||
|
// metadata blob.
|
||||||
|
bytes default_branch_id = 4;
|
||||||
|
// Default branch name, fixed at create time.
|
||||||
|
string default_branch_name = 5;
|
||||||
|
// Identity that created the repository (caller-supplied when permitted,
|
||||||
|
// else the authenticated JWT identity).
|
||||||
|
string creator = 6;
|
||||||
|
// Server-assigned creation timestamp (Unix epoch milliseconds).
|
||||||
|
uint64 created = 7;
|
||||||
|
// Current metadata pointer hash; mutated atomically via
|
||||||
|
// RepositoryMetadataSet.
|
||||||
|
bytes metadata = 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A branch in the revision graph. Tombstoned (deleted=true) branches are
|
||||||
|
// preserved by id but their name → id mapping is erased per the
|
||||||
|
// "Branch names are exclusive to live branches" invariant.
|
||||||
|
message Branch {
|
||||||
|
// Server-assigned unique identifier; stable across renames and
|
||||||
|
// deletion (tombstone preserves id).
|
||||||
|
bytes id = 1;
|
||||||
|
// Human-readable name. Unique among live branches; freed for reuse on
|
||||||
|
// BranchDelete. Validation rules are defined by lore-revision.
|
||||||
|
string name = 2;
|
||||||
|
// Identity that created the branch (caller-supplied when permitted, else
|
||||||
|
// the authenticated JWT identity).
|
||||||
|
string creator = 3;
|
||||||
|
// Free-form caller-defined tag for grouping or filtering branches by
|
||||||
|
// intent. Server stores verbatim; no enforced vocabulary.
|
||||||
|
string category = 4;
|
||||||
|
// Server-assigned creation timestamp (Unix epoch milliseconds).
|
||||||
|
uint64 created = 5;
|
||||||
|
// Signature of the current branch tip.
|
||||||
|
bytes latest = 6;
|
||||||
|
// True iff the branch has been tombstoned via BranchDelete. The record
|
||||||
|
// survives but the name → id lookup is erased.
|
||||||
|
bool deleted = 7;
|
||||||
|
// Current metadata hash; mutated atomically via BranchMetadataSet.
|
||||||
|
bytes metadata = 8;
|
||||||
|
// Ancestry chain — parent-first, root-last. stack[0] is the immediate
|
||||||
|
// parent the branch was forked from; stack[N-1] is the ultimate root.
|
||||||
|
repeated BranchPoint stack = 9;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,156 @@
|
||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package lore.repository.v1;
|
||||||
|
|
||||||
|
import "lore/model/v1/model.proto";
|
||||||
|
|
||||||
|
// Baseline repository-management service. Carries the lifecycle and
|
||||||
|
// metadata-pointer primitives — repository create / delete, lookup, list,
|
||||||
|
// and CAS update of the repository metadata pointer. The repository
|
||||||
|
// metadata blob itself is read/written through CAS storage like any other
|
||||||
|
// content; this service only mediates the pointer to its current head.
|
||||||
|
service RepositoryService {
|
||||||
|
// Create a new repository together with its default branch. The caller
|
||||||
|
// pre-generates `id` and `default_branch_id` for retry idempotency.
|
||||||
|
// Re-issuing the same `id` (or `name`) returns ALREADY_EXISTS unless the
|
||||||
|
// call is byte-for-byte the same as the prior one, in which case it
|
||||||
|
// returns the existing record (idempotent retry).
|
||||||
|
rpc RepositoryCreate (RepositoryCreateRequest) returns (RepositoryCreateResponse);
|
||||||
|
// Hard-delete a repository: clears the name → id mapping, zeroes the
|
||||||
|
// metadata pointer, and tears down all branches.
|
||||||
|
rpc RepositoryDelete (RepositoryDeleteRequest) returns (RepositoryDeleteResponse);
|
||||||
|
// Look up a repository by id or by name.
|
||||||
|
rpc RepositoryGet (RepositoryGetRequest) returns (RepositoryGetResponse);
|
||||||
|
// Stream all repositories the caller is authorised to see.
|
||||||
|
rpc RepositoryList (RepositoryListRequest) returns (stream RepositoryListResponse);
|
||||||
|
// Cheap hash-only read of a repository's current metadata pointer.
|
||||||
|
rpc RepositoryMetadataGet(RepositoryMetadataGetRequest) returns (RepositoryMetadataGetResponse);
|
||||||
|
// Compare-and-swap update of a repository's metadata pointer. CAS miss is
|
||||||
|
// signalled in-band via the response, never as a non-OK gRPC status.
|
||||||
|
rpc RepositoryMetadataSet(RepositoryMetadataSetRequest) returns (RepositoryMetadataSetResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A service to receive requests forwarded on from another Lore Server,
|
||||||
|
// to perform an RPC on behalf of a client
|
||||||
|
service ForwardedRepositoryService {
|
||||||
|
|
||||||
|
rpc RepositoryCreate (RepositoryCreateRequest) returns (RepositoryCreateResponse);
|
||||||
|
rpc RepositoryGet (RepositoryGetRequest) returns (RepositoryGetResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to create a new repository. The caller pre-generates `id` and
|
||||||
|
// `default_branch_id` so retries are idempotent — a duplicate `id` yields
|
||||||
|
// ALREADY_EXISTS unless the call is byte-for-byte the same as the prior
|
||||||
|
// success, in which case the server returns the existing record.
|
||||||
|
message RepositoryCreateRequest {
|
||||||
|
// Caller-pre-generated repository id (typically a UUIDv7).
|
||||||
|
bytes id = 1;
|
||||||
|
// Human-readable repository name. Must satisfy the validation rules in
|
||||||
|
// `lore-revision::repository::is_valid_name` and must not collide with
|
||||||
|
// any existing repository: `/`-separated segments of ASCII alphanumerics,
|
||||||
|
// `-`, `_` and `.`, where no segment is empty or starts with `.`.
|
||||||
|
string name = 2;
|
||||||
|
// Free-form description, stored verbatim in the repository metadata.
|
||||||
|
string description = 3;
|
||||||
|
// Caller-pre-generated default branch id (typically a UUIDv7).
|
||||||
|
bytes default_branch_id = 4;
|
||||||
|
// Default branch name, e.g. "main". Subject to the same name-validation
|
||||||
|
// limits as a regular branch name.
|
||||||
|
string default_branch_name = 5;
|
||||||
|
// Identity to attribute as the repository creator. If unset, the server
|
||||||
|
// uses the authenticated JWT identity. If set, the caller must have
|
||||||
|
// permission to attribute repositories to other identities.
|
||||||
|
optional string creator = 6;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response containing the freshly-created repository record.
|
||||||
|
message RepositoryCreateResponse {
|
||||||
|
// Full Repository record including server-assigned `created` timestamp
|
||||||
|
// and the server-assigned metadata pointer.
|
||||||
|
lore.model.v1.Repository repository = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to hard-delete a repository by id. Names are not used here
|
||||||
|
// because they may have been recycled after a prior delete.
|
||||||
|
message RepositoryDeleteRequest {
|
||||||
|
// Repository id obtained from a prior RepositoryGet / RepositoryList.
|
||||||
|
bytes id = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response carrying the last-known repository record. Repositories are
|
||||||
|
// hard-deleted, so this is the caller's only chance to see the deleted
|
||||||
|
// record's id, name and creator.
|
||||||
|
message RepositoryDeleteResponse {
|
||||||
|
// Repository record as it was immediately before deletion.
|
||||||
|
lore.model.v1.Repository repository = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to look up a repository by id or by name.
|
||||||
|
message RepositoryGetRequest {
|
||||||
|
// Lookup mode.
|
||||||
|
oneof query {
|
||||||
|
// Lookup by repository id.
|
||||||
|
bytes id = 1;
|
||||||
|
// Lookup by repository name.
|
||||||
|
string name = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response containing the resolved repository record.
|
||||||
|
message RepositoryGetResponse {
|
||||||
|
// Repository record matching the lookup.
|
||||||
|
lore.model.v1.Repository repository = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to stream repositories the caller is authorised to see, with
|
||||||
|
// optional filters. When auth is configured the server first consults
|
||||||
|
// the auth service for the caller's permitted resource set; when auth is
|
||||||
|
// off the server returns all locally-known repositories.
|
||||||
|
message RepositoryListRequest {
|
||||||
|
// If set, only repositories whose `creator` field is an exact
|
||||||
|
// byte-for-byte case-sensitive match are emitted.
|
||||||
|
optional string creator = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One-per-stream-message response carrying a single repository record.
|
||||||
|
message RepositoryListResponse {
|
||||||
|
// A repository matching the request's filters and the caller's
|
||||||
|
// authorisation.
|
||||||
|
lore.model.v1.Repository repository = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request for a cheap hash-only read of a repository's metadata pointer.
|
||||||
|
message RepositoryMetadataGetRequest {
|
||||||
|
// Repository id.
|
||||||
|
bytes id = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response carrying the current metadata hash.
|
||||||
|
message RepositoryMetadataGetResponse {
|
||||||
|
// Current metadata pointer.
|
||||||
|
bytes metadata = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request for a compare-and-swap update of a repository's metadata
|
||||||
|
// pointer. The proposed metadata blob must already be addressable in CAS
|
||||||
|
// before issuing this call; the server validates that any Address-typed
|
||||||
|
// values inside the blob reference live blobs and refuses to install a
|
||||||
|
// blob that mutates read-only fields (name, creator, created).
|
||||||
|
message RepositoryMetadataSetRequest {
|
||||||
|
// Repository id.
|
||||||
|
bytes id = 1;
|
||||||
|
// The metadata hash the caller expects to be currently set. The server
|
||||||
|
// compares this to the actual current value and only swaps on match.
|
||||||
|
bytes expected = 2;
|
||||||
|
// The metadata hash to install if the CAS succeeds.
|
||||||
|
bytes updated = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response always returned with gRPC OK regardless of CAS hit or miss. On
|
||||||
|
// a successful CAS, response.metadata == request.updated. On a CAS miss,
|
||||||
|
// response.metadata reflects the unchanged prior value; the caller compares
|
||||||
|
// response.metadata vs request.updated to detect the miss and retry.
|
||||||
|
message RepositoryMetadataSetResponse {
|
||||||
|
// The repository's current metadata pointer after the call.
|
||||||
|
bytes metadata = 1;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,233 @@
|
||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package lore.revision.v1;
|
||||||
|
|
||||||
|
import "lore/model/v1/model.proto";
|
||||||
|
|
||||||
|
// Baseline revision-graph service. Carries the minimal, stable set of
|
||||||
|
// graph primitives — branch lifecycle, metadata CAS, revision listing.
|
||||||
|
// Presentation helpers (describe / tree / diff) live separately on
|
||||||
|
// lore.thin_client.v1.ThinClientService.
|
||||||
|
service RevisionService {
|
||||||
|
// Create a new branch as a fork of an existing revision chain.
|
||||||
|
rpc BranchCreate (BranchCreateRequest) returns (BranchCreateResponse);
|
||||||
|
// Tombstone a live branch by id. Idempotent on already-tombstoned
|
||||||
|
// branches.
|
||||||
|
rpc BranchDelete (BranchDeleteRequest) returns (BranchDeleteResponse);
|
||||||
|
// Look up a branch by id (live or tombstoned) or by name (live only).
|
||||||
|
rpc BranchGet (BranchGetRequest) returns (BranchGetResponse);
|
||||||
|
// Stream all branches matching the optional filters.
|
||||||
|
rpc BranchList (BranchListRequest) returns (stream BranchListResponse);
|
||||||
|
// Set the tip of a branch to a specific revision. Supports force and
|
||||||
|
// fast-forward-merge semantics.
|
||||||
|
rpc BranchPush (BranchPushRequest) returns (BranchPushResponse);
|
||||||
|
// Cheap hash-only read of a branch's current metadata pointer.
|
||||||
|
rpc BranchMetadataGet(BranchMetadataGetRequest) returns (BranchMetadataGetResponse);
|
||||||
|
// Compare-and-swap update of a branch's metadata pointer. CAS miss is
|
||||||
|
// signalled in-band via the response, never as a non-OK gRPC status.
|
||||||
|
rpc BranchMetadataSet(BranchMetadataSetRequest) returns (BranchMetadataSetResponse);
|
||||||
|
// Page through a branch's revision history. Server picks page size.
|
||||||
|
rpc RevisionList (RevisionListRequest) returns (RevisionListResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to create a new branch. The caller must supply a fully-resolved
|
||||||
|
// ancestry stack (no `number == 0` tip resolution is performed for
|
||||||
|
// BranchCreate). The caller also pre-generates the branch `id` so that
|
||||||
|
// retries are idempotent — a duplicate `id` already in use returns
|
||||||
|
// ALREADY_EXISTS.
|
||||||
|
message BranchCreateRequest {
|
||||||
|
// Caller-pre-generated branch id (typically a UUIDv7). Re-issuing the
|
||||||
|
// same id on retry yields ALREADY_EXISTS rather than creating a
|
||||||
|
// duplicate; this gives the RPC end-to-end retry idempotency.
|
||||||
|
bytes id = 1;
|
||||||
|
// Human-readable name for the new branch. Must not collide with any
|
||||||
|
// live branch (tombstoned names are free for reuse).
|
||||||
|
string name = 2;
|
||||||
|
// Identity to attribute as the branch creator. If unset, the server
|
||||||
|
// uses the authenticated JWT identity. If set, the caller must have
|
||||||
|
// permission to attribute branches to other identities.
|
||||||
|
optional string creator = 3;
|
||||||
|
// Free-form caller-defined tag for grouping or filtering. Server
|
||||||
|
// stores verbatim; empty string allowed.
|
||||||
|
string category = 4;
|
||||||
|
// Ancestry chain — parent-first, root-last. stack[0] is the
|
||||||
|
// immediate parent the new branch is forked from. Every entry's
|
||||||
|
// revision_signature must resolve to a known revision on its
|
||||||
|
// branch_id.
|
||||||
|
repeated lore.model.v1.BranchPoint stack = 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response containing the newly-created branch record.
|
||||||
|
message BranchCreateResponse {
|
||||||
|
// Full Branch record including server-assigned `created` timestamp
|
||||||
|
// and the preserved stack.
|
||||||
|
lore.model.v1.Branch branch = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to tombstone a live branch by id. Names are not used here
|
||||||
|
// because they may have been recycled after a prior delete.
|
||||||
|
message BranchDeleteRequest {
|
||||||
|
// Branch id obtained from a prior BranchGet / BranchList.
|
||||||
|
bytes id = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response carrying the post-delete branch record. The record's name
|
||||||
|
// field is preserved even though the name → id mapping has been
|
||||||
|
// erased.
|
||||||
|
message BranchDeleteResponse {
|
||||||
|
// Tombstoned branch record (deleted = true).
|
||||||
|
lore.model.v1.Branch branch = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to look up a branch by id or by name.
|
||||||
|
message BranchGetRequest {
|
||||||
|
// Lookup mode.
|
||||||
|
oneof query {
|
||||||
|
// Lookup by branch id — returns the branch live or tombstoned.
|
||||||
|
bytes id = 1;
|
||||||
|
// Lookup by branch name — returns the live branch with that name
|
||||||
|
// only. Tombstoned branches are not resolvable by name.
|
||||||
|
string name = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response containing the resolved branch record.
|
||||||
|
message BranchGetResponse {
|
||||||
|
// Branch record matching the lookup.
|
||||||
|
lore.model.v1.Branch branch = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to stream branches with optional filters.
|
||||||
|
message BranchListRequest {
|
||||||
|
// If set, only branches whose `creator` field is an exact
|
||||||
|
// byte-for-byte case-sensitive match are emitted. If unset, no
|
||||||
|
// creator filter is applied.
|
||||||
|
optional string creator = 1;
|
||||||
|
// If true, tombstoned branches are emitted with `Branch.deleted =
|
||||||
|
// true`. Default false (only live branches emitted).
|
||||||
|
bool include_deleted = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One-per-stream-message response carrying a single branch record.
|
||||||
|
message BranchListResponse {
|
||||||
|
// A branch matching the request's filters.
|
||||||
|
lore.model.v1.Branch branch = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to push a revision as a branch's new tip.
|
||||||
|
message BranchPushRequest {
|
||||||
|
// Target branch id.
|
||||||
|
bytes id = 1;
|
||||||
|
// Content signature of the revision to push. Caller must ensure the
|
||||||
|
// revision and all data it references are present in CAS before
|
||||||
|
// calling.
|
||||||
|
bytes revision_signature = 2;
|
||||||
|
// When true, the server replaces the tip directly without checking
|
||||||
|
// whether the new tip descends from the current one. Wins over
|
||||||
|
// `fast_forward_merge` when both are set.
|
||||||
|
bool force = 3;
|
||||||
|
// When true and the new tip does not descend from the current tip,
|
||||||
|
// the server attempts a fast-forward merge. Mutually superseded by
|
||||||
|
// `force`.
|
||||||
|
bool fast_forward_merge = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response describing the resulting branch tip after a push.
|
||||||
|
message BranchPushResponse {
|
||||||
|
// Signature of the resulting tip (may equal the request's
|
||||||
|
// revision_signature, or a new merge revision in the
|
||||||
|
// fast-forward-merge case).
|
||||||
|
bytes revision_signature = 1;
|
||||||
|
// Per-branch number of the resulting tip.
|
||||||
|
uint64 revision_number = 2;
|
||||||
|
// True iff the server performed a fast-forward merge to land the
|
||||||
|
// push.
|
||||||
|
bool fast_forward_merged = 3;
|
||||||
|
// Optional human-readable diagnostic. Free-form; clients should not
|
||||||
|
// parse it.
|
||||||
|
optional string message = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request for a cheap hash-only read of a branch's metadata pointer.
|
||||||
|
message BranchMetadataGetRequest {
|
||||||
|
// Branch id.
|
||||||
|
bytes id = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response carrying the current metadata hash.
|
||||||
|
message BranchMetadataGetResponse {
|
||||||
|
// Current metadata pointer.
|
||||||
|
bytes metadata = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request for a compare-and-swap update of a branch's metadata pointer.
|
||||||
|
message BranchMetadataSetRequest {
|
||||||
|
// Branch id.
|
||||||
|
bytes id = 1;
|
||||||
|
// The metadata hash the caller expects to be currently set. The
|
||||||
|
// server compares this to the actual current value and only swaps
|
||||||
|
// on match.
|
||||||
|
bytes expected = 2;
|
||||||
|
// The metadata hash to install if the CAS succeeds.
|
||||||
|
bytes updated = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response always returned with gRPC OK regardless of CAS hit or miss.
|
||||||
|
// On a successful CAS, response.metadata == request.updated. On a CAS
|
||||||
|
// miss, response.metadata reflects the unchanged prior value; the
|
||||||
|
// caller compares response.metadata vs request.updated to detect the
|
||||||
|
// miss and retry.
|
||||||
|
message BranchMetadataSetResponse {
|
||||||
|
// The branch's current metadata pointer after the call.
|
||||||
|
bytes metadata = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to page through a branch's revision history. The start
|
||||||
|
// anchor selects which revision the page is anchored at, and the page
|
||||||
|
// walks the history from that revision.
|
||||||
|
message RevisionListRequest {
|
||||||
|
// Start anchor for the page.
|
||||||
|
oneof start {
|
||||||
|
// Identifier-based anchor: the branch's revision with that
|
||||||
|
// number, or, for a number the branch's first-parent line skips,
|
||||||
|
// the line's nearest revision numbered below it. `number == 0`
|
||||||
|
// resolves to the branch's latest revision. A number above the
|
||||||
|
// latest revision, or with no revision of the line at or below it,
|
||||||
|
// is not found.
|
||||||
|
lore.model.v1.RevisionIdentifier identifier = 1;
|
||||||
|
// Signature-based anchor (typically a cursor returned by a
|
||||||
|
// previous response).
|
||||||
|
bytes signature = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response carrying a page of revision items (newer-to-older within
|
||||||
|
// the page) plus optional cursors for the next pages in either
|
||||||
|
// direction.
|
||||||
|
message RevisionListResponse {
|
||||||
|
// The page of revisions, newest-to-oldest. The revision the request's
|
||||||
|
// `start` anchor resolves to, as `RevisionListRequest` describes, is
|
||||||
|
// guaranteed to appear somewhere in the page, but is not necessarily
|
||||||
|
// items[0] — the server may align the page on a wider boundary (e.g.
|
||||||
|
// a cached segment) and return items both newer and older than the
|
||||||
|
// anchor. Server picks page size.
|
||||||
|
repeated lore.model.v1.RevisionItem items = 1;
|
||||||
|
// Cursor (signature) to feed back as `start.signature` to fetch
|
||||||
|
// the page of revisions newer than this one. Unset when no further
|
||||||
|
// newer revisions exist.
|
||||||
|
optional bytes signature_forward = 2;
|
||||||
|
// Cursor (signature) to feed back as `start.signature` to fetch
|
||||||
|
// the page of revisions older than this one. Unset when no further
|
||||||
|
// older revisions exist.
|
||||||
|
optional bytes signature_backward = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A service to receive requests forwarded on from another Lore Sever,
|
||||||
|
// to perform an RPC on behalf of a client
|
||||||
|
service ForwardedRevisionService {
|
||||||
|
|
||||||
|
rpc BranchCreate (BranchCreateRequest) returns (BranchCreateResponse);
|
||||||
|
rpc BranchDelete (BranchDeleteRequest) returns (BranchDeleteResponse);
|
||||||
|
rpc BranchGet (BranchGetRequest) returns (BranchGetResponse);
|
||||||
|
rpc BranchList (BranchListRequest) returns (stream BranchListResponse);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,281 @@
|
||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package lore.thin_client.v1;
|
||||||
|
|
||||||
|
import "lore/model/v1/model.proto";
|
||||||
|
|
||||||
|
// File-system entry kind for tree listings and diff entries.
|
||||||
|
enum NodeType {
|
||||||
|
// A directory.
|
||||||
|
DIRECTORY = 0;
|
||||||
|
// A regular file.
|
||||||
|
FILE = 1;
|
||||||
|
// A symbolic link.
|
||||||
|
LINK = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// File mode for a file-system entry.
|
||||||
|
enum FileMode {
|
||||||
|
// No special file mode.
|
||||||
|
NONE = 0;
|
||||||
|
// File is executable.
|
||||||
|
EXECUTABLE = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per-path action describing what happened between two states (or relative
|
||||||
|
// to the common ancestor in 3-way merges).
|
||||||
|
enum Action {
|
||||||
|
// No change at this path.
|
||||||
|
KEEP = 0;
|
||||||
|
// The path was added.
|
||||||
|
ADD = 1;
|
||||||
|
// The path was removed.
|
||||||
|
DELETE = 2;
|
||||||
|
// The path was moved (rename + parent change).
|
||||||
|
MOVE = 3;
|
||||||
|
// The path was copied to a new location.
|
||||||
|
COPY = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type tag for a Metadata value, mirroring the corresponding urc enum.
|
||||||
|
enum MetadataType {
|
||||||
|
// Address bytes (content reference).
|
||||||
|
ADDRESS = 0;
|
||||||
|
// Boolean value encoded as "true" / "false" string.
|
||||||
|
BOOLEAN = 1;
|
||||||
|
// Opaque binary value.
|
||||||
|
BINARY = 2;
|
||||||
|
// Addressing context bytes.
|
||||||
|
CONTEXT = 3;
|
||||||
|
// Hash bytes.
|
||||||
|
HASH = 4;
|
||||||
|
// Numeric value encoded as a string.
|
||||||
|
NUMERIC = 5;
|
||||||
|
// UTF-8 string value.
|
||||||
|
STRING = 6;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One per-path change in a revision diff. Replaces the old urc Path +
|
||||||
|
// PathDiff pair with a single "what happened to this path" entry.
|
||||||
|
// In 3-way mode wrapped inside DiffConflict, the change is rooted at the
|
||||||
|
// common ancestor.
|
||||||
|
message DiffChange {
|
||||||
|
reserved 5; // deprecated hash-only content_from
|
||||||
|
reserved 6; // deprecated hash-only content_to
|
||||||
|
|
||||||
|
// Destination path (where the entry lives in the "to" side).
|
||||||
|
string path = 1;
|
||||||
|
// Source path for MOVE / COPY actions; empty otherwise.
|
||||||
|
string path_from = 2;
|
||||||
|
// What kind of change occurred at this path.
|
||||||
|
Action action = 3;
|
||||||
|
// The kind of node at `path` in the "to" side.
|
||||||
|
NodeType node_type = 4;
|
||||||
|
// True when the server auto-resolved this change in 3-way mode (only
|
||||||
|
// meaningful when the request set `autoresolve = true`).
|
||||||
|
bool automerged = 7;
|
||||||
|
// Index into the per-stream partition table built from `DiffPartition`
|
||||||
|
// payloads. 0 = the request's repository (the parent partition, never
|
||||||
|
// announced). Non-zero values MUST be preceded on the same stream by
|
||||||
|
// a `DiffPartition` whose `index` matches; the consumer's content
|
||||||
|
// fetch for this change MUST target the corresponding partition,
|
||||||
|
// not the request's repository id.
|
||||||
|
uint32 link_repository_index = 8;
|
||||||
|
// True when a link change tracks its parent's branch; false for pinned
|
||||||
|
// links and non-link changes. Only meaningful on a LINK-typed entry; read
|
||||||
|
// it from the entry for the mount path itself.
|
||||||
|
bool tracking = 9;
|
||||||
|
// Content address on the "from" side; unset if the action is ADD. On a
|
||||||
|
// DIRECTORY the hash is over the entry's children rather than over
|
||||||
|
// content, so it identifies what the directory holds but cannot be
|
||||||
|
// fetched.
|
||||||
|
lore.model.v1.Address content_from = 10;
|
||||||
|
// Content address on the "to" side; unset if the action is DELETE. On a
|
||||||
|
// DIRECTORY the hash is over the entry's children rather than over
|
||||||
|
// content, so it identifies what the directory holds but cannot be
|
||||||
|
// fetched.
|
||||||
|
lore.model.v1.Address content_to = 11;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pair of per-path changes describing a 3-way merge conflict at a single
|
||||||
|
// path. Each side's change is rooted at the common ancestor: in particular
|
||||||
|
// `change_from.content_from == change_to.content_from` and both equal the
|
||||||
|
// resolved base's content address for that path.
|
||||||
|
message DiffConflict {
|
||||||
|
// The change one side made relative to the common ancestor.
|
||||||
|
DiffChange change_from = 1;
|
||||||
|
// The change the other side made relative to the common ancestor.
|
||||||
|
DiffChange change_to = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per-stream partition table entry. Announces a linked partition and
|
||||||
|
// the stable index that `DiffChange.link_repository_index`,
|
||||||
|
// `TreeNode.link_repository_index` or `TreeRevision.link_repository_index`
|
||||||
|
// will use to reference it for the remainder of this stream. Server emits
|
||||||
|
// each entry at most once, in discovery order starting at index 1,
|
||||||
|
// strictly before the first `DiffChange` (or `DiffConflict` half),
|
||||||
|
// `TreeNode` or `TreeRevision` that references it. In a diff, an entry for
|
||||||
|
// a link the diff touches may have no change referencing it. Index 0 is
|
||||||
|
// reserved for the parent partition and never announced.
|
||||||
|
message DiffPartition {
|
||||||
|
// Stable per-stream index. Server assigns 1, 2, 3, … in discovery
|
||||||
|
// order. Never zero.
|
||||||
|
uint32 index = 1;
|
||||||
|
// The partition bytes corresponding to `index` (a Lore `Partition`,
|
||||||
|
// i.e. the repository scope the content of every `DiffChange` with
|
||||||
|
// `link_repository_index == index` resolves under).
|
||||||
|
bytes link_partition = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A single entry in a revision tree listing.
|
||||||
|
message TreeNode {
|
||||||
|
// Repository-relative path of this entry.
|
||||||
|
string path = 1;
|
||||||
|
// Whether this entry is a directory, file, or link.
|
||||||
|
NodeType node_type = 2;
|
||||||
|
// Content address for FILE / LINK entries; unused for DIRECTORY.
|
||||||
|
lore.model.v1.Address address = 3;
|
||||||
|
// Original size in bytes. For DIRECTORY entries, this is the cumulative size of its descendant files.
|
||||||
|
uint64 size = 4;
|
||||||
|
// File mode for this entry. For possible flags and values, see enum FileMode.
|
||||||
|
uint64 mode = 5;
|
||||||
|
// True when a link entry tracks its parent's branch; false for pinned links
|
||||||
|
// and non-link entries.
|
||||||
|
bool tracking = 6;
|
||||||
|
// Index of the TreeRevision naming the revision that last changed this
|
||||||
|
// entry. 0 when the request does not ask for attribution or the revision
|
||||||
|
// can't be resolved.
|
||||||
|
uint32 last_revision_index = 7;
|
||||||
|
// Index into the per-stream partition table built from `DiffPartition`
|
||||||
|
// payloads: the partition this entry's content resolves under, as for a
|
||||||
|
// `DiffChange`. For a LINK entry it is the linked repository, for any
|
||||||
|
// other entry the repository the entry is in. 0 = the request's
|
||||||
|
// repository (the parent partition, never announced). A non-zero value
|
||||||
|
// is preceded on the same stream by the `DiffPartition` whose `index`
|
||||||
|
// matches.
|
||||||
|
uint32 link_repository_index = 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Self-describing revision record. Carries the resolved RevisionIdentifier
|
||||||
|
// so callers querying by bare signature learn the resolved (branch, number)
|
||||||
|
// in the same response.
|
||||||
|
message Revision {
|
||||||
|
// Content signature of this revision. Globally unique; never appears on
|
||||||
|
// two branches.
|
||||||
|
bytes signature = 1;
|
||||||
|
// Resolved (branch, number) for this revision. Echoed by the server so
|
||||||
|
// signature-only queries can recover the per-branch coordinates.
|
||||||
|
lore.model.v1.RevisionIdentifier identifier = 2;
|
||||||
|
// Free-form commit message.
|
||||||
|
string commit_message = 3;
|
||||||
|
// Commit timestamp (Unix epoch milliseconds). Always commit time, never
|
||||||
|
// authorship time.
|
||||||
|
uint64 timestamp = 4;
|
||||||
|
// Identity that originally created the revision.
|
||||||
|
string created_by = 5;
|
||||||
|
// Identity that committed the revision (may differ from created_by).
|
||||||
|
string committed_by = 6;
|
||||||
|
// Per-revision metadata entries.
|
||||||
|
repeated Metadata metadata = 7;
|
||||||
|
// Self-side parent (the predecessor on this revision's own branch).
|
||||||
|
// Unset on a branch root; otherwise set.
|
||||||
|
optional Parent parent_self = 8;
|
||||||
|
// Other-side parent (only set on merge commits).
|
||||||
|
optional Parent parent_other = 9;
|
||||||
|
// Per-branch revision number.
|
||||||
|
uint64 number = 10;
|
||||||
|
|
||||||
|
// A parent reference grouping the parent revision's signature and
|
||||||
|
// resolved identifier.
|
||||||
|
message Parent {
|
||||||
|
// Signature of the parent revision.
|
||||||
|
bytes signature = 1;
|
||||||
|
// Resolved (branch, number) for the parent revision.
|
||||||
|
lore.model.v1.RevisionIdentifier identifier = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Typed metadata key/value pair associated with a Branch or Revision.
|
||||||
|
message Metadata {
|
||||||
|
// Caller-defined key.
|
||||||
|
string key = 1;
|
||||||
|
// Encoded value; interpretation depends on `metadata_type`.
|
||||||
|
string value = 2;
|
||||||
|
// Type tag indicating how `value` should be parsed.
|
||||||
|
MetadataType metadata_type = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// File-content diff request. ContentDiff is server-streaming and operates
|
||||||
|
// purely on CAS addresses — no path field, no revision. Each address is
|
||||||
|
// one a `DiffChange` reported, so it resolves the same way here.
|
||||||
|
message ContentDiffRequest {
|
||||||
|
reserved 1; // deprecated hash-only address_from
|
||||||
|
reserved 2; // deprecated hash-only address_to
|
||||||
|
reserved 3; // deprecated hash-only address_base
|
||||||
|
|
||||||
|
// Number of context lines around each hunk in the unified diff
|
||||||
|
// output. Server picks a default if unset.
|
||||||
|
optional uint32 context_lines = 4;
|
||||||
|
// When true, lines that differ only in trailing whitespace are
|
||||||
|
// treated as equal for stat / change-detection purposes. The
|
||||||
|
// displayed diff text uses original (un-normalised) content.
|
||||||
|
bool ignore_whitespace_eol = 5;
|
||||||
|
// When true, runs of internal whitespace are collapsed to a single
|
||||||
|
// space before comparing for stat / change-detection purposes.
|
||||||
|
bool ignore_whitespace_inline = 6;
|
||||||
|
// Maximum size in bytes of the generated diff text. When exceeded,
|
||||||
|
// the response header sets `truncated = true` and emits no chunks;
|
||||||
|
// summary stats are still computed.
|
||||||
|
optional uint64 max_diff_size = 7;
|
||||||
|
// Content address of the "from" side. Unset represents "no content"
|
||||||
|
// (e.g. file added).
|
||||||
|
lore.model.v1.Address address_from = 8;
|
||||||
|
// Content address of the "to" side. Unset represents "no content"
|
||||||
|
// (e.g. file deleted).
|
||||||
|
lore.model.v1.Address address_to = 9;
|
||||||
|
// Common ancestor's content address. Presence triggers 3-way merge
|
||||||
|
// mode; absence gives 2-way unified diff. There is no separate mode
|
||||||
|
// flag.
|
||||||
|
lore.model.v1.Address address_base = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server-streamed response for ContentDiff. The first message MUST carry
|
||||||
|
// `payload.header`; subsequent messages carry `payload.chunk`. Server MUST
|
||||||
|
// NOT emit a ContentDiffResponse with `payload` unset.
|
||||||
|
message ContentDiffResponse {
|
||||||
|
oneof payload {
|
||||||
|
// Summary stats and mode flags, computed up-front and emitted first.
|
||||||
|
ContentDiffHeader header = 1;
|
||||||
|
// A chunk of diff text. Concatenating `chunk.diff` strings in
|
||||||
|
// arrival order reproduces the full diff text.
|
||||||
|
ContentDiffChunkResponse chunk = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Header for a ContentDiff stream. Reports summary stats and short-circuit
|
||||||
|
// flags that may end the stream after the header.
|
||||||
|
message ContentDiffHeader {
|
||||||
|
// Number of lines added (after any whitespace preprocessing).
|
||||||
|
uint64 lines_added = 1;
|
||||||
|
// Number of lines deleted (after any whitespace preprocessing).
|
||||||
|
uint64 lines_deleted = 2;
|
||||||
|
// True when the input is detected as binary; the stream emits no
|
||||||
|
// chunks and stats are zero.
|
||||||
|
bool binary = 3;
|
||||||
|
// True when the generated diff would exceed `max_diff_size`; the
|
||||||
|
// stream emits no chunks but stats are still reported.
|
||||||
|
bool truncated = 4;
|
||||||
|
// True only in 3-way mode when the merge produced conflict markers.
|
||||||
|
bool has_conflicts = 5;
|
||||||
|
// Number of conflict regions in the merged text (3-way only).
|
||||||
|
uint32 conflict_count = 6;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A single chunk of diff text. Server picks chunk boundaries on UTF-8
|
||||||
|
// character boundaries; clients MUST NOT assume line alignment. Reserved
|
||||||
|
// for future additive fields (hunk index, byte offsets, etc.) under
|
||||||
|
// proto3 append-only rules.
|
||||||
|
message ContentDiffChunkResponse {
|
||||||
|
// Diff text for this chunk.
|
||||||
|
string diff = 1;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,188 @@
|
||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package lore.thin_client.v1;
|
||||||
|
|
||||||
|
import "lore/model/v1/model.proto";
|
||||||
|
import "lore/thin_client/v1/model.proto";
|
||||||
|
|
||||||
|
// Thin-client presentation helpers — describe / tree / diff RPCs that are
|
||||||
|
// convenience helpers for clients that lack local cache or compute ( web UIs).
|
||||||
|
// Sits alongside the baseline lore.revision.v1.RevisionService and shares the
|
||||||
|
// same backing revision-graph state.
|
||||||
|
service ThinClientService {
|
||||||
|
// Stream a unified diff or 3-way merge of two CAS blobs as header +
|
||||||
|
// chunked text.
|
||||||
|
rpc ContentDiff (ContentDiffRequest) returns (stream ContentDiffResponse);
|
||||||
|
// Return the full Revision record for a specific revision.
|
||||||
|
rpc RevisionInfo(RevisionInfoRequest) returns (RevisionInfoResponse);
|
||||||
|
// Stream a unified 2-way / 3-way diff between two revisions as
|
||||||
|
// header + DiffChange / DiffConflict items.
|
||||||
|
rpc RevisionDiff(RevisionDiffRequest) returns (stream RevisionDiffResponse);
|
||||||
|
// Stream the file/directory tree at a revision as header + TreeNode
|
||||||
|
// items.
|
||||||
|
rpc RevisionTree(RevisionTreeRequest) returns (stream RevisionTreeResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to describe a single revision by identifier or signature.
|
||||||
|
message RevisionInfoRequest {
|
||||||
|
oneof query {
|
||||||
|
// Identifier-based lookup; `number == 0` resolves to the tip of
|
||||||
|
// the branch.
|
||||||
|
lore.model.v1.RevisionIdentifier identifier = 1;
|
||||||
|
// Signature-based lookup.
|
||||||
|
bytes signature = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response carrying the resolved Revision record. Self-describing —
|
||||||
|
// includes the resolved RevisionIdentifier even when queried by
|
||||||
|
// signature.
|
||||||
|
message RevisionInfoResponse {
|
||||||
|
// The full Revision record.
|
||||||
|
Revision revision = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to diff two revisions. Server picks the diff mode (2-way vs
|
||||||
|
// 3-way) from revision metadata; callers do not declare it.
|
||||||
|
message RevisionDiffRequest {
|
||||||
|
// "From" side specifier.
|
||||||
|
oneof query_from {
|
||||||
|
// Identifier-based "from" (`number == 0` = tip).
|
||||||
|
lore.model.v1.RevisionIdentifier identifier_from = 1;
|
||||||
|
// Signature-based "from".
|
||||||
|
bytes signature_from = 2;
|
||||||
|
}
|
||||||
|
// "To" side specifier.
|
||||||
|
oneof query_to {
|
||||||
|
// Identifier-based "to" (`number == 0` = tip).
|
||||||
|
lore.model.v1.RevisionIdentifier identifier_to = 3;
|
||||||
|
// Signature-based "to".
|
||||||
|
bytes signature_to = 4;
|
||||||
|
}
|
||||||
|
// When true and the server picks 3-way mode, auto-resolved
|
||||||
|
// DiffChange entries are flagged via `automerged = true`. Silently
|
||||||
|
// ignored in 2-way mode.
|
||||||
|
bool autoresolve = 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Header for a RevisionDiff stream. Echoes the resolved revisions so
|
||||||
|
// callers querying by signature learn the (branch, number) and vice
|
||||||
|
// versa. Optional `_base` fields are populated only when the server
|
||||||
|
// selected a 3-way diff.
|
||||||
|
message RevisionDiffHeader {
|
||||||
|
// Resolved (branch, number) of the "from" side.
|
||||||
|
lore.model.v1.RevisionIdentifier identifier_from = 1;
|
||||||
|
// Resolved signature of the "from" side.
|
||||||
|
bytes signature_from = 2;
|
||||||
|
// Resolved (branch, number) of the "to" side.
|
||||||
|
lore.model.v1.RevisionIdentifier identifier_to = 3;
|
||||||
|
// Resolved signature of the "to" side.
|
||||||
|
bytes signature_to = 4;
|
||||||
|
// Resolved (branch, number) of the common ancestor base. Set only
|
||||||
|
// in 3-way mode.
|
||||||
|
optional lore.model.v1.RevisionIdentifier identifier_base = 5;
|
||||||
|
// Resolved signature of the common ancestor base. Set only in
|
||||||
|
// 3-way mode.
|
||||||
|
optional bytes signature_base = 6;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server-streamed response for RevisionDiff. First message carries
|
||||||
|
// `payload.header`; subsequent messages stream `DiffChange` always,
|
||||||
|
// `DiffConflict` only in 3-way mode, and `DiffPartition` lazily as the
|
||||||
|
// server discovers linked repositories during the walk. Each
|
||||||
|
// `DiffPartition` is emitted strictly before the first `DiffChange` or
|
||||||
|
// `DiffConflict` half that references its index.
|
||||||
|
//
|
||||||
|
// A link the diff adds, removes, re-pins or remounts on either side
|
||||||
|
// announces a `DiffPartition` for its repository whatever the caller's
|
||||||
|
// link-read access. A stream with no `DiffPartition` is the same for every
|
||||||
|
// caller.
|
||||||
|
message RevisionDiffResponse {
|
||||||
|
oneof payload {
|
||||||
|
// Header echoing the resolved revisions.
|
||||||
|
RevisionDiffHeader header = 1;
|
||||||
|
// A per-path change.
|
||||||
|
DiffChange change = 2;
|
||||||
|
// A 3-way merge conflict pair (3-way mode only).
|
||||||
|
DiffConflict conflict = 3;
|
||||||
|
// A linked-repository announcement.
|
||||||
|
DiffPartition partition = 4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to walk the file/directory tree at a specific revision.
|
||||||
|
message RevisionTreeRequest {
|
||||||
|
// Revision specifier.
|
||||||
|
oneof query {
|
||||||
|
// Identifier-based lookup; `number == 0` resolves to the tip of
|
||||||
|
// the branch.
|
||||||
|
lore.model.v1.RevisionIdentifier identifier = 1;
|
||||||
|
// Signature-based lookup.
|
||||||
|
bytes signature = 2;
|
||||||
|
}
|
||||||
|
// If set and non-empty, only entries under this path are emitted, not
|
||||||
|
// the entry at the path itself. If unset or empty, the walk covers the
|
||||||
|
// full tree from the repository root.
|
||||||
|
optional string path_prefix = 3;
|
||||||
|
// If set, limits the depth of descent below the prefix root. 1
|
||||||
|
// emits only direct children of the prefix root; 2 emits direct
|
||||||
|
// children plus grandchildren; etc. 0 or unset means unbounded.
|
||||||
|
optional uint32 max_depth = 4;
|
||||||
|
// If true, populate `TreeNode.last_revision_index` and emit the revisions
|
||||||
|
// it names as `TreeRevision` payloads. Off by default. Attribution reads the
|
||||||
|
// delta block of each walked revision and the file metadata blocks of its
|
||||||
|
// entries, and loads each distinct revision an entry names once. The
|
||||||
|
// header's `last_revision_included` reports whether the server attributes.
|
||||||
|
bool include_last_revision = 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Header for a RevisionTree stream. Echoes the resolved revision so
|
||||||
|
// callers querying by signature learn the (branch, number) and vice
|
||||||
|
// versa.
|
||||||
|
message RevisionTreeHeader {
|
||||||
|
// Resolved (branch, number) of the revision being walked.
|
||||||
|
lore.model.v1.RevisionIdentifier identifier = 1;
|
||||||
|
// Resolved signature of the revision being walked.
|
||||||
|
bytes signature = 2;
|
||||||
|
// True when the stream attributes its entries, as
|
||||||
|
// `RevisionTreeRequest.include_last_revision` asks. A server without
|
||||||
|
// attribution leaves it false.
|
||||||
|
bool last_revision_included = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A revision named by TreeNode.last_revision_index. Emitted once per
|
||||||
|
// revision, in discovery order from index 1, and always before the first
|
||||||
|
// TreeNode naming it.
|
||||||
|
message TreeRevision {
|
||||||
|
// Per-stream index, assigned in discovery order.
|
||||||
|
uint32 index = 1;
|
||||||
|
// Carries only attribution-facing fields: `signature`, `identifier`,
|
||||||
|
// `number`, `commit_message`, `timestamp` and `committed_by`. Call
|
||||||
|
// RevisionInfo for the full record. `identifier.branch_id` is zero for a
|
||||||
|
// revision whose metadata names no branch.
|
||||||
|
Revision revision = 2;
|
||||||
|
// Index into the per-stream partition table built from `DiffPartition`
|
||||||
|
// payloads: the partition the revision is in. 0 = the request's
|
||||||
|
// repository (the parent partition, never announced). A non-zero value
|
||||||
|
// is preceded on the same stream by the `DiffPartition` whose `index`
|
||||||
|
// matches.
|
||||||
|
uint32 link_repository_index = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server-streamed response for RevisionTree. First message carries
|
||||||
|
// `payload.header`; subsequent messages stream `TreeNode` items in
|
||||||
|
// server-natural order, interleaved with `DiffPartition` payloads as the
|
||||||
|
// walk meets linked repositories, and with `TreeRevision` payloads when
|
||||||
|
// attribution is requested.
|
||||||
|
message RevisionTreeResponse {
|
||||||
|
oneof payload {
|
||||||
|
// Header echoing the resolved revision.
|
||||||
|
RevisionTreeHeader header = 1;
|
||||||
|
// A tree entry (directory, file, or link).
|
||||||
|
TreeNode node = 2;
|
||||||
|
// A revision named by a later TreeNode.
|
||||||
|
TreeRevision revision = 3;
|
||||||
|
// A linked-repository announcement.
|
||||||
|
DiffPartition partition = 4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,145 @@
|
||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package lore.user.v1;
|
||||||
|
|
||||||
|
// User directory. Clients call this service to resolve user names and ids.
|
||||||
|
// Every RPC is called with the caller's token in the gRPC metadata as
|
||||||
|
// `authorization: Bearer <token>`.
|
||||||
|
service UserService {
|
||||||
|
// Resolve user IDs to users. IDs the directory does not know are omitted
|
||||||
|
// from the answer rather than reported as errors.
|
||||||
|
rpc UserGet(UserGetRequest) returns (UserGetResponse);
|
||||||
|
// Find the users whose username or display name equals a given name.
|
||||||
|
rpc UserFind(UserFindRequest) returns (UserFindResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A 3rd party registry of the repositories and the users' permissions
|
||||||
|
// on them. The Lore server calls it with the caller's token: it registers a
|
||||||
|
// repository on create, unregisters it on delete, and asks it which
|
||||||
|
// repositories a caller may list. Every RPC is called with the token in the
|
||||||
|
// gRPC metadata as `authorization: Bearer <token>`.
|
||||||
|
//
|
||||||
|
// The registry answers each rejection with the status code the RPC
|
||||||
|
// documents. A rejection the RPC documents with a reason carries a
|
||||||
|
// `google.rpc.ErrorInfo` (AIP-193) in the status details, as
|
||||||
|
// `lore/error/v1/error.proto` defines it: `domain` `lore.error.v1`, `reason`
|
||||||
|
// the name of a `lore.error.v1.ErrorReason` value, and `metadata["field"]`
|
||||||
|
// the request field the reason is about.
|
||||||
|
service RepositoryRegistryService {
|
||||||
|
// Stream the repositories the bearer holds permissions on, one per
|
||||||
|
// message, with the permissions held on each. Repositories the bearer
|
||||||
|
// holds no permission on are not listed. The registry refuses with
|
||||||
|
// `PERMISSION_DENIED` when the caller may not list repositories, and with
|
||||||
|
// `UNAUTHENTICATED` when the token is missing, invalid or expired.
|
||||||
|
rpc RepositoryList(RepositoryListRequest) returns (stream RepositoryListResponse);
|
||||||
|
// Register a repository the Lore server is creating, with the caller as
|
||||||
|
// its owner, so that `RepositoryList` lists it. The Lore server calls this
|
||||||
|
// before it stores the repository and refuses the create when this fails.
|
||||||
|
// The registry refuses with:
|
||||||
|
// - `ALREADY_EXISTS` when the repository is registered under another name. See `RepositoryRegisterResponse`.
|
||||||
|
// - `PERMISSION_DENIED` when the caller may not create the repository.
|
||||||
|
// - `UNAUTHENTICATED` when the token is missing, invalid or expired.
|
||||||
|
// - `NOT_FOUND` when an entity the registry requires for the registration does not exist. The registry defines which entities it requires.
|
||||||
|
// - `INVALID_ARGUMENT` with an `ErrorInfo` field of `name` and a reason of `ERROR_REASON_INVALID_FORMAT`, `ERROR_REASON_MISSING_REQUIRED_FIELD` or `ERROR_REASON_UNSPECIFIED` when the registry rejects the name.
|
||||||
|
rpc RepositoryRegister(RepositoryRegisterRequest) returns (RepositoryRegisterResponse);
|
||||||
|
// Unregister a repository the Lore server is deleting. The Lore server
|
||||||
|
// refuses the delete when this fails, so the registry authorizes the
|
||||||
|
// delete. The registry refuses with `PERMISSION_DENIED` when the caller may
|
||||||
|
// not delete the repository, and with `UNAUTHENTICATED` when the token is
|
||||||
|
// missing, invalid or expired.
|
||||||
|
rpc RepositoryUnregister(RepositoryUnregisterRequest) returns (RepositoryUnregisterResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A user as the directory knows them.
|
||||||
|
message User {
|
||||||
|
// The durable user identifier, the value Lore records as a repository's
|
||||||
|
// `creator`, a revision's author or a lock's `owner`.
|
||||||
|
string id = 1;
|
||||||
|
// The name shown for the user.
|
||||||
|
string display_name = 2;
|
||||||
|
// The login name, unique among the directory's users. In OIDC tokens
|
||||||
|
// this is `preferred_username`. Empty when the directory has none.
|
||||||
|
string username = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to resolve user IDs within a partition.
|
||||||
|
message UserGetRequest {
|
||||||
|
// The partition the caller is working in, so a directory that
|
||||||
|
// scopes user visibility by partition can restrict its answer.
|
||||||
|
// A directory that does not scope by partition ignores it.
|
||||||
|
bytes partition = 1;
|
||||||
|
// The user IDs to resolve.
|
||||||
|
repeated string id = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response carrying the users known by the directory.
|
||||||
|
message UserGetResponse {
|
||||||
|
// One entry per requested ID the directory knows, each carrying its `id`,
|
||||||
|
// so the order carries no meaning. Unknown IDs are absent.
|
||||||
|
repeated User user = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to find users by name within a partition.
|
||||||
|
message UserFindRequest {
|
||||||
|
// The partition the caller is working in. See `UserGetRequest`.
|
||||||
|
bytes partition = 1;
|
||||||
|
// Which field the name is matched against, exactly.
|
||||||
|
oneof query {
|
||||||
|
// `User.username`. Unique, so at most one user matches.
|
||||||
|
string username = 2;
|
||||||
|
// `User.display_name`. Not unique, so several users may match.
|
||||||
|
string display_name = 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response carrying every user the query matched.
|
||||||
|
message UserFindResponse {
|
||||||
|
// The matching users. Empty when none matches.
|
||||||
|
repeated User user = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to stream the caller's repositories. The caller ID is read from
|
||||||
|
// the token.
|
||||||
|
message RepositoryListRequest {}
|
||||||
|
|
||||||
|
// One-per-stream-message response carrying a single repository the bearer
|
||||||
|
// holds permissions on.
|
||||||
|
message RepositoryListResponse {
|
||||||
|
// The repository id.
|
||||||
|
bytes id = 1;
|
||||||
|
// The permission names the bearer holds on the repository.
|
||||||
|
repeated string permission = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request to register a repository. The credential is the token of the
|
||||||
|
// caller creating the repository, forwarded by the Lore server. It cannot be
|
||||||
|
// scoped to the repository, which does not exist yet, so the registry must
|
||||||
|
// accept the authn token.
|
||||||
|
message RepositoryRegisterRequest {
|
||||||
|
// The repository id.
|
||||||
|
bytes id = 1;
|
||||||
|
// The repository name.
|
||||||
|
string name = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response to a repository register. Registering a repository already
|
||||||
|
// registered under the same name succeeds for any caller allowed to
|
||||||
|
// register it, so a retried create does too. A repository registered under
|
||||||
|
// another name answers `ALREADY_EXISTS`, and the Lore server refuses the
|
||||||
|
// create.
|
||||||
|
message RepositoryRegisterResponse {}
|
||||||
|
|
||||||
|
// Request to unregister a repository. The credential is the token the caller
|
||||||
|
// sent with the delete, forwarded by the Lore server: a token scoped to the
|
||||||
|
// repository when the client signed in over OIDC, and the login token
|
||||||
|
// otherwise, so the registry must accept either. The registry must refuse a
|
||||||
|
// caller without permission to delete the repository with
|
||||||
|
// `PERMISSION_DENIED`.
|
||||||
|
message RepositoryUnregisterRequest {
|
||||||
|
// The repository id.
|
||||||
|
bytes id = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response to a repository unregister. Unregistering a repository that is
|
||||||
|
// not registered succeeds.
|
||||||
|
message RepositoryUnregisterResponse {}
|
||||||
|
|
@ -0,0 +1,276 @@
|
||||||
|
//! lore-forge's side of Lore's protocols.
|
||||||
|
//!
|
||||||
|
//! This is the only crate that depends on Lore's protocol definitions, vendored under
|
||||||
|
//! `proto/` and pinned to a Lore commit. It serves the two gRPC services Lore reaches at
|
||||||
|
//! `[environment.endpoint] user_url`:
|
||||||
|
//!
|
||||||
|
//! - `lore.user.v1.RepositoryRegistryService`, which `loreserver` calls before creating or
|
||||||
|
//! deleting a repository, and for `lore repository list`;
|
||||||
|
//! - `lore.user.v1.UserService`, which Lore clients call to show names for user IDs.
|
||||||
|
//!
|
||||||
|
//! It also renders the `loreserver` configuration that points Lore at lore-forge, and reads
|
||||||
|
//! repositories from `loreserver` for the web UI ([`reader`]).
|
||||||
|
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use forge_access::repos;
|
||||||
|
use forge_access::repos::RegistryError;
|
||||||
|
use forge_id::Issuer;
|
||||||
|
use forge_id::issuer::Claims;
|
||||||
|
use forge_id::issuer::LiveError;
|
||||||
|
use forge_id::users;
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
use tokio_stream::Stream;
|
||||||
|
use tonic::Request;
|
||||||
|
use tonic::Response;
|
||||||
|
use tonic::Status;
|
||||||
|
use tonic_types::ErrorDetails;
|
||||||
|
use tonic_types::StatusExt;
|
||||||
|
|
||||||
|
pub mod reader;
|
||||||
|
|
||||||
|
#[allow(clippy::all, unreachable_pub)]
|
||||||
|
pub mod proto {
|
||||||
|
tonic::include_proto!("lore.user.v1");
|
||||||
|
|
||||||
|
/// The loreserver services the repository browser reads, nested as their packages are, so
|
||||||
|
/// the generated cross-package paths resolve.
|
||||||
|
pub mod lore {
|
||||||
|
pub mod model {
|
||||||
|
pub mod v1 {
|
||||||
|
tonic::include_proto!("lore.model.v1");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub mod revision {
|
||||||
|
pub mod v1 {
|
||||||
|
tonic::include_proto!("lore.revision.v1");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub mod repository {
|
||||||
|
pub mod v1 {
|
||||||
|
tonic::include_proto!("lore.repository.v1");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub mod thin_client {
|
||||||
|
pub mod v1 {
|
||||||
|
tonic::include_proto!("lore.thin_client.v1");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use proto::repository_registry_service_server::RepositoryRegistryService;
|
||||||
|
use proto::repository_registry_service_server::RepositoryRegistryServiceServer;
|
||||||
|
use proto::user_service_server::UserService;
|
||||||
|
use proto::user_service_server::UserServiceServer;
|
||||||
|
|
||||||
|
/// Serves Lore's user directory and repository registry from lore-forge's database.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Directory {
|
||||||
|
pool: SqlitePool,
|
||||||
|
issuer: Arc<Issuer>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Directory {
|
||||||
|
pub fn new(pool: SqlitePool, issuer: Arc<Issuer>) -> Self {
|
||||||
|
Directory { pool, issuer }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Both services, ready to mount at `user_url`.
|
||||||
|
pub fn routes(&self) -> tonic::service::Routes {
|
||||||
|
tonic::service::Routes::new(UserServiceServer::new(self.clone()))
|
||||||
|
.add_service(RepositoryRegistryServiceServer::new(self.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The caller, from the `authorization: Bearer` metadata. Accepts login tokens and
|
||||||
|
/// repository-scoped tokens, since `loreserver` forwards either.
|
||||||
|
async fn caller<T>(&self, request: &Request<T>) -> Result<Claims, Status> {
|
||||||
|
let token = request
|
||||||
|
.metadata()
|
||||||
|
.get("authorization")
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.and_then(|value| {
|
||||||
|
value.strip_prefix("Bearer ").or_else(|| value.strip_prefix("bearer "))
|
||||||
|
})
|
||||||
|
.ok_or_else(|| Status::unauthenticated("a bearer token is required"))?;
|
||||||
|
match self.issuer.verify_live(token.trim()).await {
|
||||||
|
Ok(claims) => Ok(claims),
|
||||||
|
Err(LiveError::Invalid(error)) => {
|
||||||
|
tracing::debug!("directory refused a token: {error}");
|
||||||
|
Err(Status::unauthenticated("the token is missing, invalid or expired"))
|
||||||
|
}
|
||||||
|
Err(LiveError::Database(error)) => Err(internal(error)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn internal(error: impl std::fmt::Display) -> Status {
|
||||||
|
tracing::error!("directory error: {error}");
|
||||||
|
Status::internal("internal error")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn registry_status(error: RegistryError) -> Status {
|
||||||
|
match error {
|
||||||
|
RegistryError::InvalidName(reason) => {
|
||||||
|
let details = ErrorDetails::with_error_info(
|
||||||
|
"ERROR_REASON_INVALID_FORMAT",
|
||||||
|
"lore.error.v1",
|
||||||
|
[("field".to_owned(), "name".to_owned())],
|
||||||
|
);
|
||||||
|
Status::with_error_details(tonic::Code::InvalidArgument, reason.to_string(), details)
|
||||||
|
}
|
||||||
|
RegistryError::InvalidId => Status::invalid_argument("repository IDs are 16 bytes"),
|
||||||
|
RegistryError::NamespaceNotFound(_) => Status::not_found(error.to_string()),
|
||||||
|
RegistryError::PermissionDenied(_) => Status::permission_denied(error.to_string()),
|
||||||
|
RegistryError::AlreadyExists => Status::already_exists(error.to_string()),
|
||||||
|
RegistryError::Database(error) => internal(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn user_message(user: users::User) -> proto::User {
|
||||||
|
proto::User { id: user.id, display_name: user.display_name, username: user.username }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tonic::async_trait]
|
||||||
|
impl UserService for Directory {
|
||||||
|
async fn user_get(
|
||||||
|
&self,
|
||||||
|
request: Request<proto::UserGetRequest>,
|
||||||
|
) -> Result<Response<proto::UserGetResponse>, Status> {
|
||||||
|
self.caller(&request).await?;
|
||||||
|
let users = users::get_many(&self.pool, &request.get_ref().id).await.map_err(internal)?;
|
||||||
|
Ok(Response::new(proto::UserGetResponse {
|
||||||
|
user: users.into_iter().map(user_message).collect(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn user_find(
|
||||||
|
&self,
|
||||||
|
request: Request<proto::UserFindRequest>,
|
||||||
|
) -> Result<Response<proto::UserFindResponse>, Status> {
|
||||||
|
use proto::user_find_request::Query;
|
||||||
|
self.caller(&request).await?;
|
||||||
|
let found = match &request.get_ref().query {
|
||||||
|
Some(Query::Username(name)) => users::find_by_username(&self.pool, name)
|
||||||
|
.await
|
||||||
|
.map(|user| user.into_iter().collect()),
|
||||||
|
Some(Query::DisplayName(name)) => users::find_by_display_name(&self.pool, name).await,
|
||||||
|
None => Ok(Vec::new()),
|
||||||
|
}
|
||||||
|
.map_err(internal)?;
|
||||||
|
Ok(Response::new(proto::UserFindResponse {
|
||||||
|
user: found.into_iter().map(user_message).collect(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListStream =
|
||||||
|
Pin<Box<dyn Stream<Item = Result<proto::RepositoryListResponse, Status>> + Send + 'static>>;
|
||||||
|
|
||||||
|
#[tonic::async_trait]
|
||||||
|
impl RepositoryRegistryService for Directory {
|
||||||
|
type RepositoryListStream = ListStream;
|
||||||
|
|
||||||
|
async fn repository_list(
|
||||||
|
&self,
|
||||||
|
request: Request<proto::RepositoryListRequest>,
|
||||||
|
) -> Result<Response<Self::RepositoryListStream>, Status> {
|
||||||
|
let caller = self.caller(&request).await?;
|
||||||
|
let listed = repos::list_for_user(&self.pool, &caller.sub).await.map_err(internal)?;
|
||||||
|
let messages: Vec<_> = listed
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(repo, actions)| {
|
||||||
|
let id = hex_to_bytes(&repo.id)?;
|
||||||
|
let permission = actions.names().into_iter().map(str::to_owned).collect();
|
||||||
|
Some(Ok(proto::RepositoryListResponse { id, permission }))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Ok(Response::new(Box::pin(tokio_stream::iter(messages))))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn repository_register(
|
||||||
|
&self,
|
||||||
|
request: Request<proto::RepositoryRegisterRequest>,
|
||||||
|
) -> Result<Response<proto::RepositoryRegisterResponse>, Status> {
|
||||||
|
let caller = self.caller(&request).await?;
|
||||||
|
let message = request.get_ref();
|
||||||
|
let repo = repos::register(&self.pool, &caller.sub, &message.id, &message.name)
|
||||||
|
.await
|
||||||
|
.map_err(registry_status)?;
|
||||||
|
tracing::info!(repo = %repo.full_name(), user = %caller.sub, "repository registered");
|
||||||
|
Ok(Response::new(proto::RepositoryRegisterResponse {}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn repository_unregister(
|
||||||
|
&self,
|
||||||
|
request: Request<proto::RepositoryUnregisterRequest>,
|
||||||
|
) -> Result<Response<proto::RepositoryUnregisterResponse>, Status> {
|
||||||
|
let caller = self.caller(&request).await?;
|
||||||
|
repos::unregister(&self.pool, &caller.sub, &request.get_ref().id)
|
||||||
|
.await
|
||||||
|
.map_err(registry_status)?;
|
||||||
|
Ok(Response::new(proto::RepositoryUnregisterResponse {}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex_to_bytes(hex: &str) -> Option<Vec<u8>> {
|
||||||
|
(0..hex.len())
|
||||||
|
.step_by(2)
|
||||||
|
.map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `loreserver` settings that make it trust lore-forge: verify lore-forge's tokens with
|
||||||
|
/// per-repository authorization, advertise lore-forge as the OIDC issuer, and use
|
||||||
|
/// lore-forge as the user directory and repository registry.
|
||||||
|
pub fn loreserver_config(config: &forge_id::IssuerConfig) -> String {
|
||||||
|
let quote = |value: &str| format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""));
|
||||||
|
format!(
|
||||||
|
"# Generated by lore-forge. Merge into loreserver's configuration.\n\
|
||||||
|
# loreserver fetches lore-forge's signing keys at startup, so start lore-forge first.\n\
|
||||||
|
\n\
|
||||||
|
[server.auth]\n\
|
||||||
|
jwt_issuer = {issuer}\n\
|
||||||
|
jwt_audience = [{audience}]\n\
|
||||||
|
jwt_typ = \"at+jwt\"\n\
|
||||||
|
resource_claim = \"resources\"\n\
|
||||||
|
\n\
|
||||||
|
[server.auth.oidc]\n\
|
||||||
|
client_id = {client_id}\n\
|
||||||
|
scopes = [\"openid\", \"offline_access\"]\n\
|
||||||
|
resource_template = {template}\n\
|
||||||
|
\n\
|
||||||
|
[environment.endpoint]\n\
|
||||||
|
user_url = {issuer}\n",
|
||||||
|
issuer = quote(&config.issuer),
|
||||||
|
audience = quote(&config.lore_url),
|
||||||
|
client_id = quote(&config.client_id),
|
||||||
|
template = quote(&config.resource_template()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hex_round_trip() {
|
||||||
|
assert_eq!(hex_to_bytes("00ff10"), Some(vec![0, 255, 16]));
|
||||||
|
assert_eq!(hex_to_bytes("0g"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn generated_config_names_lore_forge() {
|
||||||
|
let config = forge_id::IssuerConfig::new(
|
||||||
|
&"https://forge.example.com".parse().unwrap(),
|
||||||
|
&"https://lore.example.com".parse().unwrap(),
|
||||||
|
"lore-cli",
|
||||||
|
);
|
||||||
|
let toml = loreserver_config(&config);
|
||||||
|
assert!(toml.contains("jwt_issuer = \"https://forge.example.com\""));
|
||||||
|
assert!(toml.contains("jwt_audience = [\"https://lore.example.com\"]"));
|
||||||
|
assert!(toml.contains("resource_template = \"https://lore.example.com/partitions/{id}\""));
|
||||||
|
assert!(toml.contains("user_url = \"https://forge.example.com\""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,526 @@
|
||||||
|
//! Reads repositories from `loreserver` for the web UI, as the browsing user.
|
||||||
|
//!
|
||||||
|
//! Every call carries a repository-scoped token that the issuer minted for the viewer
|
||||||
|
//! (`Issuer::browse_token`), so `loreserver` applies the same rule to a page view as to the
|
||||||
|
//! CLI. Facts this relies on, read in Lore's source at `6b12f00`:
|
||||||
|
//!
|
||||||
|
//! - public gRPC without a certificate is plaintext HTTP/2;
|
||||||
|
//! - partition-scoped calls need `authorization: Bearer <scoped token>` and the repository id
|
||||||
|
//! as 16 raw bytes under both `lore-partition-bin` and `urc-repository-id-bin`;
|
||||||
|
//! - file content comes decoded from the HTTP endpoint at
|
||||||
|
//! `/v1/repository/<id>/content/<hash>-<context>`, authorised by the same token;
|
||||||
|
//! - `ThinClientService.ContentDiff` is unimplemented, so file diffs are computed here.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use tokio_stream::StreamExt;
|
||||||
|
use tonic::Request;
|
||||||
|
use tonic::metadata::MetadataValue;
|
||||||
|
use tonic::transport::Channel;
|
||||||
|
use tonic::transport::Endpoint;
|
||||||
|
|
||||||
|
use crate::proto::lore::model::v1 as model;
|
||||||
|
use crate::proto::lore::repository::v1 as repository;
|
||||||
|
use crate::proto::lore::revision::v1 as revision;
|
||||||
|
use crate::proto::lore::thin_client::v1 as thin;
|
||||||
|
|
||||||
|
/// A failed read.
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ReadError {
|
||||||
|
#[error("the Lore server did not answer: {0}")]
|
||||||
|
Unavailable(String),
|
||||||
|
#[error("not found")]
|
||||||
|
NotFound,
|
||||||
|
#[error("the Lore server refused the read: {0}")]
|
||||||
|
Refused(String),
|
||||||
|
#[error("the Lore server answered with an error: {0}")]
|
||||||
|
Other(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<tonic::Status> for ReadError {
|
||||||
|
fn from(status: tonic::Status) -> Self {
|
||||||
|
use tonic::Code;
|
||||||
|
match status.code() {
|
||||||
|
Code::Unavailable | Code::DeadlineExceeded | Code::Cancelled => ReadError::Unavailable(status.message().to_owned()),
|
||||||
|
// loreserver reports an unknown revision or path as a failed precondition.
|
||||||
|
Code::NotFound | Code::FailedPrecondition => ReadError::NotFound,
|
||||||
|
Code::PermissionDenied | Code::Unauthenticated => ReadError::Refused(status.message().to_owned()),
|
||||||
|
code => ReadError::Other(format!("{code:?}: {}", status.message())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<reqwest::Error> for ReadError {
|
||||||
|
fn from(error: reqwest::Error) -> Self {
|
||||||
|
ReadError::Unavailable(error.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connections to one `loreserver`. Cheap to clone.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Lore {
|
||||||
|
channel: Channel,
|
||||||
|
http: reqwest::Client,
|
||||||
|
content_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Lore {
|
||||||
|
/// `grpc_url` is the public gRPC endpoint (`http://host:41337`), `content_url` the HTTP
|
||||||
|
/// endpoint (`http://host:41339`). Nothing connects until the first read.
|
||||||
|
pub fn new(grpc_url: &str, content_url: &str) -> Result<Self, String> {
|
||||||
|
let channel = Endpoint::from_shared(grpc_url.to_owned())
|
||||||
|
.map_err(|error| format!("{grpc_url}: {error}"))?
|
||||||
|
.connect_timeout(Duration::from_secs(5))
|
||||||
|
.timeout(Duration::from_secs(30))
|
||||||
|
.connect_lazy();
|
||||||
|
let http = reqwest::Client::builder()
|
||||||
|
.timeout(Duration::from_secs(30))
|
||||||
|
.redirect(reqwest::redirect::Policy::none())
|
||||||
|
.build()
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
Ok(Lore { channel, http, content_url: content_url.trim_end_matches('/').to_owned() })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads repository `repo_id` (32 hex digits) with `token`.
|
||||||
|
pub fn repo(&self, repo_id: &str, token: String) -> Option<Repo> {
|
||||||
|
let id: [u8; 16] = unhex(repo_id)?.try_into().ok()?;
|
||||||
|
Some(Repo { lore: self.clone(), id, token })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a read starts: a branch's tip, or a revision by signature.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum At {
|
||||||
|
Tip(Vec<u8>),
|
||||||
|
Revision(Vec<u8>),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Branch {
|
||||||
|
pub id: Vec<u8>,
|
||||||
|
pub name: String,
|
||||||
|
/// The tip's signature; all zeros for a branch with no revisions.
|
||||||
|
pub latest: Vec<u8>,
|
||||||
|
pub created_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Branch {
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.latest.iter().all(|byte| *byte == 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One page of a branch's history, newest first, following first parents.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct Page {
|
||||||
|
/// Revision numbers and signatures.
|
||||||
|
pub items: Vec<(u64, Vec<u8>)>,
|
||||||
|
/// Where the next older page starts.
|
||||||
|
pub older: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Revision {
|
||||||
|
pub signature: Vec<u8>,
|
||||||
|
pub branch_id: Vec<u8>,
|
||||||
|
pub number: u64,
|
||||||
|
pub message: String,
|
||||||
|
pub timestamp_ms: u64,
|
||||||
|
/// User IDs, as lore-forge issued them.
|
||||||
|
pub created_by: String,
|
||||||
|
pub committed_by: String,
|
||||||
|
/// First parent first; empty for the first revision.
|
||||||
|
pub parents: Vec<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Kind {
|
||||||
|
Directory,
|
||||||
|
File,
|
||||||
|
Link,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<i32> for Kind {
|
||||||
|
fn from(value: i32) -> Self {
|
||||||
|
match thin::NodeType::try_from(value) {
|
||||||
|
Ok(thin::NodeType::Directory) => Kind::Directory,
|
||||||
|
Ok(thin::NodeType::Link) => Kind::Link,
|
||||||
|
_ => Kind::File,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A content address.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct Address {
|
||||||
|
pub hash: Vec<u8>,
|
||||||
|
pub context: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Address {
|
||||||
|
fn from_proto(address: Option<model::Address>) -> Option<Address> {
|
||||||
|
address.filter(|a| !a.hash.is_empty() && a.hash.iter().any(|b| *b != 0)).map(|a| Address { hash: a.hash, context: a.context })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `hash[-context]` form loreserver's HTTP routes take.
|
||||||
|
pub fn path(&self) -> String {
|
||||||
|
if self.context.is_empty() || self.context.iter().all(|b| *b == 0) {
|
||||||
|
hex(&self.hash)
|
||||||
|
} else {
|
||||||
|
format!("{}-{}", hex(&self.hash), hex(&self.context))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Entry {
|
||||||
|
/// The full path from the repository root.
|
||||||
|
pub path: String,
|
||||||
|
pub kind: Kind,
|
||||||
|
pub size: u64,
|
||||||
|
pub address: Option<Address>,
|
||||||
|
/// The revision that last changed it, when attribution was asked for.
|
||||||
|
pub last: Option<Revision>,
|
||||||
|
/// The entry lies in a linked repository, which this reader cannot open.
|
||||||
|
pub linked: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Entry {
|
||||||
|
pub fn name(&self) -> &str {
|
||||||
|
self.path.rsplit('/').next().unwrap_or(&self.path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A directory listing.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Tree {
|
||||||
|
/// The revision listed.
|
||||||
|
pub signature: Vec<u8>,
|
||||||
|
pub entries: Vec<Entry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Action {
|
||||||
|
Add,
|
||||||
|
Delete,
|
||||||
|
Modify,
|
||||||
|
Move,
|
||||||
|
Copy,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Change {
|
||||||
|
pub path: String,
|
||||||
|
/// The old path of a move or copy.
|
||||||
|
pub path_from: Option<String>,
|
||||||
|
pub action: Action,
|
||||||
|
pub kind: Kind,
|
||||||
|
pub from: Option<Address>,
|
||||||
|
pub to: Option<Address>,
|
||||||
|
pub linked: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// File content, perhaps cut short.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Content {
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
/// The whole file's size.
|
||||||
|
pub size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Content {
|
||||||
|
pub fn truncated(&self) -> bool {
|
||||||
|
(self.bytes.len() as u64) < self.size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads from one repository as one user.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Repo {
|
||||||
|
lore: Lore,
|
||||||
|
id: [u8; 16],
|
||||||
|
token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Repo {
|
||||||
|
fn request<T>(&self, message: T) -> Request<T> {
|
||||||
|
let mut request = Request::new(message);
|
||||||
|
let metadata = request.metadata_mut();
|
||||||
|
if let Ok(value) = format!("Bearer {}", self.token).parse() {
|
||||||
|
metadata.insert("authorization", value);
|
||||||
|
}
|
||||||
|
metadata.insert_bin("lore-partition-bin", MetadataValue::from_bytes(&self.id));
|
||||||
|
metadata.insert_bin("urc-repository-id-bin", MetadataValue::from_bytes(&self.id));
|
||||||
|
request
|
||||||
|
}
|
||||||
|
|
||||||
|
fn revisions_client(&self) -> revision::revision_service_client::RevisionServiceClient<Channel> {
|
||||||
|
revision::revision_service_client::RevisionServiceClient::new(self.lore.channel.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn thin_client(&self) -> thin::thin_client_service_client::ThinClientServiceClient<Channel> {
|
||||||
|
thin::thin_client_service_client::ThinClientServiceClient::new(self.lore.channel.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The repository's default branch, fixed when it was created.
|
||||||
|
pub async fn default_branch(&self) -> Result<Option<Vec<u8>>, ReadError> {
|
||||||
|
let mut client = repository::repository_service_client::RepositoryServiceClient::new(self.lore.channel.clone());
|
||||||
|
let query = repository::repository_get_request::Query::Id(self.id.to_vec());
|
||||||
|
let found = client.repository_get(self.request(repository::RepositoryGetRequest { query: Some(query) })).await?;
|
||||||
|
Ok(found.into_inner().repository.map(|repo| repo.default_branch_id).filter(|id| !id.is_empty()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Live branches, in the server's order.
|
||||||
|
pub async fn branches(&self) -> Result<Vec<Branch>, ReadError> {
|
||||||
|
let request = revision::BranchListRequest { creator: None, include_deleted: false };
|
||||||
|
let mut stream = self.revisions_client().branch_list(self.request(request)).await?.into_inner();
|
||||||
|
let mut branches = Vec::new();
|
||||||
|
while let Some(item) = stream.next().await {
|
||||||
|
if let Some(branch) = item?.branch.filter(|branch| !branch.deleted) {
|
||||||
|
branches.push(Branch { id: branch.id, name: branch.name, latest: branch.latest, created_ms: branch.created });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(branches)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One page of history from `at`, newest first. Pages hold at most 100 revisions.
|
||||||
|
pub async fn history(&self, at: &At) -> Result<Page, ReadError> {
|
||||||
|
use revision::revision_list_request::Start;
|
||||||
|
let start = match at {
|
||||||
|
At::Tip(branch) => Start::Identifier(model::RevisionIdentifier { branch_id: branch.clone(), number: 0 }),
|
||||||
|
At::Revision(signature) => Start::Signature(signature.clone()),
|
||||||
|
};
|
||||||
|
let page = self.revisions_client().revision_list(self.request(revision::RevisionListRequest { start: Some(start) })).await?.into_inner();
|
||||||
|
let mut items: Vec<_> = page.items.into_iter().map(|item| (item.number, item.signature)).collect();
|
||||||
|
items.sort_by_key(|item| std::cmp::Reverse(item.0));
|
||||||
|
Ok(Page { items, older: page.signature_backward.filter(|s| s.iter().any(|b| *b != 0)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The full record of one revision.
|
||||||
|
pub async fn revision(&self, at: &At) -> Result<Revision, ReadError> {
|
||||||
|
use thin::revision_info_request::Query;
|
||||||
|
let query = match at {
|
||||||
|
At::Tip(branch) => Query::Identifier(model::RevisionIdentifier { branch_id: branch.clone(), number: 0 }),
|
||||||
|
At::Revision(signature) => Query::Signature(signature.clone()),
|
||||||
|
};
|
||||||
|
let info = self.thin_client().revision_info(self.request(thin::RevisionInfoRequest { query: Some(query) })).await?.into_inner();
|
||||||
|
info.revision.map(revision_from).ok_or(ReadError::NotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The records of several revisions, in the order given, read a few at a time.
|
||||||
|
pub async fn revisions(&self, signatures: &[Vec<u8>]) -> Result<Vec<Revision>, ReadError> {
|
||||||
|
const AT_ONCE: usize = 16;
|
||||||
|
let mut found = Vec::with_capacity(signatures.len());
|
||||||
|
for chunk in signatures.chunks(AT_ONCE) {
|
||||||
|
let mut tasks = tokio::task::JoinSet::new();
|
||||||
|
for (i, signature) in chunk.iter().enumerate() {
|
||||||
|
let repo = self.clone();
|
||||||
|
let at = At::Revision(signature.clone());
|
||||||
|
tasks.spawn(async move { (i, repo.revision(&at).await) });
|
||||||
|
}
|
||||||
|
let mut batch: Vec<Option<Revision>> = vec![None; chunk.len()];
|
||||||
|
while let Some(done) = tasks.join_next().await {
|
||||||
|
let (i, revision) = done.map_err(|error| ReadError::Other(error.to_string()))?;
|
||||||
|
batch[i] = Some(revision?);
|
||||||
|
}
|
||||||
|
found.extend(batch.into_iter().flatten());
|
||||||
|
}
|
||||||
|
Ok(found)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The entries under `prefix` (no slashes at either end; empty for the root) at `at`,
|
||||||
|
/// `depth` levels down (0 for all).
|
||||||
|
pub async fn tree(&self, at: &At, prefix: &str, depth: u32, attribute: bool) -> Result<Tree, ReadError> {
|
||||||
|
use thin::revision_tree_request::Query;
|
||||||
|
use thin::revision_tree_response::Payload;
|
||||||
|
let query = match at {
|
||||||
|
At::Tip(branch) => Query::Identifier(model::RevisionIdentifier { branch_id: branch.clone(), number: 0 }),
|
||||||
|
At::Revision(signature) => Query::Signature(signature.clone()),
|
||||||
|
};
|
||||||
|
let request = thin::RevisionTreeRequest {
|
||||||
|
query: Some(query),
|
||||||
|
path_prefix: (!prefix.is_empty()).then(|| prefix.to_owned()),
|
||||||
|
max_depth: (depth > 0).then_some(depth),
|
||||||
|
include_last_revision: attribute,
|
||||||
|
};
|
||||||
|
let mut stream = self.thin_client().revision_tree(self.request(request)).await?.into_inner();
|
||||||
|
let mut signature = Vec::new();
|
||||||
|
let mut revisions: HashMap<u32, Revision> = HashMap::new();
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
while let Some(item) = stream.next().await {
|
||||||
|
match item?.payload {
|
||||||
|
Some(Payload::Header(header)) => signature = header.signature,
|
||||||
|
Some(Payload::Revision(named)) => {
|
||||||
|
if let Some(revision) = named.revision {
|
||||||
|
revisions.insert(named.index, revision_from(revision));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(Payload::Node(node)) => entries.push(Entry {
|
||||||
|
path: join(prefix, &node.path),
|
||||||
|
kind: Kind::from(node.node_type),
|
||||||
|
size: node.size,
|
||||||
|
address: Address::from_proto(node.address),
|
||||||
|
last: (node.last_revision_index != 0).then(|| revisions.get(&node.last_revision_index).cloned()).flatten(),
|
||||||
|
linked: node.link_repository_index != 0,
|
||||||
|
}),
|
||||||
|
Some(Payload::Partition(_)) | None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Tree { signature, entries })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The files and links that changed from `from` to `to`. With no `from`, everything in `to`
|
||||||
|
/// is an addition.
|
||||||
|
pub async fn diff(&self, from: Option<&[u8]>, to: &[u8]) -> Result<Vec<Change>, ReadError> {
|
||||||
|
use thin::revision_diff_request::QueryFrom;
|
||||||
|
use thin::revision_diff_request::QueryTo;
|
||||||
|
use thin::revision_diff_response::Payload;
|
||||||
|
let Some(from) = from else {
|
||||||
|
let tree = self.tree(&At::Revision(to.to_vec()), "", 0, false).await?;
|
||||||
|
return Ok(tree
|
||||||
|
.entries
|
||||||
|
.into_iter()
|
||||||
|
.filter(|entry| entry.kind != Kind::Directory)
|
||||||
|
.map(|entry| Change { path: entry.path, path_from: None, action: Action::Add, kind: entry.kind, from: None, to: entry.address, linked: entry.linked })
|
||||||
|
.collect());
|
||||||
|
};
|
||||||
|
let request = thin::RevisionDiffRequest {
|
||||||
|
query_from: Some(QueryFrom::SignatureFrom(from.to_vec())),
|
||||||
|
query_to: Some(QueryTo::SignatureTo(to.to_vec())),
|
||||||
|
autoresolve: false,
|
||||||
|
};
|
||||||
|
let mut stream = self.thin_client().revision_diff(self.request(request)).await?.into_inner();
|
||||||
|
let mut changes = Vec::new();
|
||||||
|
while let Some(item) = stream.next().await {
|
||||||
|
if let Some(Payload::Change(change)) = item?.payload {
|
||||||
|
let action = match thin::Action::try_from(change.action) {
|
||||||
|
Ok(thin::Action::Add) => Action::Add,
|
||||||
|
Ok(thin::Action::Delete) => Action::Delete,
|
||||||
|
Ok(thin::Action::Move) => Action::Move,
|
||||||
|
Ok(thin::Action::Copy) => Action::Copy,
|
||||||
|
_ => Action::Modify,
|
||||||
|
};
|
||||||
|
changes.push(Change {
|
||||||
|
path: change.path.trim_start_matches('/').to_owned(),
|
||||||
|
path_from: (!change.path_from.is_empty() && change.path_from != change.path).then(|| change.path_from.trim_start_matches('/').to_owned()),
|
||||||
|
action,
|
||||||
|
kind: Kind::from(change.node_type),
|
||||||
|
from: Address::from_proto(change.content_from),
|
||||||
|
to: Address::from_proto(change.content_to),
|
||||||
|
linked: change.link_repository_index != 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A directory's own entry adds nothing to the changes of the files in it.
|
||||||
|
changes.retain(|change| change.kind != Kind::Directory);
|
||||||
|
changes.sort_by(|a, b| a.path.cmp(&b.path));
|
||||||
|
Ok(changes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Up to `limit` bytes of the file at `address`.
|
||||||
|
pub async fn content(&self, address: &Address, limit: u64) -> Result<Content, ReadError> {
|
||||||
|
let url = format!("{}/v1/repository/{}/content/{}", self.lore.content_url, hex(&self.id), address.path());
|
||||||
|
let mut request = self.lore.http.get(url).bearer_auth(&self.token);
|
||||||
|
if limit > 0 {
|
||||||
|
request = request.header(reqwest::header::RANGE, format!("bytes=0-{}", limit - 1));
|
||||||
|
}
|
||||||
|
let response = request.send().await?;
|
||||||
|
let status = response.status();
|
||||||
|
if status == reqwest::StatusCode::NOT_FOUND {
|
||||||
|
return Err(ReadError::NotFound);
|
||||||
|
}
|
||||||
|
if status == reqwest::StatusCode::RANGE_NOT_SATISFIABLE {
|
||||||
|
// An empty file has no byte 0.
|
||||||
|
return Ok(Content { bytes: Vec::new(), size: 0 });
|
||||||
|
}
|
||||||
|
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||||
|
return Err(ReadError::Refused(status.to_string()));
|
||||||
|
}
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(ReadError::Other(format!("content: {status}")));
|
||||||
|
}
|
||||||
|
// `Content-Range: bytes 0-99/1234` gives the whole size of a partial answer.
|
||||||
|
let total = response
|
||||||
|
.headers()
|
||||||
|
.get(reqwest::header::CONTENT_RANGE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.and_then(|value| value.rsplit('/').next())
|
||||||
|
.and_then(|total| total.parse::<u64>().ok());
|
||||||
|
let bytes = response.bytes().await?.to_vec();
|
||||||
|
let size = total.unwrap_or(bytes.len() as u64);
|
||||||
|
Ok(Content { bytes, size })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn revision_from(revision: thin::Revision) -> Revision {
|
||||||
|
let parents = [revision.parent_self, revision.parent_other]
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.map(|parent| parent.signature)
|
||||||
|
.filter(|signature| signature.iter().any(|byte| *byte != 0))
|
||||||
|
.collect();
|
||||||
|
let branch_id = revision.identifier.map(|id| id.branch_id).unwrap_or_default();
|
||||||
|
Revision {
|
||||||
|
signature: revision.signature,
|
||||||
|
branch_id,
|
||||||
|
number: revision.number,
|
||||||
|
message: revision.commit_message,
|
||||||
|
timestamp_ms: revision.timestamp,
|
||||||
|
created_by: revision.created_by,
|
||||||
|
committed_by: revision.committed_by,
|
||||||
|
parents,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `node_path` as a full path: the server may send paths relative to the prefix.
|
||||||
|
fn join(prefix: &str, node_path: &str) -> String {
|
||||||
|
let path = node_path.trim_start_matches('/');
|
||||||
|
if prefix.is_empty() || path == prefix || path.starts_with(&format!("{prefix}/")) {
|
||||||
|
path.to_owned()
|
||||||
|
} else {
|
||||||
|
format!("{prefix}/{path}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lowercase hex.
|
||||||
|
pub fn hex(bytes: &[u8]) -> String {
|
||||||
|
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes hex, or `None`.
|
||||||
|
pub fn unhex(text: &str) -> Option<Vec<u8>> {
|
||||||
|
if !text.len().is_multiple_of(2) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
(0..text.len()).step_by(2).map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hex_round_trips() {
|
||||||
|
assert_eq!(hex(&[0, 15, 255]), "000fff");
|
||||||
|
assert_eq!(unhex("000fff"), Some(vec![0, 15, 255]));
|
||||||
|
assert_eq!(unhex("0g"), None);
|
||||||
|
assert_eq!(unhex("abc"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paths_join_whether_or_not_the_server_sends_the_prefix() {
|
||||||
|
assert_eq!(join("", "a/b"), "a/b");
|
||||||
|
assert_eq!(join("a", "a/b"), "a/b");
|
||||||
|
assert_eq!(join("a", "b"), "a/b");
|
||||||
|
assert_eq!(join("a", "/a/b"), "a/b");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn addresses_leave_out_an_empty_context() {
|
||||||
|
let address = Address { hash: vec![0xab; 2], context: vec![0; 16] };
|
||||||
|
assert_eq!(address.path(), "abab");
|
||||||
|
let address = Address { hash: vec![0xab; 2], context: vec![1] };
|
||||||
|
assert_eq!(address.path(), "abab-01");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,23 @@
|
||||||
|
[package]
|
||||||
|
name = "forge-store"
|
||||||
|
description = "SQLite access and migrations for lore-forge"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
testing = ["dep:tempfile"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
sqlx.workspace = true
|
||||||
|
tempfile = { workspace = true, optional = true }
|
||||||
|
thiserror.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
forge-store = { path = ".", features = ["testing"] }
|
||||||
|
tokio.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
@ -0,0 +1,167 @@
|
||||||
|
-- Phase 1 schema: accounts, namespaces and access, and the token issuer.
|
||||||
|
-- Times are Unix seconds. Secrets are stored only as SHA-256 hashes or AES-GCM ciphertext.
|
||||||
|
-- Before 0.1.0 this migration may be rewritten in place rather than followed by new ones.
|
||||||
|
|
||||||
|
-- Accounts -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
CREATE TABLE users (
|
||||||
|
-- Stable internal ID. Lore records it in revision history as the `identity` claim.
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
-- NULL when the account cannot sign in with a password.
|
||||||
|
password_hash TEXT,
|
||||||
|
instance_role TEXT NOT NULL CHECK (instance_role IN ('owner', 'admin', 'member')),
|
||||||
|
disabled INTEGER NOT NULL DEFAULT 0 CHECK (disabled IN (0, 1)),
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
token_hash BLOB NOT NULL UNIQUE,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
auth_method TEXT NOT NULL CHECK (auth_method IN ('password', 'provider', 'passkey')),
|
||||||
|
user_agent TEXT NOT NULL DEFAULT '',
|
||||||
|
persistent INTEGER NOT NULL CHECK (persistent IN (0, 1)),
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
last_seen_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
revoked_at INTEGER
|
||||||
|
);
|
||||||
|
CREATE INDEX sessions_user ON sessions (user_id);
|
||||||
|
|
||||||
|
CREATE TABLE settings (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Namespaces and access ------------------------------------------------------------------
|
||||||
|
|
||||||
|
CREATE TABLE orgs (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
-- Preset every member holds on every repository of the organisation, or NULL for none.
|
||||||
|
base_preset TEXT CHECK (base_preset IN ('reader', 'writer', 'maintainer', 'admin')),
|
||||||
|
-- Whether members who are not owners may create repositories.
|
||||||
|
members_can_create_repos INTEGER NOT NULL DEFAULT 0 CHECK (members_can_create_repos IN (0, 1)),
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- The single name table shared by users and organisations, so the two cannot collide.
|
||||||
|
CREATE TABLE namespaces (
|
||||||
|
name TEXT PRIMARY KEY COLLATE NOCASE,
|
||||||
|
kind TEXT NOT NULL CHECK (kind IN ('user', 'org')),
|
||||||
|
user_id TEXT UNIQUE REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
org_id TEXT UNIQUE REFERENCES orgs (id) ON DELETE CASCADE,
|
||||||
|
CHECK ((kind = 'user' AND user_id IS NOT NULL AND org_id IS NULL)
|
||||||
|
OR (kind = 'org' AND org_id IS NOT NULL AND user_id IS NULL))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE org_members (
|
||||||
|
org_id TEXT NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
role TEXT NOT NULL CHECK (role IN ('owner', 'member')),
|
||||||
|
PRIMARY KEY (org_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX org_members_user ON org_members (user_id);
|
||||||
|
|
||||||
|
CREATE TABLE teams (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
org_id TEXT NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL COLLATE NOCASE,
|
||||||
|
UNIQUE (org_id, name)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE team_members (
|
||||||
|
team_id TEXT NOT NULL REFERENCES teams (id) ON DELETE CASCADE,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (team_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX team_members_user ON team_members (user_id);
|
||||||
|
|
||||||
|
CREATE TABLE repos (
|
||||||
|
-- Lore's repository ID: 16 bytes as 32 lowercase hex digits.
|
||||||
|
id TEXT PRIMARY KEY CHECK (length(id) = 32),
|
||||||
|
namespace TEXT NOT NULL REFERENCES namespaces (name) COLLATE NOCASE,
|
||||||
|
name TEXT NOT NULL COLLATE NOCASE,
|
||||||
|
created_by TEXT REFERENCES users (id) ON DELETE SET NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
UNIQUE (namespace, name)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE grants (
|
||||||
|
repo_id TEXT NOT NULL REFERENCES repos (id) ON DELETE CASCADE,
|
||||||
|
subject_kind TEXT NOT NULL CHECK (subject_kind IN ('user', 'team')),
|
||||||
|
subject_id TEXT NOT NULL,
|
||||||
|
preset TEXT CHECK (preset IN ('reader', 'writer', 'maintainer', 'admin', 'owner')),
|
||||||
|
-- Space-separated Lore actions granted on top of the preset.
|
||||||
|
extra_actions TEXT NOT NULL DEFAULT '',
|
||||||
|
PRIMARY KEY (repo_id, subject_kind, subject_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX grants_subject ON grants (subject_kind, subject_id);
|
||||||
|
|
||||||
|
-- Issuer ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
CREATE TABLE signing_keys (
|
||||||
|
kid TEXT PRIMARY KEY,
|
||||||
|
alg TEXT NOT NULL CHECK (alg = 'ES256'),
|
||||||
|
-- AES-GCM ciphertext of the private scalar, under the environment-supplied key.
|
||||||
|
private_key BLOB NOT NULL,
|
||||||
|
public_jwk TEXT NOT NULL,
|
||||||
|
state TEXT NOT NULL CHECK (state IN ('current', 'previous', 'retired')),
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX signing_keys_one_current ON signing_keys (state) WHERE state = 'current';
|
||||||
|
|
||||||
|
CREATE TABLE device_codes (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
device_code_hash BLOB NOT NULL UNIQUE,
|
||||||
|
user_code TEXT NOT NULL UNIQUE,
|
||||||
|
client_id TEXT NOT NULL,
|
||||||
|
scope TEXT NOT NULL DEFAULT '',
|
||||||
|
-- What the requesting device said about itself, shown on the approval page.
|
||||||
|
requested_by TEXT NOT NULL DEFAULT '',
|
||||||
|
status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'denied', 'consumed')),
|
||||||
|
user_id TEXT REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
interval_secs INTEGER NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
last_polled_at INTEGER
|
||||||
|
);
|
||||||
|
|
||||||
|
-- One row per Lore CLI login. Its refresh tokens rotate; revoking the row ends the login.
|
||||||
|
CREATE TABLE cli_logins (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
client_id TEXT NOT NULL,
|
||||||
|
scope TEXT NOT NULL DEFAULT '',
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
last_used_at INTEGER NOT NULL,
|
||||||
|
-- Absolute end of the login, regardless of use.
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
revoked_at INTEGER
|
||||||
|
);
|
||||||
|
CREATE INDEX cli_logins_user ON cli_logins (user_id);
|
||||||
|
|
||||||
|
CREATE TABLE refresh_tokens (
|
||||||
|
token_hash BLOB PRIMARY KEY,
|
||||||
|
login_id TEXT NOT NULL REFERENCES cli_logins (id) ON DELETE CASCADE,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
-- Set when the token is rotated out. A rotated-out token presented again after the grace
|
||||||
|
-- period ends the login.
|
||||||
|
superseded_at INTEGER
|
||||||
|
);
|
||||||
|
CREATE INDEX refresh_tokens_login ON refresh_tokens (login_id);
|
||||||
|
|
||||||
|
-- Shared ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
CREATE TABLE audit_log (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
at INTEGER NOT NULL,
|
||||||
|
actor_id TEXT,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
target TEXT NOT NULL DEFAULT '',
|
||||||
|
detail TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
|
CREATE INDEX audit_log_at ON audit_log (at);
|
||||||
|
|
@ -0,0 +1,85 @@
|
||||||
|
-- Phase 1 accounts: invite keys, sign-in providers, API tokens and service accounts.
|
||||||
|
|
||||||
|
-- Service accounts are rows of `users` with kind 'service'. They have no password and no
|
||||||
|
-- namespace of their own; their username is '<owner>.<name>', which no person's can be,
|
||||||
|
-- since person usernames may not contain '.'.
|
||||||
|
ALTER TABLE users ADD COLUMN kind TEXT NOT NULL DEFAULT 'person' CHECK (kind IN ('person', 'service'));
|
||||||
|
ALTER TABLE users ADD COLUMN owner_namespace TEXT COLLATE NOCASE REFERENCES namespaces (name) ON DELETE CASCADE;
|
||||||
|
CREATE INDEX users_owner_namespace ON users (owner_namespace) WHERE owner_namespace IS NOT NULL;
|
||||||
|
|
||||||
|
-- Invite keys, as in piki. The key is kept in plain text so admins can copy the link again.
|
||||||
|
CREATE TABLE invite_keys (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
invite_key TEXT NOT NULL UNIQUE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
max_uses INTEGER NOT NULL CHECK (max_uses >= 1),
|
||||||
|
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
|
||||||
|
created_by TEXT REFERENCES users (id) ON DELETE SET NULL,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE invite_key_uses (
|
||||||
|
invite_key_id TEXT NOT NULL REFERENCES invite_keys (id) ON DELETE CASCADE,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
used_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (invite_key_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Sign-in providers, as in piki. Client secrets are AES-GCM ciphertext under the secret key.
|
||||||
|
CREATE TABLE oauth_provider_configs (
|
||||||
|
provider TEXT PRIMARY KEY CHECK (provider IN ('github', 'discord', 'google')),
|
||||||
|
client_id TEXT NOT NULL DEFAULT '',
|
||||||
|
client_secret BLOB,
|
||||||
|
enabled INTEGER NOT NULL DEFAULT 0 CHECK (enabled IN (0, 1)),
|
||||||
|
updated_by TEXT REFERENCES users (id) ON DELETE SET NULL,
|
||||||
|
updated_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- A provider account linked to a lore-forge account. Never matched by email or username.
|
||||||
|
CREATE TABLE oauth_identities (
|
||||||
|
provider TEXT NOT NULL CHECK (provider IN ('github', 'discord', 'google')),
|
||||||
|
subject_id TEXT NOT NULL,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
provider_username TEXT NOT NULL DEFAULT '',
|
||||||
|
provider_display_name TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
last_used_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (provider, subject_id),
|
||||||
|
UNIQUE (user_id, provider)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- One sign-in or link attempt. Single use; the state value is stored hashed.
|
||||||
|
CREATE TABLE oauth_flows (
|
||||||
|
state_hash BLOB PRIMARY KEY,
|
||||||
|
provider TEXT NOT NULL CHECK (provider IN ('github', 'discord', 'google')),
|
||||||
|
intent TEXT NOT NULL CHECK (intent IN ('signin', 'link')),
|
||||||
|
user_id TEXT REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
session_id TEXT REFERENCES sessions (id) ON DELETE CASCADE,
|
||||||
|
next_path TEXT NOT NULL DEFAULT '/',
|
||||||
|
pkce_verifier TEXT NOT NULL,
|
||||||
|
nonce TEXT NOT NULL DEFAULT '',
|
||||||
|
persistent INTEGER NOT NULL DEFAULT 0 CHECK (persistent IN (0, 1)),
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
used_at INTEGER
|
||||||
|
);
|
||||||
|
CREATE INDEX oauth_flows_expiry ON oauth_flows (expires_at);
|
||||||
|
|
||||||
|
-- API tokens of people and service accounts. Scopes: 'lore' signs the Lore CLI in (API-key
|
||||||
|
-- token exchange, or a service account's client secret); 'api' reads the JSON API.
|
||||||
|
CREATE TABLE api_tokens (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
token_hash BLOB NOT NULL UNIQUE,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
scopes TEXT NOT NULL,
|
||||||
|
created_by TEXT REFERENCES users (id) ON DELETE SET NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER,
|
||||||
|
last_used_at INTEGER,
|
||||||
|
revoked_at INTEGER
|
||||||
|
);
|
||||||
|
CREATE INDEX api_tokens_user ON api_tokens (user_id);
|
||||||
|
|
||||||
|
-- A CLI login started with an API token ends when the token is revoked.
|
||||||
|
ALTER TABLE cli_logins ADD COLUMN api_token_id TEXT REFERENCES api_tokens (id) ON DELETE CASCADE;
|
||||||
|
|
@ -0,0 +1,168 @@
|
||||||
|
//! SQLite access for lore-forge: opening the database and applying migrations.
|
||||||
|
//!
|
||||||
|
//! Domain crates own their queries and run them against the [`Store`]'s pool. This crate
|
||||||
|
//! owns the schema, the connection settings and a few helpers every crate shares.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::time::Duration;
|
||||||
|
use std::time::SystemTime;
|
||||||
|
use std::time::UNIX_EPOCH;
|
||||||
|
|
||||||
|
use sqlx::sqlite::SqliteConnectOptions;
|
||||||
|
use sqlx::sqlite::SqliteJournalMode;
|
||||||
|
use sqlx::sqlite::SqlitePoolOptions;
|
||||||
|
use sqlx::sqlite::SqliteSynchronous;
|
||||||
|
|
||||||
|
pub use sqlx;
|
||||||
|
pub use sqlx::SqlitePool;
|
||||||
|
|
||||||
|
/// The database file inside the data directory.
|
||||||
|
pub const DATABASE_FILE: &str = "lore-forge.sqlite";
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum StoreError {
|
||||||
|
#[error("opening the database: {0}")]
|
||||||
|
Open(#[source] sqlx::Error),
|
||||||
|
#[error("applying migrations: {0}")]
|
||||||
|
Migrate(#[from] sqlx::migrate::MigrateError),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lore-forge database.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Store {
|
||||||
|
pool: SqlitePool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Store {
|
||||||
|
/// Opens (creating if needed) the database in `data_dir` and applies pending migrations.
|
||||||
|
pub async fn open(data_dir: &Path) -> Result<Self, StoreError> {
|
||||||
|
let path = data_dir.join(DATABASE_FILE);
|
||||||
|
let options = SqliteConnectOptions::from_str("sqlite:")
|
||||||
|
.map_err(StoreError::Open)?
|
||||||
|
.filename(path)
|
||||||
|
.create_if_missing(true);
|
||||||
|
Self::open_with(options).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn open_with(options: SqliteConnectOptions) -> Result<Self, StoreError> {
|
||||||
|
let options = options
|
||||||
|
// Readers do not block the single writer.
|
||||||
|
.journal_mode(SqliteJournalMode::Wal)
|
||||||
|
.synchronous(SqliteSynchronous::Normal)
|
||||||
|
.foreign_keys(true)
|
||||||
|
.busy_timeout(Duration::from_secs(5));
|
||||||
|
let pool = SqlitePoolOptions::new()
|
||||||
|
.max_connections(8)
|
||||||
|
.connect_with(options)
|
||||||
|
.await
|
||||||
|
.map_err(StoreError::Open)?;
|
||||||
|
sqlx::migrate!("./migrations").run(&pool).await?;
|
||||||
|
tracing::debug!("database ready");
|
||||||
|
Ok(Self { pool })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pool(&self) -> &SqlitePool {
|
||||||
|
&self.pool
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current time in Unix seconds, the unit every table uses.
|
||||||
|
pub fn now() -> i64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|elapsed| elapsed.as_secs() as i64)
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `error` is a violation of a UNIQUE or PRIMARY KEY constraint.
|
||||||
|
pub fn is_unique_violation(error: &sqlx::Error) -> bool {
|
||||||
|
matches!(error, sqlx::Error::Database(db) if db.is_unique_violation())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An instance setting from the `settings` table.
|
||||||
|
pub async fn setting(pool: &SqlitePool, key: &str) -> Result<Option<String>, sqlx::Error> {
|
||||||
|
let row: Option<(String,)> = sqlx::query_as("SELECT value FROM settings WHERE key = ?")
|
||||||
|
.bind(key)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(row.map(|(value,)| value))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets an instance setting.
|
||||||
|
pub async fn set_setting(pool: &SqlitePool, key: &str, value: &str) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO settings (key, value) VALUES (?, ?)
|
||||||
|
ON CONFLICT (key) DO UPDATE SET value = excluded.value",
|
||||||
|
)
|
||||||
|
.bind(key)
|
||||||
|
.bind(value)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records an entry in the audit log.
|
||||||
|
pub async fn audit<'e, E>(
|
||||||
|
executor: E,
|
||||||
|
actor_id: Option<&str>,
|
||||||
|
action: &str,
|
||||||
|
target: &str,
|
||||||
|
detail: &str,
|
||||||
|
) -> Result<(), sqlx::Error>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Sqlite>,
|
||||||
|
{
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO audit_log (at, actor_id, action, target, detail) VALUES (?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(now())
|
||||||
|
.bind(actor_id)
|
||||||
|
.bind(action)
|
||||||
|
.bind(target)
|
||||||
|
.bind(detail)
|
||||||
|
.execute(executor)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A store in a fresh temporary directory, for tests in this and other crates.
|
||||||
|
#[cfg(feature = "testing")]
|
||||||
|
pub mod testing {
|
||||||
|
use super::Store;
|
||||||
|
|
||||||
|
pub struct TestStore {
|
||||||
|
pub store: Store,
|
||||||
|
_dir: tempfile::TempDir,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::ops::Deref for TestStore {
|
||||||
|
type Target = Store;
|
||||||
|
fn deref(&self) -> &Store {
|
||||||
|
&self.store
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn store() -> TestStore {
|
||||||
|
let dir = tempfile::tempdir().expect("temporary directory");
|
||||||
|
let store = Store::open(dir.path()).await.expect("open test store");
|
||||||
|
TestStore { store, _dir: dir }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#[tokio::test]
|
||||||
|
async fn opens_and_migrates() {
|
||||||
|
let store = super::testing::store().await;
|
||||||
|
let tables: Vec<(String,)> =
|
||||||
|
sqlx::query_as("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
|
||||||
|
.fetch_all(store.pool())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let names: Vec<_> = tables.into_iter().map(|(name,)| name).collect();
|
||||||
|
for expected in ["users", "repos", "grants", "signing_keys", "cli_logins"] {
|
||||||
|
assert!(names.iter().any(|name| name == expected), "{expected} missing");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,31 @@
|
||||||
|
[package]
|
||||||
|
name = "forge-web"
|
||||||
|
description = "lore-forge's HTTP server: the issuer endpoints, server-rendered pages and JSON API"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
axum.workspace = true
|
||||||
|
forge-access.workspace = true
|
||||||
|
forge-id.workspace = true
|
||||||
|
forge-lore.workspace = true
|
||||||
|
forge-store.workspace = true
|
||||||
|
maud.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
serde_json.workspace = true
|
||||||
|
similar.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
url.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tokio-stream.workspace = true
|
||||||
|
tonic.workspace = true
|
||||||
|
base64.workspace = true
|
||||||
|
forge-store = { workspace = true, features = ["testing"] }
|
||||||
|
tower.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
# Web UI assets
|
||||||
|
|
||||||
|
Served from memory under `/static/` (`src/pages/mod.rs` includes them at build time).
|
||||||
|
|
||||||
|
| File | What | Source | License | SHA-256 |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| `app.css` | The stylesheet: the desktop client's pixel look (Sweetie 16 palette, VGA font) | written here | the project's | |
|
||||||
|
| `vga-8x16.ttf` | IBM VGA 8x16 (`AcPlus_IBM_VGA_8x16.ttf`) from The Ultimate Oldschool PC Font Pack v2.2 by VileR | copied from `desktop/vendor/fonts/`; originally <https://int10h.org/oldschool-pc-fonts/> | [CC BY-SA 4.0](vga-8x16-LICENSE.txt) | `57f71fe16b57b5bd24c4f49c3414b99d7f3a2481f77096ef1d491f916ce429a6` |
|
||||||
|
| `vga-8x16-LICENSE.txt` | The font pack's licence | the same | | `f50b4b5c45aa4096cd341b58b9390439fc5c27ea015262d381ad0c9d57a158de` |
|
||||||
|
|
||||||
|
`/licenses` shows the font's licence, linked from every page's footer. The content security
|
||||||
|
policy allows fonts from `'self'` only, so the font must stay served from here.
|
||||||
|
|
@ -0,0 +1,315 @@
|
||||||
|
/* lore-forge: the same pixel-art look as forge-desktop. IBM VGA 8x16 at whole multiples of
|
||||||
|
16px, the Sweetie 16 palette, hard edges, bevelled buttons and hard drop shadows. */
|
||||||
|
|
||||||
|
@font-face {
|
||||||
|
font-family: "VGA";
|
||||||
|
src: url("/static/vga-8x16.ttf") format("truetype");
|
||||||
|
font-display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--ink: #1a1c2c;
|
||||||
|
--panel: #333c57;
|
||||||
|
--raised: #566c86;
|
||||||
|
--muted: #94b0c2;
|
||||||
|
--paper: #f4f4f4;
|
||||||
|
--forge: #ef7d57;
|
||||||
|
--spark: #ffcd75;
|
||||||
|
--green: #38b764;
|
||||||
|
--red: #b13e53;
|
||||||
|
--blue: #41a6f6;
|
||||||
|
--shadow: #0d0e16;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
html {
|
||||||
|
font-family: "VGA", ui-monospace, Menlo, monospace;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 20px;
|
||||||
|
-webkit-font-smoothing: none;
|
||||||
|
-moz-osx-font-smoothing: unset;
|
||||||
|
font-smooth: never;
|
||||||
|
text-rendering: optimizeSpeed;
|
||||||
|
}
|
||||||
|
|
||||||
|
body { margin: 0; background: var(--ink); color: var(--paper); min-height: 100vh; display: flex; flex-direction: column; }
|
||||||
|
|
||||||
|
a { color: var(--blue); text-decoration: none; }
|
||||||
|
a:hover { color: var(--spark); text-decoration: underline; }
|
||||||
|
|
||||||
|
h1, h2, h3 { font-weight: normal; margin: 0; }
|
||||||
|
h1 { font-size: 32px; line-height: 40px; margin-bottom: 16px; }
|
||||||
|
h2 { font-size: 16px; text-transform: uppercase; color: var(--spark); margin: 24px 0 8px; }
|
||||||
|
h2:first-child { margin-top: 0; }
|
||||||
|
p { margin: 0 0 12px; }
|
||||||
|
code, pre, kbd { font-family: inherit; font-size: inherit; }
|
||||||
|
code { color: var(--spark); }
|
||||||
|
pre { background: var(--ink); border: 2px solid var(--raised); padding: 8px 12px; margin: 0 0 12px; overflow-x: auto; white-space: pre; }
|
||||||
|
strong { font-weight: normal; color: var(--spark); }
|
||||||
|
hr, .rule { border: 0; border-top: 2px dotted var(--raised); margin: 16px 0; }
|
||||||
|
|
||||||
|
.muted { color: var(--muted); }
|
||||||
|
.warn { color: var(--spark); }
|
||||||
|
.big { font-size: 32px; line-height: 40px; letter-spacing: 4px; color: var(--spark); margin: 8px 0 16px; }
|
||||||
|
|
||||||
|
/* Top bar ---------------------------------------------------------------------------------- */
|
||||||
|
|
||||||
|
header.bar {
|
||||||
|
display: flex; align-items: center; gap: 24px;
|
||||||
|
padding: 12px 24px 10px;
|
||||||
|
border-bottom: 2px dotted var(--raised);
|
||||||
|
}
|
||||||
|
.brand { font-size: 32px; line-height: 40px; color: var(--paper); }
|
||||||
|
.brand:hover { color: var(--forge); text-decoration: none; }
|
||||||
|
.brand::before { content: ""; display: inline-block; width: 16px; height: 16px; background: var(--forge); margin-right: 12px; box-shadow: 4px 4px 0 var(--red); vertical-align: 4px; }
|
||||||
|
nav.top { display: flex; gap: 4px; flex: 1; }
|
||||||
|
nav.top a {
|
||||||
|
padding: 4px 12px; color: var(--muted); text-transform: uppercase;
|
||||||
|
border: 2px solid transparent;
|
||||||
|
}
|
||||||
|
nav.top a:hover { color: var(--paper); text-decoration: none; background: var(--panel); }
|
||||||
|
nav.top a.on { color: var(--ink); background: var(--forge); border-color: var(--spark) var(--red) var(--red) var(--spark); }
|
||||||
|
.who { display: flex; align-items: center; gap: 12px; color: var(--muted); }
|
||||||
|
.who a { color: var(--paper); }
|
||||||
|
|
||||||
|
main { flex: 1; width: 100%; max-width: 1120px; margin: 0 auto; padding: 24px; }
|
||||||
|
main.narrow { max-width: 520px; padding-top: 48px; }
|
||||||
|
|
||||||
|
footer.foot {
|
||||||
|
display: flex; gap: 16px; justify-content: space-between;
|
||||||
|
padding: 10px 24px 12px; color: var(--muted);
|
||||||
|
border-top: 2px dotted var(--raised);
|
||||||
|
}
|
||||||
|
footer.foot a { color: var(--muted); }
|
||||||
|
|
||||||
|
/* Panels ----------------------------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 2px solid var(--raised);
|
||||||
|
box-shadow: 4px 4px 0 var(--shadow);
|
||||||
|
padding: 16px;
|
||||||
|
margin: 0 0 24px;
|
||||||
|
}
|
||||||
|
.panel > .head {
|
||||||
|
margin: -16px -16px 16px; padding: 4px 16px;
|
||||||
|
background: var(--raised); color: var(--paper); text-transform: uppercase;
|
||||||
|
display: flex; justify-content: space-between; align-items: center; gap: 12px;
|
||||||
|
}
|
||||||
|
.panel > .head .tag { margin: 0; }
|
||||||
|
.panel.flush { padding: 0; }
|
||||||
|
.panel.flush > .head { margin: 0; }
|
||||||
|
.panel.flush > .body { padding: 16px; }
|
||||||
|
|
||||||
|
.cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 0 24px; }
|
||||||
|
|
||||||
|
.split { display: grid; grid-template-columns: 220px 1fr; gap: 24px; align-items: start; }
|
||||||
|
@media (max-width: 760px) { .split { grid-template-columns: 1fr; } }
|
||||||
|
|
||||||
|
nav.side { background: var(--ink); border: 2px solid var(--raised); padding: 2px; }
|
||||||
|
nav.side .label { padding: 4px 8px; color: var(--muted); text-transform: uppercase; }
|
||||||
|
nav.side a { display: flex; gap: 8px; align-items: center; height: 24px; padding: 2px 8px; color: var(--paper); }
|
||||||
|
nav.side a:hover { background: var(--panel); text-decoration: none; }
|
||||||
|
nav.side a.on { background: var(--raised); }
|
||||||
|
nav.side a.on::before { content: ""; width: 8px; height: 8px; background: var(--forge); }
|
||||||
|
|
||||||
|
/* Lists ------------------------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
table.list { width: 100%; border-collapse: collapse; background: var(--ink); border: 2px solid var(--raised); margin: 0 0 12px; }
|
||||||
|
table.list th {
|
||||||
|
text-align: left; font-weight: normal; text-transform: uppercase; color: var(--muted);
|
||||||
|
background: var(--panel); padding: 2px 8px; border-bottom: 2px solid var(--raised);
|
||||||
|
}
|
||||||
|
table.list td { padding: 2px 8px; height: 24px; vertical-align: middle; border-top: 1px solid var(--panel); }
|
||||||
|
table.list tr:hover td { background: #222536; }
|
||||||
|
table.list td.num, table.list th.num { text-align: right; }
|
||||||
|
table.list td.act { text-align: right; white-space: nowrap; }
|
||||||
|
table.list td.act form { display: inline; }
|
||||||
|
table.list .empty td { color: var(--muted); padding: 8px; }
|
||||||
|
|
||||||
|
dl.kv { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0 0 12px; }
|
||||||
|
dl.kv dt { color: var(--muted); text-transform: uppercase; }
|
||||||
|
dl.kv dd { margin: 0; }
|
||||||
|
|
||||||
|
/* Tags, LEDs ------------------------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.tag {
|
||||||
|
display: inline-block; padding: 0 6px; margin: 0 4px 0 0;
|
||||||
|
background: var(--raised); color: var(--paper); text-transform: uppercase;
|
||||||
|
line-height: 20px;
|
||||||
|
}
|
||||||
|
.tag.forge { background: var(--forge); color: var(--ink); }
|
||||||
|
.tag.spark { background: var(--spark); color: var(--ink); }
|
||||||
|
.tag.green { background: var(--green); color: var(--ink); }
|
||||||
|
.tag.red { background: var(--red); color: var(--paper); }
|
||||||
|
.tag.blue { background: var(--blue); color: var(--ink); }
|
||||||
|
.tag.dim { background: transparent; color: var(--muted); box-shadow: inset 0 0 0 2px var(--raised); }
|
||||||
|
|
||||||
|
.led { display: inline-block; width: 10px; height: 10px; background: var(--raised); box-shadow: 2px 2px 0 var(--shadow); }
|
||||||
|
.led.on { background: var(--green); }
|
||||||
|
.led.off { background: var(--red); }
|
||||||
|
|
||||||
|
.square { display: inline-block; width: 12px; height: 12px; vertical-align: -1px; margin-right: 8px; }
|
||||||
|
|
||||||
|
/* Notices ---------------------------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.notice { padding: 6px 12px; margin: 0 0 16px; border: 2px solid; background: var(--ink); }
|
||||||
|
.notice::before { margin-right: 8px; }
|
||||||
|
.notice.ok { border-color: var(--green); color: var(--green); }
|
||||||
|
.notice.ok::before { content: "OK"; color: var(--ink); background: var(--green); padding: 0 4px; }
|
||||||
|
.notice.err { border-color: var(--red); color: var(--paper); }
|
||||||
|
.notice.err::before { content: "ERR"; color: var(--paper); background: var(--red); padding: 0 4px; }
|
||||||
|
.notice.info { border-color: var(--spark); color: var(--spark); }
|
||||||
|
|
||||||
|
.secret { display: block; background: var(--ink); border: 2px dashed var(--spark); padding: 8px 12px; color: var(--spark); word-break: break-all; user-select: all; margin: 0 0 12px; }
|
||||||
|
|
||||||
|
/* Forms ------------------------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
form.stack { display: grid; gap: 12px; max-width: 420px; }
|
||||||
|
form.stack label, .field { display: grid; gap: 4px; text-transform: uppercase; color: var(--muted); }
|
||||||
|
form.stack label.check { display: flex; gap: 8px; align-items: center; color: var(--paper); text-transform: none; }
|
||||||
|
form.row { display: flex; flex-wrap: wrap; gap: 8px; align-items: end; margin: 0 0 12px; }
|
||||||
|
form.row label { display: grid; gap: 4px; text-transform: uppercase; color: var(--muted); }
|
||||||
|
form.row label.check { display: flex; gap: 8px; align-items: center; height: 28px; color: var(--paper); text-transform: none; }
|
||||||
|
form.inline { display: inline; }
|
||||||
|
.actions { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 8px; }
|
||||||
|
|
||||||
|
input:not([type="checkbox"]):not([type="radio"]), select, textarea {
|
||||||
|
font: inherit; color: var(--paper);
|
||||||
|
background: var(--ink);
|
||||||
|
border: 2px solid var(--raised);
|
||||||
|
border-radius: 0;
|
||||||
|
padding: 2px 8px; height: 28px;
|
||||||
|
outline: none;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
textarea { height: auto; }
|
||||||
|
input:focus, select:focus, textarea:focus { border-color: var(--spark); }
|
||||||
|
input::placeholder { color: var(--raised); }
|
||||||
|
input[type="checkbox"], input[type="radio"] {
|
||||||
|
appearance: none; width: 16px; height: 16px; margin: 0;
|
||||||
|
background: var(--ink); border: 2px solid var(--raised); cursor: pointer;
|
||||||
|
}
|
||||||
|
input[type="checkbox"]:checked, input[type="radio"]:checked { background: var(--forge); box-shadow: inset 0 0 0 2px var(--ink); }
|
||||||
|
input[type="checkbox"]:focus-visible, input[type="radio"]:focus-visible { border-color: var(--spark); }
|
||||||
|
select { appearance: none; padding-right: 24px; background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(-45deg, transparent 50%, var(--muted) 50%); background-size: 5px 5px; background-position: right 12px center, right 7px center; background-repeat: no-repeat; }
|
||||||
|
|
||||||
|
fieldset { border: 2px solid var(--raised); padding: 8px 12px; margin: 0; }
|
||||||
|
legend { color: var(--muted); text-transform: uppercase; padding: 0 4px; }
|
||||||
|
.checks { display: flex; flex-wrap: wrap; gap: 4px 16px; }
|
||||||
|
.checks label { display: flex; gap: 8px; align-items: center; color: var(--paper); text-transform: none; }
|
||||||
|
|
||||||
|
/* Buttons: a bevelled face, a hard shadow, pressed by moving into it. */
|
||||||
|
button, .btn {
|
||||||
|
font: inherit; text-transform: uppercase; cursor: pointer;
|
||||||
|
display: inline-flex; align-items: center; height: 28px; padding: 0 12px;
|
||||||
|
color: var(--paper); background: var(--raised);
|
||||||
|
border: 0; border-radius: 0;
|
||||||
|
box-shadow: inset 2px 2px 0 var(--muted), inset -2px -2px 0 var(--panel), 2px 2px 0 var(--shadow);
|
||||||
|
justify-self: start; white-space: nowrap;
|
||||||
|
}
|
||||||
|
button:hover, .btn:hover { background: var(--muted); color: var(--ink); text-decoration: none; }
|
||||||
|
button:active, .btn:active { transform: translate(2px, 2px); box-shadow: inset 2px 2px 0 var(--muted), inset -2px -2px 0 var(--panel); }
|
||||||
|
button:focus-visible, .btn:focus-visible { outline: 2px solid var(--spark); outline-offset: 2px; }
|
||||||
|
button.primary, .btn.primary { background: var(--forge); color: var(--ink); box-shadow: inset 2px 2px 0 var(--spark), inset -2px -2px 0 var(--red), 2px 2px 0 var(--shadow); }
|
||||||
|
button.primary:hover, .btn.primary:hover { background: var(--spark); }
|
||||||
|
button.danger { background: var(--red); color: var(--paper); box-shadow: inset 2px 2px 0 var(--forge), inset -2px -2px 0 #6b1f30, 2px 2px 0 var(--shadow); }
|
||||||
|
button.danger:hover { background: var(--forge); color: var(--ink); }
|
||||||
|
button.small { height: 24px; padding: 0 8px; }
|
||||||
|
button.link { background: none; box-shadow: none; color: var(--blue); padding: 0; height: auto; text-transform: none; }
|
||||||
|
button.link:hover { color: var(--spark); text-decoration: underline; }
|
||||||
|
button:disabled { background: var(--panel); color: var(--raised); box-shadow: inset 2px 2px 0 var(--raised), inset -2px -2px 0 var(--ink); cursor: default; transform: none; }
|
||||||
|
|
||||||
|
/* Sign-in providers: the same buttons, with a coloured square for each. */
|
||||||
|
.providers { display: grid; gap: 8px; margin-top: 8px; }
|
||||||
|
.providers button { width: 100%; justify-content: flex-start; gap: 12px; }
|
||||||
|
.providers button::before { content: ""; width: 12px; height: 12px; background: var(--ink); }
|
||||||
|
.providers .github::before { background: var(--paper); }
|
||||||
|
.providers .discord::before { background: var(--blue); }
|
||||||
|
.providers .google::before { background: var(--green); }
|
||||||
|
/* The first submit button in the sign-in form is a hidden password submit, so Enter signs in
|
||||||
|
with the password rather than the first provider. */
|
||||||
|
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||||
|
|
||||||
|
/* Repository header ------------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
.crumbs { font-size: 32px; line-height: 40px; margin-bottom: 16px; }
|
||||||
|
.crumbs a { color: var(--paper); }
|
||||||
|
.crumbs a:hover { color: var(--forge); }
|
||||||
|
.crumbs .sep { color: var(--raised); margin: 0 8px; }
|
||||||
|
.tabs { display: flex; gap: 4px; margin: 0 0 -2px; }
|
||||||
|
.tabs a { padding: 4px 16px; color: var(--muted); text-transform: uppercase; background: var(--ink); border: 2px solid var(--raised); border-bottom: 0; }
|
||||||
|
.tabs a:hover { color: var(--paper); text-decoration: none; }
|
||||||
|
.tabs a.on { background: var(--panel); color: var(--spark); position: relative; z-index: 1; }
|
||||||
|
|
||||||
|
pre.licence { white-space: pre-wrap; max-height: 480px; overflow-y: auto; }
|
||||||
|
|
||||||
|
/* Repository browser ----------------------------------------------------------------------- */
|
||||||
|
|
||||||
|
.repobar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; margin: 0 0 12px; }
|
||||||
|
.repobar form { display: flex; gap: 8px; align-items: center; }
|
||||||
|
.repobar .rev { color: var(--muted); }
|
||||||
|
.path { margin: 0 0 8px; }
|
||||||
|
.path a { color: var(--paper); }
|
||||||
|
.path .sep { color: var(--raised); margin: 0 4px; }
|
||||||
|
|
||||||
|
/* File and folder squares, like the desktop explorer's icons. */
|
||||||
|
.icon { display: inline-block; width: 10px; height: 12px; margin-right: 8px; vertical-align: -1px; background: var(--muted); box-shadow: inset -2px 0 0 var(--raised); }
|
||||||
|
.icon.dir { width: 12px; height: 10px; background: var(--spark); box-shadow: inset 0 2px 0 #c99a4a; }
|
||||||
|
.icon.link { background: var(--blue); }
|
||||||
|
table.list td.name a { color: var(--paper); }
|
||||||
|
table.list td.name a:hover { color: var(--spark); }
|
||||||
|
table.list td.dim, .dim { color: var(--muted); }
|
||||||
|
|
||||||
|
/* File contents with line numbers in a gutter. */
|
||||||
|
table.code { width: 100%; border-collapse: collapse; background: var(--ink); border: 2px solid var(--raised); margin: 0 0 12px; }
|
||||||
|
table.code td { padding: 0 12px; white-space: pre; vertical-align: top; }
|
||||||
|
table.code td.ln { width: 1%; text-align: right; color: var(--raised); user-select: none; border-right: 2px solid var(--panel); }
|
||||||
|
.codewrap { overflow-x: auto; }
|
||||||
|
|
||||||
|
/* Diffs: whole lines tinted, the marker column kept. */
|
||||||
|
table.code tr.add td.text { background: #1f3b33; color: #a7f0ba; }
|
||||||
|
table.code tr.del td.text { background: #3d2030; color: #f2a7b6; }
|
||||||
|
table.code tr.hunk td { color: var(--blue); background: #1d2540; }
|
||||||
|
.change { margin: 0 0 16px; }
|
||||||
|
.change h3 { margin: 0 0 4px; font-size: 16px; }
|
||||||
|
.change h3 .tag { margin-right: 8px; }
|
||||||
|
|
||||||
|
/* The revision graph: one SVG per row, coloured by branch. */
|
||||||
|
svg.graph { display: block; }
|
||||||
|
table.list td.graph { padding: 0 0 0 4px; height: 20px; width: 1%; }
|
||||||
|
table.list tr.rev td { height: 20px; padding-top: 0; padding-bottom: 0; }
|
||||||
|
svg.graph .ink { fill: var(--ink); }
|
||||||
|
svg.graph .b0 { fill: var(--forge); }
|
||||||
|
svg.graph .b1 { fill: var(--blue); }
|
||||||
|
svg.graph .b2 { fill: var(--green); }
|
||||||
|
svg.graph .b3 { fill: var(--spark); }
|
||||||
|
svg.graph .b4 { fill: var(--red); }
|
||||||
|
svg.graph .b5 { fill: var(--paper); }
|
||||||
|
svg.graph .bm { fill: var(--muted); }
|
||||||
|
.swatch { display: inline-block; width: 8px; height: 8px; margin-right: 8px; box-shadow: 0 0 0 1px var(--ink); }
|
||||||
|
.swatch.b0 { background: var(--forge); } .swatch.b1 { background: var(--blue); }
|
||||||
|
.swatch.b2 { background: var(--green); } .swatch.b3 { background: var(--spark); }
|
||||||
|
.swatch.b4 { background: var(--red); } .swatch.b5 { background: var(--paper); }
|
||||||
|
.swatch.bm { background: var(--muted); }
|
||||||
|
|
||||||
|
/* TREE: branches open to revisions, revisions to their changes. Opening is a link: the
|
||||||
|
server renders what is open. */
|
||||||
|
.tree { background: var(--ink); border: 2px solid var(--raised); padding: 4px 0; margin: 0 0 12px; }
|
||||||
|
.tree a.node { display: block; padding: 2px 8px; color: var(--paper); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.tree a.node:hover { background: #222536; text-decoration: none; }
|
||||||
|
.tree a.node::before { content: "+"; display: inline-block; width: 16px; color: var(--muted); }
|
||||||
|
.tree a.node.open::before { content: "-"; color: var(--spark); }
|
||||||
|
.tree a.node.revision { padding-left: 32px; }
|
||||||
|
.tree a.node.revision.open { background: var(--panel); }
|
||||||
|
ul.changes { list-style: none; margin: 0 0 4px 72px; padding: 0; }
|
||||||
|
ul.changes.flat { margin-left: 0; }
|
||||||
|
ul.changes li { padding: 1px 0; }
|
||||||
|
ul.changes .tag { margin-right: 8px; }
|
||||||
|
table.list tr.rev.on td { background: var(--panel); }
|
||||||
|
.tag.head { margin-right: 4px; color: var(--ink); }
|
||||||
|
.tag.head.b0 { background: var(--forge); } .tag.head.b1 { background: var(--blue); }
|
||||||
|
.tag.head.b2 { background: var(--green); } .tag.head.b3 { background: var(--spark); }
|
||||||
|
.tag.head.b4 { background: var(--red); color: var(--paper); } .tag.head.b5 { background: var(--paper); }
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
AcPlus_IBM_VGA_8x16.ttf
|
||||||
|
AcPlus_IBM_VGA_8x16-2x.ttf
|
||||||
|
The Ultimate Oldschool PC Font Pack v2.2
|
||||||
|
|
||||||
|
Font adaptation by VileR.
|
||||||
|
Original material: https://int10h.org/oldschool-pc-fonts/
|
||||||
|
Font file included unmodified.
|
||||||
|
|
||||||
|
Licensed under Creative Commons Attribution-ShareAlike 4.0 International:
|
||||||
|
https://creativecommons.org/licenses/by-sa/4.0/
|
||||||
|
Full license terms: https://creativecommons.org/licenses/by-sa/4.0/legalcode
|
||||||
|
|
||||||
|
Upstream attribution and licensing statement:
|
||||||
|
https://int10h.org/oldschool-pc-fonts/readme/#legal_stuff
|
||||||
Binary file not shown.
|
|
@ -0,0 +1,82 @@
|
||||||
|
//! The JSON API under `/api/v1`, authenticated by API tokens with the `api` scope. It calls
|
||||||
|
//! the same services as the pages.
|
||||||
|
|
||||||
|
use axum::Json;
|
||||||
|
use axum::extract::FromRequestParts;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::http::header;
|
||||||
|
use axum::http::request::Parts;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_id::api_tokens;
|
||||||
|
use forge_id::api_tokens::Scope;
|
||||||
|
use forge_id::users::User;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
fn error(status: StatusCode, message: &str) -> Response {
|
||||||
|
(status, Json(json!({ "error": message }))).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The caller of an API request, from `Authorization: Bearer lf_...`.
|
||||||
|
pub struct Caller(pub User);
|
||||||
|
|
||||||
|
impl FromRequestParts<AppState> for Caller {
|
||||||
|
type Rejection = Response;
|
||||||
|
|
||||||
|
async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Self::Rejection> {
|
||||||
|
let unauthorised = || {
|
||||||
|
let mut response = error(StatusCode::UNAUTHORIZED, "an API token with the api scope is required");
|
||||||
|
response.headers_mut().insert(header::WWW_AUTHENTICATE, header::HeaderValue::from_static("Bearer"));
|
||||||
|
response
|
||||||
|
};
|
||||||
|
let token = parts
|
||||||
|
.headers
|
||||||
|
.get(header::AUTHORIZATION)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.and_then(|value| value.strip_prefix("Bearer "))
|
||||||
|
.ok_or_else(unauthorised)?;
|
||||||
|
match api_tokens::authenticate(state.pool(), token.trim(), Scope::Api).await {
|
||||||
|
Ok(Some((_, user))) => Ok(Caller(user)),
|
||||||
|
Ok(None) => Err(unauthorised()),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("API token lookup failed: {e}");
|
||||||
|
Err(error(StatusCode::INTERNAL_SERVER_ERROR, "server error"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn user(Caller(user): Caller) -> Response {
|
||||||
|
Json(json!({
|
||||||
|
"id": user.id,
|
||||||
|
"username": user.username,
|
||||||
|
"display_name": user.display_name,
|
||||||
|
"role": user.role.as_str(),
|
||||||
|
"service_account": user.service,
|
||||||
|
}))
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn repos(State(state): State<AppState>, Caller(user): Caller) -> Response {
|
||||||
|
match forge_access::repos::list_for_user(state.pool(), &user.id).await {
|
||||||
|
Ok(repos) => Json(json!({
|
||||||
|
"repositories": repos.iter().map(|(repo, actions)| json!({
|
||||||
|
"id": repo.id,
|
||||||
|
"name": repo.full_name(),
|
||||||
|
"actions": actions.names(),
|
||||||
|
})).collect::<Vec<_>>(),
|
||||||
|
}))
|
||||||
|
.into_response(),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("API repository list failed: {e}");
|
||||||
|
error(StatusCode::INTERNAL_SERVER_ERROR, "server error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn not_found() -> Response {
|
||||||
|
error(StatusCode::NOT_FOUND, "no such endpoint")
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,335 @@
|
||||||
|
//! A small in-process stand-in for `loreserver`'s read side, for the repository browser's
|
||||||
|
//! tests: the revision, repository and thin client gRPC services, and the HTTP content route.
|
||||||
|
//! Every call must carry the reader's headers for repository [`REPO`], or it is refused.
|
||||||
|
//!
|
||||||
|
//! The repository holds three revisions:
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! main r2 "Edit the readme" README.md changed
|
||||||
|
//! r1 "First revision" README.md, src/main.rs
|
||||||
|
//! feature r3 "Add the logo" art/logo.png (binary), from r1
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::pin::Pin;
|
||||||
|
|
||||||
|
use forge_lore::proto::lore::model::v1 as model;
|
||||||
|
use forge_lore::proto::lore::repository::v1 as repository;
|
||||||
|
use forge_lore::proto::lore::revision::v1 as revision;
|
||||||
|
use forge_lore::proto::lore::thin_client::v1 as thin;
|
||||||
|
use tokio_stream::Stream;
|
||||||
|
use tonic::Request;
|
||||||
|
use tonic::Response;
|
||||||
|
use tonic::Status;
|
||||||
|
|
||||||
|
/// The repository the fake serves.
|
||||||
|
pub const REPO: [u8; 16] = [3; 16];
|
||||||
|
pub const MAIN: [u8; 16] = [1; 16];
|
||||||
|
pub const FEATURE: [u8; 16] = [2; 16];
|
||||||
|
pub const R1: [u8; 32] = [11; 32];
|
||||||
|
pub const R2: [u8; 32] = [12; 32];
|
||||||
|
pub const R3: [u8; 32] = [21; 32];
|
||||||
|
|
||||||
|
type Stream_<T> = Pin<Box<dyn Stream<Item = Result<T, Status>> + Send>>;
|
||||||
|
|
||||||
|
fn stream<T: Send + 'static>(items: Vec<T>) -> Stream_<T> {
|
||||||
|
Box::pin(tokio_stream::iter(items.into_iter().map(Ok)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Blob contents by the first byte of their hash.
|
||||||
|
fn blob(hash: u8) -> Option<&'static [u8]> {
|
||||||
|
match hash {
|
||||||
|
1 => Some(b"hello\n"),
|
||||||
|
2 => Some(b"hello\nworld\n"),
|
||||||
|
3 => Some(b"fn main() {}\n"),
|
||||||
|
4 => Some(b"\x89PNG\r\n\x1a\n\0\0\0"),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Rev {
|
||||||
|
sig: [u8; 32],
|
||||||
|
branch: [u8; 16],
|
||||||
|
number: u64,
|
||||||
|
message: &'static str,
|
||||||
|
parent: Option<[u8; 32]>,
|
||||||
|
files: &'static [(&'static str, u8)],
|
||||||
|
}
|
||||||
|
|
||||||
|
const REVS: [Rev; 3] = [
|
||||||
|
Rev { sig: R1, branch: MAIN, number: 1, message: "First revision", parent: None, files: &[("README.md", 1), ("src/main.rs", 3)] },
|
||||||
|
Rev { sig: R2, branch: MAIN, number: 2, message: "Edit the readme", parent: Some(R1), files: &[("README.md", 2), ("src/main.rs", 3)] },
|
||||||
|
Rev { sig: R3, branch: FEATURE, number: 1, message: "Add the logo", parent: Some(R1), files: &[("README.md", 1), ("art/logo.png", 4), ("src/main.rs", 3)] },
|
||||||
|
];
|
||||||
|
|
||||||
|
fn find(sig: &[u8]) -> Result<&'static Rev, Status> {
|
||||||
|
REVS.iter().find(|rev| rev.sig == sig).ok_or_else(|| Status::failed_precondition("A required Auth entity was not found"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn address(hash: u8) -> model::Address {
|
||||||
|
model::Address { hash: vec![hash; 32], context: vec![0; 16] }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record(rev: &Rev, author: &str) -> thin::Revision {
|
||||||
|
thin::Revision {
|
||||||
|
signature: rev.sig.to_vec(),
|
||||||
|
identifier: Some(model::RevisionIdentifier { branch_id: rev.branch.to_vec(), number: rev.number }),
|
||||||
|
commit_message: rev.message.to_owned(),
|
||||||
|
timestamp: 1_764_000_000_000 + rev.number * 60_000 + u64::from(rev.branch[0]) * 1000,
|
||||||
|
created_by: author.to_owned(),
|
||||||
|
committed_by: author.to_owned(),
|
||||||
|
metadata: Vec::new(),
|
||||||
|
parent_self: rev.parent.map(|parent| thin::revision::Parent { signature: parent.to_vec(), identifier: None }),
|
||||||
|
parent_other: None,
|
||||||
|
number: rev.number,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Refuses calls without a bearer token and this repository's ID in both headers.
|
||||||
|
fn check<T>(request: &Request<T>) -> Result<(), Status> {
|
||||||
|
let metadata = request.metadata();
|
||||||
|
let bearer = metadata.get("authorization").and_then(|v| v.to_str().ok()).is_some_and(|v| v.starts_with("Bearer ey"));
|
||||||
|
let repo = |key: &str| metadata.get_bin(key).and_then(|v| v.to_bytes().ok()).is_some_and(|v| v.as_ref() == REPO);
|
||||||
|
if bearer && repo("lore-partition-bin") && repo("urc-repository-id-bin") {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(Status::permission_denied("Not allowed"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_sig(start: Option<&[u8]>, branch: Option<&[u8]>) -> Result<[u8; 32], Status> {
|
||||||
|
if let Some(sig) = start {
|
||||||
|
return Ok(find(sig)?.sig);
|
||||||
|
}
|
||||||
|
match branch {
|
||||||
|
Some(b) if b == MAIN => Ok(R2),
|
||||||
|
Some(b) if b == FEATURE => Ok(R3),
|
||||||
|
_ => Err(Status::failed_precondition("A required Auth entity was not found")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fake. `author` is the user ID recorded on every revision.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct FakeLore {
|
||||||
|
pub author: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tonic::async_trait]
|
||||||
|
impl revision::revision_service_server::RevisionService for FakeLore {
|
||||||
|
async fn branch_create(&self, _: Request<revision::BranchCreateRequest>) -> Result<Response<revision::BranchCreateResponse>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
async fn branch_delete(&self, _: Request<revision::BranchDeleteRequest>) -> Result<Response<revision::BranchDeleteResponse>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
async fn branch_get(&self, _: Request<revision::BranchGetRequest>) -> Result<Response<revision::BranchGetResponse>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
type BranchListStream = Stream_<revision::BranchListResponse>;
|
||||||
|
async fn branch_list(&self, request: Request<revision::BranchListRequest>) -> Result<Response<Self::BranchListStream>, Status> {
|
||||||
|
check(&request)?;
|
||||||
|
let branch = |id: [u8; 16], name: &str, latest: [u8; 32]| revision::BranchListResponse {
|
||||||
|
branch: Some(model::Branch { id: id.to_vec(), name: name.to_owned(), latest: latest.to_vec(), ..Default::default() }),
|
||||||
|
};
|
||||||
|
// The server's order, not the default branch first.
|
||||||
|
Ok(Response::new(stream(vec![branch(FEATURE, "feature", R3), branch(MAIN, "main", R2)])))
|
||||||
|
}
|
||||||
|
async fn branch_push(&self, _: Request<revision::BranchPushRequest>) -> Result<Response<revision::BranchPushResponse>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
async fn branch_metadata_get(&self, _: Request<revision::BranchMetadataGetRequest>) -> Result<Response<revision::BranchMetadataGetResponse>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
async fn branch_metadata_set(&self, _: Request<revision::BranchMetadataSetRequest>) -> Result<Response<revision::BranchMetadataSetResponse>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
async fn revision_list(&self, request: Request<revision::RevisionListRequest>) -> Result<Response<revision::RevisionListResponse>, Status> {
|
||||||
|
use revision::revision_list_request::Start;
|
||||||
|
check(&request)?;
|
||||||
|
let mut at = match &request.get_ref().start {
|
||||||
|
Some(Start::Signature(sig)) => start_sig(Some(sig), None)?,
|
||||||
|
Some(Start::Identifier(id)) => start_sig(None, Some(&id.branch_id))?,
|
||||||
|
None => return Err(Status::invalid_argument("start")),
|
||||||
|
};
|
||||||
|
let mut items = Vec::new();
|
||||||
|
loop {
|
||||||
|
let rev = find(&at)?;
|
||||||
|
items.push(model::RevisionItem { number: rev.number, signature: rev.sig.to_vec(), ..Default::default() });
|
||||||
|
match rev.parent {
|
||||||
|
Some(parent) => at = parent,
|
||||||
|
None => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Response::new(revision::RevisionListResponse { items, signature_forward: None, signature_backward: None }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tonic::async_trait]
|
||||||
|
impl repository::repository_service_server::RepositoryService for FakeLore {
|
||||||
|
async fn repository_create(&self, _: Request<repository::RepositoryCreateRequest>) -> Result<Response<repository::RepositoryCreateResponse>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
async fn repository_delete(&self, _: Request<repository::RepositoryDeleteRequest>) -> Result<Response<repository::RepositoryDeleteResponse>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
async fn repository_get(&self, request: Request<repository::RepositoryGetRequest>) -> Result<Response<repository::RepositoryGetResponse>, Status> {
|
||||||
|
check(&request)?;
|
||||||
|
Ok(Response::new(repository::RepositoryGetResponse {
|
||||||
|
repository: Some(model::Repository { id: REPO.to_vec(), default_branch_id: MAIN.to_vec(), default_branch_name: "main".into(), ..Default::default() }),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
type RepositoryListStream = Stream_<repository::RepositoryListResponse>;
|
||||||
|
async fn repository_list(&self, _: Request<repository::RepositoryListRequest>) -> Result<Response<Self::RepositoryListStream>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
async fn repository_metadata_get(&self, _: Request<repository::RepositoryMetadataGetRequest>) -> Result<Response<repository::RepositoryMetadataGetResponse>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
async fn repository_metadata_set(&self, _: Request<repository::RepositoryMetadataSetRequest>) -> Result<Response<repository::RepositoryMetadataSetResponse>, Status> {
|
||||||
|
Err(Status::unimplemented("fake"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tonic::async_trait]
|
||||||
|
impl thin::thin_client_service_server::ThinClientService for FakeLore {
|
||||||
|
type ContentDiffStream = Stream_<thin::ContentDiffResponse>;
|
||||||
|
async fn content_diff(&self, _: Request<thin::ContentDiffRequest>) -> Result<Response<Self::ContentDiffStream>, Status> {
|
||||||
|
// As in loreserver.
|
||||||
|
Err(Status::unimplemented("ContentDiff"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn revision_info(&self, request: Request<thin::RevisionInfoRequest>) -> Result<Response<thin::RevisionInfoResponse>, Status> {
|
||||||
|
use thin::revision_info_request::Query;
|
||||||
|
check(&request)?;
|
||||||
|
let sig = match &request.get_ref().query {
|
||||||
|
Some(Query::Signature(sig)) => start_sig(Some(sig), None)?,
|
||||||
|
Some(Query::Identifier(id)) => start_sig(None, Some(&id.branch_id))?,
|
||||||
|
None => return Err(Status::invalid_argument("query")),
|
||||||
|
};
|
||||||
|
Ok(Response::new(thin::RevisionInfoResponse { revision: Some(record(find(&sig)?, &self.author)) }))
|
||||||
|
}
|
||||||
|
|
||||||
|
type RevisionDiffStream = Stream_<thin::RevisionDiffResponse>;
|
||||||
|
async fn revision_diff(&self, request: Request<thin::RevisionDiffRequest>) -> Result<Response<Self::RevisionDiffStream>, Status> {
|
||||||
|
use thin::revision_diff_request::QueryFrom;
|
||||||
|
use thin::revision_diff_request::QueryTo;
|
||||||
|
use thin::revision_diff_response::Payload;
|
||||||
|
check(&request)?;
|
||||||
|
let (Some(QueryFrom::SignatureFrom(from)), Some(QueryTo::SignatureTo(to))) = (&request.get_ref().query_from, &request.get_ref().query_to) else {
|
||||||
|
return Err(Status::invalid_argument("the fake takes signatures"));
|
||||||
|
};
|
||||||
|
let (from, to) = (find(from)?, find(to)?);
|
||||||
|
let before: BTreeMap<_, _> = from.files.iter().copied().collect();
|
||||||
|
let after: BTreeMap<_, _> = to.files.iter().copied().collect();
|
||||||
|
let mut changes = Vec::new();
|
||||||
|
for path in before.keys().chain(after.keys()).collect::<std::collections::BTreeSet<_>>() {
|
||||||
|
let (action, old, new) = match (before.get(path), after.get(path)) {
|
||||||
|
(None, Some(&new)) => (thin::Action::Add, None, Some(new)),
|
||||||
|
(Some(&old), None) => (thin::Action::Delete, Some(old), None),
|
||||||
|
(Some(&old), Some(&new)) if old != new => (thin::Action::Keep, Some(old), Some(new)),
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
changes.push(thin::RevisionDiffResponse {
|
||||||
|
payload: Some(Payload::Change(thin::DiffChange {
|
||||||
|
path: path.to_string(),
|
||||||
|
action: action as i32,
|
||||||
|
node_type: thin::NodeType::File as i32,
|
||||||
|
content_from: old.map(address),
|
||||||
|
content_to: new.map(address),
|
||||||
|
..Default::default()
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(Response::new(stream(changes)))
|
||||||
|
}
|
||||||
|
|
||||||
|
type RevisionTreeStream = Stream_<thin::RevisionTreeResponse>;
|
||||||
|
async fn revision_tree(&self, request: Request<thin::RevisionTreeRequest>) -> Result<Response<Self::RevisionTreeStream>, Status> {
|
||||||
|
use thin::revision_tree_request::Query;
|
||||||
|
use thin::revision_tree_response::Payload;
|
||||||
|
check(&request)?;
|
||||||
|
let query = request.get_ref();
|
||||||
|
let sig = match &query.query {
|
||||||
|
Some(Query::Signature(sig)) => start_sig(Some(sig), None)?,
|
||||||
|
Some(Query::Identifier(id)) => start_sig(None, Some(&id.branch_id))?,
|
||||||
|
None => return Err(Status::invalid_argument("query")),
|
||||||
|
};
|
||||||
|
let rev = find(&sig)?;
|
||||||
|
let prefix = query.path_prefix.clone().unwrap_or_default();
|
||||||
|
let depth = query.max_depth.unwrap_or(0) as usize;
|
||||||
|
// Every file and every directory above it, as full paths.
|
||||||
|
let mut entries: BTreeMap<String, Option<u8>> = BTreeMap::new();
|
||||||
|
for (path, hash) in rev.files {
|
||||||
|
let parts: Vec<&str> = path.split('/').collect();
|
||||||
|
for i in 1..parts.len() {
|
||||||
|
entries.entry(parts[..i].join("/")).or_insert(None);
|
||||||
|
}
|
||||||
|
entries.insert(path.to_string(), Some(*hash));
|
||||||
|
}
|
||||||
|
let mut out = vec![thin::RevisionTreeResponse {
|
||||||
|
payload: Some(Payload::Header(thin::RevisionTreeHeader { identifier: None, signature: rev.sig.to_vec(), last_revision_included: query.include_last_revision })),
|
||||||
|
}];
|
||||||
|
if query.include_last_revision {
|
||||||
|
out.push(thin::RevisionTreeResponse { payload: Some(Payload::Revision(thin::TreeRevision { index: 1, revision: Some(record(rev, &self.author)), link_repository_index: 0 })) });
|
||||||
|
}
|
||||||
|
for (path, hash) in entries {
|
||||||
|
let below = if prefix.is_empty() { Some(path.as_str()) } else { path.strip_prefix(&format!("{prefix}/")) };
|
||||||
|
let Some(below) = below else { continue };
|
||||||
|
if depth > 0 && below.split('/').count() > depth {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push(thin::RevisionTreeResponse {
|
||||||
|
payload: Some(Payload::Node(thin::TreeNode {
|
||||||
|
path,
|
||||||
|
node_type: if hash.is_some() { thin::NodeType::File } else { thin::NodeType::Directory } as i32,
|
||||||
|
address: hash.map(address),
|
||||||
|
size: hash.and_then(blob).map_or(0, |b| b.len() as u64),
|
||||||
|
last_revision_index: if query.include_last_revision { 1 } else { 0 },
|
||||||
|
..Default::default()
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if out.len() <= 2 && !prefix.is_empty() && !rev.files.iter().any(|(p, _)| p.starts_with(&format!("{prefix}/"))) {
|
||||||
|
return Err(Status::failed_precondition("no such path"));
|
||||||
|
}
|
||||||
|
Ok(Response::new(stream(out)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts the fake on two local ports, returning the gRPC and HTTP base URLs.
|
||||||
|
pub async fn start(author: &str) -> (String, String) {
|
||||||
|
use axum::extract::Path;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
|
||||||
|
let fake = FakeLore { author: author.to_owned() };
|
||||||
|
let grpc = tonic::service::Routes::new(revision::revision_service_server::RevisionServiceServer::new(fake.clone()))
|
||||||
|
.add_service(repository::repository_service_server::RepositoryServiceServer::new(fake.clone()))
|
||||||
|
.add_service(thin::thin_client_service_server::ThinClientServiceServer::new(fake))
|
||||||
|
.into_axum_router();
|
||||||
|
let content = axum::Router::new().route(
|
||||||
|
"/v1/repository/{repo}/content/{address}",
|
||||||
|
axum::routing::get(|Path((repo, address)): Path<(String, String)>, headers: HeaderMap| async move {
|
||||||
|
let bearer = headers.get("authorization").and_then(|v| v.to_str().ok()).is_some_and(|v| v.starts_with("Bearer ey"));
|
||||||
|
if !bearer {
|
||||||
|
return StatusCode::UNAUTHORIZED.into_response();
|
||||||
|
}
|
||||||
|
if repo != forge_lore::reader::hex(&REPO) {
|
||||||
|
return StatusCode::FORBIDDEN.into_response();
|
||||||
|
}
|
||||||
|
let hash = forge_lore::reader::unhex(address.split('-').next().unwrap_or_default()).and_then(|h| h.first().copied());
|
||||||
|
match hash.and_then(blob) {
|
||||||
|
Some(bytes) => bytes.to_vec().into_response(),
|
||||||
|
None => StatusCode::NOT_FOUND.into_response(),
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let serve = |router: axum::Router| async move {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||||
|
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
|
||||||
|
url
|
||||||
|
};
|
||||||
|
(serve(grpc).await, serve(content).await)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,105 @@
|
||||||
|
//! HTTP handlers for the issuer's endpoints. The logic lives in `forge_id::issuer`.
|
||||||
|
|
||||||
|
use axum::Json;
|
||||||
|
use axum::body::Bytes;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::http::HeaderValue;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::http::header;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_id::issuer::Form;
|
||||||
|
use forge_id::issuer::OAuthError;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
/// A JSON answer that must not be cached (RFC 6749 section 5.1).
|
||||||
|
fn no_store(status: StatusCode, body: serde_json::Value) -> Response {
|
||||||
|
let mut response = (status, Json(body)).into_response();
|
||||||
|
let headers = response.headers_mut();
|
||||||
|
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||||
|
headers.insert(header::PRAGMA, HeaderValue::from_static("no-cache"));
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
fn oauth_error(error: OAuthError) -> Response {
|
||||||
|
let status = StatusCode::from_u16(error.status).unwrap_or(StatusCode::BAD_REQUEST);
|
||||||
|
no_store(status, error.body())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses a form-encoded body, refusing other content types.
|
||||||
|
fn form(headers: &HeaderMap, body: &Bytes) -> Result<Form, OAuthError> {
|
||||||
|
let content_type = headers
|
||||||
|
.get(header::CONTENT_TYPE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.unwrap_or("");
|
||||||
|
let essence = content_type.split(';').next().unwrap_or("").trim();
|
||||||
|
if !essence.eq_ignore_ascii_case("application/x-www-form-urlencoded") {
|
||||||
|
return Err(OAuthError::described(
|
||||||
|
"invalid_request",
|
||||||
|
"the body must be application/x-www-form-urlencoded",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(Form::parse(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn discovery(State(state): State<AppState>) -> Response {
|
||||||
|
let mut response = Json(state.issuer().discovery()).into_response();
|
||||||
|
response
|
||||||
|
.headers_mut()
|
||||||
|
.insert(header::CACHE_CONTROL, HeaderValue::from_static("public, max-age=300"));
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn jwks(State(state): State<AppState>) -> Response {
|
||||||
|
let mut response = Json(state.issuer().keys().jwks()).into_response();
|
||||||
|
// Short, so a rotated key reaches verifiers quickly.
|
||||||
|
response
|
||||||
|
.headers_mut()
|
||||||
|
.insert(header::CACHE_CONTROL, HeaderValue::from_static("public, max-age=60"));
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn device_authorization(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
body: Bytes,
|
||||||
|
) -> Response {
|
||||||
|
let result = async {
|
||||||
|
let form = form(&headers, &body)?;
|
||||||
|
let user_agent = headers
|
||||||
|
.get(header::USER_AGENT)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.unwrap_or("an unidentified client");
|
||||||
|
state
|
||||||
|
.issuer()
|
||||||
|
.device_authorize(form.get("client_id")?, form.get("scope")?, user_agent)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
match result {
|
||||||
|
Ok(authorization) => no_store(
|
||||||
|
StatusCode::OK,
|
||||||
|
serde_json::to_value(authorization).expect("device authorization serialises"),
|
||||||
|
),
|
||||||
|
Err(error) => oauth_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn token(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
|
||||||
|
let authorization = headers.get(header::AUTHORIZATION).and_then(|value| value.to_str().ok());
|
||||||
|
let result = async { state.issuer().token(&form(&headers, &body)?, authorization).await }.await;
|
||||||
|
match result {
|
||||||
|
Ok(tokens) => no_store(StatusCode::OK, tokens),
|
||||||
|
Err(error) => oauth_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn revoke(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
|
||||||
|
let result = async { state.issuer().revoke(&form(&headers, &body)?).await }.await;
|
||||||
|
match result {
|
||||||
|
Ok(()) => no_store(StatusCode::OK, serde_json::json!({})),
|
||||||
|
Err(error) => oauth_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,184 @@
|
||||||
|
//! lore-forge's HTTP server: the issuer's endpoints, the server-rendered UI and the JSON API.
|
||||||
|
//!
|
||||||
|
//! Security rules from `.ai/designs/web-ui.md` apply throughout: no inline script or style,
|
||||||
|
//! a strict content security policy, server-side sessions, CSRF protection on every unsafe
|
||||||
|
//! method, and URLs derived from the configured canonical URL, never from request headers.
|
||||||
|
|
||||||
|
// Handlers return a ready page as their error, which is how axum is meant to be used.
|
||||||
|
#![allow(clippy::result_large_err)]
|
||||||
|
|
||||||
|
mod api;
|
||||||
|
mod issuer_routes;
|
||||||
|
mod limiter;
|
||||||
|
mod pages;
|
||||||
|
mod security;
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Router;
|
||||||
|
use axum::extract::DefaultBodyLimit;
|
||||||
|
use axum::routing::get;
|
||||||
|
use axum::routing::post;
|
||||||
|
use forge_id::Issuer;
|
||||||
|
use forge_id::oauth::OAuth;
|
||||||
|
use forge_store::SqlitePool;
|
||||||
|
|
||||||
|
/// Shared state for every handler.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AppState {
|
||||||
|
inner: Arc<Inner>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Inner {
|
||||||
|
pool: SqlitePool,
|
||||||
|
issuer: Arc<Issuer>,
|
||||||
|
oauth: OAuth,
|
||||||
|
lore: forge_lore::reader::Lore,
|
||||||
|
limiter: limiter::Limiter,
|
||||||
|
/// `scheme://host[:port]` of the canonical URL, for checking `Origin`.
|
||||||
|
public_origin: String,
|
||||||
|
secure_cookies: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub fn new(pool: SqlitePool, issuer: Arc<Issuer>, oauth: OAuth, lore: forge_lore::reader::Lore) -> Self {
|
||||||
|
let public = url::Url::parse(&issuer.config().issuer).expect("issuer URL is a URL");
|
||||||
|
let public_origin = public.origin().ascii_serialization();
|
||||||
|
let secure_cookies = public.scheme() == "https";
|
||||||
|
AppState {
|
||||||
|
inner: Arc::new(Inner { pool, issuer, oauth, lore, limiter: limiter::Limiter::default(), public_origin, secure_cookies }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pool(&self) -> &SqlitePool {
|
||||||
|
&self.inner.pool
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `scheme://host[:port]` of the canonical URL.
|
||||||
|
fn public_origin(&self) -> &str {
|
||||||
|
&self.inner.public_origin
|
||||||
|
}
|
||||||
|
|
||||||
|
fn issuer(&self) -> &Issuer {
|
||||||
|
&self.inner.issuer
|
||||||
|
}
|
||||||
|
|
||||||
|
fn oauth(&self) -> &OAuth {
|
||||||
|
&self.inner.oauth
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lore(&self) -> &forge_lore::reader::Lore {
|
||||||
|
&self.inner.lore
|
||||||
|
}
|
||||||
|
|
||||||
|
fn limiter(&self) -> &limiter::Limiter {
|
||||||
|
&self.inner.limiter
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The routes this crate serves: the issuer's endpoints, the UI and the API.
|
||||||
|
pub fn router(state: AppState) -> Router {
|
||||||
|
use forge_id::issuer::paths;
|
||||||
|
use pages::admin;
|
||||||
|
use pages::auth;
|
||||||
|
use pages::browse;
|
||||||
|
use pages::orgs;
|
||||||
|
use pages::repos;
|
||||||
|
use pages::service_accounts as sa;
|
||||||
|
use pages::settings;
|
||||||
|
|
||||||
|
let issuer = Router::new()
|
||||||
|
.route(paths::DISCOVERY, get(issuer_routes::discovery))
|
||||||
|
.route(paths::JWKS, get(issuer_routes::jwks))
|
||||||
|
.route(paths::DEVICE_AUTHORIZATION, post(issuer_routes::device_authorization))
|
||||||
|
.route(paths::TOKEN, post(issuer_routes::token))
|
||||||
|
.route(paths::REVOCATION, post(issuer_routes::revoke));
|
||||||
|
|
||||||
|
let api = Router::new()
|
||||||
|
.route("/api/v1/user", get(api::user))
|
||||||
|
.route("/api/v1/repos", get(api::repos))
|
||||||
|
.route("/api/{*rest}", get(api::not_found).post(api::not_found));
|
||||||
|
|
||||||
|
let ui = Router::new()
|
||||||
|
.route("/", get(pages::home::home))
|
||||||
|
.route("/static/app.css", get(pages::stylesheet))
|
||||||
|
.route("/static/vga-8x16.ttf", get(pages::font))
|
||||||
|
.route("/licenses", get(pages::licences))
|
||||||
|
// Getting in.
|
||||||
|
.route("/setup", get(auth::setup_form).post(auth::setup))
|
||||||
|
.route("/login", get(auth::login_form).post(auth::login))
|
||||||
|
.route("/logout", post(auth::logout))
|
||||||
|
.route("/signup", get(auth::signup_form).post(auth::signup))
|
||||||
|
.route("/signup/{key}", get(auth::signup_invite_form).post(auth::signup_invite))
|
||||||
|
.route("/oauth/{provider}/start", get(auth::oauth_start_get).post(auth::oauth_start))
|
||||||
|
.route("/oauth/{provider}/callback", get(auth::oauth_callback))
|
||||||
|
.route(paths::DEVICE_VERIFICATION, get(auth::device_form).post(auth::device_decide))
|
||||||
|
// Settings.
|
||||||
|
.route("/settings", get(settings::profile).post(settings::save_profile))
|
||||||
|
.route("/settings/password", post(settings::change_password))
|
||||||
|
.route("/settings/sessions", get(settings::sessions_page))
|
||||||
|
.route("/settings/sessions/revoke-others", post(settings::revoke_other_sessions))
|
||||||
|
.route("/settings/sessions/{id}/revoke", post(settings::revoke_session))
|
||||||
|
.route("/settings/logins/{id}/revoke", post(settings::revoke_login))
|
||||||
|
.route("/settings/providers", get(settings::providers))
|
||||||
|
.route("/settings/providers/{provider}/link", post(settings::link_provider))
|
||||||
|
.route("/settings/providers/{provider}/unlink", post(settings::unlink_provider))
|
||||||
|
.route("/settings/tokens", get(settings::tokens).post(settings::create_token))
|
||||||
|
.route("/settings/tokens/{id}/revoke", post(settings::revoke_token))
|
||||||
|
.route("/settings/service-accounts", get(sa::personal_list).post(sa::personal_create))
|
||||||
|
.route("/settings/service-accounts/{id}", get(sa::personal_show))
|
||||||
|
.route("/settings/service-accounts/{id}/tokens", post(sa::personal_secret))
|
||||||
|
.route("/settings/service-accounts/{id}/tokens/{token}/revoke", post(sa::personal_revoke))
|
||||||
|
.route("/settings/service-accounts/{id}/delete", post(sa::personal_delete))
|
||||||
|
// Admin.
|
||||||
|
.route("/admin", get(admin::users))
|
||||||
|
.route("/admin/users", post(admin::create_user))
|
||||||
|
.route("/admin/users/{id}", post(admin::user_action))
|
||||||
|
.route("/admin/invites", get(admin::invites).post(admin::create_invite))
|
||||||
|
.route("/admin/invites/{id}", post(admin::invite_action))
|
||||||
|
.route("/admin/repos", get(admin::repos))
|
||||||
|
.route("/admin/audit", get(admin::audit))
|
||||||
|
.route("/admin/settings", get(admin::instance).post(admin::save_instance))
|
||||||
|
.route("/admin/keys/rotate", post(admin::rotate_key))
|
||||||
|
.route("/admin/providers", get(admin::providers))
|
||||||
|
.route("/admin/providers/{provider}", post(admin::save_provider))
|
||||||
|
// Organisations.
|
||||||
|
.route("/orgs", get(orgs::list).post(orgs::create))
|
||||||
|
.route("/orgs/{org}", get(orgs::org_root))
|
||||||
|
.route("/orgs/{org}/members", get(orgs::members).post(orgs::add_member))
|
||||||
|
.route("/orgs/{org}/members/{user}", post(orgs::member_action))
|
||||||
|
.route("/orgs/{org}/teams", get(orgs::teams).post(orgs::create_team))
|
||||||
|
.route("/orgs/{org}/teams/{team}", get(orgs::team))
|
||||||
|
.route("/orgs/{org}/teams/{team}/members", post(orgs::add_team_member))
|
||||||
|
.route("/orgs/{org}/teams/{team}/members/{user}/remove", post(orgs::remove_team_member))
|
||||||
|
.route("/orgs/{org}/teams/{team}/delete", post(orgs::delete_team))
|
||||||
|
.route("/orgs/{org}/settings", get(orgs::settings).post(orgs::save_settings))
|
||||||
|
.route("/orgs/{org}/service-accounts", get(sa::org_list).post(sa::org_create))
|
||||||
|
.route("/orgs/{org}/service-accounts/{id}", get(sa::org_show))
|
||||||
|
.route("/orgs/{org}/service-accounts/{id}/tokens", post(sa::org_secret))
|
||||||
|
.route("/orgs/{org}/service-accounts/{id}/tokens/{token}/revoke", post(sa::org_revoke))
|
||||||
|
.route("/orgs/{org}/service-accounts/{id}/delete", post(sa::org_delete))
|
||||||
|
// Owners and repositories occupy the rest of the top level; reserved names keep them
|
||||||
|
// clear of the routes above.
|
||||||
|
.route("/{owner}", get(orgs::owner))
|
||||||
|
.route("/{owner}/{repo}", get(browse::files))
|
||||||
|
.route("/{owner}/{repo}/graph", get(browse::graph_page))
|
||||||
|
.route("/{owner}/{repo}/tree", get(browse::tree_page))
|
||||||
|
.route("/{owner}/{repo}/revision/{signature}", get(browse::revision_page))
|
||||||
|
.route("/{owner}/{repo}/access", get(repos::access).post(repos::set_access))
|
||||||
|
.layer(axum::middleware::from_fn_with_state(state.clone(), security::csrf_cookie));
|
||||||
|
|
||||||
|
Router::new()
|
||||||
|
.merge(issuer)
|
||||||
|
.merge(api)
|
||||||
|
.merge(ui)
|
||||||
|
.fallback(pages::not_found)
|
||||||
|
.layer(axum::middleware::from_fn(security::headers))
|
||||||
|
.layer(DefaultBodyLimit::max(64 * 1024))
|
||||||
|
.with_state(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod fake_lore;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
|
@ -0,0 +1,62 @@
|
||||||
|
//! Sign-in rate limiting: after too many failed passwords for one username, further attempts
|
||||||
|
//! are refused for a while, whatever the password. Kept in memory; a restart clears it.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
const WINDOW_SECS: i64 = 15 * 60;
|
||||||
|
const MAX_FAILURES: usize = 10;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Limiter {
|
||||||
|
failures: Mutex<HashMap<String, Vec<i64>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Limiter {
|
||||||
|
fn key(username: &str) -> String {
|
||||||
|
username.trim().to_ascii_lowercase()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seconds until `username` may try again, or `None` when it may now.
|
||||||
|
pub fn blocked(&self, username: &str) -> Option<i64> {
|
||||||
|
let now = forge_store::now();
|
||||||
|
let mut failures = self.failures.lock().expect("limiter lock");
|
||||||
|
let times = failures.get_mut(&Self::key(username))?;
|
||||||
|
times.retain(|at| now - at < WINDOW_SECS);
|
||||||
|
(times.len() >= MAX_FAILURES).then(|| WINDOW_SECS - (now - times[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn failed(&self, username: &str) {
|
||||||
|
let now = forge_store::now();
|
||||||
|
let mut failures = self.failures.lock().expect("limiter lock");
|
||||||
|
// Forget usernames whose failures have all aged out, so the map cannot grow forever.
|
||||||
|
if failures.len() > 10_000 {
|
||||||
|
failures.retain(|_, times| times.iter().any(|at| now - at < WINDOW_SECS));
|
||||||
|
}
|
||||||
|
let times = failures.entry(Self::key(username)).or_default();
|
||||||
|
times.push(now);
|
||||||
|
if times.len() > MAX_FAILURES {
|
||||||
|
times.remove(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn succeeded(&self, username: &str) {
|
||||||
|
self.failures.lock().expect("limiter lock").remove(&Self::key(username));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#[test]
|
||||||
|
fn blocks_after_repeated_failures() {
|
||||||
|
let limiter = super::Limiter::default();
|
||||||
|
for _ in 0..super::MAX_FAILURES {
|
||||||
|
assert!(limiter.blocked("Alice").is_none());
|
||||||
|
limiter.failed("alice");
|
||||||
|
}
|
||||||
|
assert!(limiter.blocked("ALICE").is_some());
|
||||||
|
assert!(limiter.blocked("bob").is_none());
|
||||||
|
limiter.succeeded("alice");
|
||||||
|
assert!(limiter.blocked("alice").is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,535 @@
|
||||||
|
//! Instance administration: users, invites, repositories and the audit log for admins;
|
||||||
|
//! instance settings and sign-in providers for the owner.
|
||||||
|
|
||||||
|
use axum::Form;
|
||||||
|
use axum::extract::Path;
|
||||||
|
use axum::extract::Query;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_id::instance;
|
||||||
|
use forge_id::instance::OrgCreation;
|
||||||
|
use forge_id::instance::SignupMode;
|
||||||
|
use forge_id::invites;
|
||||||
|
use forge_id::oauth::Provider;
|
||||||
|
use forge_id::users;
|
||||||
|
use forge_id::users::AccountError;
|
||||||
|
use forge_id::users::CreateUserError;
|
||||||
|
use forge_id::users::InstanceRole;
|
||||||
|
use forge_id::users::NewUser;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
use maud::Markup;
|
||||||
|
use maud::html;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::Done;
|
||||||
|
use super::Nav;
|
||||||
|
use super::Notice;
|
||||||
|
use super::Viewer;
|
||||||
|
use super::ago;
|
||||||
|
use super::csrf;
|
||||||
|
use super::date;
|
||||||
|
use super::done;
|
||||||
|
use super::forbidden_page;
|
||||||
|
use super::page;
|
||||||
|
use super::server_error;
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Section {
|
||||||
|
Users,
|
||||||
|
Invites,
|
||||||
|
Repos,
|
||||||
|
Audit,
|
||||||
|
Instance,
|
||||||
|
Providers,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layout(viewer: &Viewer, section: Section, title: &str, notice: Notice, body: Markup) -> Response {
|
||||||
|
let item = |s: Section, href: &str, label: &str| {
|
||||||
|
html! { a href=(href) class=[(s == section).then_some("on")] { (label) } }
|
||||||
|
};
|
||||||
|
page(notice.status(), title, viewer.chrome(Nav::Admin), html! {
|
||||||
|
h1 { "Admin" }
|
||||||
|
div.split {
|
||||||
|
nav.side {
|
||||||
|
div.label { "Instance" }
|
||||||
|
(item(Section::Users, "/admin", "Users"))
|
||||||
|
(item(Section::Invites, "/admin/invites", "Invites"))
|
||||||
|
(item(Section::Repos, "/admin/repos", "Repositories"))
|
||||||
|
(item(Section::Audit, "/admin/audit", "Audit log"))
|
||||||
|
@if viewer.is_owner() {
|
||||||
|
div.label { "Owner" }
|
||||||
|
(item(Section::Instance, "/admin/settings", "Settings"))
|
||||||
|
(item(Section::Providers, "/admin/providers", "Sign-in providers"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div { (notice.render()) (body) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_admin(viewer: &Viewer) -> Result<(), Response> {
|
||||||
|
if viewer.is_admin() { Ok(()) } else { Err(forbidden_page(viewer, "Only instance admins can see this.")) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_owner(viewer: &Viewer) -> Result<(), Response> {
|
||||||
|
if viewer.is_owner() { Ok(()) } else { Err(forbidden_page(viewer, "Only the instance owner can see this.")) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn role_tag(role: InstanceRole) -> Markup {
|
||||||
|
let class = match role {
|
||||||
|
InstanceRole::Owner => "forge",
|
||||||
|
InstanceRole::Admin => "spark",
|
||||||
|
InstanceRole::Member => "dim",
|
||||||
|
};
|
||||||
|
html! { span class={ "tag " (class) } { (role.as_str()) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Users -------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async fn users_page(state: &AppState, viewer: &Viewer, notice: Notice) -> Response {
|
||||||
|
let list = match users::list(state.pool()).await {
|
||||||
|
Ok(list) => list,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
layout(viewer, Section::Users, "Users", notice, html! {
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Username" } th { "Name" } th { "Role" } th { "State" } th {} } }
|
||||||
|
tbody {
|
||||||
|
@for user in &list {
|
||||||
|
tr {
|
||||||
|
td { a href={ "/" (user.username) } { (user.username) } }
|
||||||
|
td { (user.display_name) }
|
||||||
|
td { (role_tag(user.role)) }
|
||||||
|
td { @if user.disabled { span.tag.red { "disabled" } } @else { span.tag.green { "active" } } }
|
||||||
|
td.act {
|
||||||
|
@if user.id != viewer.id() && (viewer.is_owner() || user.role != InstanceRole::Owner) {
|
||||||
|
form method="post" action={ "/admin/users/" (user.id) } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
select name="role" {
|
||||||
|
@for role in [InstanceRole::Member, InstanceRole::Admin, InstanceRole::Owner] {
|
||||||
|
@if viewer.is_owner() || role != InstanceRole::Owner {
|
||||||
|
option value=(role.as_str()) selected[role == user.role] { (role.as_str()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
" "
|
||||||
|
button.small type="submit" name="action" value="role" { "Set" }
|
||||||
|
" "
|
||||||
|
@if user.disabled {
|
||||||
|
button.small type="submit" name="action" value="enable" { "Enable" }
|
||||||
|
} @else {
|
||||||
|
button.small.danger type="submit" name="action" value="disable" { "Disable" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(super::panel("New user", html! {
|
||||||
|
form.row method="post" action="/admin/users" {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Username" input name="username" required maxlength="39"; }
|
||||||
|
label { "Display name" input name="display_name" required maxlength="100"; }
|
||||||
|
label { "Password" input type="password" name="password" required minlength=(forge_id::password::MIN_LENGTH) autocomplete="new-password"; }
|
||||||
|
button.primary type="submit" { "Create" }
|
||||||
|
}
|
||||||
|
p.muted { "Or send an invite link: Invites." }
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn users(State(state): State<AppState>, viewer: Viewer, Query(d): Query<Done>) -> Response {
|
||||||
|
if let Err(refused) = require_admin(&viewer) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
users_page(&state, &viewer, d.notice()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct NewUserForm {
|
||||||
|
csrf: String,
|
||||||
|
username: String,
|
||||||
|
display_name: String,
|
||||||
|
password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_user(State(state): State<AppState>, viewer: Viewer, headers: HeaderMap, Form(form): Form<NewUserForm>) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf).and_then(|()| require_admin(&viewer)) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let created = users::create(state.pool(), NewUser {
|
||||||
|
username: form.username.trim(),
|
||||||
|
display_name: &form.display_name,
|
||||||
|
password: Some(&form.password),
|
||||||
|
role: InstanceRole::Member,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match created {
|
||||||
|
Ok(_) => done("/admin", "created"),
|
||||||
|
Err(CreateUserError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => users_page(&state, &viewer, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct UserActionForm {
|
||||||
|
csrf: String,
|
||||||
|
action: String,
|
||||||
|
#[serde(default)]
|
||||||
|
role: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn user_action(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<UserActionForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf).and_then(|()| require_admin(&viewer)) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let target = match users::get(state.pool(), &id).await {
|
||||||
|
Ok(Some(user)) if !user.service => user,
|
||||||
|
Ok(_) => return super::not_found_page(Some(&viewer)),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
// Admins manage members and admins; only the owner touches owners or makes new ones.
|
||||||
|
let role = InstanceRole::parse(&form.role);
|
||||||
|
if !viewer.is_owner() && (target.role == InstanceRole::Owner || (form.action == "role" && role == InstanceRole::Owner)) {
|
||||||
|
return forbidden_page(&viewer, "Only the instance owner can change owners.");
|
||||||
|
}
|
||||||
|
if target.id == viewer.id() {
|
||||||
|
return users_page(&state, &viewer, Notice::err("Use another admin account to change your own.")).await;
|
||||||
|
}
|
||||||
|
let pool = state.pool();
|
||||||
|
let result = match form.action.as_str() {
|
||||||
|
"role" => users::set_role(pool, &target.id, role, viewer.id()).await,
|
||||||
|
"disable" => users::set_disabled(pool, &target.id, true, viewer.id()).await,
|
||||||
|
"enable" => users::set_disabled(pool, &target.id, false, viewer.id()).await,
|
||||||
|
_ => return users_page(&state, &viewer, Notice::err("Unknown action.")).await,
|
||||||
|
};
|
||||||
|
match result {
|
||||||
|
Ok(()) => done("/admin", "saved"),
|
||||||
|
Err(AccountError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => users_page(&state, &viewer, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invites -----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async fn invites_page(state: &AppState, viewer: &Viewer, notice: Notice) -> Response {
|
||||||
|
let (list, mode) = match tokio::try_join!(invites::list(state.pool()), instance::signup_mode(state.pool())) {
|
||||||
|
Ok(found) => found,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
layout(viewer, Section::Invites, "Invites", notice, html! {
|
||||||
|
@if mode == SignupMode::Closed {
|
||||||
|
p.notice.info { "Signup is closed, so invite links do not work. The owner can change this in Settings." }
|
||||||
|
}
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Name" } th.num { "Used" } th { "Link" } th { "Created" } th {} } }
|
||||||
|
tbody {
|
||||||
|
@for invite in &list {
|
||||||
|
tr {
|
||||||
|
td { (invite.name) " " @if !invite.active { span.tag.red { "off" } } @else if !invite.usable() { span.tag.dim { "used up" } } }
|
||||||
|
td.num { (invite.uses) "/" (invite.max_uses) }
|
||||||
|
td { @if invite.usable() { code { (state.issuer().config().url(&format!("/signup/{}", invite.invite_key))) } } }
|
||||||
|
td.muted { (date(invite.created_at)) }
|
||||||
|
td.act {
|
||||||
|
form method="post" action={ "/admin/invites/" (invite.id) } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
@if invite.active {
|
||||||
|
button.small.danger type="submit" name="active" value="0" { "Disable" }
|
||||||
|
} @else {
|
||||||
|
button.small type="submit" name="active" value="1" { "Enable" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if list.is_empty() { tr.empty { td colspan="5" { "No invites." } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
form.row method="post" action="/admin/invites" {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Name" input name="name" required maxlength="100" placeholder="art team"; }
|
||||||
|
label { "Uses" input type="number" name="max_uses" required min="1" max="10000" value="1"; }
|
||||||
|
button.primary type="submit" { "Create invite" }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn invites(State(state): State<AppState>, viewer: Viewer, Query(d): Query<Done>) -> Response {
|
||||||
|
if let Err(refused) = require_admin(&viewer) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
invites_page(&state, &viewer, d.notice()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct InviteForm {
|
||||||
|
csrf: String,
|
||||||
|
name: String,
|
||||||
|
max_uses: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_invite(State(state): State<AppState>, viewer: Viewer, headers: HeaderMap, Form(form): Form<InviteForm>) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf).and_then(|()| require_admin(&viewer)) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
match invites::create(state.pool(), &form.name, form.max_uses, viewer.id()).await {
|
||||||
|
Ok(_) => done("/admin/invites", "created"),
|
||||||
|
Err(invites::InviteError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => invites_page(&state, &viewer, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct InviteActionForm {
|
||||||
|
csrf: String,
|
||||||
|
active: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn invite_action(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<InviteActionForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf).and_then(|()| require_admin(&viewer)) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
match invites::set_active(state.pool(), &id, form.active == "1", viewer.id()).await {
|
||||||
|
Ok(()) => done("/admin/invites", "saved"),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Repositories and audit log ----------------------------------------------------------------
|
||||||
|
|
||||||
|
pub async fn repos(State(state): State<AppState>, viewer: Viewer) -> Response {
|
||||||
|
if let Err(refused) = require_admin(&viewer) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let list = match forge_access::repos::list_all(state.pool()).await {
|
||||||
|
Ok(list) => list,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
layout(&viewer, Section::Repos, "Repositories", Notice::None, html! {
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Repository" } th { "Lore ID" } } }
|
||||||
|
tbody {
|
||||||
|
@for repo in &list {
|
||||||
|
tr { td { (repo.full_name()) } td.muted { (repo.id) } }
|
||||||
|
}
|
||||||
|
@if list.is_empty() { tr.empty { td colspan="2" { "No repositories." } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.muted { "Repositories are created and deleted through Lore, which asks lore-forge first." }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An audit entry: when, who, action, target, detail.
|
||||||
|
type AuditRow = (i64, Option<String>, String, String, String);
|
||||||
|
|
||||||
|
pub async fn audit(State(state): State<AppState>, viewer: Viewer) -> Response {
|
||||||
|
if let Err(refused) = require_admin(&viewer) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let rows: Vec<AuditRow> = match sqlx::query_as(
|
||||||
|
"SELECT a.at, coalesce(u.username, a.actor_id) AS actor, a.action, a.target, a.detail
|
||||||
|
FROM audit_log a LEFT JOIN users u ON u.id = a.actor_id
|
||||||
|
ORDER BY a.id DESC LIMIT 200",
|
||||||
|
)
|
||||||
|
.fetch_all(state.pool())
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(rows) => rows,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
layout(&viewer, Section::Audit, "Audit log", Notice::None, html! {
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "When" } th { "Who" } th { "Action" } th { "Target" } th { "Detail" } } }
|
||||||
|
tbody {
|
||||||
|
@for (at, actor, action, target, detail) in &rows {
|
||||||
|
tr {
|
||||||
|
td.muted title=(date(*at)) { (ago(*at)) }
|
||||||
|
td { (actor.as_deref().unwrap_or("-")) }
|
||||||
|
td { span.tag.dim { (action) } }
|
||||||
|
td { (target) }
|
||||||
|
td.muted { (detail) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.muted { "The latest 200 entries." }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Instance settings (owner) -----------------------------------------------------------------
|
||||||
|
|
||||||
|
async fn instance_page(state: &AppState, viewer: &Viewer, notice: Notice) -> Response {
|
||||||
|
let (signup, orgs, key) = match tokio::try_join!(
|
||||||
|
instance::signup_mode(state.pool()),
|
||||||
|
instance::org_creation(state.pool()),
|
||||||
|
state.issuer().keys().current(),
|
||||||
|
) {
|
||||||
|
Ok(found) => found,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
layout(viewer, Section::Instance, "Settings", notice, html! {
|
||||||
|
form.stack method="post" action="/admin/settings" {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
fieldset {
|
||||||
|
legend { "Signup" }
|
||||||
|
@for (mode, text) in [
|
||||||
|
(SignupMode::Closed, "Closed: admins create accounts"),
|
||||||
|
(SignupMode::Invite, "Invite links only"),
|
||||||
|
(SignupMode::Open, "Open to anyone who can reach this site"),
|
||||||
|
] {
|
||||||
|
label.check { input type="radio" name="signup" value=(mode.as_str()) checked[mode == signup]; (text) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fieldset {
|
||||||
|
legend { "Who may create organisations" }
|
||||||
|
@for (policy, text) in [(OrgCreation::Admins, "Instance admins"), (OrgCreation::Everyone, "Everyone")] {
|
||||||
|
label.check { input type="radio" name="orgs" value=(policy.as_str()) checked[policy == orgs]; (text) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
button.primary type="submit" { "Save" }
|
||||||
|
}
|
||||||
|
h2 { "Addresses" }
|
||||||
|
dl.kv {
|
||||||
|
dt { "Public URL" } dd { (state.issuer().config().issuer) }
|
||||||
|
dt { "Lore server" } dd { (state.issuer().config().lore_url) }
|
||||||
|
}
|
||||||
|
p.muted { "Set with LORE_FORGE_PUBLIC_URL and LORE_FORGE_LORE_URL." }
|
||||||
|
h2 { "Token signing key" }
|
||||||
|
@if let Some((kid, created)) = &key {
|
||||||
|
dl.kv { dt { "Current" } dd { code { (kid) } } dt { "Since" } dd { (date(*created)) } }
|
||||||
|
}
|
||||||
|
form method="post" action="/admin/keys/rotate" {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
button.danger type="submit" { "Rotate key" }
|
||||||
|
}
|
||||||
|
p.muted { "The previous key keeps verifying, so tokens signed just before stay valid. Rotating twice in a row ends tokens signed with the oldest key." }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn instance(State(state): State<AppState>, viewer: Viewer, Query(d): Query<Done>) -> Response {
|
||||||
|
if let Err(refused) = require_owner(&viewer) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
instance_page(&state, &viewer, d.notice()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct InstanceForm {
|
||||||
|
csrf: String,
|
||||||
|
signup: String,
|
||||||
|
orgs: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn save_instance(State(state): State<AppState>, viewer: Viewer, headers: HeaderMap, Form(form): Form<InstanceForm>) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf).and_then(|()| require_owner(&viewer)) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let (Some(signup), Some(orgs)) = (SignupMode::parse(&form.signup), OrgCreation::parse(&form.orgs)) else {
|
||||||
|
return instance_page(&state, &viewer, Notice::err("Choose a setting for each.")).await;
|
||||||
|
};
|
||||||
|
match instance::set(state.pool(), signup, orgs, viewer.id()).await {
|
||||||
|
Ok(()) => done("/admin/settings", "saved"),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn rotate_key(State(state): State<AppState>, viewer: Viewer, headers: HeaderMap, Form(form): Form<super::auth::CsrfOnly>) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf).and_then(|()| require_owner(&viewer)) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
match state.issuer().keys().rotate().await {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = forge_store::audit(state.pool(), Some(viewer.id()), "keys.rotate.request", "", "").await;
|
||||||
|
done("/admin/settings", "saved")
|
||||||
|
}
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sign-in providers (owner) -----------------------------------------------------------------
|
||||||
|
|
||||||
|
async fn providers_page(state: &AppState, viewer: &Viewer, notice: Notice) -> Response {
|
||||||
|
let summaries = match state.oauth().summaries().await {
|
||||||
|
Ok(summaries) => summaries,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
layout(viewer, Section::Providers, "Sign-in providers", notice, html! {
|
||||||
|
p.muted { "People link a provider from their own settings; it then signs them in. It never creates accounts." }
|
||||||
|
@for s in &summaries {
|
||||||
|
(super::panel(s.provider.label(), html! {
|
||||||
|
dl.kv {
|
||||||
|
dt { "Callback URL" } dd { code { (super::auth::callback_url(state, s.provider)) } }
|
||||||
|
dt { "Register at" } dd { a href=(s.provider.console_url()) { (s.provider.console_url()) } }
|
||||||
|
dt { "State" } dd {
|
||||||
|
@if s.enabled && s.has_secret && !s.client_id.is_empty() { span.tag.green { "on" } }
|
||||||
|
@else if s.enabled { span.tag.spark { "incomplete" } }
|
||||||
|
@else { span.tag.dim { "off" } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
form.row method="post" action={ "/admin/providers/" (s.provider.as_str()) } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Client ID" input name="client_id" value=(s.client_id) autocomplete="off"; }
|
||||||
|
label { "Client secret"
|
||||||
|
input type="password" name="client_secret" autocomplete="off"
|
||||||
|
placeholder=(if s.has_secret { "unchanged" } else { "" });
|
||||||
|
}
|
||||||
|
label.check { input type="checkbox" name="enabled" value="on" checked[s.enabled]; "Enabled" }
|
||||||
|
button.primary type="submit" { "Save" }
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
p.muted { "Secrets are stored encrypted with LORE_FORGE_SECRET_KEY." }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn providers(State(state): State<AppState>, viewer: Viewer, Query(d): Query<Done>) -> Response {
|
||||||
|
if let Err(refused) = require_owner(&viewer) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
providers_page(&state, &viewer, d.notice()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ProviderForm {
|
||||||
|
csrf: String,
|
||||||
|
client_id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
client_secret: String,
|
||||||
|
#[serde(default)]
|
||||||
|
enabled: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn save_provider(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(provider): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<ProviderForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf).and_then(|()| require_owner(&viewer)) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let Some(provider) = Provider::parse(&provider) else {
|
||||||
|
return super::not_found_page(Some(&viewer));
|
||||||
|
};
|
||||||
|
match state.oauth().save(provider, &form.client_id, &form.client_secret, form.enabled.is_some(), viewer.id()).await {
|
||||||
|
Ok(()) => done("/admin/providers", "saved"),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,611 @@
|
||||||
|
//! Getting in: first-run setup, sign-in by password or provider, signup, sign-out, and the
|
||||||
|
//! device approval page `lore auth login` opens.
|
||||||
|
|
||||||
|
use axum::Extension;
|
||||||
|
use axum::Form;
|
||||||
|
use axum::extract::Path;
|
||||||
|
use axum::extract::Query;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::http::header;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::response::Redirect;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_id::instance;
|
||||||
|
use forge_id::instance::SignupMode;
|
||||||
|
use forge_id::invites;
|
||||||
|
use forge_id::invites::InviteError;
|
||||||
|
use forge_id::oauth::Intent;
|
||||||
|
use forge_id::oauth::Provider;
|
||||||
|
use forge_id::sessions;
|
||||||
|
use forge_id::sessions::AuthMethod;
|
||||||
|
use forge_id::users;
|
||||||
|
use forge_id::users::CreateUserError;
|
||||||
|
use forge_id::users::InstanceRole;
|
||||||
|
use forge_id::users::NewUser;
|
||||||
|
use forge_id::users::User;
|
||||||
|
use forge_store::sqlx;
|
||||||
|
use maud::Markup;
|
||||||
|
use maud::html;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::Notice;
|
||||||
|
use super::Viewer;
|
||||||
|
use super::ago;
|
||||||
|
use super::csrf;
|
||||||
|
use super::csrf_field;
|
||||||
|
use super::local_path;
|
||||||
|
use super::login_redirect;
|
||||||
|
use super::narrow;
|
||||||
|
use super::panel;
|
||||||
|
use super::public;
|
||||||
|
use super::server_error;
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::security::CsrfToken;
|
||||||
|
use crate::security::MaybeSession;
|
||||||
|
use crate::security::session_cookie_name;
|
||||||
|
use crate::security::set_cookie;
|
||||||
|
|
||||||
|
/// The settings key that marks first-run setup as done. Its primary key makes concurrent
|
||||||
|
/// setups race safely: only one insert wins.
|
||||||
|
const SETUP_DONE: &str = "setup.completed";
|
||||||
|
|
||||||
|
pub async fn needs_setup(state: &AppState) -> Result<bool, sqlx::Error> {
|
||||||
|
Ok(users::count(state.pool()).await? == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn user_agent(headers: &HeaderMap) -> &str {
|
||||||
|
headers.get(header::USER_AGENT).and_then(|v| v.to_str().ok()).unwrap_or("")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a session for `user` and answers a redirect to `next` that sets its cookie.
|
||||||
|
async fn sign_in(
|
||||||
|
state: &AppState,
|
||||||
|
user: &User,
|
||||||
|
method: AuthMethod,
|
||||||
|
headers: &HeaderMap,
|
||||||
|
persistent: bool,
|
||||||
|
next: &str,
|
||||||
|
) -> Response {
|
||||||
|
match sessions::create(state.pool(), user, method, user_agent(headers), persistent).await {
|
||||||
|
Ok(new) => {
|
||||||
|
let mut response = Redirect::to(next).into_response();
|
||||||
|
let max_age = persistent.then_some(sessions::PERSISTENT_IDLE_SECS);
|
||||||
|
response
|
||||||
|
.headers_mut()
|
||||||
|
.append(header::SET_COOKIE, set_cookie(state, &session_cookie_name(state), &new.token, max_age));
|
||||||
|
response
|
||||||
|
}
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn account_fields(username: &str, display_name: &str) -> Markup {
|
||||||
|
html! {
|
||||||
|
label { "Username" input name="username" required autocomplete="username" maxlength="39" value=(username); }
|
||||||
|
label { "Display name" input name="display_name" required maxlength="100" value=(display_name); }
|
||||||
|
label { "Password" input type="password" name="password" required minlength=(forge_id::password::MIN_LENGTH) autocomplete="new-password"; }
|
||||||
|
label { "Confirm password" input type="password" name="password_confirm" required autocomplete="new-password"; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// First-run setup ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct AccountForm {
|
||||||
|
csrf: String,
|
||||||
|
username: String,
|
||||||
|
display_name: String,
|
||||||
|
password: String,
|
||||||
|
password_confirm: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup_page(csrf: &CsrfToken, notice: Notice, username: &str, display_name: &str) -> Response {
|
||||||
|
public(notice.status(), "Set up", csrf, panel("Set up lore-forge", html! {
|
||||||
|
p.muted { "Create the owner account. Available until the first account exists." }
|
||||||
|
(notice.render())
|
||||||
|
form.stack method="post" action="/setup" {
|
||||||
|
(csrf_field(csrf))
|
||||||
|
(account_fields(username, display_name))
|
||||||
|
button.primary type="submit" { "Create owner" }
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn setup_form(State(state): State<AppState>, Extension(csrf): Extension<CsrfToken>) -> Response {
|
||||||
|
match needs_setup(&state).await {
|
||||||
|
Ok(true) => setup_page(&csrf, Notice::None, "", ""),
|
||||||
|
Ok(false) => Redirect::to("/login").into_response(),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn setup(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(csrf_token): Extension<CsrfToken>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<AccountForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
if form.password != form.password_confirm {
|
||||||
|
return setup_page(&csrf_token, Notice::err("The passwords do not match."), &form.username, &form.display_name);
|
||||||
|
}
|
||||||
|
let claimed = sqlx::query("INSERT INTO settings (key, value) VALUES (?, ?)")
|
||||||
|
.bind(SETUP_DONE)
|
||||||
|
.bind(forge_store::now().to_string())
|
||||||
|
.execute(state.pool())
|
||||||
|
.await;
|
||||||
|
match claimed {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(error) if forge_store::is_unique_violation(&error) => return Redirect::to("/login").into_response(),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
}
|
||||||
|
let created = users::create(state.pool(), NewUser {
|
||||||
|
username: form.username.trim(),
|
||||||
|
display_name: &form.display_name,
|
||||||
|
password: Some(&form.password),
|
||||||
|
role: InstanceRole::Owner,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
match created {
|
||||||
|
Ok(user) => sign_in(&state, &user, AuthMethod::Password, &headers, true, "/").await,
|
||||||
|
Err(error) => {
|
||||||
|
// Let setup be retried.
|
||||||
|
let _ = sqlx::query("DELETE FROM settings WHERE key = ?").bind(SETUP_DONE).execute(state.pool()).await;
|
||||||
|
match error {
|
||||||
|
CreateUserError::Database(error) => server_error(error),
|
||||||
|
other => setup_page(&csrf_token, Notice::err(other), &form.username, &form.display_name),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sign-in -----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct NextQuery {
|
||||||
|
next: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct LoginForm {
|
||||||
|
csrf: String,
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
#[serde(default)]
|
||||||
|
stay_signed_in: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
next: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn login_page(state: &AppState, csrf: &CsrfToken, next: &str, notice: Notice, username: &str) -> Response {
|
||||||
|
let status = if matches!(notice, Notice::Err(_)) { StatusCode::UNAUTHORIZED } else { StatusCode::OK };
|
||||||
|
let providers = match state.oauth().enabled().await {
|
||||||
|
Ok(providers) => providers,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let signup = instance::signup_mode(state.pool()).await.unwrap_or(SignupMode::Closed);
|
||||||
|
public(status, "Sign in", csrf, panel("Sign in", html! {
|
||||||
|
(notice.render())
|
||||||
|
form.stack method="post" action="/login" {
|
||||||
|
// Enter in a field submits the first button: make that the password sign-in.
|
||||||
|
button.visually-hidden type="submit" tabindex="-1" aria-hidden="true" { "Sign in" }
|
||||||
|
(csrf_field(csrf))
|
||||||
|
input type="hidden" name="next" value=(next);
|
||||||
|
label { "Username" input name="username" required autocomplete="username" value=(username); }
|
||||||
|
label { "Password" input type="password" name="password" required autocomplete="current-password"; }
|
||||||
|
label.check { input type="checkbox" name="stay_signed_in" value="on" checked; "Stay signed in" }
|
||||||
|
button.primary type="submit" { "Sign in" }
|
||||||
|
@if !providers.is_empty() {
|
||||||
|
div.rule {}
|
||||||
|
div.providers {
|
||||||
|
@for provider in &providers {
|
||||||
|
button class=(provider.as_str()) type="submit" formnovalidate
|
||||||
|
formaction={ "/oauth/" (provider.as_str()) "/start" } {
|
||||||
|
"Sign in with " (provider.label())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if signup == SignupMode::Open {
|
||||||
|
div.rule {}
|
||||||
|
p { "No account? " a href="/signup" { "Sign up" } }
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn login_form(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
MaybeSession(session): MaybeSession,
|
||||||
|
Extension(csrf): Extension<CsrfToken>,
|
||||||
|
Query(query): Query<NextQuery>,
|
||||||
|
) -> Response {
|
||||||
|
match needs_setup(&state).await {
|
||||||
|
Ok(true) => return Redirect::to("/setup").into_response(),
|
||||||
|
Ok(false) => {}
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
}
|
||||||
|
let next = local_path(query.next.as_deref());
|
||||||
|
if session.is_some() {
|
||||||
|
return Redirect::to(next).into_response();
|
||||||
|
}
|
||||||
|
login_page(&state, &csrf, next, Notice::None, "").await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn login(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(csrf_token): Extension<CsrfToken>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<LoginForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let next = local_path(form.next.as_deref()).to_owned();
|
||||||
|
let username = form.username.trim();
|
||||||
|
if let Some(wait) = state.limiter().blocked(username) {
|
||||||
|
let message = format!("Too many failed attempts. Try again in {} minutes.", (wait + 59) / 60);
|
||||||
|
return login_page(&state, &csrf_token, &next, Notice::Err(message), username).await;
|
||||||
|
}
|
||||||
|
let user = match users::authenticate(state.pool(), username, &form.password).await {
|
||||||
|
Ok(Some(user)) => user,
|
||||||
|
Ok(None) => {
|
||||||
|
state.limiter().failed(username);
|
||||||
|
let _ = forge_store::audit(state.pool(), None, "session.failed", username, "password").await;
|
||||||
|
return login_page(&state, &csrf_token, &next, Notice::err("Wrong username or password."), username).await;
|
||||||
|
}
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
state.limiter().succeeded(username);
|
||||||
|
sign_in(&state, &user, AuthMethod::Password, &headers, form.stay_signed_in.is_some(), &next).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct CsrfOnly {
|
||||||
|
pub csrf: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn logout(State(state): State<AppState>, headers: HeaderMap, Form(form): Form<CsrfOnly>) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let name = session_cookie_name(&state);
|
||||||
|
if let Some(token) = crate::security::read_cookie(&headers, &name)
|
||||||
|
&& let Err(error) = sessions::revoke_token(state.pool(), &token).await
|
||||||
|
{
|
||||||
|
return server_error(error);
|
||||||
|
}
|
||||||
|
let mut response = Redirect::to("/login").into_response();
|
||||||
|
response.headers_mut().append(header::SET_COOKIE, set_cookie(&state, &name, "", Some(0)));
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
// Signup ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn signup_page(csrf: &CsrfToken, action: &str, notice: Notice, username: &str, display_name: &str) -> Response {
|
||||||
|
public(notice.status(), "Sign up", csrf, panel("Create an account", html! {
|
||||||
|
(notice.render())
|
||||||
|
form.stack method="post" action=(action) {
|
||||||
|
(csrf_field(csrf))
|
||||||
|
(account_fields(username, display_name))
|
||||||
|
button.primary type="submit" { "Create account" }
|
||||||
|
}
|
||||||
|
div.rule {}
|
||||||
|
p { "Have an account? " a href="/login" { "Sign in" } }
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signup_closed(csrf: &CsrfToken, text: &str) -> Response {
|
||||||
|
public(StatusCode::FORBIDDEN, "Sign up", csrf, panel("Sign up", html! {
|
||||||
|
p { (text) }
|
||||||
|
p { a href="/login" { "Sign in" } }
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the key opens signup: the instance must not be closed, and the key usable.
|
||||||
|
async fn usable_invite(state: &AppState, key: &str) -> Result<bool, sqlx::Error> {
|
||||||
|
if instance::signup_mode(state.pool()).await? == SignupMode::Closed {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
Ok(invites::find(state.pool(), key).await?.is_some_and(|invite| invite.usable()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn signup_form(State(state): State<AppState>, Extension(csrf): Extension<CsrfToken>) -> Response {
|
||||||
|
match instance::signup_mode(state.pool()).await {
|
||||||
|
Ok(SignupMode::Open) => signup_page(&csrf, "/signup", Notice::None, "", ""),
|
||||||
|
Ok(SignupMode::Invite) => signup_closed(&csrf, "Signup needs an invite link. Ask an admin for one."),
|
||||||
|
Ok(SignupMode::Closed) => signup_closed(&csrf, "Signup is closed. Ask an admin for an account."),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn signup_invite_form(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(csrf): Extension<CsrfToken>,
|
||||||
|
Path(key): Path<String>,
|
||||||
|
) -> Response {
|
||||||
|
match usable_invite(&state, &key).await {
|
||||||
|
Ok(true) => signup_page(&csrf, &format!("/signup/{key}"), Notice::None, "", ""),
|
||||||
|
Ok(false) => signup_closed(&csrf, "This invite is not valid any more."),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_account(
|
||||||
|
state: &AppState,
|
||||||
|
csrf_token: &CsrfToken,
|
||||||
|
headers: &HeaderMap,
|
||||||
|
form: AccountForm,
|
||||||
|
key: Option<&str>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(state, headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let action = key.map_or_else(|| "/signup".to_owned(), |key| format!("/signup/{key}"));
|
||||||
|
let again = |notice: Notice| signup_page(csrf_token, &action, notice, &form.username, &form.display_name);
|
||||||
|
if form.password != form.password_confirm {
|
||||||
|
return again(Notice::err("The passwords do not match."));
|
||||||
|
}
|
||||||
|
let new = NewUser {
|
||||||
|
username: form.username.trim(),
|
||||||
|
display_name: &form.display_name,
|
||||||
|
password: Some(&form.password),
|
||||||
|
role: InstanceRole::Member,
|
||||||
|
};
|
||||||
|
let created = match key {
|
||||||
|
Some(key) => {
|
||||||
|
if !matches!(usable_invite(state, key).await, Ok(true)) {
|
||||||
|
return signup_closed(csrf_token, "This invite is not valid any more.");
|
||||||
|
}
|
||||||
|
invites::sign_up(state.pool(), key, new).await
|
||||||
|
}
|
||||||
|
None => match instance::signup_mode(state.pool()).await {
|
||||||
|
Ok(SignupMode::Open) => users::create(state.pool(), new).await.map_err(InviteError::from),
|
||||||
|
Ok(_) => return signup_closed(csrf_token, "Signup is closed."),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
match created {
|
||||||
|
Ok(user) => sign_in(state, &user, AuthMethod::Password, headers, true, "/").await,
|
||||||
|
Err(InviteError::Database(error) | InviteError::User(CreateUserError::Database(error))) => server_error(error),
|
||||||
|
Err(InviteError::Unusable) => signup_closed(csrf_token, "This invite is not valid any more."),
|
||||||
|
Err(other) => again(Notice::err(other)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn signup(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(csrf_token): Extension<CsrfToken>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<AccountForm>,
|
||||||
|
) -> Response {
|
||||||
|
create_account(&state, &csrf_token, &headers, form, None).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn signup_invite(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(csrf_token): Extension<CsrfToken>,
|
||||||
|
Path(key): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<AccountForm>,
|
||||||
|
) -> Response {
|
||||||
|
create_account(&state, &csrf_token, &headers, form, Some(&key)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// Provider sign-in --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub fn callback_url(state: &AppState, provider: Provider) -> String {
|
||||||
|
state.issuer().config().url(&format!("/oauth/{}/callback", provider.as_str()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct StartForm {
|
||||||
|
csrf: String,
|
||||||
|
#[serde(default)]
|
||||||
|
stay_signed_in: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
next: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A start must be a POST from the sign-in form; anything else goes back to it.
|
||||||
|
pub async fn oauth_start_get() -> Response {
|
||||||
|
Redirect::to("/login").into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn oauth_start(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(csrf_token): Extension<CsrfToken>,
|
||||||
|
Path(provider): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<StartForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let next = local_path(form.next.as_deref()).to_owned();
|
||||||
|
let Some(provider) = Provider::parse(&provider) else {
|
||||||
|
return login_page(&state, &csrf_token, &next, Notice::err("Unknown sign-in provider."), "").await;
|
||||||
|
};
|
||||||
|
let redirect_uri = callback_url(&state, provider);
|
||||||
|
let persistent = form.stay_signed_in.is_some();
|
||||||
|
match state.oauth().start(provider, Intent::SignIn, None, None, &next, persistent, &redirect_uri).await {
|
||||||
|
Ok(url) => Redirect::to(&url).into_response(),
|
||||||
|
Err(error) => login_page(&state, &csrf_token, &next, Notice::err(error), "").await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct CallbackQuery {
|
||||||
|
code: Option<String>,
|
||||||
|
state: Option<String>,
|
||||||
|
error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn oauth_callback(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
MaybeSession(session): MaybeSession,
|
||||||
|
Extension(csrf_token): Extension<CsrfToken>,
|
||||||
|
Path(provider): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Query(query): Query<CallbackQuery>,
|
||||||
|
) -> Response {
|
||||||
|
let Some(provider) = Provider::parse(&provider) else {
|
||||||
|
return super::not_found_page(None);
|
||||||
|
};
|
||||||
|
let failed = |message: String| async {
|
||||||
|
// A link attempt from settings goes back there; a sign-in to the sign-in page.
|
||||||
|
match &session {
|
||||||
|
Some(session) => {
|
||||||
|
let viewer = Viewer { session: session.clone(), csrf: csrf_token.clone() };
|
||||||
|
super::settings::providers_page(&state, &viewer, Notice::Err(message)).await
|
||||||
|
}
|
||||||
|
None => login_page(&state, &csrf_token, "/", Notice::Err(message), "").await,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if query.error.is_some() {
|
||||||
|
return failed(format!("{} sign-in was cancelled.", provider.label())).await;
|
||||||
|
}
|
||||||
|
let (Some(code), Some(flow_state)) = (query.code, query.state) else {
|
||||||
|
return failed("The provider's answer was incomplete.".to_owned()).await;
|
||||||
|
};
|
||||||
|
let finished = match state.oauth().finish(provider, &flow_state, &code, &callback_url(&state, provider)).await {
|
||||||
|
Ok(finished) => finished,
|
||||||
|
Err(forge_id::oauth::OAuthError::Database(error)) => return server_error(error),
|
||||||
|
Err(error) => return failed(error.to_string()).await,
|
||||||
|
};
|
||||||
|
match finished.intent {
|
||||||
|
Intent::SignIn => {
|
||||||
|
let user_id = match state.oauth().linked_user(&finished.identity).await {
|
||||||
|
Ok(user_id) => user_id,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let user = match user_id {
|
||||||
|
Some(id) => users::get(state.pool(), &id).await,
|
||||||
|
None => Ok(None),
|
||||||
|
};
|
||||||
|
match user {
|
||||||
|
Ok(Some(user)) if !user.disabled && !user.service => {
|
||||||
|
let next = local_path(Some(&finished.next)).to_owned();
|
||||||
|
sign_in(&state, &user, AuthMethod::Provider, &headers, finished.persistent, &next).await
|
||||||
|
}
|
||||||
|
Ok(_) => {
|
||||||
|
let message = format!(
|
||||||
|
"No account is linked to that {} account. Sign in with your password, then link it in Settings.",
|
||||||
|
provider.label()
|
||||||
|
);
|
||||||
|
login_page(&state, &csrf_token, "/", Notice::Err(message), "").await
|
||||||
|
}
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Intent::Link => {
|
||||||
|
// Only the session that started the link may finish it, so a link started by
|
||||||
|
// someone else cannot attach their provider account to this one.
|
||||||
|
let Some(session) = session.as_ref().filter(|s| {
|
||||||
|
Some(&s.id) == finished.session_id.as_ref() && Some(&s.user.id) == finished.user_id.as_ref()
|
||||||
|
}) else {
|
||||||
|
return failed("This link was started in another session. Start again from Settings.".to_owned()).await;
|
||||||
|
};
|
||||||
|
match state.oauth().link(&session.user.id, &finished.identity).await {
|
||||||
|
Ok(()) => super::done("/settings/providers", "linked"),
|
||||||
|
Err(forge_id::oauth::OAuthError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => failed(error.to_string()).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Device approval ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct DeviceQuery {
|
||||||
|
user_code: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct DeviceForm {
|
||||||
|
csrf: String,
|
||||||
|
user_code: String,
|
||||||
|
decision: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn device_form(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
MaybeSession(session): MaybeSession,
|
||||||
|
Extension(csrf_token): Extension<CsrfToken>,
|
||||||
|
Query(query): Query<DeviceQuery>,
|
||||||
|
) -> Response {
|
||||||
|
let code = query.user_code.as_deref().map(str::trim).filter(|code| !code.is_empty());
|
||||||
|
let Some(session) = session else {
|
||||||
|
let next = match code {
|
||||||
|
Some(code) => {
|
||||||
|
let query = url::form_urlencoded::Serializer::new(String::new()).append_pair("user_code", code).finish();
|
||||||
|
format!("/device?{query}")
|
||||||
|
}
|
||||||
|
None => "/device".to_owned(),
|
||||||
|
};
|
||||||
|
return login_redirect(&next);
|
||||||
|
};
|
||||||
|
let viewer = Viewer { session, csrf: csrf_token };
|
||||||
|
let chrome = || viewer.chrome(super::Nav::None);
|
||||||
|
let Some(code) = code else {
|
||||||
|
return narrow(StatusCode::OK, "Sign in a device", chrome(), panel("Sign in a Lore client", html! {
|
||||||
|
p { "Enter the code your terminal shows." }
|
||||||
|
form.stack method="get" action="/device" {
|
||||||
|
label { "Code" input name="user_code" required autocomplete="off" placeholder="XXXX-XXXX"; }
|
||||||
|
button.primary type="submit" { "Continue" }
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
let request = match state.issuer().pending_device_request(code).await {
|
||||||
|
Ok(request) => request,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let Some(request) = request else {
|
||||||
|
return narrow(StatusCode::NOT_FOUND, "Unknown code", chrome(), panel("Unknown code", html! {
|
||||||
|
p { "The code expired or was already used. Run " code { "lore auth login" } " again." }
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
narrow(StatusCode::OK, "Approve sign-in", chrome(), panel("Approve sign-in", html! {
|
||||||
|
p { "Sign a Lore client in as " strong { (viewer.session.user.username) } "?" }
|
||||||
|
p.muted { "Check that your terminal shows:" }
|
||||||
|
p.big { (request.user_code) }
|
||||||
|
dl.kv {
|
||||||
|
dt { "Client" } dd { (request.requested_by) }
|
||||||
|
dt { "Requested" } dd { (ago(request.created_at)) }
|
||||||
|
}
|
||||||
|
p.warn { "The client gets your access to every repository until you sign it out. Deny if you did not just run lore auth login." }
|
||||||
|
form.actions method="post" action="/device" {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
input type="hidden" name="user_code" value=(request.user_code);
|
||||||
|
button.primary type="submit" name="decision" value="approve" { "Approve" }
|
||||||
|
button.danger type="submit" name="decision" value="deny" { "Deny" }
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn device_decide(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<DeviceForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let approve = form.decision == "approve";
|
||||||
|
let decided = match state.issuer().decide_device_request(&form.user_code, viewer.id(), approve).await {
|
||||||
|
Ok(decided) => decided,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let body = match (decided, approve) {
|
||||||
|
(false, _) => panel("Code expired", html! { p { "Run " code { "lore auth login" } " again." } }),
|
||||||
|
(true, true) => panel("Client signed in", html! { p { "Return to your terminal." } }),
|
||||||
|
(true, false) => panel("Sign-in denied", html! { p { "The client was not signed in." } }),
|
||||||
|
};
|
||||||
|
narrow(StatusCode::OK, "Device sign-in", viewer.chrome(super::Nav::None), body)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,802 @@
|
||||||
|
//! The read-only repository browser: FILES, GRAPH and TREE, as in the desktop explorer, and
|
||||||
|
//! one revision with its changes.
|
||||||
|
//!
|
||||||
|
//! Everything is read from `loreserver` as the viewer, with a one-minute read-only token the
|
||||||
|
//! issuer mints per page view. Where a page is pinned is in its query: `b` (a branch name),
|
||||||
|
//! `rev` (a revision signature in hex) and `path`.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use axum::extract::Path;
|
||||||
|
use axum::extract::Query;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_lore::reader;
|
||||||
|
use forge_lore::reader::At;
|
||||||
|
use forge_lore::reader::Branch;
|
||||||
|
use forge_lore::reader::Change;
|
||||||
|
use forge_lore::reader::Entry;
|
||||||
|
use forge_lore::reader::Kind;
|
||||||
|
use forge_lore::reader::ReadError;
|
||||||
|
use forge_lore::reader::Revision;
|
||||||
|
use maud::Markup;
|
||||||
|
use maud::html;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::Viewer;
|
||||||
|
use super::date;
|
||||||
|
use super::graph;
|
||||||
|
use super::not_found_page;
|
||||||
|
use super::repos;
|
||||||
|
use super::repos::Loaded;
|
||||||
|
use super::repos::Tab;
|
||||||
|
use super::server_error;
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
/// Files larger than this show only their start.
|
||||||
|
const TEXT_LIMIT: u64 = 512 * 1024;
|
||||||
|
/// Lines shown of one file.
|
||||||
|
const MAX_LINES: usize = 10_000;
|
||||||
|
/// Diffs are drawn for files up to this size, and for this many files of a revision.
|
||||||
|
const DIFF_LIMIT: u64 = 256 * 1024;
|
||||||
|
const DIFF_FILES: usize = 30;
|
||||||
|
/// GRAPH reads this many branches, and this many revisions of each.
|
||||||
|
const GRAPH_BRANCHES: usize = 12;
|
||||||
|
const GRAPH_PER_BRANCH: usize = 50;
|
||||||
|
/// TREE lists this many revisions of the open branch.
|
||||||
|
const TREE_REVISIONS: usize = 50;
|
||||||
|
|
||||||
|
/// Where a page is pinned.
|
||||||
|
#[derive(Default, Deserialize)]
|
||||||
|
pub struct Where {
|
||||||
|
b: Option<String>,
|
||||||
|
rev: Option<String>,
|
||||||
|
path: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Where {
|
||||||
|
fn path(&self) -> &str {
|
||||||
|
self.path.as_deref().unwrap_or("").trim_matches('/')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn revision(&self) -> Option<Vec<u8>> {
|
||||||
|
self.rev.as_deref().and_then(reader::unhex).filter(|sig| sig.len() == 32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An open repository: its frame, a reader, its branches (the default first) and the branch
|
||||||
|
/// the page is on.
|
||||||
|
struct Browse {
|
||||||
|
loaded: Loaded,
|
||||||
|
reader: reader::Repo,
|
||||||
|
branches: Vec<Branch>,
|
||||||
|
current: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Browse {
|
||||||
|
fn branch(&self) -> Option<&Branch> {
|
||||||
|
self.current.map(|i| &self.branches[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A link to `page` ("" for FILES) keeping the branch, with `rev` and `path` when given.
|
||||||
|
fn link(&self, page: &str, rev: Option<&[u8]>, path: &str) -> String {
|
||||||
|
let mut query = url::form_urlencoded::Serializer::new(String::new());
|
||||||
|
if let Some(branch) = self.branch()
|
||||||
|
&& self.current != Some(0)
|
||||||
|
{
|
||||||
|
query.append_pair("b", &branch.name);
|
||||||
|
}
|
||||||
|
if let Some(rev) = rev {
|
||||||
|
query.append_pair("rev", &reader::hex(rev));
|
||||||
|
}
|
||||||
|
if !path.is_empty() {
|
||||||
|
query.append_pair("path", path);
|
||||||
|
}
|
||||||
|
let query = query.finish();
|
||||||
|
let base = self.loaded.base();
|
||||||
|
let page = if page.is_empty() { String::new() } else { format!("/{page}") };
|
||||||
|
if query.is_empty() { format!("{base}{page}") } else { format!("{base}{page}?{query}") }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn branch_link(&self, page: &str, index: usize) -> String {
|
||||||
|
let base = self.loaded.base();
|
||||||
|
let page = if page.is_empty() { String::new() } else { format!("/{page}") };
|
||||||
|
if index == 0 {
|
||||||
|
format!("{base}{page}")
|
||||||
|
} else {
|
||||||
|
let query = url::form_urlencoded::Serializer::new(String::new()).append_pair("b", &self.branches[index].name).finish();
|
||||||
|
format!("{base}{page}?{query}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn revision_link(&self, signature: &[u8]) -> String {
|
||||||
|
format!("{}/revision/{}", self.loaded.base(), reader::hex(signature))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn branch_name(&self, id: &[u8]) -> Option<&str> {
|
||||||
|
self.branches.iter().find(|branch| branch.id == id).map(|branch| branch.name.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn colour(&self, branch_id: &[u8]) -> Option<usize> {
|
||||||
|
self.branches.iter().position(|branch| branch.id == branch_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens the repository for the viewer, or answers the page that says why not.
|
||||||
|
async fn open(state: &AppState, viewer: &Viewer, owner: &str, name: &str, tab: Tab, wanted: Option<&str>) -> Result<Browse, Response> {
|
||||||
|
let loaded = repos::load(state, viewer, owner, name).await?;
|
||||||
|
let token = match state.issuer().browse_token(&viewer.session.user, &loaded.repo.id).await {
|
||||||
|
Ok(Some(token)) => token,
|
||||||
|
Ok(None) => return Err(not_found_page(Some(viewer))),
|
||||||
|
Err(error) => return Err(server_error(error)),
|
||||||
|
};
|
||||||
|
let Some(reader) = state.lore().repo(&loaded.repo.id, token) else {
|
||||||
|
return Err(server_error(format!("repository ID {} is not 16 bytes of hex", loaded.repo.id)));
|
||||||
|
};
|
||||||
|
let (mut branches, default) = match tokio::try_join!(reader.branches(), reader.default_branch()) {
|
||||||
|
Ok(found) => found,
|
||||||
|
Err(error) => return Err(failed(viewer, &loaded, tab, error)),
|
||||||
|
};
|
||||||
|
// The default branch first: it takes the first colour and needs no `b` in links.
|
||||||
|
let first = default
|
||||||
|
.and_then(|id| branches.iter().position(|branch| branch.id == id))
|
||||||
|
.or_else(|| branches.iter().position(|branch| branch.name == "main"));
|
||||||
|
if let Some(first) = first {
|
||||||
|
let branch = branches.remove(first);
|
||||||
|
branches.insert(0, branch);
|
||||||
|
}
|
||||||
|
let current = match wanted {
|
||||||
|
Some(name) => match branches.iter().position(|branch| branch.name == name) {
|
||||||
|
Some(found) => Some(found),
|
||||||
|
None => return Err(repos::layout_with(viewer, &loaded, tab, StatusCode::NOT_FOUND, html! {}, html! { p { "No branch named " code { (name) } "." } })),
|
||||||
|
},
|
||||||
|
None => (!branches.is_empty()).then_some(0),
|
||||||
|
};
|
||||||
|
Ok(Browse { loaded, reader, branches, current })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The page for a failed read.
|
||||||
|
fn failed(viewer: &Viewer, loaded: &Loaded, tab: Tab, error: ReadError) -> Response {
|
||||||
|
let (status, message) = match &error {
|
||||||
|
ReadError::NotFound => (StatusCode::NOT_FOUND, "No such revision or path.".to_owned()),
|
||||||
|
_ => {
|
||||||
|
tracing::error!("reading {} from loreserver: {error}", loaded.repo.full_name());
|
||||||
|
(StatusCode::BAD_GATEWAY, format!("Could not read the repository from the Lore server: {error}"))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
repos::layout_with(viewer, loaded, tab, status, html! { div.notice.err { (message) } }, html! {})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// User IDs to usernames, for the given revisions' authors.
|
||||||
|
async fn names<'a>(state: &AppState, revisions: impl Iterator<Item = &'a Revision>) -> HashMap<String, String> {
|
||||||
|
let ids: Vec<String> = revisions.map(|r| r.committed_by.clone()).collect::<HashSet<_>>().into_iter().collect();
|
||||||
|
match forge_id::users::get_many(state.pool(), &ids).await {
|
||||||
|
Ok(users) => users.into_iter().map(|user| (user.id, user.username)).collect(),
|
||||||
|
Err(error) => {
|
||||||
|
tracing::error!("looking up revision authors: {error}");
|
||||||
|
HashMap::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn author(names: &HashMap<String, String>, id: &str) -> Markup {
|
||||||
|
match names.get(id) {
|
||||||
|
Some(name) => html! { a href={ "/" (name) } { (name) } },
|
||||||
|
None => html! { span.dim { (short_text(id, 12)) } },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn when(revision: &Revision) -> String {
|
||||||
|
date((revision.timestamp_ms / 1000) as i64)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn short(signature: &[u8]) -> String {
|
||||||
|
reader::hex(&signature[..signature.len().min(5)])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn first_line(message: &str) -> &str {
|
||||||
|
// A merge made by `lore branch merge` has no message.
|
||||||
|
message.lines().find(|line| !line.trim().is_empty()).unwrap_or("(no message)")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn short_text(text: &str, max: usize) -> String {
|
||||||
|
match text.char_indices().nth(max) {
|
||||||
|
Some((cut, _)) => format!("{}...", &text[..cut]),
|
||||||
|
None => text.to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn size(bytes: u64) -> String {
|
||||||
|
const UNITS: [&str; 4] = ["KiB", "MiB", "GiB", "TiB"];
|
||||||
|
if bytes < 1024 {
|
||||||
|
return format!("{bytes} B");
|
||||||
|
}
|
||||||
|
let mut value = bytes as f64 / 1024.0;
|
||||||
|
let mut unit = 0;
|
||||||
|
while value >= 1024.0 && unit < UNITS.len() - 1 {
|
||||||
|
value /= 1024.0;
|
||||||
|
unit += 1;
|
||||||
|
}
|
||||||
|
format!("{value:.1} {}", UNITS[unit])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parent_of(path: &str) -> &str {
|
||||||
|
path.rsplit_once('/').map_or("", |(parent, _)| parent)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bar above each tab: branch choice, the pinned revision, the clone command.
|
||||||
|
fn bar(state: &AppState, browse: &Browse, page: &str, pinned: Option<&[u8]>) -> Markup {
|
||||||
|
let action = if page.is_empty() { browse.loaded.base() } else { format!("{}/{page}", browse.loaded.base()) };
|
||||||
|
html! {
|
||||||
|
div.repobar {
|
||||||
|
@if !browse.branches.is_empty() {
|
||||||
|
form method="get" action=(action) {
|
||||||
|
label.field { "Branch "
|
||||||
|
select name="b" {
|
||||||
|
@for (i, branch) in browse.branches.iter().enumerate() {
|
||||||
|
option value=(branch.name) selected[browse.current == Some(i)] { (branch.name) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
button.small type="submit" { "Go" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if let Some(pinned) = pinned {
|
||||||
|
span.rev { "at revision " a href=(browse.revision_link(pinned)) { code { (short(pinned)) } } }
|
||||||
|
a href=(browse.link(page, None, "")) { "back to the branch tip" }
|
||||||
|
}
|
||||||
|
span.dim { "lore clone " (super::lore_remote(state)) "/" (browse.loaded.repo.full_name()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The page for a repository with no revisions yet.
|
||||||
|
fn empty(state: &AppState, viewer: &Viewer, browse: &Browse, tab: Tab) -> Response {
|
||||||
|
let remote = super::lore_remote(state);
|
||||||
|
let full = browse.loaded.repo.full_name();
|
||||||
|
repos::layout(viewer, &browse.loaded, tab, super::Notice::None, html! {
|
||||||
|
h2 { "Nothing pushed yet" }
|
||||||
|
p { "Commit and push from a workspace:" }
|
||||||
|
pre { code { "lore clone " (remote) "/" (full) "\ncd " (browse.loaded.repo.name) "\nlore commit -m \"First revision\"\nlore push" } }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// FILES ---------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub async fn files(State(state): State<AppState>, viewer: Viewer, Path((owner, name)): Path<(String, String)>, Query(at): Query<Where>) -> Response {
|
||||||
|
let browse = match open(&state, &viewer, &owner, &name, Tab::Files, at.b.as_deref()).await {
|
||||||
|
Ok(browse) => browse,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let pinned = at.revision();
|
||||||
|
let revision = match (&pinned, browse.branch()) {
|
||||||
|
(Some(signature), _) => signature.clone(),
|
||||||
|
(None, Some(branch)) if !branch.is_empty() => branch.latest.clone(),
|
||||||
|
_ => return empty(&state, &viewer, &browse, Tab::Files),
|
||||||
|
};
|
||||||
|
let path = at.path();
|
||||||
|
let read = At::Revision(revision.clone());
|
||||||
|
|
||||||
|
// A path is either a directory to list or a file to show; its parent's listing says which.
|
||||||
|
let mut target: Option<Entry> = None;
|
||||||
|
if !path.is_empty() {
|
||||||
|
match browse.reader.tree(&read, parent_of(path), 1, true).await {
|
||||||
|
Ok(tree) => target = tree.entries.into_iter().find(|entry| entry.path == path),
|
||||||
|
Err(error) => return failed(&viewer, &browse.loaded, Tab::Files, error),
|
||||||
|
}
|
||||||
|
if target.is_none() {
|
||||||
|
return failed(&viewer, &browse.loaded, Tab::Files, ReadError::NotFound);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let body = match target {
|
||||||
|
Some(entry) if entry.kind != Kind::Directory => file_view(&state, &browse, &entry).await,
|
||||||
|
_ => match browse.reader.tree(&read, path, 1, true).await {
|
||||||
|
Ok(tree) => {
|
||||||
|
let names = names(&state, tree.entries.iter().filter_map(|entry| entry.last.as_ref())).await;
|
||||||
|
listing(&browse, path, tree.entries, pinned.as_deref(), &names)
|
||||||
|
}
|
||||||
|
Err(error) => return failed(&viewer, &browse.loaded, Tab::Files, error),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
repos::layout(&viewer, &browse.loaded, Tab::Files, super::Notice::None, html! {
|
||||||
|
(bar(&state, &browse, "", pinned.as_deref()))
|
||||||
|
(crumbs(&browse, path, pinned.as_deref()))
|
||||||
|
(body)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn crumbs(browse: &Browse, path: &str, pinned: Option<&[u8]>) -> Markup {
|
||||||
|
// Each part with the path up to it.
|
||||||
|
let parts: Vec<(&str, &str)> = path.match_indices('/').map(|(i, _)| i).chain([path.len()]).filter(|_| !path.is_empty()).map(|end| {
|
||||||
|
let start = path[..end].rfind('/').map_or(0, |i| i + 1);
|
||||||
|
(&path[start..end], &path[..end])
|
||||||
|
}).collect();
|
||||||
|
html! {
|
||||||
|
div.path {
|
||||||
|
a href=(browse.link("", pinned, "")) { (browse.loaded.repo.name) }
|
||||||
|
@for (part, upto) in parts {
|
||||||
|
span.sep { "/" }
|
||||||
|
a href=(browse.link("", pinned, upto)) { (part) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn listing(browse: &Browse, path: &str, mut entries: Vec<Entry>, pinned: Option<&[u8]>, names: &HashMap<String, String>) -> Markup {
|
||||||
|
entries.sort_by(|a, b| (a.kind != Kind::Directory).cmp(&(b.kind != Kind::Directory)).then_with(|| a.name().to_lowercase().cmp(&b.name().to_lowercase())));
|
||||||
|
html! {
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Name" } th.num { "Size" } th { "Last change" } th { "By" } th { "When" } } }
|
||||||
|
tbody {
|
||||||
|
@if !path.is_empty() {
|
||||||
|
tr { td.name colspan="5" { span.icon.dir {} a href=(browse.link("", pinned, parent_of(path))) { ".." } } }
|
||||||
|
}
|
||||||
|
@if entries.is_empty() {
|
||||||
|
tr.empty { td colspan="5" { "Empty directory." } }
|
||||||
|
}
|
||||||
|
@for entry in &entries {
|
||||||
|
tr {
|
||||||
|
td.name {
|
||||||
|
span class={ "icon " (match entry.kind { Kind::Directory => "dir", Kind::Link => "link", Kind::File => "file" }) } {}
|
||||||
|
a href=(browse.link("", pinned, &entry.path)) { (entry.name()) }
|
||||||
|
}
|
||||||
|
td.num.dim { @if entry.kind == Kind::File { (size(entry.size)) } }
|
||||||
|
@match &entry.last {
|
||||||
|
Some(last) => {
|
||||||
|
td { a href=(browse.revision_link(&last.signature)) { (short_text(first_line(&last.message), 60)) } }
|
||||||
|
td { (author(names, &last.committed_by)) }
|
||||||
|
td.dim { (when(last)) }
|
||||||
|
}
|
||||||
|
None => { td.dim {} td {} td {} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn file_view(state: &AppState, browse: &Browse, entry: &Entry) -> Markup {
|
||||||
|
let names = names(state, entry.last.iter()).await;
|
||||||
|
let content = match (&entry.address, entry.linked, entry.kind) {
|
||||||
|
(_, true, _) | (_, _, Kind::Link) => html! { p.muted { "This entry is in a linked repository." } },
|
||||||
|
(None, _, _) => html! { p.muted { "Empty file." } },
|
||||||
|
(Some(address), _, _) => match browse.reader.content(address, TEXT_LIMIT).await {
|
||||||
|
Ok(content) => match text(&content.bytes) {
|
||||||
|
Some(text) => html! {
|
||||||
|
@if content.truncated() { p.muted { "Showing the first " (size(content.bytes.len() as u64)) " of " (size(content.size)) "." } }
|
||||||
|
(code(text))
|
||||||
|
},
|
||||||
|
None => html! { p.muted { "Binary file, " (size(content.size)) ". Not shown." } },
|
||||||
|
},
|
||||||
|
Err(error) => html! { div.notice.err { "Could not read the file: " (error) } },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
html! {
|
||||||
|
dl.kv {
|
||||||
|
dt { "Size" } dd { (size(entry.size)) }
|
||||||
|
@if let Some(last) = &entry.last {
|
||||||
|
dt { "Last change" }
|
||||||
|
dd { a href=(browse.revision_link(&last.signature)) { (short_text(first_line(&last.message), 80)) } " " span.dim { (when(last)) } }
|
||||||
|
dt { "By" } dd { (author(&names, &last.committed_by)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if let Some(last) = &entry.last {
|
||||||
|
p { a href=(browse.link("", Some(&last.signature), &entry.path)) { "This file at its last change" } }
|
||||||
|
}
|
||||||
|
(content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The text of `bytes`, or `None` for binary content. A cut-off last character is allowed.
|
||||||
|
fn text(bytes: &[u8]) -> Option<&str> {
|
||||||
|
if bytes[..bytes.len().min(8000)].contains(&0) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match std::str::from_utf8(bytes) {
|
||||||
|
Ok(text) => Some(text),
|
||||||
|
Err(error) if error.error_len().is_none() => std::str::from_utf8(&bytes[..error.valid_up_to()]).ok(),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn code(text: &str) -> Markup {
|
||||||
|
let lines: Vec<&str> = text.lines().collect();
|
||||||
|
html! {
|
||||||
|
div.codewrap {
|
||||||
|
table.code {
|
||||||
|
tbody {
|
||||||
|
@for (n, line) in lines.iter().take(MAX_LINES).enumerate() {
|
||||||
|
tr { td.ln { (n + 1) } td.text { (line) } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if lines.len() > MAX_LINES { p.muted { "Showing " (MAX_LINES) " of " (lines.len()) " lines." } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GRAPH ---------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub async fn graph_page(State(state): State<AppState>, viewer: Viewer, Path((owner, name)): Path<(String, String)>, Query(at): Query<Where>) -> Response {
|
||||||
|
let browse = match open(&state, &viewer, &owner, &name, Tab::Graph, at.b.as_deref()).await {
|
||||||
|
Ok(browse) => browse,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
if browse.branches.iter().all(Branch::is_empty) {
|
||||||
|
return empty(&state, &viewer, &browse, Tab::Graph);
|
||||||
|
}
|
||||||
|
let mut signatures = Vec::new();
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
for branch in browse.branches.iter().filter(|branch| !branch.is_empty()).take(GRAPH_BRANCHES) {
|
||||||
|
let page = match browse.reader.history(&At::Revision(branch.latest.clone())).await {
|
||||||
|
Ok(page) => page,
|
||||||
|
Err(error) => return failed(&viewer, &browse.loaded, Tab::Graph, error),
|
||||||
|
};
|
||||||
|
for (_, signature) in page.items.into_iter().take(GRAPH_PER_BRANCH) {
|
||||||
|
if seen.insert(signature.clone()) {
|
||||||
|
signatures.push(signature);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let revisions = match browse.reader.revisions(&signatures).await {
|
||||||
|
Ok(revisions) => newest_first(revisions),
|
||||||
|
Err(error) => return failed(&viewer, &browse.loaded, Tab::Graph, error),
|
||||||
|
};
|
||||||
|
let names = names(&state, revisions.iter()).await;
|
||||||
|
let heads: HashMap<&[u8], Vec<(usize, &str)>> = browse.branches.iter().enumerate().fold(HashMap::new(), |mut heads, (i, branch)| {
|
||||||
|
heads.entry(branch.latest.as_slice()).or_default().push((i, branch.name.as_str()));
|
||||||
|
heads
|
||||||
|
});
|
||||||
|
let ids: Vec<(String, Vec<String>)> =
|
||||||
|
revisions.iter().map(|r| (reader::hex(&r.signature), r.parents.iter().map(|p| reader::hex(p)).collect())).collect();
|
||||||
|
let nodes: Vec<graph::Node> = revisions
|
||||||
|
.iter()
|
||||||
|
.zip(&ids)
|
||||||
|
.map(|(r, (id, parents))| graph::Node { id, parents: parents.iter().map(String::as_str).collect(), colour: browse.colour(&r.branch_id) })
|
||||||
|
.collect();
|
||||||
|
let colours: HashMap<&str, &'static str> = nodes.iter().map(|node| (node.id, graph::class(node.colour))).collect();
|
||||||
|
let colour_of = |id: &str| colours.get(id).copied().unwrap_or("bm");
|
||||||
|
let (rows, widest) = graph::layout(&nodes);
|
||||||
|
let selected = at.revision();
|
||||||
|
repos::layout(&viewer, &browse.loaded, Tab::Graph, super::Notice::None, html! {
|
||||||
|
div.repobar {
|
||||||
|
@for (i, branch) in browse.branches.iter().enumerate().take(GRAPH_BRANCHES) {
|
||||||
|
span { span class={ "swatch " (graph::class(Some(i))) } {} a href=(browse.branch_link("", i)) { (branch.name) } }
|
||||||
|
}
|
||||||
|
span.dim { "Newest " (GRAPH_PER_BRANCH) " revisions of each branch." }
|
||||||
|
}
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Rev" } th { "Revision" } th { "Message" } th { "By" } th { "When" } } }
|
||||||
|
tbody {
|
||||||
|
@for (i, revision) in revisions.iter().enumerate() {
|
||||||
|
tr.rev class=[(selected.as_deref() == Some(revision.signature.as_slice())).then_some("on")] {
|
||||||
|
td.graph { (graph::draw(&rows, &nodes, i, widest, &colour_of)) }
|
||||||
|
td { a href=(browse.revision_link(&revision.signature)) { code { (short(&revision.signature)) } } }
|
||||||
|
td {
|
||||||
|
@if let Some(names) = heads.get(revision.signature.as_slice()) {
|
||||||
|
@for (i, name) in names {
|
||||||
|
span class={ "tag head " (graph::class(Some(*i))) } { (name) } " "
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(short_text(first_line(&revision.message), 80))
|
||||||
|
}
|
||||||
|
td { (author(&names, &revision.committed_by)) }
|
||||||
|
td.dim { (when(revision)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Orders revisions so every revision comes before its parents, newest first among those
|
||||||
|
/// ready, so the graph's lanes run downwards even when clocks disagree.
|
||||||
|
fn newest_first(revisions: Vec<Revision>) -> Vec<Revision> {
|
||||||
|
let index: HashMap<&[u8], usize> = revisions.iter().enumerate().map(|(i, r)| (r.signature.as_slice(), i)).collect();
|
||||||
|
let mut children = vec![0usize; revisions.len()];
|
||||||
|
for revision in &revisions {
|
||||||
|
for parent in &revision.parents {
|
||||||
|
if let Some(&p) = index.get(parent.as_slice()) {
|
||||||
|
children[p] += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut done = vec![false; revisions.len()];
|
||||||
|
let mut order = Vec::with_capacity(revisions.len());
|
||||||
|
for _ in 0..revisions.len() {
|
||||||
|
let next = (0..revisions.len())
|
||||||
|
.filter(|&i| !done[i] && children[i] == 0)
|
||||||
|
.max_by_key(|&i| (revisions[i].timestamp_ms, revisions[i].number))
|
||||||
|
// A cycle cannot happen in a revision graph; take the newest left if it did.
|
||||||
|
.or_else(|| (0..revisions.len()).filter(|&i| !done[i]).max_by_key(|&i| revisions[i].timestamp_ms));
|
||||||
|
let Some(next) = next else { break };
|
||||||
|
done[next] = true;
|
||||||
|
for parent in &revisions[next].parents {
|
||||||
|
if let Some(&p) = index.get(parent.as_slice()) {
|
||||||
|
children[p] = children[p].saturating_sub(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
order.push(next);
|
||||||
|
}
|
||||||
|
let mut slots: Vec<Option<Revision>> = revisions.into_iter().map(Some).collect();
|
||||||
|
order.into_iter().filter_map(|i| slots[i].take()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TREE ----------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub async fn tree_page(State(state): State<AppState>, viewer: Viewer, Path((owner, name)): Path<(String, String)>, Query(at): Query<Where>) -> Response {
|
||||||
|
let browse = match open(&state, &viewer, &owner, &name, Tab::Tree, at.b.as_deref()).await {
|
||||||
|
Ok(browse) => browse,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let open_revision = at.revision();
|
||||||
|
let mut revisions = Vec::new();
|
||||||
|
if let Some(branch) = browse.branch().filter(|branch| !branch.is_empty()) {
|
||||||
|
let page = match browse.reader.history(&At::Revision(branch.latest.clone())).await {
|
||||||
|
Ok(page) => page,
|
||||||
|
Err(error) => return failed(&viewer, &browse.loaded, Tab::Tree, error),
|
||||||
|
};
|
||||||
|
let signatures: Vec<_> = page.items.into_iter().take(TREE_REVISIONS).map(|(_, signature)| signature).collect();
|
||||||
|
revisions = match browse.reader.revisions(&signatures).await {
|
||||||
|
Ok(revisions) => revisions,
|
||||||
|
Err(error) => return failed(&viewer, &browse.loaded, Tab::Tree, error),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let changes = match open_revision.as_ref().and_then(|sig| revisions.iter().find(|r| &r.signature == sig)) {
|
||||||
|
Some(revision) => match browse.reader.diff(revision.parents.first().map(Vec::as_slice), &revision.signature).await {
|
||||||
|
Ok(changes) => Some(changes),
|
||||||
|
Err(error) => return failed(&viewer, &browse.loaded, Tab::Tree, error),
|
||||||
|
},
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
let names = names(&state, revisions.iter()).await;
|
||||||
|
repos::layout(&viewer, &browse.loaded, Tab::Tree, super::Notice::None, html! {
|
||||||
|
div.tree {
|
||||||
|
@if browse.branches.is_empty() { p.muted { "No branches." } }
|
||||||
|
@for (i, branch) in browse.branches.iter().enumerate() {
|
||||||
|
@let is_open = browse.current == Some(i);
|
||||||
|
a.node.branch class=[is_open.then_some("open")] href=(browse.branch_link("tree", i)) {
|
||||||
|
span class={ "swatch " (graph::class(Some(i))) } {}
|
||||||
|
(branch.name)
|
||||||
|
@if branch.is_empty() { span.dim { " (no revisions)" } }
|
||||||
|
}
|
||||||
|
@if is_open && !revisions.is_empty() {
|
||||||
|
div.children {
|
||||||
|
@for revision in &revisions {
|
||||||
|
@let open_here = open_revision.as_deref() == Some(revision.signature.as_slice());
|
||||||
|
a.node.revision class=[open_here.then_some("open")] href=(if open_here { browse.link("tree", None, "") } else { browse.link("tree", Some(&revision.signature), "") }) {
|
||||||
|
span.dim { "#" (revision.number) " " }
|
||||||
|
(short_text(first_line(&revision.message), 70))
|
||||||
|
span.dim { " " (names.get(&revision.committed_by).map_or("", String::as_str)) " " (when(revision)) }
|
||||||
|
}
|
||||||
|
@if open_here {
|
||||||
|
@if let Some(changes) = &changes {
|
||||||
|
ul.changes {
|
||||||
|
@if changes.is_empty() { li.dim { "No changes." } }
|
||||||
|
@for change in changes {
|
||||||
|
li { (change_line(&browse, change, &revision.signature)) }
|
||||||
|
}
|
||||||
|
li { a href=(browse.revision_link(&revision.signature)) { "Open the revision" } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn change_tag(change: &Change) -> Markup {
|
||||||
|
match change.action {
|
||||||
|
reader::Action::Add => html! { span.tag.green { "A" } },
|
||||||
|
reader::Action::Delete => html! { span.tag.red { "D" } },
|
||||||
|
reader::Action::Move => html! { span.tag.blue { "R" } },
|
||||||
|
reader::Action::Copy => html! { span.tag.blue { "C" } },
|
||||||
|
reader::Action::Modify => html! { span.tag.spark { "M" } },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn change_line(browse: &Browse, change: &Change, revision: &[u8]) -> Markup {
|
||||||
|
html! {
|
||||||
|
(change_tag(change))
|
||||||
|
@if change.action == reader::Action::Delete {
|
||||||
|
span.dim { (change.path) }
|
||||||
|
} @else {
|
||||||
|
a href=(browse.link("", Some(revision), &change.path)) { (change.path) }
|
||||||
|
}
|
||||||
|
@if let Some(from) = &change.path_from { span.dim { " from " (from) } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One revision --------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub async fn revision_page(State(state): State<AppState>, viewer: Viewer, Path((owner, name, signature)): Path<(String, String, String)>) -> Response {
|
||||||
|
let browse = match open(&state, &viewer, &owner, &name, Tab::Graph, None).await {
|
||||||
|
Ok(browse) => browse,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let Some(signature) = reader::unhex(&signature).filter(|sig| sig.len() == 32) else {
|
||||||
|
return failed(&viewer, &browse.loaded, Tab::Graph, ReadError::NotFound);
|
||||||
|
};
|
||||||
|
let revision = match browse.reader.revision(&At::Revision(signature.clone())).await {
|
||||||
|
Ok(revision) => revision,
|
||||||
|
Err(error) => return failed(&viewer, &browse.loaded, Tab::Graph, error),
|
||||||
|
};
|
||||||
|
let changes = match browse.reader.diff(revision.parents.first().map(Vec::as_slice), &signature).await {
|
||||||
|
Ok(changes) => changes,
|
||||||
|
Err(error) => return failed(&viewer, &browse.loaded, Tab::Graph, error),
|
||||||
|
};
|
||||||
|
let names = names(&state, std::iter::once(&revision)).await;
|
||||||
|
let mut diffs = Vec::new();
|
||||||
|
for change in changes.iter().filter(|c| c.kind == Kind::File && !c.linked).take(DIFF_FILES) {
|
||||||
|
diffs.push(file_diff(&browse, change, &signature).await);
|
||||||
|
}
|
||||||
|
let message = revision.message.trim();
|
||||||
|
repos::layout(&viewer, &browse.loaded, Tab::Graph, super::Notice::None, html! {
|
||||||
|
h2 { (first_line(message)) }
|
||||||
|
@if message.lines().count() > 1 { pre { (message) } }
|
||||||
|
dl.kv {
|
||||||
|
dt { "Revision" }
|
||||||
|
dd {
|
||||||
|
"#" (revision.number)
|
||||||
|
@if let Some(branch) = browse.branch_name(&revision.branch_id) { " on " span.tag.dim { (branch) } }
|
||||||
|
}
|
||||||
|
dt { "Signature" } dd { code { (reader::hex(&revision.signature)) } }
|
||||||
|
dt { "By" } dd { (author(&names, &revision.committed_by)) }
|
||||||
|
dt { "When" } dd { (when(&revision)) }
|
||||||
|
dt { "Parents" }
|
||||||
|
dd {
|
||||||
|
@if revision.parents.is_empty() { span.dim { "none: the first revision" } }
|
||||||
|
@for parent in &revision.parents { a href=(browse.revision_link(parent)) { code { (short(parent)) } } " " }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p { a href=(browse.link("", Some(&signature), "")) { "Browse files at this revision" } }
|
||||||
|
h2 { "Changes" }
|
||||||
|
@if changes.is_empty() { p.muted { "No changes." } }
|
||||||
|
ul.changes.flat { @for change in &changes { li { (change_line(&browse, change, &signature)) } } }
|
||||||
|
@for diff in diffs { (diff) }
|
||||||
|
@if changes.iter().filter(|c| c.kind == Kind::File).count() > DIFF_FILES {
|
||||||
|
p.muted { "Diffs are shown for the first " (DIFF_FILES) " files." }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn file_diff(browse: &Browse, change: &Change, revision: &[u8]) -> Markup {
|
||||||
|
let old = if change.action == reader::Action::Add { Ok(None) } else { read(browse, change.from.as_ref()).await };
|
||||||
|
let new = if change.action == reader::Action::Delete { Ok(None) } else { read(browse, change.to.as_ref()).await };
|
||||||
|
let body = match (old, new) {
|
||||||
|
(Err(error), _) | (_, Err(error)) => html! { div.notice.err { "Could not read the file: " (error) } },
|
||||||
|
(Ok(old), Ok(new)) => {
|
||||||
|
let too_big = [&old, &new].iter().any(|c| c.as_ref().is_some_and(|c| c.truncated()));
|
||||||
|
let old_text = old.as_ref().map_or(Some(""), |c| text(&c.bytes));
|
||||||
|
let new_text = new.as_ref().map_or(Some(""), |c| text(&c.bytes));
|
||||||
|
match (too_big, old_text, new_text) {
|
||||||
|
(true, _, _) => html! { p.muted { "Too large to show." } },
|
||||||
|
(false, Some(old), Some(new)) => unified(old, new),
|
||||||
|
_ => html! { p.muted { "Binary file." } },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
html! {
|
||||||
|
div.change {
|
||||||
|
h3 {
|
||||||
|
(change_tag(change))
|
||||||
|
@if change.action == reader::Action::Delete { (change.path) }
|
||||||
|
@else { a href=(browse.link("", Some(revision), &change.path)) { (change.path) } }
|
||||||
|
}
|
||||||
|
(body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read(browse: &Browse, address: Option<&reader::Address>) -> Result<Option<reader::Content>, ReadError> {
|
||||||
|
match address {
|
||||||
|
None => Ok(None),
|
||||||
|
Some(address) => browse.reader.content(address, DIFF_LIMIT).await.map(Some),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A hunk's `start,length` in unified diff form: 1-based, or `n,0` for an empty side.
|
||||||
|
fn hunk_range(start: usize, end: usize) -> String {
|
||||||
|
if end == start { format!("{start},0") } else { format!("{},{}", start + 1, end - start) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A unified diff with three lines of context, as table rows with both line numbers.
|
||||||
|
fn unified(old: &str, new: &str) -> Markup {
|
||||||
|
use similar::ChangeTag;
|
||||||
|
let diff = similar::TextDiff::from_lines(old, new);
|
||||||
|
let groups = diff.grouped_ops(3);
|
||||||
|
if groups.is_empty() {
|
||||||
|
return html! { p.muted { "No text changes." } };
|
||||||
|
}
|
||||||
|
html! {
|
||||||
|
div.codewrap {
|
||||||
|
table.code.diff {
|
||||||
|
tbody {
|
||||||
|
@for group in &groups {
|
||||||
|
@if let (Some(first), Some(last)) = (group.first(), group.last()) {
|
||||||
|
tr.hunk {
|
||||||
|
td.ln {} td.ln {}
|
||||||
|
td.text {
|
||||||
|
"@@ -" (hunk_range(first.old_range().start, last.old_range().end))
|
||||||
|
" +" (hunk_range(first.new_range().start, last.new_range().end)) " @@"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@for op in group {
|
||||||
|
@for line in diff.iter_changes(op) {
|
||||||
|
@let (class, sign) = match line.tag() {
|
||||||
|
ChangeTag::Delete => ("del", "-"),
|
||||||
|
ChangeTag::Insert => ("add", "+"),
|
||||||
|
ChangeTag::Equal => ("same", " "),
|
||||||
|
};
|
||||||
|
tr class=(class) {
|
||||||
|
td.ln { @if let Some(n) = line.old_index() { (n + 1) } }
|
||||||
|
td.ln { @if let Some(n) = line.new_index() { (n + 1) } }
|
||||||
|
td.text { (sign) (line.value().trim_end_matches(['\n', '\r'])) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn revision(sig: u8, parents: &[u8], timestamp_ms: u64) -> Revision {
|
||||||
|
Revision {
|
||||||
|
signature: vec![sig; 32],
|
||||||
|
branch_id: vec![0; 16],
|
||||||
|
number: sig as u64,
|
||||||
|
message: String::new(),
|
||||||
|
timestamp_ms,
|
||||||
|
created_by: String::new(),
|
||||||
|
committed_by: String::new(),
|
||||||
|
parents: parents.iter().map(|p| vec![*p; 32]).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn children_come_before_parents_even_with_odd_clocks() {
|
||||||
|
// 2's clock is behind its parent 1's.
|
||||||
|
let ordered = newest_first(vec![revision(1, &[], 500), revision(2, &[1], 100), revision(3, &[2], 900)]);
|
||||||
|
let order: Vec<u8> = ordered.iter().map(|r| r.signature[0]).collect();
|
||||||
|
assert_eq!(order, vec![3, 2, 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn text_is_told_from_binary() {
|
||||||
|
assert_eq!(text(b"hello\n"), Some("hello\n"));
|
||||||
|
assert_eq!(text(b"a\0b"), None);
|
||||||
|
// A multi-byte character cut by the size limit.
|
||||||
|
assert_eq!(text(&[b'a', 0xc3]), Some("a"));
|
||||||
|
assert_eq!(text(&[0xff, 0xfe, b'a']), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn diffs_number_both_sides() {
|
||||||
|
let html = unified("a\nb\nc\n", "a\nB\nc\n").into_string();
|
||||||
|
assert!(html.contains("@@ -1,3 +1,3 @@"), "{html}");
|
||||||
|
assert!(unified("", "new\n").into_string().contains("@@ -0,0 +1,1 @@"));
|
||||||
|
assert!(html.contains("<tr class=\"del\">"), "{html}");
|
||||||
|
assert!(html.contains("<tr class=\"add\">"), "{html}");
|
||||||
|
assert!(!html.contains("style="));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sizes_read_well() {
|
||||||
|
assert_eq!(size(12), "12 B");
|
||||||
|
assert_eq!(size(2048), "2.0 KiB");
|
||||||
|
assert_eq!(size(5 * 1024 * 1024), "5.0 MiB");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,184 @@
|
||||||
|
//! The revision graph: lanes laid out newest first, drawn one table row at a time as a small
|
||||||
|
//! SVG. The layout is the desktop explorer's (`desktop/gui/src/explorer.cpp`): each lane holds
|
||||||
|
//! the revision it is waiting to reach; a revision takes the first lane leading to it, and a
|
||||||
|
//! parent already waited for is joined rather than given a new lane.
|
||||||
|
//!
|
||||||
|
//! Colours are CSS classes (`b0`..`b5`, `bm` for revisions outside the listed branches), so
|
||||||
|
//! the palette stays in the stylesheet and the content security policy needs no inline style.
|
||||||
|
|
||||||
|
use maud::Markup;
|
||||||
|
use maud::html;
|
||||||
|
|
||||||
|
/// Lane spacing and row height, in pixels.
|
||||||
|
const LANE: u32 = 14;
|
||||||
|
const ROW: u32 = 20;
|
||||||
|
const LEFT: u32 = 10;
|
||||||
|
/// How many branch colours the stylesheet defines.
|
||||||
|
pub const COLOURS: usize = 6;
|
||||||
|
|
||||||
|
/// One revision as the graph sees it.
|
||||||
|
pub struct Node<'a> {
|
||||||
|
pub id: &'a str,
|
||||||
|
pub parents: Vec<&'a str>,
|
||||||
|
/// Index of the revision's branch colour, or `None` for an unlisted branch.
|
||||||
|
pub colour: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lanes around one revision.
|
||||||
|
#[derive(Debug, Default, PartialEq)]
|
||||||
|
pub struct Row<'a> {
|
||||||
|
before: Vec<Option<&'a str>>,
|
||||||
|
after: Vec<Option<&'a str>>,
|
||||||
|
node: usize,
|
||||||
|
incoming: Vec<usize>,
|
||||||
|
/// For each parent: its lane and whether it is the first parent.
|
||||||
|
parents: Vec<(usize, bool)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rows for `nodes`, which must be newest first, and the widest lane count.
|
||||||
|
pub fn layout<'a>(nodes: &[Node<'a>]) -> (Vec<Row<'a>>, usize) {
|
||||||
|
let mut lanes: Vec<Option<&str>> = Vec::new();
|
||||||
|
let mut widest = 0;
|
||||||
|
let mut rows = Vec::with_capacity(nodes.len());
|
||||||
|
for node in nodes {
|
||||||
|
let mut row = Row { before: lanes.clone(), ..Row::default() };
|
||||||
|
row.incoming = lanes.iter().enumerate().filter(|(_, lane)| **lane == Some(node.id)).map(|(i, _)| i).collect();
|
||||||
|
row.node = match row.incoming.first() {
|
||||||
|
Some(&first) => first,
|
||||||
|
None => free_lane(&mut lanes), // a branch head: nothing above leads here
|
||||||
|
};
|
||||||
|
for &i in &row.incoming {
|
||||||
|
lanes[i] = None;
|
||||||
|
}
|
||||||
|
for (k, &parent) in node.parents.iter().enumerate() {
|
||||||
|
let lane = match lanes.iter().position(|lane| *lane == Some(parent)) {
|
||||||
|
Some(joined) => joined,
|
||||||
|
None => {
|
||||||
|
let lane = if k == 0 && lanes[row.node].is_none() { row.node } else { free_lane(&mut lanes) };
|
||||||
|
lanes[lane] = Some(parent);
|
||||||
|
lane
|
||||||
|
}
|
||||||
|
};
|
||||||
|
row.parents.push((lane, k == 0));
|
||||||
|
}
|
||||||
|
while lanes.last() == Some(&None) {
|
||||||
|
lanes.pop();
|
||||||
|
}
|
||||||
|
row.after = lanes.clone();
|
||||||
|
widest = widest.max(row.before.len()).max(row.after.len()).max(row.node + 1);
|
||||||
|
rows.push(row);
|
||||||
|
}
|
||||||
|
(rows, widest)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn free_lane(lanes: &mut Vec<Option<&str>>) -> usize {
|
||||||
|
if let Some(free) = lanes.iter().position(Option::is_none) {
|
||||||
|
return free;
|
||||||
|
}
|
||||||
|
lanes.push(None);
|
||||||
|
lanes.len() - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The SVG for row `index`. `colour_of` gives the colour class of the revision a lane leads to.
|
||||||
|
pub fn draw(rows: &[Row], nodes: &[Node], index: usize, widest: usize, colour_of: &dyn Fn(&str) -> &'static str) -> Markup {
|
||||||
|
let row = &rows[index];
|
||||||
|
let node = &nodes[index];
|
||||||
|
let width = LEFT + widest as u32 * LANE;
|
||||||
|
let x = |lane: usize| LEFT + lane as u32 * LANE;
|
||||||
|
let mid = ROW / 2;
|
||||||
|
let own = class(node.colour);
|
||||||
|
// Each line is a 2-pixel rectangle, as the desktop draws them.
|
||||||
|
let vline = |lane: usize, y0: u32, y1: u32, c: &str| html! {
|
||||||
|
rect class=(c) x=(x(lane) - 1) y=(y0) width="2" height=(y1 - y0) {}
|
||||||
|
};
|
||||||
|
let hline = |from: usize, to: usize, c: &str| {
|
||||||
|
let (a, b) = (x(from.min(to)), x(from.max(to)));
|
||||||
|
html! { rect class=(c) x=(a - 1) y=(mid - 1) width=(b - a + 2) height="2" {} }
|
||||||
|
};
|
||||||
|
html! {
|
||||||
|
svg.graph width=(width) height=(ROW) viewBox=(format!("0 0 {width} {ROW}")) aria-hidden="true" {
|
||||||
|
// Lanes passing straight through.
|
||||||
|
@for (lane, waiting) in row.before.iter().enumerate() {
|
||||||
|
@if let Some(waiting) = waiting {
|
||||||
|
@if *waiting != node.id && row.after.get(lane) == Some(&Some(*waiting)) {
|
||||||
|
(vline(lane, 0, ROW, colour_of(waiting)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Into this revision from its children, then out to its parents.
|
||||||
|
@for &lane in &row.incoming {
|
||||||
|
(vline(lane, 0, mid, own))
|
||||||
|
(hline(lane, row.node, own))
|
||||||
|
}
|
||||||
|
@for (k, &(lane, first)) in row.parents.iter().enumerate() {
|
||||||
|
@let c = if first { own } else { colour_of(node.parents[k]) };
|
||||||
|
(hline(row.node, lane, c))
|
||||||
|
(vline(lane, mid, ROW, c))
|
||||||
|
}
|
||||||
|
rect.ink x=(x(row.node) - 5) y=(mid - 5) width="10" height="10" {}
|
||||||
|
rect class=(own) x=(x(row.node) - 4) y=(mid - 4) width="8" height="8" {}
|
||||||
|
@if node.parents.len() > 1 {
|
||||||
|
// Merges are hollow.
|
||||||
|
rect.ink x=(x(row.node) - 2) y=(mid - 2) width="4" height="4" {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The colour class for a branch colour index.
|
||||||
|
pub fn class(colour: Option<usize>) -> &'static str {
|
||||||
|
const CLASSES: [&str; COLOURS] = ["b0", "b1", "b2", "b3", "b4", "b5"];
|
||||||
|
colour.map_or("bm", |c| CLASSES[c % COLOURS])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn node<'a>(id: &'a str, parents: &[&'a str]) -> Node<'a> {
|
||||||
|
Node { id, parents: parents.to_vec(), colour: Some(0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_line_stays_in_one_lane() {
|
||||||
|
let nodes = [node("c", &["b"]), node("b", &["a"]), node("a", &[])];
|
||||||
|
let (rows, widest) = layout(&nodes);
|
||||||
|
assert_eq!(widest, 1);
|
||||||
|
assert!(rows.iter().all(|row| row.node == 0));
|
||||||
|
assert_eq!(rows[2].after, Vec::<Option<&str>>::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_merge_opens_a_lane_and_a_shared_parent_joins_it() {
|
||||||
|
// m merges f into main; f and b both come from a.
|
||||||
|
let nodes = [node("m", &["b", "f"]), node("f", &["a"]), node("b", &["a"]), node("a", &[])];
|
||||||
|
let (rows, widest) = layout(&nodes);
|
||||||
|
assert_eq!(widest, 2);
|
||||||
|
assert_eq!(rows[0].parents, vec![(0, true), (1, false)]);
|
||||||
|
assert_eq!(rows[1].node, 1);
|
||||||
|
// f's lane already waits for a, so b joins it instead of keeping its own.
|
||||||
|
assert_eq!(rows[2].parents, vec![(1, true)]);
|
||||||
|
assert_eq!(rows[2].after, vec![None, Some("a")]);
|
||||||
|
assert_eq!(rows[3].incoming, vec![1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_heads_get_two_lanes() {
|
||||||
|
let nodes = [node("x", &["a"]), node("y", &["a"]), node("a", &[])];
|
||||||
|
let (rows, _) = layout(&nodes);
|
||||||
|
assert_eq!(rows[0].node, 0);
|
||||||
|
assert_eq!(rows[1].node, 1);
|
||||||
|
assert_eq!(rows[2].node, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rows_draw_without_inline_style() {
|
||||||
|
let nodes = [node("m", &["b", "f"]), node("f", &["a"]), node("b", &["a"]), node("a", &[])];
|
||||||
|
let (rows, widest) = layout(&nodes);
|
||||||
|
for i in 0..nodes.len() {
|
||||||
|
let svg = draw(&rows, &nodes, i, widest, &|_| "b1").into_string();
|
||||||
|
assert!(svg.starts_with("<svg"), "{svg}");
|
||||||
|
assert!(!svg.contains("style="), "{svg}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,102 @@
|
||||||
|
//! The dashboard: the signed-in person's repositories and organisations.
|
||||||
|
|
||||||
|
use axum::extract::Query;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::response::Redirect;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_access::ActionSet;
|
||||||
|
use forge_access::repos::Repo;
|
||||||
|
use maud::Markup;
|
||||||
|
use maud::html;
|
||||||
|
|
||||||
|
use super::Done;
|
||||||
|
use super::Nav;
|
||||||
|
use super::Viewer;
|
||||||
|
use super::lore_remote;
|
||||||
|
use super::page;
|
||||||
|
use super::server_error;
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
/// The strongest preset-like label for a set of actions, for lists.
|
||||||
|
pub fn access_tag(actions: ActionSet) -> Markup {
|
||||||
|
use forge_access::Action;
|
||||||
|
let (label, class) = if actions.contains(Action::Owner) {
|
||||||
|
("owner", "forge")
|
||||||
|
} else if actions.contains(Action::Admin) {
|
||||||
|
("admin", "spark")
|
||||||
|
} else if actions.contains(Action::SetProtected) {
|
||||||
|
("maintain", "green")
|
||||||
|
} else if actions.contains(Action::Write) {
|
||||||
|
("write", "green")
|
||||||
|
} else {
|
||||||
|
("read", "dim")
|
||||||
|
};
|
||||||
|
html! { span class={ "tag " (class) } { (label) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn repo_table(repos: &[(Repo, ActionSet)], empty: &str) -> Markup {
|
||||||
|
html! {
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Repository" } th { "Access" } th { "Actions" } } }
|
||||||
|
tbody {
|
||||||
|
@for (repo, actions) in repos {
|
||||||
|
tr {
|
||||||
|
td { a href={ "/" (repo.namespace) "/" (repo.name) } { (repo.full_name()) } }
|
||||||
|
td { (access_tag(*actions)) }
|
||||||
|
td.muted { (actions.names().join(" ")) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if repos.is_empty() { tr.empty { td colspan="3" { (empty) } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn home(State(state): State<AppState>, viewer: Result<Viewer, Response>, Query(done): Query<Done>) -> Response {
|
||||||
|
match super::auth::needs_setup(&state).await {
|
||||||
|
Ok(true) => return Redirect::to("/setup").into_response(),
|
||||||
|
Ok(false) => {}
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
}
|
||||||
|
let viewer = match viewer {
|
||||||
|
Ok(viewer) => viewer,
|
||||||
|
Err(redirect) => return redirect,
|
||||||
|
};
|
||||||
|
let pool = state.pool();
|
||||||
|
let (repos, orgs) = match tokio::try_join!(
|
||||||
|
forge_access::repos::list_for_user(pool, viewer.id()),
|
||||||
|
forge_access::orgs::list_for_user(pool, viewer.id()),
|
||||||
|
) {
|
||||||
|
Ok(found) => found,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let remote = lore_remote(&state);
|
||||||
|
let username = &viewer.session.user.username;
|
||||||
|
page(StatusCode::OK, "Repositories", viewer.chrome(Nav::Repos), html! {
|
||||||
|
h1 { "Your repositories" }
|
||||||
|
(done.notice().render())
|
||||||
|
div.split {
|
||||||
|
div {
|
||||||
|
nav.side {
|
||||||
|
div.label { "Namespaces" }
|
||||||
|
a href={ "/" (username) } { (username) }
|
||||||
|
@for (org, _) in &orgs { a href={ "/" (org.name) } { (org.name) } }
|
||||||
|
a href="/orgs" { span.muted { "+ organisation" } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div {
|
||||||
|
(repo_table(&repos, "No repositories yet."))
|
||||||
|
(super::panel("Lore CLI", html! {
|
||||||
|
p.muted { "Sign the CLI in through this site, then create a repository under a namespace you own." }
|
||||||
|
pre { code {
|
||||||
|
"lore auth login " (remote) "\n"
|
||||||
|
"lore repository create " (remote) "/" (username) "/my-game\n"
|
||||||
|
"lore clone " (remote) "/" (username) "/my-game"
|
||||||
|
} }
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,408 @@
|
||||||
|
//! Server-rendered pages, and what they share: the layout, the signed-in extractor, notices
|
||||||
|
//! and formatting.
|
||||||
|
|
||||||
|
pub mod admin;
|
||||||
|
pub mod auth;
|
||||||
|
pub mod browse;
|
||||||
|
pub mod graph;
|
||||||
|
pub mod home;
|
||||||
|
pub mod orgs;
|
||||||
|
pub mod repos;
|
||||||
|
pub mod service_accounts;
|
||||||
|
pub mod settings;
|
||||||
|
|
||||||
|
use axum::extract::FromRequestParts;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::http::HeaderValue;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::http::header;
|
||||||
|
use axum::http::request::Parts;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::response::Redirect;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_id::sessions::Session;
|
||||||
|
use forge_id::users::InstanceRole;
|
||||||
|
use maud::DOCTYPE;
|
||||||
|
use maud::Markup;
|
||||||
|
use maud::html;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::security::CsrfRejected;
|
||||||
|
use crate::security::CsrfToken;
|
||||||
|
use crate::security::MaybeSession;
|
||||||
|
use crate::security::check_csrf;
|
||||||
|
|
||||||
|
const STYLESHEET: &str = include_str!("../../assets/app.css");
|
||||||
|
const FONT: &[u8] = include_bytes!("../../assets/vga-8x16.ttf");
|
||||||
|
const FONT_LICENCE: &str = include_str!("../../assets/vga-8x16-LICENSE.txt");
|
||||||
|
|
||||||
|
/// Which top-bar tab a page belongs to.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Nav {
|
||||||
|
None,
|
||||||
|
Repos,
|
||||||
|
Orgs,
|
||||||
|
Settings,
|
||||||
|
Admin,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Who is looking at a page: their session, if any, and the CSRF token for its forms.
|
||||||
|
pub struct Chrome<'a> {
|
||||||
|
pub session: Option<&'a Session>,
|
||||||
|
pub csrf: &'a CsrfToken,
|
||||||
|
pub nav: Nav,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A signed-in visitor. Extracting it sends anyone else to sign in and back.
|
||||||
|
pub struct Viewer {
|
||||||
|
pub session: Session,
|
||||||
|
pub csrf: CsrfToken,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Viewer {
|
||||||
|
pub fn chrome(&self, nav: Nav) -> Chrome<'_> {
|
||||||
|
Chrome { session: Some(&self.session), csrf: &self.csrf, nav }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn id(&self) -> &str {
|
||||||
|
&self.session.user.id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_admin(&self) -> bool {
|
||||||
|
matches!(self.session.user.role, InstanceRole::Owner | InstanceRole::Admin)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_owner(&self) -> bool {
|
||||||
|
self.session.user.role == InstanceRole::Owner
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The hidden CSRF field every form carries.
|
||||||
|
pub fn csrf_field(&self) -> Markup {
|
||||||
|
csrf_field(&self.csrf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRequestParts<AppState> for Viewer {
|
||||||
|
type Rejection = Response;
|
||||||
|
|
||||||
|
async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Self::Rejection> {
|
||||||
|
let csrf = parts.extensions.get::<CsrfToken>().cloned().expect("the CSRF layer runs first");
|
||||||
|
let MaybeSession(session) = MaybeSession::from_request_parts(parts, state).await.unwrap_or(MaybeSession(None));
|
||||||
|
match session {
|
||||||
|
Some(session) => Ok(Viewer { session, csrf }),
|
||||||
|
None => {
|
||||||
|
let next = parts.uri.path_and_query().map_or("/", |p| p.as_str());
|
||||||
|
// Unsafe requests come back to the page, not to the form target.
|
||||||
|
let next = if parts.method == axum::http::Method::GET { next } else { "/" };
|
||||||
|
Err(login_redirect(next))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn csrf_field(csrf: &CsrfToken) -> Markup {
|
||||||
|
html! { input type="hidden" name="csrf" value=(csrf.0); }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layout(title: &str, chrome: &Chrome<'_>, narrow: bool, body: Markup) -> Markup {
|
||||||
|
let tab = |nav: Nav, href: &str, label: &str| {
|
||||||
|
html! { a href=(href) class=[(chrome.nav == nav).then_some("on")] { (label) } }
|
||||||
|
};
|
||||||
|
html! {
|
||||||
|
(DOCTYPE)
|
||||||
|
html lang="en" {
|
||||||
|
head {
|
||||||
|
meta charset="utf-8";
|
||||||
|
meta name="viewport" content="width=device-width, initial-scale=1";
|
||||||
|
title { (title) " - lore-forge" }
|
||||||
|
link rel="stylesheet" href="/static/app.css";
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
header.bar {
|
||||||
|
a.brand href="/" { "LORE-FORGE" }
|
||||||
|
nav.top {
|
||||||
|
@if let Some(session) = chrome.session {
|
||||||
|
(tab(Nav::Repos, "/", "Repos"))
|
||||||
|
(tab(Nav::Orgs, "/orgs", "Orgs"))
|
||||||
|
(tab(Nav::Settings, "/settings", "Settings"))
|
||||||
|
@if matches!(session.user.role, InstanceRole::Owner | InstanceRole::Admin) {
|
||||||
|
(tab(Nav::Admin, "/admin", "Admin"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if let Some(session) = chrome.session {
|
||||||
|
div.who {
|
||||||
|
span.led.on {}
|
||||||
|
a href={ "/" (session.user.username) } { (session.user.username) }
|
||||||
|
form.inline method="post" action="/logout" {
|
||||||
|
(csrf_field(chrome.csrf))
|
||||||
|
button.small type="submit" { "Sign out" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
main class=[narrow.then_some("narrow")] { (body) }
|
||||||
|
footer.foot {
|
||||||
|
span { "lore-forge " (env!("CARGO_PKG_VERSION")) }
|
||||||
|
a href="/licenses" { "licences" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish(status: StatusCode, markup: Markup) -> Response {
|
||||||
|
let mut response = (status, markup).into_response();
|
||||||
|
response.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page in the full layout.
|
||||||
|
pub fn page(status: StatusCode, title: &str, chrome: Chrome<'_>, body: Markup) -> Response {
|
||||||
|
finish(status, layout(title, &chrome, false, body))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page with a single narrow column, for sign-in and short answers.
|
||||||
|
pub fn narrow(status: StatusCode, title: &str, chrome: Chrome<'_>, body: Markup) -> Response {
|
||||||
|
finish(status, layout(title, &chrome, true, body))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A narrow page for someone not signed in.
|
||||||
|
pub fn public(status: StatusCode, title: &str, csrf: &CsrfToken, body: Markup) -> Response {
|
||||||
|
narrow(status, title, Chrome { session: None, csrf, nav: Nav::None }, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A panel with a title bar.
|
||||||
|
pub fn panel(title: &str, body: Markup) -> Markup {
|
||||||
|
html! { section.panel { div.head { (title) } (body) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn server_error(error: impl std::fmt::Display) -> Response {
|
||||||
|
tracing::error!("page error: {error}");
|
||||||
|
let csrf = CsrfToken(String::new());
|
||||||
|
public(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
"Error",
|
||||||
|
&csrf,
|
||||||
|
panel("Error", html! { p { "Something failed on the server. It has been logged." } }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn not_found_page(viewer: Option<&Viewer>) -> Response {
|
||||||
|
let csrf = CsrfToken(String::new());
|
||||||
|
let chrome = match viewer {
|
||||||
|
Some(viewer) => viewer.chrome(Nav::None),
|
||||||
|
None => Chrome { session: None, csrf: &csrf, nav: Nav::None },
|
||||||
|
};
|
||||||
|
narrow(StatusCode::NOT_FOUND, "Not found", chrome, panel("404", html! { p { "Nothing here." } }))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn forbidden_page(viewer: &Viewer, what: &str) -> Response {
|
||||||
|
narrow(StatusCode::FORBIDDEN, "Not allowed", viewer.chrome(Nav::None), panel("403", html! { p { (what) } }))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn csrf_refused(state: &AppState, rejected: CsrfRejected) -> Response {
|
||||||
|
let public_origin = state.public_origin();
|
||||||
|
let body = match rejected {
|
||||||
|
CsrfRejected::WrongOrigin => panel("Wrong address", html! {
|
||||||
|
p {
|
||||||
|
"The form was sent from another address, so it was refused. lore-forge is at "
|
||||||
|
a href=(public_origin) { (public_origin) } "."
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
CsrfRejected::BadToken => panel("Refused", html! {
|
||||||
|
p { "The form had expired. Go back, reload and try again." }
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
let csrf = CsrfToken(String::new());
|
||||||
|
public(StatusCode::FORBIDDEN, "Refused", &csrf, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks an unsafe request's CSRF token and origin.
|
||||||
|
pub fn csrf(state: &AppState, headers: &HeaderMap, submitted: &str) -> Result<(), Response> {
|
||||||
|
check_csrf(state, headers, submitted).map_err(|rejected| csrf_refused(state, rejected))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `next` only when it is a path on this site, so sign-in cannot redirect elsewhere.
|
||||||
|
pub fn local_path(next: Option<&str>) -> &str {
|
||||||
|
match next {
|
||||||
|
Some(path) if path.starts_with('/') && !path.starts_with("//") && !path.contains('\\') => path,
|
||||||
|
_ => "/",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn login_redirect(next: &str) -> Response {
|
||||||
|
let query = url::form_urlencoded::Serializer::new(String::new()).append_pair("next", next).finish();
|
||||||
|
Redirect::to(&format!("/login?{query}")).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Notices ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// The message a page shows above its content.
|
||||||
|
pub enum Notice {
|
||||||
|
None,
|
||||||
|
Ok(&'static str),
|
||||||
|
Err(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Notice {
|
||||||
|
pub fn err(message: impl std::fmt::Display) -> Notice {
|
||||||
|
Notice::Err(message.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render(&self) -> Markup {
|
||||||
|
match self {
|
||||||
|
Notice::None => html! {},
|
||||||
|
Notice::Ok(text) => html! { p.notice.ok role="status" { (text) } },
|
||||||
|
Notice::Err(text) => html! { p.notice.err role="alert" { (text) } },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn status(&self) -> StatusCode {
|
||||||
|
if matches!(self, Notice::Err(_)) { StatusCode::UNPROCESSABLE_ENTITY } else { StatusCode::OK }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `?ok=<code>`, set by [`done`] after a successful form.
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
pub struct Done {
|
||||||
|
ok: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Done {
|
||||||
|
pub fn notice(&self) -> Notice {
|
||||||
|
let text = match self.ok.as_deref() {
|
||||||
|
Some("saved") => "Saved.",
|
||||||
|
Some("created") => "Created.",
|
||||||
|
Some("added") => "Added.",
|
||||||
|
Some("removed") => "Removed.",
|
||||||
|
Some("revoked") => "Revoked.",
|
||||||
|
Some("deleted") => "Deleted.",
|
||||||
|
Some("linked") => "Linked.",
|
||||||
|
Some("unlinked") => "Unlinked.",
|
||||||
|
Some("ended") => "Signed out everywhere else.",
|
||||||
|
Some("password") => "Password changed. Other sessions were signed out.",
|
||||||
|
_ => return Notice::None,
|
||||||
|
};
|
||||||
|
Notice::Ok(text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Redirects back to a page after a successful form, so a reload does not resend it.
|
||||||
|
pub fn done(path: &str, code: &str) -> Response {
|
||||||
|
let separator = if path.contains('?') { '&' } else { '?' };
|
||||||
|
Redirect::to(&format!("{path}{separator}ok={code}")).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Formatting --------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// A Unix time as `YYYY-MM-DD HH:MM` UTC.
|
||||||
|
pub fn date(at: i64) -> String {
|
||||||
|
let days = at.div_euclid(86_400);
|
||||||
|
let seconds = at.rem_euclid(86_400);
|
||||||
|
// Howard Hinnant's civil-from-days.
|
||||||
|
let z = days + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let doe = z - era * 146_097;
|
||||||
|
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let day = doy - (153 * mp + 2) / 5 + 1;
|
||||||
|
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||||
|
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||||
|
format!("{year:04}-{month:02}-{day:02} {:02}:{:02}", seconds / 3600, seconds % 3600 / 60)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How long ago a Unix time was, briefly.
|
||||||
|
pub fn ago(at: i64) -> String {
|
||||||
|
let seconds = (forge_store::now() - at).max(0);
|
||||||
|
match seconds {
|
||||||
|
0..=59 => "just now".to_owned(),
|
||||||
|
60..=3599 => format!("{}m ago", seconds / 60),
|
||||||
|
3600..=86_399 => format!("{}h ago", seconds / 3600),
|
||||||
|
_ => format!("{}d ago", seconds / 86_400),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A short description of a browser from its user agent.
|
||||||
|
pub fn browser(user_agent: &str) -> String {
|
||||||
|
let browser = ["Firefox", "Edg", "Chrome", "Safari", "curl"]
|
||||||
|
.into_iter()
|
||||||
|
.find(|name| user_agent.contains(name))
|
||||||
|
.map(|name| if name == "Edg" { "Edge" } else { name });
|
||||||
|
let os = ["Windows", "Mac OS X", "Linux", "Android", "iPhone"]
|
||||||
|
.into_iter()
|
||||||
|
.find(|name| user_agent.contains(name))
|
||||||
|
.map(|name| if name == "Mac OS X" { "macOS" } else { name });
|
||||||
|
match (browser, os) {
|
||||||
|
(Some(b), Some(o)) => format!("{b} on {o}"),
|
||||||
|
(Some(b), None) => b.to_owned(),
|
||||||
|
(None, Some(o)) => o.to_owned(),
|
||||||
|
(None, None) if user_agent.is_empty() => "unknown".to_owned(),
|
||||||
|
(None, None) => user_agent.chars().take(40).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `lore://` remote of the configured Lore server.
|
||||||
|
pub fn lore_remote(state: &AppState) -> String {
|
||||||
|
let lore = &state.issuer().config().lore_url;
|
||||||
|
match url::Url::parse(lore) {
|
||||||
|
Ok(url) => match (url.host_str(), url.port()) {
|
||||||
|
(Some(host), Some(port)) => format!("lore://{host}:{port}"),
|
||||||
|
(Some(host), None) => format!("lore://{host}"),
|
||||||
|
_ => lore.clone(),
|
||||||
|
},
|
||||||
|
Err(_) => lore.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Static files ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn asset(body: impl IntoResponse, content_type: &'static str) -> Response {
|
||||||
|
let mut response = body.into_response();
|
||||||
|
let headers = response.headers_mut();
|
||||||
|
headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
|
||||||
|
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("public, max-age=3600"));
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn stylesheet() -> Response {
|
||||||
|
asset(STYLESHEET, "text/css; charset=utf-8")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn font() -> Response {
|
||||||
|
asset(FONT, "font/ttf")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn licences(MaybeSession(session): MaybeSession, axum::Extension(csrf): axum::Extension<CsrfToken>) -> Response {
|
||||||
|
let chrome = Chrome { session: session.as_ref(), csrf: &csrf, nav: Nav::None };
|
||||||
|
page(StatusCode::OK, "Licences", chrome, html! {
|
||||||
|
h1 { "Licences" }
|
||||||
|
(panel("lore-forge", html! { p { "MIT licence." } }))
|
||||||
|
(panel("IBM VGA 8x16 font", html! {
|
||||||
|
p {
|
||||||
|
"From The Ultimate Oldschool PC Font Pack by VileR, "
|
||||||
|
a href="https://int10h.org/oldschool-pc-fonts/" { "int10h.org" }
|
||||||
|
". Licensed under CC BY-SA 4.0:"
|
||||||
|
}
|
||||||
|
pre.licence { (FONT_LICENCE) }
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn not_found(MaybeSession(session): MaybeSession, csrf: Option<axum::Extension<CsrfToken>>) -> Response {
|
||||||
|
let csrf = csrf.map(|axum::Extension(c)| c).unwrap_or(CsrfToken(String::new()));
|
||||||
|
let viewer = session.map(|session| Viewer { session, csrf });
|
||||||
|
not_found_page(viewer.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#[test]
|
||||||
|
fn dates() {
|
||||||
|
assert_eq!(super::date(0), "1970-01-01 00:00");
|
||||||
|
assert_eq!(super::date(1_764_085_200), "2025-11-25 15:40");
|
||||||
|
assert_eq!(super::date(951_782_400), "2000-02-29 00:00");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,650 @@
|
||||||
|
//! Owners' pages: `/<owner>` for users and organisations, and an organisation's members,
|
||||||
|
//! teams and settings under `/orgs/<org>`.
|
||||||
|
|
||||||
|
use axum::Form;
|
||||||
|
use axum::extract::Path;
|
||||||
|
use axum::extract::Query;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_access::Namespace;
|
||||||
|
use forge_access::Preset;
|
||||||
|
use forge_access::orgs;
|
||||||
|
use forge_access::orgs::Org;
|
||||||
|
use forge_access::orgs::OrgError;
|
||||||
|
use forge_access::orgs::OrgRole;
|
||||||
|
use forge_id::instance;
|
||||||
|
use forge_id::instance::OrgCreation;
|
||||||
|
use forge_id::users;
|
||||||
|
use maud::Markup;
|
||||||
|
use maud::html;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::Done;
|
||||||
|
use super::Nav;
|
||||||
|
use super::Notice;
|
||||||
|
use super::Viewer;
|
||||||
|
use super::csrf;
|
||||||
|
use super::done;
|
||||||
|
use super::forbidden_page;
|
||||||
|
use super::not_found_page;
|
||||||
|
use super::page;
|
||||||
|
use super::server_error;
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::pages::auth::CsrfOnly;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Tab {
|
||||||
|
Repos,
|
||||||
|
Members,
|
||||||
|
Teams,
|
||||||
|
ServiceAccounts,
|
||||||
|
Settings,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the viewer may do in an organisation.
|
||||||
|
pub struct Membership {
|
||||||
|
pub org: Org,
|
||||||
|
pub role: Option<OrgRole>,
|
||||||
|
/// Instance admins manage every organisation.
|
||||||
|
pub admin: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Membership {
|
||||||
|
pub fn member(&self) -> bool {
|
||||||
|
self.role.is_some() || self.admin
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn manages(&self) -> bool {
|
||||||
|
self.role == Some(OrgRole::Owner) || self.admin
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn membership(state: &AppState, viewer: &Viewer, name: &str) -> Result<Option<Membership>, forge_store::sqlx::Error> {
|
||||||
|
let Some(org) = orgs::find(state.pool(), name).await? else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let role = orgs::role_of(state.pool(), &org.id, viewer.id()).await?;
|
||||||
|
Ok(Some(Membership { org, role, admin: viewer.is_admin() }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The organisation frame: a header and tabs over the content.
|
||||||
|
pub fn layout(viewer: &Viewer, m: &Membership, tab: Tab, notice: Notice, body: Markup) -> Response {
|
||||||
|
let name = &m.org.name;
|
||||||
|
let item = |t: Tab, href: String, label: &str| {
|
||||||
|
html! { a href=(href) class=[(t == tab).then_some("on")] { (label) } }
|
||||||
|
};
|
||||||
|
page(notice.status(), &m.org.name, viewer.chrome(Nav::Orgs), html! {
|
||||||
|
div.crumbs {
|
||||||
|
a href={ "/" (name) } { (name) }
|
||||||
|
@if m.org.display_name != *name { span.muted { " " (m.org.display_name) } }
|
||||||
|
}
|
||||||
|
nav.tabs {
|
||||||
|
(item(Tab::Repos, format!("/{name}"), "Repos"))
|
||||||
|
@if m.member() {
|
||||||
|
(item(Tab::Members, format!("/orgs/{name}/members"), "Members"))
|
||||||
|
(item(Tab::Teams, format!("/orgs/{name}/teams"), "Teams"))
|
||||||
|
(item(Tab::ServiceAccounts, format!("/orgs/{name}/service-accounts"), "Service accounts"))
|
||||||
|
}
|
||||||
|
@if m.manages() { (item(Tab::Settings, format!("/orgs/{name}/settings"), "Settings")) }
|
||||||
|
}
|
||||||
|
section.panel {
|
||||||
|
(notice.render())
|
||||||
|
(body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads the organisation and checks the viewer may see a members-only tab, or manage it.
|
||||||
|
async fn load(state: &AppState, viewer: &Viewer, name: &str, manage: bool) -> Result<Membership, Response> {
|
||||||
|
match membership(state, viewer, name).await {
|
||||||
|
Ok(Some(m)) if (manage && m.manages()) || (!manage && m.member()) => Ok(m),
|
||||||
|
Ok(Some(_)) => Err(forbidden_page(viewer, if manage { "Only organisation owners can do this." } else { "Only members can see this." })),
|
||||||
|
Ok(None) => Err(not_found_page(Some(viewer))),
|
||||||
|
Err(error) => Err(server_error(error)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// /orgs -------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async fn may_create(state: &AppState, viewer: &Viewer) -> Result<bool, forge_store::sqlx::Error> {
|
||||||
|
Ok(viewer.is_admin() || instance::org_creation(state.pool()).await? == OrgCreation::Everyone)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn orgs_page(state: &AppState, viewer: &Viewer, notice: Notice, name: &str, display_name: &str) -> Response {
|
||||||
|
let (mine, can_create) = match tokio::try_join!(orgs::list_for_user(state.pool(), viewer.id()), may_create(state, viewer)) {
|
||||||
|
Ok(found) => found,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
page(notice.status(), "Organisations", viewer.chrome(Nav::Orgs), html! {
|
||||||
|
h1 { "Organisations" }
|
||||||
|
(notice.render())
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Name" } th { "Display name" } th { "Your role" } } }
|
||||||
|
tbody {
|
||||||
|
@for (org, role) in &mine {
|
||||||
|
tr {
|
||||||
|
td { a href={ "/" (org.name) } { (org.name) } }
|
||||||
|
td { (org.display_name) }
|
||||||
|
td { span class={ "tag " (if *role == OrgRole::Owner { "forge" } else { "dim" }) } { (role.as_str()) } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if mine.is_empty() { tr.empty { td colspan="3" { "You are not in any organisation." } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if can_create {
|
||||||
|
(super::panel("New organisation", html! {
|
||||||
|
form.row method="post" action="/orgs" {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Name" input name="name" required maxlength="39" placeholder="studio" value=(name); }
|
||||||
|
label { "Display name" input name="display_name" required maxlength="100" placeholder="Studio" value=(display_name); }
|
||||||
|
button.primary type="submit" { "Create" }
|
||||||
|
}
|
||||||
|
p.muted { "Names: lowercase letters, digits and single hyphens. They are fixed once created." }
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list(State(state): State<AppState>, viewer: Viewer, Query(done): Query<Done>) -> Response {
|
||||||
|
orgs_page(&state, &viewer, done.notice(), "", "").await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct CreateForm {
|
||||||
|
csrf: String,
|
||||||
|
name: String,
|
||||||
|
display_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create(State(state): State<AppState>, viewer: Viewer, headers: HeaderMap, Form(form): Form<CreateForm>) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
match may_create(&state, &viewer).await {
|
||||||
|
Ok(true) => {}
|
||||||
|
Ok(false) => return forbidden_page(&viewer, "Only instance admins can create organisations here."),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
}
|
||||||
|
let name = form.name.trim().to_owned();
|
||||||
|
let display_name = if form.display_name.trim().is_empty() { name.clone() } else { form.display_name.trim().to_owned() };
|
||||||
|
match orgs::create(state.pool(), &name, &display_name, viewer.id()).await {
|
||||||
|
Ok(_) => done(&format!("/{name}"), "created"),
|
||||||
|
Err(OrgError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => orgs_page(&state, &viewer, Notice::err(error), &form.name, &form.display_name).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// /<owner> ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub async fn owner(State(state): State<AppState>, viewer: Viewer, Path(name): Path<String>, Query(done): Query<Done>) -> Response {
|
||||||
|
let namespace = match forge_access::namespace(state.pool(), &name).await {
|
||||||
|
Ok(Some(namespace)) => namespace,
|
||||||
|
Ok(None) => return not_found_page(Some(&viewer)),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let repos = match forge_access::repos::list_in_namespace(state.pool(), namespace.name(), viewer.id()).await {
|
||||||
|
Ok(repos) => repos,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let remote = super::lore_remote(&state);
|
||||||
|
match namespace {
|
||||||
|
Namespace::User { name, user_id } => {
|
||||||
|
let user = match users::get(state.pool(), &user_id).await {
|
||||||
|
Ok(Some(user)) => user,
|
||||||
|
Ok(None) => return not_found_page(Some(&viewer)),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let own = user_id == viewer.id();
|
||||||
|
page(StatusCode::OK, &name, viewer.chrome(if own { Nav::Repos } else { Nav::None }), html! {
|
||||||
|
div.crumbs { (name) span.muted { " " (user.display_name) } }
|
||||||
|
(done.notice().render())
|
||||||
|
(super::home::repo_table(&repos, if own { "No repositories yet." } else { "No repositories you can see." }))
|
||||||
|
@if own {
|
||||||
|
p.muted { "New repository: " code { "lore repository create " (remote) "/" (name) "/<name>" } }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Namespace::Org { name, .. } => {
|
||||||
|
// Non-members see this tab too, with the repositories they can reach.
|
||||||
|
let m = match membership(&state, &viewer, &name).await {
|
||||||
|
Ok(Some(m)) => m,
|
||||||
|
Ok(None) => return not_found_page(Some(&viewer)),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let can_create = m.manages() || (m.role.is_some() && m.org.members_can_create_repos);
|
||||||
|
layout(&viewer, &m, Tab::Repos, done.notice(), html! {
|
||||||
|
(super::home::repo_table(&repos, "No repositories you can see."))
|
||||||
|
@if can_create {
|
||||||
|
p.muted { "New repository: " code { "lore repository create " (remote) "/" (name) "/<name>" } }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Members -----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async fn members_page(state: &AppState, viewer: &Viewer, m: &Membership, notice: Notice) -> Response {
|
||||||
|
let members = match orgs::members(state.pool(), &m.org.id).await {
|
||||||
|
Ok(members) => members,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let base = format!("/orgs/{}/members", m.org.name);
|
||||||
|
layout(viewer, m, Tab::Members, notice, html! {
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Username" } th { "Name" } th { "Role" } th {} } }
|
||||||
|
tbody {
|
||||||
|
@for member in &members {
|
||||||
|
tr {
|
||||||
|
td { a href={ "/" (member.username) } { (member.username) } }
|
||||||
|
td { (member.display_name) }
|
||||||
|
td { span class={ "tag " (if member.role == "owner" { "forge" } else { "dim" }) } { (member.role) } }
|
||||||
|
td.act {
|
||||||
|
@if m.manages() {
|
||||||
|
form method="post" action={ (base) "/" (member.user_id) } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
@if member.role == "owner" {
|
||||||
|
button.small type="submit" name="action" value="member" { "Make member" }
|
||||||
|
} @else {
|
||||||
|
button.small type="submit" name="action" value="owner" { "Make owner" }
|
||||||
|
}
|
||||||
|
" "
|
||||||
|
button.small.danger type="submit" name="action" value="remove" { "Remove" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if m.manages() {
|
||||||
|
form.row method="post" action=(base) {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Username" input name="username" required; }
|
||||||
|
label { "Role"
|
||||||
|
select name="role" { option value="member" { "member" } option value="owner" { "owner" } }
|
||||||
|
}
|
||||||
|
button.primary type="submit" { "Add member" }
|
||||||
|
}
|
||||||
|
p.muted { "Owners manage the organisation and hold Owner on all its repositories." }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn members(State(state): State<AppState>, viewer: Viewer, Path(name): Path<String>, Query(done): Query<Done>) -> Response {
|
||||||
|
match load(&state, &viewer, &name, false).await {
|
||||||
|
Ok(m) => members_page(&state, &viewer, &m, done.notice()).await,
|
||||||
|
Err(response) => response,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct AddMemberForm {
|
||||||
|
csrf: String,
|
||||||
|
username: String,
|
||||||
|
role: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn add_member(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(name): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<AddMemberForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let m = match load(&state, &viewer, &name, true).await {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let user = match users::find_by_username(state.pool(), form.username.trim()).await {
|
||||||
|
Ok(Some(user)) if !user.service => user,
|
||||||
|
Ok(_) => return members_page(&state, &viewer, &m, Notice::err(format!("No user is named '{}'.", form.username.trim()))).await,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let role = OrgRole::parse(&form.role).unwrap_or(OrgRole::Member);
|
||||||
|
match orgs::add_member(state.pool(), &m.org.id, &user.id, role).await {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = forge_store::audit(state.pool(), Some(viewer.id()), "org.member.add", &m.org.name, &user.username).await;
|
||||||
|
done(&format!("/orgs/{name}/members"), "added")
|
||||||
|
}
|
||||||
|
Err(error) => members_page(&state, &viewer, &m, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct MemberActionForm {
|
||||||
|
csrf: String,
|
||||||
|
action: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn member_action(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((name, user_id)): Path<(String, String)>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<MemberActionForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let m = match load(&state, &viewer, &name, true).await {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let pool = state.pool();
|
||||||
|
let (result, code) = match form.action.as_str() {
|
||||||
|
"remove" => (orgs::remove_member(pool, &m.org.id, &user_id).await, "removed"),
|
||||||
|
role => match OrgRole::parse(role) {
|
||||||
|
Some(role) => (orgs::set_member_role(pool, &m.org.id, &user_id, role).await, "saved"),
|
||||||
|
None => return members_page(&state, &viewer, &m, Notice::err("Unknown action.")).await,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
match result {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = forge_store::audit(pool, Some(viewer.id()), &format!("org.member.{}", form.action), &m.org.name, &user_id).await;
|
||||||
|
done(&format!("/orgs/{name}/members"), code)
|
||||||
|
}
|
||||||
|
Err(OrgError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => members_page(&state, &viewer, &m, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Teams -------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async fn teams_page(state: &AppState, viewer: &Viewer, m: &Membership, notice: Notice) -> Response {
|
||||||
|
let teams = match orgs::teams(state.pool(), &m.org.id).await {
|
||||||
|
Ok(teams) => teams,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let base = format!("/orgs/{}/teams", m.org.name);
|
||||||
|
layout(viewer, m, Tab::Teams, notice, html! {
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Team" } th.num { "Members" } } }
|
||||||
|
tbody {
|
||||||
|
@for team in &teams {
|
||||||
|
tr {
|
||||||
|
td { a href={ (base) "/" (team.name) } { (team.name) } }
|
||||||
|
td.num { (team.members) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if teams.is_empty() { tr.empty { td colspan="2" { "No teams." } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if m.manages() {
|
||||||
|
form.row method="post" action=(base) {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Name" input name="name" required maxlength="39" placeholder="artists"; }
|
||||||
|
button.primary type="submit" { "Create team" }
|
||||||
|
}
|
||||||
|
p.muted { "Teams are granted access per repository, on the repository's access page." }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn teams(State(state): State<AppState>, viewer: Viewer, Path(name): Path<String>, Query(done): Query<Done>) -> Response {
|
||||||
|
match load(&state, &viewer, &name, false).await {
|
||||||
|
Ok(m) => teams_page(&state, &viewer, &m, done.notice()).await,
|
||||||
|
Err(response) => response,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct NameForm {
|
||||||
|
csrf: String,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_team(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(name): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<NameForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let m = match load(&state, &viewer, &name, true).await {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let team = form.name.trim();
|
||||||
|
match orgs::create_team(state.pool(), &m.org.id, team).await {
|
||||||
|
Ok(_) => {
|
||||||
|
let _ = forge_store::audit(state.pool(), Some(viewer.id()), "org.team.create", &m.org.name, team).await;
|
||||||
|
done(&format!("/orgs/{name}/teams/{team}"), "created")
|
||||||
|
}
|
||||||
|
Err(OrgError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => teams_page(&state, &viewer, &m, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn team_page(state: &AppState, viewer: &Viewer, m: &Membership, team: &str, notice: Notice) -> Response {
|
||||||
|
let team = match orgs::find_team(state.pool(), &m.org.id, team).await {
|
||||||
|
Ok(Some(team)) => team,
|
||||||
|
Ok(None) => return not_found_page(Some(viewer)),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let members = match orgs::team_members(state.pool(), &team.id).await {
|
||||||
|
Ok(members) => members,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let base = format!("/orgs/{}/teams/{}", m.org.name, team.name);
|
||||||
|
layout(viewer, m, Tab::Teams, notice, html! {
|
||||||
|
h2 { a href={ "/orgs/" (m.org.name) "/teams" } { "Teams" } " / " (team.name) }
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Username" } th { "Name" } th {} } }
|
||||||
|
tbody {
|
||||||
|
@for member in &members {
|
||||||
|
tr {
|
||||||
|
td { a href={ "/" (member.username) } { (member.username) } }
|
||||||
|
td { (member.display_name) }
|
||||||
|
td.act {
|
||||||
|
@if m.manages() {
|
||||||
|
form method="post" action={ (base) "/members/" (member.user_id) "/remove" } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
button.small.danger type="submit" { "Remove" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if members.is_empty() { tr.empty { td colspan="3" { "No members." } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if m.manages() {
|
||||||
|
form.row method="post" action={ (base) "/members" } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Username" input name="name" required; }
|
||||||
|
button.primary type="submit" { "Add to team" }
|
||||||
|
}
|
||||||
|
div.rule {}
|
||||||
|
form method="post" action={ (base) "/delete" } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
button.danger type="submit" { "Delete team" }
|
||||||
|
span.muted { " Its repository grants are removed with it." }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn team(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((name, team)): Path<(String, String)>,
|
||||||
|
Query(done): Query<Done>,
|
||||||
|
) -> Response {
|
||||||
|
match load(&state, &viewer, &name, false).await {
|
||||||
|
Ok(m) => team_page(&state, &viewer, &m, &team, done.notice()).await,
|
||||||
|
Err(response) => response,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn add_team_member(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((name, team_name)): Path<(String, String)>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<NameForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let m = match load(&state, &viewer, &name, true).await {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let (team, user) = match tokio::try_join!(
|
||||||
|
orgs::find_team(state.pool(), &m.org.id, &team_name),
|
||||||
|
users::find_by_username(state.pool(), form.name.trim()),
|
||||||
|
) {
|
||||||
|
Ok(found) => found,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let Some(team) = team else {
|
||||||
|
return not_found_page(Some(&viewer));
|
||||||
|
};
|
||||||
|
let Some(user) = user else {
|
||||||
|
return team_page(&state, &viewer, &m, &team_name, Notice::err(format!("No user is named '{}'.", form.name.trim()))).await;
|
||||||
|
};
|
||||||
|
match orgs::add_team_member(state.pool(), &team.id, &user.id).await {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = forge_store::audit(state.pool(), Some(viewer.id()), "org.team.add", &team.name, &user.username).await;
|
||||||
|
done(&format!("/orgs/{name}/teams/{team_name}"), "added")
|
||||||
|
}
|
||||||
|
Err(OrgError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => team_page(&state, &viewer, &m, &team_name, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn remove_team_member(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((name, team_name, user_id)): Path<(String, String, String)>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let m = match load(&state, &viewer, &name, true).await {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let team = match orgs::find_team(state.pool(), &m.org.id, &team_name).await {
|
||||||
|
Ok(Some(team)) => team,
|
||||||
|
Ok(None) => return not_found_page(Some(&viewer)),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
match orgs::remove_team_member(state.pool(), &team.id, &user_id).await {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = forge_store::audit(state.pool(), Some(viewer.id()), "org.team.remove", &team.name, &user_id).await;
|
||||||
|
done(&format!("/orgs/{name}/teams/{team_name}"), "removed")
|
||||||
|
}
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_team(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((name, team_name)): Path<(String, String)>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let m = match load(&state, &viewer, &name, true).await {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let team = match orgs::find_team(state.pool(), &m.org.id, &team_name).await {
|
||||||
|
Ok(Some(team)) => team,
|
||||||
|
Ok(None) => return not_found_page(Some(&viewer)),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
match orgs::delete_team(state.pool(), &team.id).await {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = forge_store::audit(state.pool(), Some(viewer.id()), "org.team.delete", &m.org.name, &team.name).await;
|
||||||
|
done(&format!("/orgs/{name}/teams"), "deleted")
|
||||||
|
}
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Settings ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async fn settings_page(viewer: &Viewer, m: &Membership, notice: Notice) -> Response {
|
||||||
|
let org = &m.org;
|
||||||
|
layout(viewer, m, Tab::Settings, notice, html! {
|
||||||
|
form.stack method="post" action={ "/orgs/" (org.name) "/settings" } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Display name" input name="display_name" required maxlength="100" value=(org.display_name); }
|
||||||
|
label { "Base permission"
|
||||||
|
select name="base_preset" {
|
||||||
|
option value="" selected[org.base_preset.is_none()] { "none" }
|
||||||
|
@for preset in Preset::ALL.into_iter().filter(|p| *p != Preset::Owner) {
|
||||||
|
option value=(preset.as_str()) selected[org.base_preset == Some(preset)] { (preset.as_str()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.muted { "Every member holds the base permission on every repository of the organisation." }
|
||||||
|
label.check { input type="checkbox" name="members_can_create_repos" value="on" checked[org.members_can_create_repos]; "Members may create repositories" }
|
||||||
|
button.primary type="submit" { "Save" }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn settings(State(state): State<AppState>, viewer: Viewer, Path(name): Path<String>, Query(done): Query<Done>) -> Response {
|
||||||
|
match load(&state, &viewer, &name, true).await {
|
||||||
|
Ok(m) => settings_page(&viewer, &m, done.notice()).await,
|
||||||
|
Err(response) => response,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct SettingsForm {
|
||||||
|
csrf: String,
|
||||||
|
display_name: String,
|
||||||
|
base_preset: String,
|
||||||
|
#[serde(default)]
|
||||||
|
members_can_create_repos: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn save_settings(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(name): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<SettingsForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let m = match load(&state, &viewer, &name, true).await {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let preset = Preset::parse(&form.base_preset);
|
||||||
|
let can_create = form.members_can_create_repos.is_some();
|
||||||
|
match orgs::update(state.pool(), &m.org.id, &form.display_name, preset, can_create).await {
|
||||||
|
Ok(()) => {
|
||||||
|
let detail = format!("base={} members_create={can_create}", form.base_preset);
|
||||||
|
let _ = forge_store::audit(state.pool(), Some(viewer.id()), "org.settings", &m.org.name, &detail).await;
|
||||||
|
done(&format!("/orgs/{name}/settings"), "saved")
|
||||||
|
}
|
||||||
|
Err(OrgError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => settings_page(&viewer, &m, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `/orgs/<org>` goes to the organisation's page.
|
||||||
|
pub async fn org_root(Path(name): Path<String>) -> Response {
|
||||||
|
axum::response::IntoResponse::into_response(axum::response::Redirect::to(&format!("/{name}")))
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,306 @@
|
||||||
|
//! A repository's frame (header and tabs) and, for its admins, who has access. The FILES,
|
||||||
|
//! GRAPH and TREE tabs are in [`super::browse`].
|
||||||
|
|
||||||
|
use axum::extract::Path;
|
||||||
|
use axum::extract::Query;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_access::Action;
|
||||||
|
use forge_access::ActionSet;
|
||||||
|
use forge_access::Namespace;
|
||||||
|
use forge_access::Preset;
|
||||||
|
use forge_access::orgs;
|
||||||
|
use forge_access::orgs::GrantSubject;
|
||||||
|
use forge_access::orgs::OrgError;
|
||||||
|
use forge_access::orgs::Subject;
|
||||||
|
use forge_access::repos::Repo;
|
||||||
|
use forge_id::users;
|
||||||
|
use maud::Markup;
|
||||||
|
use maud::html;
|
||||||
|
|
||||||
|
use super::Done;
|
||||||
|
use super::Nav;
|
||||||
|
use super::Notice;
|
||||||
|
use super::Viewer;
|
||||||
|
use super::csrf;
|
||||||
|
use super::done;
|
||||||
|
use super::not_found_page;
|
||||||
|
use super::page;
|
||||||
|
use super::server_error;
|
||||||
|
use super::settings::Pairs;
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
/// The actions granted only individually, in the advanced view.
|
||||||
|
const ADVANCED: [Action; 4] = [Action::PushProtected, Action::Obliterate, Action::Presign, Action::Migrate];
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Tab {
|
||||||
|
Files,
|
||||||
|
Graph,
|
||||||
|
Tree,
|
||||||
|
Access,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Loaded {
|
||||||
|
pub repo: Repo,
|
||||||
|
pub actions: ActionSet,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Loaded {
|
||||||
|
pub fn base(&self) -> String {
|
||||||
|
format!("/{}/{}", self.repo.namespace, self.repo.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn manages(&self) -> bool {
|
||||||
|
self.actions.contains(Action::Admin) || self.actions.contains(Action::Owner)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The repository, if it exists and the viewer holds any action on it. Others get a 404, so
|
||||||
|
/// private repositories do not show they exist.
|
||||||
|
pub async fn load(state: &AppState, viewer: &Viewer, owner: &str, name: &str) -> Result<Loaded, Response> {
|
||||||
|
let repo = match forge_access::repos::find_by_name(state.pool(), owner, name).await {
|
||||||
|
Ok(Some(repo)) => repo,
|
||||||
|
Ok(None) => return Err(not_found_page(Some(viewer))),
|
||||||
|
Err(error) => return Err(server_error(error)),
|
||||||
|
};
|
||||||
|
let actions = match forge_access::resolve(state.pool(), viewer.id(), &repo.id).await {
|
||||||
|
Ok(actions) => actions,
|
||||||
|
Err(error) => return Err(server_error(error)),
|
||||||
|
};
|
||||||
|
if actions.is_empty() {
|
||||||
|
return Err(not_found_page(Some(viewer)));
|
||||||
|
}
|
||||||
|
Ok(Loaded { repo, actions })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn layout(viewer: &Viewer, loaded: &Loaded, tab: Tab, notice: Notice, body: Markup) -> Response {
|
||||||
|
layout_with(viewer, loaded, tab, notice.status(), notice.render(), body)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`layout`] with any status, for pages that report a Lore failure.
|
||||||
|
pub fn layout_with(viewer: &Viewer, loaded: &Loaded, tab: Tab, status: axum::http::StatusCode, notice: Markup, body: Markup) -> Response {
|
||||||
|
let repo = &loaded.repo;
|
||||||
|
let base = loaded.base();
|
||||||
|
let item = |t: Tab, href: String, label: &str| {
|
||||||
|
html! { a href=(href) class=[(t == tab).then_some("on")] { (label) } }
|
||||||
|
};
|
||||||
|
page(status, &repo.full_name(), viewer.chrome(Nav::Repos), html! {
|
||||||
|
div.crumbs {
|
||||||
|
a href={ "/" (repo.namespace) } { (repo.namespace) }
|
||||||
|
span.sep { "/" }
|
||||||
|
a href=(base) { (repo.name) }
|
||||||
|
}
|
||||||
|
nav.tabs {
|
||||||
|
(item(Tab::Files, base.clone(), "Files"))
|
||||||
|
(item(Tab::Graph, format!("{base}/graph"), "Graph"))
|
||||||
|
(item(Tab::Tree, format!("{base}/tree"), "Tree"))
|
||||||
|
@if loaded.manages() { (item(Tab::Access, format!("{base}/access"), "Access")) }
|
||||||
|
}
|
||||||
|
section.panel {
|
||||||
|
(notice)
|
||||||
|
(body)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Access ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn subject_label(subject: &GrantSubject) -> Markup {
|
||||||
|
match subject {
|
||||||
|
GrantSubject::User { username, .. } => html! { span.tag.dim { "user" } a href={ "/" (username) } { (username) } },
|
||||||
|
GrantSubject::Team { name, .. } => html! { span.tag.blue { "team" } (name) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn access_page(state: &AppState, viewer: &Viewer, loaded: &Loaded, notice: Notice) -> Response {
|
||||||
|
let repo = &loaded.repo;
|
||||||
|
let grants = match orgs::grants(state.pool(), &repo.id).await {
|
||||||
|
Ok(grants) => grants,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let namespace = forge_access::namespace(state.pool(), &repo.namespace).await.ok().flatten();
|
||||||
|
let (org, teams) = match &namespace {
|
||||||
|
Some(Namespace::Org { org_id, .. }) => {
|
||||||
|
let org = orgs::find(state.pool(), &repo.namespace).await.ok().flatten();
|
||||||
|
(org, orgs::teams(state.pool(), org_id).await.unwrap_or_default())
|
||||||
|
}
|
||||||
|
_ => (None, Vec::new()),
|
||||||
|
};
|
||||||
|
let base = format!("/{}/{}/access", repo.namespace, repo.name);
|
||||||
|
layout(viewer, loaded, Tab::Access, notice, html! {
|
||||||
|
h2 { "Implicit" }
|
||||||
|
ul {
|
||||||
|
@match &namespace {
|
||||||
|
Some(Namespace::User { name, .. }) => li { a href={ "/" (name) } { (name) } " owns its personal namespace: " span.tag.forge { "owner" } }
|
||||||
|
Some(Namespace::Org { name, .. }) => {
|
||||||
|
li { "Owners of " a href={ "/" (name) } { (name) } ": " span.tag.forge { "owner" } }
|
||||||
|
li { "Members of " (name) ": "
|
||||||
|
@match org.as_ref().and_then(|o| o.base_preset) {
|
||||||
|
Some(preset) => span.tag { (preset.as_str()) }
|
||||||
|
None => span.muted { "nothing (no base permission)" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h2 { "Grants" }
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Who" } th { "Preset" } th { "Extra actions" } th {} } }
|
||||||
|
tbody {
|
||||||
|
@for grant in &grants {
|
||||||
|
@let (kind, id) = match &grant.subject {
|
||||||
|
GrantSubject::User { id, .. } => ("user", id),
|
||||||
|
GrantSubject::Team { id, .. } => ("team", id),
|
||||||
|
};
|
||||||
|
tr {
|
||||||
|
td { (subject_label(&grant.subject)) }
|
||||||
|
td { @if let Some(p) = grant.preset { span.tag { (p.as_str()) } } @else { span.muted { "none" } } }
|
||||||
|
td { @for a in grant.extra.to_vec() { span.tag.spark { (a.as_str()) } } }
|
||||||
|
td.act {
|
||||||
|
form method="post" action=(base) {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
input type="hidden" name="kind" value=(kind);
|
||||||
|
input type="hidden" name="id" value=(id);
|
||||||
|
input type="hidden" name="preset" value="";
|
||||||
|
button.small.danger type="submit" { "Remove" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if grants.is_empty() { tr.empty { td colspan="4" { "No grants." } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h2 { "Grant access" }
|
||||||
|
form method="post" action=(base) {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
div.row.actions {
|
||||||
|
label.field { "Who"
|
||||||
|
select name="kind" {
|
||||||
|
option value="user" { "user or service account" }
|
||||||
|
@if !teams.is_empty() { option value="team" { "team" } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
label.field { "Name"
|
||||||
|
input name="name" required list="teams" placeholder="username or team";
|
||||||
|
}
|
||||||
|
label.field { "Preset"
|
||||||
|
select name="preset" {
|
||||||
|
option value="" { "none" }
|
||||||
|
@for preset in Preset::ALL {
|
||||||
|
option value=(preset.as_str()) selected[preset == Preset::Writer] { (preset.as_str()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if !teams.is_empty() {
|
||||||
|
datalist #teams { @for team in &teams { option value=(team.name) {} } }
|
||||||
|
}
|
||||||
|
fieldset {
|
||||||
|
legend { "Advanced: extra actions" }
|
||||||
|
div.checks {
|
||||||
|
@for action in ADVANCED {
|
||||||
|
label { input type="checkbox" name="extra" value=(action.as_str()); (action.as_str()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div.actions { button.primary type="submit" { "Grant" } }
|
||||||
|
}
|
||||||
|
h2 { "Presets" }
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Preset" } th { "Lore actions" } th { "For" } } }
|
||||||
|
tbody {
|
||||||
|
tr { td { "reader" } td { "read" } td.muted { "clone and browse" } }
|
||||||
|
tr { td { "writer" } td { "write" } td.muted { "push to unprotected branches, take locks" } }
|
||||||
|
tr { td { "maintainer" } td { "write set-protected" } td.muted { "also protect branches" } }
|
||||||
|
tr { td { "admin" } td { "write admin" } td.muted { "also release others' locks, manage access" } }
|
||||||
|
tr { td { "owner" } td { "write owner" } td.muted { "also delete the repository" } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.muted { code { "push-protected" } " bypasses review on protected branches; give it only to CI service accounts that need it." }
|
||||||
|
p.muted { "Changes reach Lore clients within five minutes." }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn access(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((owner, name)): Path<(String, String)>,
|
||||||
|
Query(done): Query<Done>,
|
||||||
|
) -> Response {
|
||||||
|
let loaded = match load(&state, &viewer, &owner, &name).await {
|
||||||
|
Ok(loaded) if loaded.manages() => loaded,
|
||||||
|
Ok(_) => return super::forbidden_page(&viewer, "Only repository admins can manage access."),
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
access_page(&state, &viewer, &loaded, done.notice()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds, changes or removes a grant. The form names the subject by `name` (a username or a
|
||||||
|
/// team of the repository's organisation) or, from a row's remove button, by `id`.
|
||||||
|
pub async fn set_access(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((owner, name)): Path<(String, String)>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
body: axum::body::Bytes,
|
||||||
|
) -> Response {
|
||||||
|
let form = Pairs::parse(&body);
|
||||||
|
if let Err(refused) = csrf(&state, &headers, form.get("csrf")) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let loaded = match load(&state, &viewer, &owner, &name).await {
|
||||||
|
Ok(loaded) if loaded.manages() => loaded,
|
||||||
|
Ok(_) => return super::forbidden_page(&viewer, "Only repository admins can manage access."),
|
||||||
|
Err(response) => return response,
|
||||||
|
};
|
||||||
|
let repo = &loaded.repo;
|
||||||
|
let preset = Preset::parse(form.get("preset"));
|
||||||
|
let extra = form
|
||||||
|
.all("extra")
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|name| ADVANCED.into_iter().find(|a| a.as_str() == name))
|
||||||
|
.fold(ActionSet::EMPTY, ActionSet::with);
|
||||||
|
let kind = form.get("kind");
|
||||||
|
let target = form.get("name").trim().to_owned();
|
||||||
|
let subject_id = if !form.get("id").is_empty() {
|
||||||
|
form.get("id").to_owned()
|
||||||
|
} else if kind == "team" {
|
||||||
|
let org = match orgs::find(state.pool(), &repo.namespace).await {
|
||||||
|
Ok(org) => org,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let team = match org {
|
||||||
|
Some(org) => orgs::find_team(state.pool(), &org.id, &target).await,
|
||||||
|
None => Ok(None),
|
||||||
|
};
|
||||||
|
match team {
|
||||||
|
Ok(Some(team)) => team.id,
|
||||||
|
Ok(None) => return access_page(&state, &viewer, &loaded, Notice::err(format!("No team is named '{target}'."))).await,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match users::find_by_username(state.pool(), &target).await {
|
||||||
|
Ok(Some(user)) => user.id,
|
||||||
|
Ok(None) => return access_page(&state, &viewer, &loaded, Notice::err(format!("No user is named '{target}'."))).await,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Only an Owner may hand out Owner, which includes deleting the repository.
|
||||||
|
if preset == Some(Preset::Owner) && !loaded.actions.contains(Action::Owner) {
|
||||||
|
return access_page(&state, &viewer, &loaded, Notice::err("Only owners can grant Owner.")).await;
|
||||||
|
}
|
||||||
|
let subject = if kind == "team" { Subject::Team(&subject_id) } else { Subject::User(&subject_id) };
|
||||||
|
match orgs::set_grant(state.pool(), &repo.id, subject, preset, extra).await {
|
||||||
|
Ok(()) => {
|
||||||
|
let detail = format!("{kind} {subject_id} {} {}", preset.map_or("none", Preset::as_str), extra.names().join(","));
|
||||||
|
let _ = forge_store::audit(state.pool(), Some(viewer.id()), "grant.set", &repo.full_name(), &detail).await;
|
||||||
|
let removed = preset.is_none() && extra.is_empty();
|
||||||
|
done(&format!("/{}/{}/access", repo.namespace, repo.name), if removed { "removed" } else { "saved" })
|
||||||
|
}
|
||||||
|
Err(OrgError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => access_page(&state, &viewer, &loaded, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,333 @@
|
||||||
|
//! Service accounts: non-human identities for CI, owned by a person
|
||||||
|
//! (`/settings/service-accounts`) or an organisation (`/orgs/<org>/service-accounts`). They
|
||||||
|
//! log the Lore CLI in with client credentials: their name and one of their tokens.
|
||||||
|
|
||||||
|
use axum::Form;
|
||||||
|
use axum::extract::Path;
|
||||||
|
use axum::extract::Query;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_id::api_tokens;
|
||||||
|
use forge_id::api_tokens::Scope;
|
||||||
|
use forge_id::users;
|
||||||
|
use forge_id::users::CreateUserError;
|
||||||
|
use forge_id::users::User;
|
||||||
|
use maud::Markup;
|
||||||
|
use maud::html;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::Done;
|
||||||
|
use super::Notice;
|
||||||
|
use super::Viewer;
|
||||||
|
use super::csrf;
|
||||||
|
use super::done;
|
||||||
|
use super::not_found_page;
|
||||||
|
use super::orgs;
|
||||||
|
use super::server_error;
|
||||||
|
use super::settings;
|
||||||
|
use super::settings::Pairs;
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::pages::auth::CsrfOnly;
|
||||||
|
|
||||||
|
/// Whose service accounts a page shows.
|
||||||
|
enum Owner {
|
||||||
|
Person,
|
||||||
|
Org(orgs::Membership),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Place {
|
||||||
|
owner: Owner,
|
||||||
|
namespace: String,
|
||||||
|
base: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Place {
|
||||||
|
fn frame(&self, viewer: &Viewer, notice: Notice, body: Markup) -> Response {
|
||||||
|
match &self.owner {
|
||||||
|
Owner::Person => settings::layout(viewer, settings::Section::ServiceAccounts, "Service accounts", notice, body),
|
||||||
|
Owner::Org(m) => orgs::layout(viewer, m, orgs::Tab::ServiceAccounts, notice, body),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn manages(&self) -> bool {
|
||||||
|
match &self.owner {
|
||||||
|
Owner::Person => true,
|
||||||
|
Owner::Org(m) => m.manages(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn personal(viewer: &Viewer) -> Place {
|
||||||
|
Place {
|
||||||
|
owner: Owner::Person,
|
||||||
|
namespace: viewer.session.user.username.clone(),
|
||||||
|
base: "/settings/service-accounts".to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn org_place(state: &AppState, viewer: &Viewer, name: &str) -> Result<Place, Response> {
|
||||||
|
match orgs::membership(state, viewer, name).await {
|
||||||
|
Ok(Some(m)) if m.member() => Ok(Place {
|
||||||
|
namespace: m.org.name.clone(),
|
||||||
|
base: format!("/orgs/{}/service-accounts", m.org.name),
|
||||||
|
owner: Owner::Org(m),
|
||||||
|
}),
|
||||||
|
Ok(Some(_)) => Err(super::forbidden_page(viewer, "Only members can see this.")),
|
||||||
|
Ok(None) => Err(not_found_page(Some(viewer))),
|
||||||
|
Err(error) => Err(server_error(error)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn list_page(state: &AppState, viewer: &Viewer, place: &Place, notice: Notice) -> Response {
|
||||||
|
let accounts = match users::service_accounts(state.pool(), &place.namespace).await {
|
||||||
|
Ok(accounts) => accounts,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
place.frame(viewer, notice, html! {
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Name" } th { "Display name" } } }
|
||||||
|
tbody {
|
||||||
|
@for account in &accounts {
|
||||||
|
tr {
|
||||||
|
td { a href={ (place.base) "/" (account.id) } { (account.username) } }
|
||||||
|
td { (account.display_name) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if accounts.is_empty() { tr.empty { td colspan="2" { "No service accounts." } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if place.manages() {
|
||||||
|
form.row method="post" action=(place.base) {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Name" input name="name" required maxlength="39" placeholder="ci"; }
|
||||||
|
label { "Display name" input name="display_name" maxlength="100" placeholder="Build agent"; }
|
||||||
|
button.primary type="submit" { "Create" }
|
||||||
|
}
|
||||||
|
p.muted { "A service account is named " code { (place.namespace) ".<name>" } ". Grant it access on each repository's access page." }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn account_page(state: &AppState, viewer: &Viewer, place: &Place, account: &User, notice: Notice, secret: Option<&str>) -> Response {
|
||||||
|
let tokens = match api_tokens::list(state.pool(), &account.id).await {
|
||||||
|
Ok(tokens) => tokens,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let base = format!("{}/{}", place.base, account.id);
|
||||||
|
let remote = super::lore_remote(state);
|
||||||
|
place.frame(viewer, notice, html! {
|
||||||
|
h2 { a href=(place.base) { "Service accounts" } " / " (account.username) }
|
||||||
|
dl.kv {
|
||||||
|
dt { "Client ID" } dd { code { (account.username) } }
|
||||||
|
dt { "Name" } dd { (account.display_name) }
|
||||||
|
dt { "ID" } dd.muted { (account.id) }
|
||||||
|
}
|
||||||
|
@if place.manages() {
|
||||||
|
h2 { "Secrets" }
|
||||||
|
(settings::token_section(viewer, &tokens, &format!("{base}/tokens"), &[Scope::Lore], secret))
|
||||||
|
pre { code { "LORE_CLIENT_SECRET=<secret> lore auth login --client-id " (account.username) " " (remote) } }
|
||||||
|
div.rule {}
|
||||||
|
form method="post" action={ (base) "/delete" } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
button.danger type="submit" { "Delete service account" }
|
||||||
|
span.muted { " Its secrets, logins and grants go with it." }
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
p.muted { "Only organisation owners manage its secrets." }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The service account `id`, if it belongs to the place.
|
||||||
|
async fn find(state: &AppState, place: &Place, id: &str) -> Result<Option<User>, forge_store::sqlx::Error> {
|
||||||
|
let owner = users::service_account_owner(state.pool(), id).await?;
|
||||||
|
if !owner.is_some_and(|owner| owner.eq_ignore_ascii_case(&place.namespace)) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
users::get(state.pool(), id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handlers, each in a personal and an organisation form -------------------------------------
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct CreateForm {
|
||||||
|
csrf: String,
|
||||||
|
name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
display_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create(state: &AppState, viewer: &Viewer, place: &Place, headers: &HeaderMap, form: CreateForm) -> Response {
|
||||||
|
if let Err(refused) = csrf(state, headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
if !place.manages() {
|
||||||
|
return super::forbidden_page(viewer, "Only organisation owners can do this.");
|
||||||
|
}
|
||||||
|
let name = form.name.trim();
|
||||||
|
let display_name = if form.display_name.trim().is_empty() { name } else { form.display_name.trim() };
|
||||||
|
match users::create_service_account(state.pool(), &place.namespace, name, display_name, viewer.id()).await {
|
||||||
|
Ok(account) => done(&format!("{}/{}", place.base, account.id), "created"),
|
||||||
|
Err(CreateUserError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => list_page(state, viewer, place, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn show(state: &AppState, viewer: &Viewer, place: &Place, id: &str, notice: Notice) -> Response {
|
||||||
|
match find(state, place, id).await {
|
||||||
|
Ok(Some(account)) => account_page(state, viewer, place, &account, notice, None).await,
|
||||||
|
Ok(None) => not_found_page(Some(viewer)),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_secret(state: &AppState, viewer: &Viewer, place: &Place, id: &str, headers: &HeaderMap, form: Pairs) -> Response {
|
||||||
|
if let Err(refused) = csrf(state, headers, form.get("csrf")) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
if !place.manages() {
|
||||||
|
return super::forbidden_page(viewer, "Only organisation owners can do this.");
|
||||||
|
}
|
||||||
|
let account = match find(state, place, id).await {
|
||||||
|
Ok(Some(account)) => account,
|
||||||
|
Ok(None) => return not_found_page(Some(viewer)),
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let (name, _, days) = settings::token_request(&form);
|
||||||
|
match api_tokens::create(state.pool(), &account.id, &name, &[Scope::Lore], days, viewer.id()).await {
|
||||||
|
Ok(new) => account_page(state, viewer, place, &account, Notice::Ok("Secret created."), Some(&new.secret)).await,
|
||||||
|
Err(api_tokens::TokenError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => account_page(state, viewer, place, &account, Notice::err(error), None).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn revoke_secret(state: &AppState, viewer: &Viewer, place: &Place, id: &str, token: &str, headers: &HeaderMap, form: CsrfOnly) -> Response {
|
||||||
|
if let Err(refused) = csrf(state, headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
if !place.manages() {
|
||||||
|
return super::forbidden_page(viewer, "Only organisation owners can do this.");
|
||||||
|
}
|
||||||
|
match find(state, place, id).await {
|
||||||
|
Ok(Some(account)) => match api_tokens::revoke(state.pool(), &account.id, token, viewer.id()).await {
|
||||||
|
Ok(_) => done(&format!("{}/{}", place.base, account.id), "revoked"),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
},
|
||||||
|
Ok(None) => not_found_page(Some(viewer)),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete(state: &AppState, viewer: &Viewer, place: &Place, id: &str, headers: &HeaderMap, form: CsrfOnly) -> Response {
|
||||||
|
if let Err(refused) = csrf(state, headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
if !place.manages() {
|
||||||
|
return super::forbidden_page(viewer, "Only organisation owners can do this.");
|
||||||
|
}
|
||||||
|
match find(state, place, id).await {
|
||||||
|
Ok(Some(account)) => match users::delete_service_account(state.pool(), &account.id, viewer.id()).await {
|
||||||
|
Ok(()) => done(&place.base, "deleted"),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
},
|
||||||
|
Ok(None) => not_found_page(Some(viewer)),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn personal_list(State(state): State<AppState>, viewer: Viewer, Query(d): Query<Done>) -> Response {
|
||||||
|
let place = personal(&viewer);
|
||||||
|
list_page(&state, &viewer, &place, d.notice()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn personal_create(State(state): State<AppState>, viewer: Viewer, headers: HeaderMap, Form(form): Form<CreateForm>) -> Response {
|
||||||
|
let place = personal(&viewer);
|
||||||
|
create(&state, &viewer, &place, &headers, form).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn personal_show(State(state): State<AppState>, viewer: Viewer, Path(id): Path<String>, Query(d): Query<Done>) -> Response {
|
||||||
|
let place = personal(&viewer);
|
||||||
|
show(&state, &viewer, &place, &id, d.notice()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn personal_secret(State(state): State<AppState>, viewer: Viewer, Path(id): Path<String>, headers: HeaderMap, body: axum::body::Bytes) -> Response {
|
||||||
|
let place = personal(&viewer);
|
||||||
|
create_secret(&state, &viewer, &place, &id, &headers, Pairs::parse(&body)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn personal_revoke(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((id, token)): Path<(String, String)>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
let place = personal(&viewer);
|
||||||
|
revoke_secret(&state, &viewer, &place, &id, &token, &headers, form).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn personal_delete(State(state): State<AppState>, viewer: Viewer, Path(id): Path<String>, headers: HeaderMap, Form(form): Form<CsrfOnly>) -> Response {
|
||||||
|
let place = personal(&viewer);
|
||||||
|
delete(&state, &viewer, &place, &id, &headers, form).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn org_list(State(state): State<AppState>, viewer: Viewer, Path(org): Path<String>, Query(d): Query<Done>) -> Response {
|
||||||
|
match org_place(&state, &viewer, &org).await {
|
||||||
|
Ok(place) => list_page(&state, &viewer, &place, d.notice()).await,
|
||||||
|
Err(response) => response,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn org_create(State(state): State<AppState>, viewer: Viewer, Path(org): Path<String>, headers: HeaderMap, Form(form): Form<CreateForm>) -> Response {
|
||||||
|
match org_place(&state, &viewer, &org).await {
|
||||||
|
Ok(place) => create(&state, &viewer, &place, &headers, form).await,
|
||||||
|
Err(response) => response,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn org_show(State(state): State<AppState>, viewer: Viewer, Path((org, id)): Path<(String, String)>, Query(d): Query<Done>) -> Response {
|
||||||
|
match org_place(&state, &viewer, &org).await {
|
||||||
|
Ok(place) => show(&state, &viewer, &place, &id, d.notice()).await,
|
||||||
|
Err(response) => response,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn org_secret(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((org, id)): Path<(String, String)>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
body: axum::body::Bytes,
|
||||||
|
) -> Response {
|
||||||
|
match org_place(&state, &viewer, &org).await {
|
||||||
|
Ok(place) => create_secret(&state, &viewer, &place, &id, &headers, Pairs::parse(&body)).await,
|
||||||
|
Err(response) => response,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn org_revoke(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((org, id, token)): Path<(String, String, String)>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
match org_place(&state, &viewer, &org).await {
|
||||||
|
Ok(place) => revoke_secret(&state, &viewer, &place, &id, &token, &headers, form).await,
|
||||||
|
Err(response) => response,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn org_delete(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path((org, id)): Path<(String, String)>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
match org_place(&state, &viewer, &org).await {
|
||||||
|
Ok(place) => delete(&state, &viewer, &place, &id, &headers, form).await,
|
||||||
|
Err(response) => response,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,506 @@
|
||||||
|
//! A person's own settings: profile and password, sessions and CLI logins, linked sign-in
|
||||||
|
//! providers, API tokens.
|
||||||
|
|
||||||
|
use axum::Form;
|
||||||
|
use axum::extract::Path;
|
||||||
|
use axum::extract::Query;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use axum::response::Redirect;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_id::api_tokens;
|
||||||
|
use forge_id::api_tokens::Scope;
|
||||||
|
use forge_id::oauth::Intent;
|
||||||
|
use forge_id::oauth::Provider;
|
||||||
|
use forge_id::sessions;
|
||||||
|
use forge_id::users;
|
||||||
|
use forge_id::users::AccountError;
|
||||||
|
use maud::Markup;
|
||||||
|
use maud::html;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::Done;
|
||||||
|
use super::Nav;
|
||||||
|
use super::Notice;
|
||||||
|
use super::Viewer;
|
||||||
|
use super::ago;
|
||||||
|
use super::browser;
|
||||||
|
use super::csrf;
|
||||||
|
use super::date;
|
||||||
|
use super::done;
|
||||||
|
use super::page;
|
||||||
|
use super::server_error;
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::pages::auth::CsrfOnly;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Section {
|
||||||
|
Profile,
|
||||||
|
Sessions,
|
||||||
|
Providers,
|
||||||
|
Tokens,
|
||||||
|
ServiceAccounts,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn layout(viewer: &Viewer, section: Section, title: &str, notice: Notice, body: Markup) -> Response {
|
||||||
|
let item = |s: Section, href: &str, label: &str| {
|
||||||
|
html! { a href=(href) class=[(s == section).then_some("on")] { (label) } }
|
||||||
|
};
|
||||||
|
page(notice.status(), title, viewer.chrome(Nav::Settings), html! {
|
||||||
|
h1 { "Settings" }
|
||||||
|
div.split {
|
||||||
|
nav.side {
|
||||||
|
div.label { (viewer.session.user.username) }
|
||||||
|
(item(Section::Profile, "/settings", "Profile"))
|
||||||
|
(item(Section::Sessions, "/settings/sessions", "Sessions"))
|
||||||
|
(item(Section::Providers, "/settings/providers", "Sign-in providers"))
|
||||||
|
(item(Section::Tokens, "/settings/tokens", "API tokens"))
|
||||||
|
(item(Section::ServiceAccounts, "/settings/service-accounts", "Service accounts"))
|
||||||
|
}
|
||||||
|
div {
|
||||||
|
(notice.render())
|
||||||
|
(body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Profile -----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async fn profile_page(state: &AppState, viewer: &Viewer, notice: Notice) -> Response {
|
||||||
|
let has_password = match users::has_password(state.pool(), viewer.id()).await {
|
||||||
|
Ok(has) => has,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let user = &viewer.session.user;
|
||||||
|
layout(viewer, Section::Profile, "Profile", notice, html! {
|
||||||
|
(super::panel("Profile", html! {
|
||||||
|
dl.kv {
|
||||||
|
dt { "Username" } dd { (user.username) }
|
||||||
|
dt { "Role" } dd { span.tag { (user.role.as_str()) } }
|
||||||
|
dt { "ID" } dd.muted { (user.id) }
|
||||||
|
}
|
||||||
|
form.stack method="post" action="/settings" {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Display name" input name="display_name" required maxlength="100" value=(user.display_name); }
|
||||||
|
button.primary type="submit" { "Save" }
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
(super::panel("Password", html! {
|
||||||
|
form.stack method="post" action="/settings/password" {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
@if has_password {
|
||||||
|
label { "Current password" input type="password" name="current" required autocomplete="current-password"; }
|
||||||
|
} @else {
|
||||||
|
p.muted { "This account has no password yet." }
|
||||||
|
input type="hidden" name="current" value="";
|
||||||
|
}
|
||||||
|
label { "New password" input type="password" name="new" required minlength=(forge_id::password::MIN_LENGTH) autocomplete="new-password"; }
|
||||||
|
label { "Confirm" input type="password" name="confirm" required autocomplete="new-password"; }
|
||||||
|
button.primary type="submit" { "Change password" }
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn profile(State(state): State<AppState>, viewer: Viewer, Query(done): Query<Done>) -> Response {
|
||||||
|
profile_page(&state, &viewer, done.notice()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ProfileForm {
|
||||||
|
csrf: String,
|
||||||
|
display_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn save_profile(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<ProfileForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
match users::set_display_name(state.pool(), viewer.id(), &form.display_name).await {
|
||||||
|
Ok(()) => done("/settings", "saved"),
|
||||||
|
Err(AccountError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => profile_page(&state, &viewer, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct PasswordForm {
|
||||||
|
csrf: String,
|
||||||
|
current: String,
|
||||||
|
new: String,
|
||||||
|
confirm: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn change_password(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<PasswordForm>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
if form.new != form.confirm {
|
||||||
|
return profile_page(&state, &viewer, Notice::err("The new passwords do not match.")).await;
|
||||||
|
}
|
||||||
|
match users::change_password(state.pool(), viewer.id(), &form.current, &form.new, &viewer.session.id).await {
|
||||||
|
Ok(()) => done("/settings", "password"),
|
||||||
|
Err(AccountError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => profile_page(&state, &viewer, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sessions ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub async fn sessions_page(State(state): State<AppState>, viewer: Viewer, Query(done): Query<Done>) -> Response {
|
||||||
|
let pool = state.pool();
|
||||||
|
let (browsers, logins) = match tokio::try_join!(sessions::list(pool, viewer.id()), sessions::cli_logins(pool, viewer.id())) {
|
||||||
|
Ok(found) => found,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
layout(&viewer, Section::Sessions, "Sessions", done.notice(), html! {
|
||||||
|
(super::panel("Browser sessions", html! {
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Browser" } th { "Via" } th { "Signed in" } th { "Last seen" } th {} } }
|
||||||
|
tbody {
|
||||||
|
@for s in &browsers {
|
||||||
|
tr {
|
||||||
|
td { (browser(&s.user_agent)) }
|
||||||
|
td { span.tag.dim { (s.auth_method) } }
|
||||||
|
td.muted { (date(s.created_at)) }
|
||||||
|
td { (ago(s.last_seen_at)) }
|
||||||
|
td.act {
|
||||||
|
@if s.id == viewer.session.id {
|
||||||
|
span.tag.green { "this one" }
|
||||||
|
} @else {
|
||||||
|
form method="post" action={ "/settings/sessions/" (s.id) "/revoke" } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
button.small.danger type="submit" { "Sign out" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if browsers.len() > 1 {
|
||||||
|
form method="post" action="/settings/sessions/revoke-others" {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
button.danger type="submit" { "Sign out all others" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
(super::panel("Lore CLI logins", html! {
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Client" } th { "Started" } th { "Last used" } th { "Ends" } th {} } }
|
||||||
|
tbody {
|
||||||
|
@for l in &logins {
|
||||||
|
tr {
|
||||||
|
td { (if l.description.is_empty() { "lore" } else { &l.description }) }
|
||||||
|
td.muted { (date(l.created_at)) }
|
||||||
|
td { (ago(l.last_used_at)) }
|
||||||
|
td.muted { (date(l.expires_at)) }
|
||||||
|
td.act {
|
||||||
|
form method="post" action={ "/settings/logins/" (l.id) "/revoke" } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
button.small.danger type="submit" { "Sign out" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if logins.is_empty() { tr.empty { td colspan="5" { "None. " code { "lore auth login" } " adds one." } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.muted { "A signed-out client loses repository access within five minutes." }
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn revoke_session(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
match sessions::revoke(state.pool(), viewer.id(), &id).await {
|
||||||
|
Ok(_) => done("/settings/sessions", "revoked"),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn revoke_other_sessions(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
match sessions::revoke_others(state.pool(), viewer.id(), &viewer.session.id).await {
|
||||||
|
Ok(_) => done("/settings/sessions", "ended"),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn revoke_login(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
match sessions::revoke_cli_login(state.pool(), viewer.id(), &id).await {
|
||||||
|
Ok(_) => done("/settings/sessions", "revoked"),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Providers ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub async fn providers_page(state: &AppState, viewer: &Viewer, notice: Notice) -> Response {
|
||||||
|
let oauth = state.oauth();
|
||||||
|
let (enabled, linked) = match tokio::try_join!(oauth.enabled(), oauth.linked(viewer.id())) {
|
||||||
|
Ok(found) => found,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
layout(viewer, Section::Providers, "Sign-in providers", notice, html! {
|
||||||
|
(super::panel("Sign-in providers", html! {
|
||||||
|
p.muted { "A linked account signs you in to this one. Accounts are matched only by this link, never by email." }
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Provider" } th { "Account" } th { "Linked" } th { "Last used" } th {} } }
|
||||||
|
tbody {
|
||||||
|
@for provider in Provider::ALL {
|
||||||
|
@let link = linked.iter().find(|l| l.provider == provider);
|
||||||
|
@if link.is_some() || enabled.contains(&provider) {
|
||||||
|
tr {
|
||||||
|
td { (provider.label()) }
|
||||||
|
@if let Some(link) = link {
|
||||||
|
td { (link.username) }
|
||||||
|
td.muted { (date(link.created_at)) }
|
||||||
|
td { (ago(link.last_used_at)) }
|
||||||
|
td.act {
|
||||||
|
form method="post" action={ "/settings/providers/" (provider.as_str()) "/unlink" } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
button.small.danger type="submit" { "Unlink" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
td.muted colspan="3" { "not linked" }
|
||||||
|
td.act {
|
||||||
|
form method="post" action={ "/settings/providers/" (provider.as_str()) "/link" } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
button.small.primary type="submit" { "Link" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if enabled.is_empty() && linked.is_empty() {
|
||||||
|
tr.empty { td colspan="5" { "No providers are set up on this instance." } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn providers(State(state): State<AppState>, viewer: Viewer, Query(done): Query<Done>) -> Response {
|
||||||
|
providers_page(&state, &viewer, done.notice()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn link_provider(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(provider): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let Some(provider) = Provider::parse(&provider) else {
|
||||||
|
return super::not_found_page(Some(&viewer));
|
||||||
|
};
|
||||||
|
let redirect_uri = super::auth::callback_url(&state, provider);
|
||||||
|
let started = state
|
||||||
|
.oauth()
|
||||||
|
.start(provider, Intent::Link, Some(viewer.id()), Some(&viewer.session.id), "/settings/providers", false, &redirect_uri)
|
||||||
|
.await;
|
||||||
|
match started {
|
||||||
|
Ok(url) => Redirect::to(&url).into_response(),
|
||||||
|
Err(error) => providers_page(&state, &viewer, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn unlink_provider(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(provider): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let Some(provider) = Provider::parse(&provider) else {
|
||||||
|
return super::not_found_page(Some(&viewer));
|
||||||
|
};
|
||||||
|
match state.oauth().unlink(viewer.id(), provider).await {
|
||||||
|
Ok(()) => done("/settings/providers", "unlinked"),
|
||||||
|
Err(forge_id::oauth::OAuthError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => providers_page(&state, &viewer, Notice::err(error)).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// API tokens --------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// The token table and the form for a new one, shared with service accounts.
|
||||||
|
pub fn token_section(
|
||||||
|
viewer: &Viewer,
|
||||||
|
tokens: &[api_tokens::ApiToken],
|
||||||
|
action: &str,
|
||||||
|
scopes: &[Scope],
|
||||||
|
new_secret: Option<&str>,
|
||||||
|
) -> Markup {
|
||||||
|
html! {
|
||||||
|
@if let Some(secret) = new_secret {
|
||||||
|
p.notice.info { "Copy the token now. It is not shown again." }
|
||||||
|
code.secret { (secret) }
|
||||||
|
}
|
||||||
|
table.list {
|
||||||
|
thead { tr { th { "Name" } th { "Scopes" } th { "Created" } th { "Expires" } th { "Last used" } th {} } }
|
||||||
|
tbody {
|
||||||
|
@for t in tokens {
|
||||||
|
tr {
|
||||||
|
td { (t.name) }
|
||||||
|
td { @for scope in t.scopes.split(' ') { span.tag.dim { (scope) } } }
|
||||||
|
td.muted { (date(t.created_at)) }
|
||||||
|
td.muted { @if let Some(at) = t.expires_at { (date(at)) } @else { "never" } }
|
||||||
|
td { @if let Some(at) = t.last_used_at { (ago(at)) } @else { span.muted { "never" } } }
|
||||||
|
td.act {
|
||||||
|
form method="post" action={ (action) "/" (t.id) "/revoke" } {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
button.small.danger type="submit" { "Revoke" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if tokens.is_empty() { tr.empty { td colspan="6" { "No tokens." } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
form.row method="post" action=(action) {
|
||||||
|
(viewer.csrf_field())
|
||||||
|
label { "Name" input name="name" required maxlength="100" placeholder="build agent"; }
|
||||||
|
@if scopes.len() > 1 {
|
||||||
|
@for scope in scopes {
|
||||||
|
label.check { input type="checkbox" name="scope" value=(scope.as_str()) checked[*scope == Scope::Lore]; (scope.as_str()) }
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
@for scope in scopes { input type="hidden" name="scope" value=(scope.as_str()); }
|
||||||
|
}
|
||||||
|
label { "Expires"
|
||||||
|
select name="days" {
|
||||||
|
option value="30" { "30 days" }
|
||||||
|
option value="90" selected { "90 days" }
|
||||||
|
option value="365" { "1 year" }
|
||||||
|
option value="0" { "never" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
button.primary type="submit" { "Create token" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn tokens_page(state: &AppState, viewer: &Viewer, notice: Notice, new_secret: Option<&str>) -> Response {
|
||||||
|
let tokens = match api_tokens::list(state.pool(), viewer.id()).await {
|
||||||
|
Ok(tokens) => tokens,
|
||||||
|
Err(error) => return server_error(error),
|
||||||
|
};
|
||||||
|
let remote = super::lore_remote(state);
|
||||||
|
layout(viewer, Section::Tokens, "API tokens", notice, html! {
|
||||||
|
(super::panel("API tokens", html! {
|
||||||
|
(token_section(viewer, &tokens, "/settings/tokens", &Scope::ALL, new_secret))
|
||||||
|
p.muted { span.tag.dim { "lore" } " signs the Lore CLI in without a browser. " span.tag.dim { "api" } " reads the JSON API under /api/v1." }
|
||||||
|
pre { code { "LORE_TOKEN=<token> lore auth login --token-type api-key " (remote) } }
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn tokens(State(state): State<AppState>, viewer: Viewer, Query(done): Query<Done>) -> Response {
|
||||||
|
tokens_page(&state, &viewer, done.notice(), None).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A form with repeated fields, which `axum::Form` cannot read into a struct.
|
||||||
|
pub struct Pairs(pub Vec<(String, String)>);
|
||||||
|
|
||||||
|
impl Pairs {
|
||||||
|
pub fn parse(body: &[u8]) -> Pairs {
|
||||||
|
Pairs(url::form_urlencoded::parse(body).into_owned().collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, key: &str) -> &str {
|
||||||
|
self.0.iter().find(|(k, _)| k == key).map_or("", |(_, v)| v.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn all(&self, key: &str) -> Vec<&str> {
|
||||||
|
self.0.iter().filter(|(k, _)| k == key).map(|(_, v)| v.as_str()).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a new-token form: name, scopes and lifetime in days (0 for none).
|
||||||
|
pub fn token_request(form: &Pairs) -> (String, Vec<Scope>, Option<i64>) {
|
||||||
|
let scopes = form.all("scope").into_iter().filter_map(Scope::parse).collect();
|
||||||
|
let days = form.get("days").parse::<i64>().ok().filter(|d| (1..=3650).contains(d));
|
||||||
|
(form.get("name").to_owned(), scopes, days)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_token(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
headers: HeaderMap,
|
||||||
|
body: axum::body::Bytes,
|
||||||
|
) -> Response {
|
||||||
|
let form = Pairs::parse(&body);
|
||||||
|
if let Err(refused) = csrf(&state, &headers, form.get("csrf")) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
let (name, scopes, days) = token_request(&form);
|
||||||
|
match api_tokens::create(state.pool(), viewer.id(), &name, &scopes, days, viewer.id()).await {
|
||||||
|
// Shown once, on this response: a redirect would have to carry the secret.
|
||||||
|
Ok(new) => tokens_page(&state, &viewer, Notice::Ok("Token created."), Some(&new.secret)).await,
|
||||||
|
Err(api_tokens::TokenError::Database(error)) => server_error(error),
|
||||||
|
Err(error) => tokens_page(&state, &viewer, Notice::err(error), None).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn revoke_token(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
viewer: Viewer,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Form(form): Form<CsrfOnly>,
|
||||||
|
) -> Response {
|
||||||
|
if let Err(refused) = csrf(&state, &headers, &form.csrf) {
|
||||||
|
return refused;
|
||||||
|
}
|
||||||
|
match api_tokens::revoke(state.pool(), viewer.id(), &id, viewer.id()).await {
|
||||||
|
Ok(_) => done("/settings/tokens", "revoked"),
|
||||||
|
Err(error) => server_error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,143 @@
|
||||||
|
//! Cookies, sessions, CSRF protection and security headers.
|
||||||
|
|
||||||
|
use axum::extract::FromRequestParts;
|
||||||
|
use axum::extract::Request;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::http::HeaderValue;
|
||||||
|
use axum::http::header;
|
||||||
|
use axum::http::request::Parts;
|
||||||
|
use axum::middleware::Next;
|
||||||
|
use axum::response::Response;
|
||||||
|
use forge_id::crypto;
|
||||||
|
use forge_id::sessions;
|
||||||
|
use forge_id::sessions::Session;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
const CSP: &str = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; \
|
||||||
|
form-action 'self'; frame-ancestors 'none'; base-uri 'none'";
|
||||||
|
|
||||||
|
/// Security headers for every response.
|
||||||
|
pub async fn headers(request: Request, next: Next) -> Response {
|
||||||
|
let mut response = next.run(request).await;
|
||||||
|
let headers = response.headers_mut();
|
||||||
|
headers.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(CSP));
|
||||||
|
headers.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
|
||||||
|
headers.insert(header::REFERRER_POLICY, HeaderValue::from_static("same-origin"));
|
||||||
|
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cookie names. On https the `__Host-` prefix pins cookies to this exact host and path, so a
|
||||||
|
/// sibling subdomain cannot plant or overwrite them.
|
||||||
|
fn cookie_name(state: &AppState, base: &str) -> String {
|
||||||
|
if state.inner.secure_cookies { format!("__Host-{base}") } else { base.to_owned() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn session_cookie_name(state: &AppState) -> String {
|
||||||
|
cookie_name(state, "lf_session")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn csrf_cookie_name(state: &AppState) -> String {
|
||||||
|
cookie_name(state, "lf_csrf")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value of cookie `name` in a request.
|
||||||
|
pub fn read_cookie(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||||
|
headers
|
||||||
|
.get_all(header::COOKIE)
|
||||||
|
.iter()
|
||||||
|
.filter_map(|value| value.to_str().ok())
|
||||||
|
.flat_map(|value| value.split(';'))
|
||||||
|
.filter_map(|pair| pair.trim().split_once('='))
|
||||||
|
.find(|(key, _)| *key == name)
|
||||||
|
.map(|(_, value)| value.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `Set-Cookie` value. `max_age` of `None` makes a cookie that ends with the browser
|
||||||
|
/// session; `Some(0)` clears it.
|
||||||
|
pub fn set_cookie(state: &AppState, name: &str, value: &str, max_age: Option<i64>) -> HeaderValue {
|
||||||
|
let mut cookie = format!("{name}={value}; Path=/; HttpOnly; SameSite=Lax");
|
||||||
|
if state.inner.secure_cookies {
|
||||||
|
cookie.push_str("; Secure");
|
||||||
|
}
|
||||||
|
if let Some(seconds) = max_age {
|
||||||
|
cookie.push_str(&format!("; Max-Age={seconds}"));
|
||||||
|
}
|
||||||
|
HeaderValue::from_str(&cookie).expect("cookie values are base64url")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The CSRF token for this browser, to embed in forms.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct CsrfToken(pub String);
|
||||||
|
|
||||||
|
/// Ensures every browser has a CSRF cookie and hands its value to handlers. Forms embed the
|
||||||
|
/// value; [`check_csrf`] compares the two (the double-submit pattern), and also checks
|
||||||
|
/// `Origin`.
|
||||||
|
pub async fn csrf_cookie(State(state): State<AppState>, mut request: Request, next: Next) -> Response {
|
||||||
|
let name = csrf_cookie_name(&state);
|
||||||
|
let existing = read_cookie(request.headers(), &name)
|
||||||
|
.filter(|value| value.len() >= 32 && value.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'));
|
||||||
|
let (token, fresh) = match existing {
|
||||||
|
Some(token) => (token, false),
|
||||||
|
None => (crypto::random_token(), true),
|
||||||
|
};
|
||||||
|
request.extensions_mut().insert(CsrfToken(token.clone()));
|
||||||
|
let mut response = next.run(request).await;
|
||||||
|
if fresh {
|
||||||
|
response.headers_mut().append(header::SET_COOKIE, set_cookie(&state, &name, &token, None));
|
||||||
|
}
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why an unsafe request was refused.
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub enum CsrfRejected {
|
||||||
|
/// The browser says the form came from another origin. Usually lore-forge was opened at
|
||||||
|
/// an address other than its public URL, such as `127.0.0.1` for `localhost`.
|
||||||
|
WrongOrigin,
|
||||||
|
/// The form's token is missing, stale, or does not match the cookie.
|
||||||
|
BadToken,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks an unsafe request: the form's token must equal the cookie's, and a present
|
||||||
|
/// `Origin` must be the canonical origin.
|
||||||
|
pub fn check_csrf(state: &AppState, headers: &HeaderMap, submitted: &str) -> Result<(), CsrfRejected> {
|
||||||
|
if let Some(origin) = headers.get(header::ORIGIN)
|
||||||
|
&& origin.to_str().ok() != Some(state.inner.public_origin.as_str())
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
origin = ?origin,
|
||||||
|
expected = %state.inner.public_origin,
|
||||||
|
"refused a form post from another origin",
|
||||||
|
);
|
||||||
|
return Err(CsrfRejected::WrongOrigin);
|
||||||
|
}
|
||||||
|
let cookie = read_cookie(headers, &csrf_cookie_name(state)).ok_or(CsrfRejected::BadToken)?;
|
||||||
|
if crypto::constant_time_eq(cookie.as_bytes(), submitted.as_bytes()) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(CsrfRejected::BadToken)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The signed-in user's session, if any.
|
||||||
|
pub struct MaybeSession(pub Option<Session>);
|
||||||
|
|
||||||
|
impl FromRequestParts<AppState> for MaybeSession {
|
||||||
|
type Rejection = std::convert::Infallible;
|
||||||
|
|
||||||
|
async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Self::Rejection> {
|
||||||
|
let Some(token) = read_cookie(&parts.headers, &session_cookie_name(state)) else {
|
||||||
|
return Ok(MaybeSession(None));
|
||||||
|
};
|
||||||
|
match sessions::lookup(state.pool(), &token).await {
|
||||||
|
Ok(session) => Ok(MaybeSession(session)),
|
||||||
|
Err(error) => {
|
||||||
|
tracing::error!("session lookup failed: {error}");
|
||||||
|
Ok(MaybeSession(None))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,641 @@
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Router;
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::http::Request;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::http::header;
|
||||||
|
use forge_id::Issuer;
|
||||||
|
use forge_id::IssuerConfig;
|
||||||
|
use forge_id::crypto::SecretKey;
|
||||||
|
use forge_id::keys::Keys;
|
||||||
|
use tower::ServiceExt;
|
||||||
|
|
||||||
|
const ORIGIN: &str = "http://forge.test:8080";
|
||||||
|
|
||||||
|
struct App {
|
||||||
|
router: Router,
|
||||||
|
store: forge_store::testing::TestStore,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn app() -> App {
|
||||||
|
app_with(None).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An app whose sign-in providers live under `provider_base`, reading the fake loreserver.
|
||||||
|
async fn app_with(provider_base: Option<&str>) -> App {
|
||||||
|
let (grpc, content) = crate::fake_lore::start("author-id").await;
|
||||||
|
build(provider_base, forge_lore::reader::Lore::new(&grpc, &content).unwrap()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn build(provider_base: Option<&str>, lore: forge_lore::reader::Lore) -> App {
|
||||||
|
let store = forge_store::testing::store().await;
|
||||||
|
let pool = store.pool().clone();
|
||||||
|
let secret = SecretKey::from_base64(&SecretKey::generate_base64()).unwrap();
|
||||||
|
let keys = Arc::new(Keys::load_or_create(pool.clone(), secret.clone()).await.unwrap());
|
||||||
|
let config = IssuerConfig::new(
|
||||||
|
&ORIGIN.parse().unwrap(),
|
||||||
|
&"http://lore.test:41337".parse().unwrap(),
|
||||||
|
"lore-cli",
|
||||||
|
);
|
||||||
|
let issuer = Arc::new(Issuer::new(pool.clone(), keys, config));
|
||||||
|
let mut oauth = forge_id::oauth::OAuth::new(pool.clone(), secret);
|
||||||
|
if let Some(base) = provider_base {
|
||||||
|
oauth = oauth.with_test_base(base);
|
||||||
|
}
|
||||||
|
App { router: super::router(super::AppState::new(pool, issuer, oauth, lore)), store }
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Reply {
|
||||||
|
status: StatusCode,
|
||||||
|
headers: axum::http::HeaderMap,
|
||||||
|
body: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Reply {
|
||||||
|
fn json(&self) -> serde_json::Value {
|
||||||
|
serde_json::from_str(&self.body).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value of a cookie this response sets.
|
||||||
|
fn cookie(&self, name: &str) -> Option<String> {
|
||||||
|
self.headers
|
||||||
|
.get_all(header::SET_COOKIE)
|
||||||
|
.iter()
|
||||||
|
.filter_map(|value| value.to_str().ok())
|
||||||
|
.find_map(|value| value.strip_prefix(&format!("{name}=")))
|
||||||
|
.map(|rest| rest.split(';').next().unwrap().to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn location(&self) -> &str {
|
||||||
|
self.headers.get(header::LOCATION).unwrap().to_str().unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl App {
|
||||||
|
async fn send(&self, request: Request<Body>) -> Reply {
|
||||||
|
let response = self.router.clone().oneshot(request).await.unwrap();
|
||||||
|
let status = response.status();
|
||||||
|
let headers = response.headers().clone();
|
||||||
|
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
|
Reply { status, headers, body: String::from_utf8_lossy(&bytes).into_owned() }
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get(&self, path: &str, cookies: &str) -> Reply {
|
||||||
|
self.send(Request::get(path).header(header::COOKIE, cookies).body(Body::empty()).unwrap()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn post_form(&self, path: &str, cookies: &str, pairs: &[(&str, &str)]) -> Reply {
|
||||||
|
let body = url::form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish();
|
||||||
|
self.send(
|
||||||
|
Request::post(path)
|
||||||
|
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
||||||
|
.header(header::COOKIE, cookies)
|
||||||
|
.header(header::ORIGIN, ORIGIN)
|
||||||
|
.body(Body::from(body))
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs first-run setup and returns the browser's cookies.
|
||||||
|
async fn set_up(&self) -> String {
|
||||||
|
let csrf = self.get("/setup", "").await.cookie("lf_csrf").unwrap();
|
||||||
|
let cookies = format!("lf_csrf={csrf}");
|
||||||
|
let reply = self
|
||||||
|
.post_form("/setup", &cookies, &[
|
||||||
|
("csrf", &csrf),
|
||||||
|
("username", "alice"),
|
||||||
|
("display_name", "Alice"),
|
||||||
|
("password", "a long password"),
|
||||||
|
("password_confirm", "a long password"),
|
||||||
|
])
|
||||||
|
.await;
|
||||||
|
assert_eq!(reply.status, StatusCode::SEE_OTHER, "{}", reply.body);
|
||||||
|
let session = reply.cookie("lf_session").unwrap();
|
||||||
|
format!("lf_csrf={csrf}; lf_session={session}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn csrf_of(cookies: &str) -> String {
|
||||||
|
cookies.split("; ").find_map(|c| c.strip_prefix("lf_csrf=")).unwrap().to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn discovery_and_jwks() {
|
||||||
|
let app = app().await;
|
||||||
|
let discovery = app.get("/.well-known/openid-configuration", "").await;
|
||||||
|
assert_eq!(discovery.status, StatusCode::OK);
|
||||||
|
let document = discovery.json();
|
||||||
|
assert_eq!(document["issuer"], ORIGIN);
|
||||||
|
assert_eq!(document["token_endpoint"], format!("{ORIGIN}/oauth/token"));
|
||||||
|
assert_eq!(document["device_authorization_endpoint"], format!("{ORIGIN}/oauth/device_authorization"));
|
||||||
|
let jwks = app.get("/oauth/jwks", "").await.json();
|
||||||
|
assert_eq!(jwks["keys"][0]["alg"], "ES256");
|
||||||
|
assert_eq!(jwks["keys"][0]["kty"], "EC");
|
||||||
|
assert!(discovery.headers.get(header::CONTENT_SECURITY_POLICY).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn first_run_goes_to_setup_and_setup_closes() {
|
||||||
|
let app = app().await;
|
||||||
|
assert_eq!(app.get("/", "").await.location(), "/setup");
|
||||||
|
let cookies = app.set_up().await;
|
||||||
|
let home = app.get("/", &cookies).await;
|
||||||
|
assert_eq!(home.status, StatusCode::OK);
|
||||||
|
assert!(home.body.contains("Your repositories"));
|
||||||
|
assert!(!home.body.contains("<script"), "pages carry no inline script");
|
||||||
|
assert_eq!(app.get("/setup", "").await.location(), "/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn forms_refuse_missing_tokens_and_foreign_origins() {
|
||||||
|
let app = app().await;
|
||||||
|
app.set_up().await;
|
||||||
|
let csrf = app.get("/login", "").await.cookie("lf_csrf").unwrap();
|
||||||
|
let pairs = [("csrf", csrf.as_str()), ("username", "alice"), ("password", "a long password")];
|
||||||
|
|
||||||
|
let no_cookie = app.post_form("/login", "", &pairs).await;
|
||||||
|
assert_eq!(no_cookie.status, StatusCode::FORBIDDEN);
|
||||||
|
assert!(no_cookie.body.contains("The form had expired"), "{}", no_cookie.body);
|
||||||
|
|
||||||
|
let body = url::form_urlencoded::Serializer::new(String::new()).extend_pairs(pairs).finish();
|
||||||
|
let foreign = app
|
||||||
|
.send(
|
||||||
|
Request::post("/login")
|
||||||
|
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
|
||||||
|
.header(header::COOKIE, format!("lf_csrf={csrf}"))
|
||||||
|
.header(header::ORIGIN, "https://evil.example")
|
||||||
|
.body(Body::from(body))
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(foreign.status, StatusCode::FORBIDDEN);
|
||||||
|
// The refusal names the address to use, since the usual cause is opening lore-forge at
|
||||||
|
// another address for the same machine.
|
||||||
|
assert!(foreign.body.contains("Wrong address"), "{}", foreign.body);
|
||||||
|
assert!(foreign.body.contains(&format!("href=\"{ORIGIN}\"")), "{}", foreign.body);
|
||||||
|
|
||||||
|
let ok = app.post_form("/login", &format!("lf_csrf={csrf}"), &pairs).await;
|
||||||
|
assert_eq!(ok.status, StatusCode::SEE_OTHER);
|
||||||
|
assert!(ok.cookie("lf_session").is_some());
|
||||||
|
|
||||||
|
let wrong = app
|
||||||
|
.post_form("/login", &format!("lf_csrf={csrf}"), &[("csrf", &csrf), ("username", "alice"), ("password", "nope")])
|
||||||
|
.await;
|
||||||
|
assert_eq!(wrong.status, StatusCode::UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn sign_in_redirects_only_to_local_paths() {
|
||||||
|
let app = app().await;
|
||||||
|
app.set_up().await;
|
||||||
|
let csrf = app.get("/login", "").await.cookie("lf_csrf").unwrap();
|
||||||
|
let cookies = format!("lf_csrf={csrf}");
|
||||||
|
for (next, expected) in [("/device?user_code=X", "/device?user_code=X"), ("//evil.example", "/"), ("https://evil.example", "/")] {
|
||||||
|
let reply = app
|
||||||
|
.post_form("/login", &cookies, &[
|
||||||
|
("csrf", &csrf),
|
||||||
|
("username", "alice"),
|
||||||
|
("password", "a long password"),
|
||||||
|
("next", next),
|
||||||
|
])
|
||||||
|
.await;
|
||||||
|
assert_eq!(reply.location(), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn cli_login_through_the_device_page() {
|
||||||
|
let app = app().await;
|
||||||
|
let cookies = app.set_up().await;
|
||||||
|
let csrf = csrf_of(&cookies);
|
||||||
|
|
||||||
|
let start = app.post_form("/oauth/device_authorization", "", &[("client_id", "lore-cli"), ("scope", "openid offline_access")]).await;
|
||||||
|
assert_eq!(start.status, StatusCode::OK, "{}", start.body);
|
||||||
|
assert_eq!(start.headers.get(header::CACHE_CONTROL).unwrap(), "no-store");
|
||||||
|
let start = start.json();
|
||||||
|
let user_code = start["user_code"].as_str().unwrap();
|
||||||
|
let device_code = start["device_code"].as_str().unwrap();
|
||||||
|
let complete = start["verification_uri_complete"].as_str().unwrap();
|
||||||
|
let path = complete.strip_prefix(ORIGIN).unwrap();
|
||||||
|
|
||||||
|
// Signed out, the page sends the person to sign in and back.
|
||||||
|
let signed_out = app.get(path, "").await;
|
||||||
|
assert!(signed_out.location().starts_with("/login?next=%2Fdevice%3Fuser_code%3D"));
|
||||||
|
|
||||||
|
let page = app.get(path, &cookies).await;
|
||||||
|
assert_eq!(page.status, StatusCode::OK);
|
||||||
|
assert!(page.body.contains(user_code));
|
||||||
|
|
||||||
|
let poll = [("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), ("device_code", device_code), ("client_id", "lore-cli")];
|
||||||
|
let pending = app.post_form("/oauth/token", "", &poll).await;
|
||||||
|
assert_eq!(pending.status, StatusCode::BAD_REQUEST);
|
||||||
|
assert_eq!(pending.json()["error"], "authorization_pending");
|
||||||
|
|
||||||
|
let approved = app
|
||||||
|
.post_form("/device", &cookies, &[("csrf", &csrf), ("user_code", user_code), ("decision", "approve")])
|
||||||
|
.await;
|
||||||
|
assert!(approved.body.contains("Client signed in"), "{}", approved.body);
|
||||||
|
|
||||||
|
let tokens = app.post_form("/oauth/token", "", &poll).await;
|
||||||
|
assert_eq!(tokens.status, StatusCode::OK, "{}", tokens.body);
|
||||||
|
let tokens = tokens.json();
|
||||||
|
assert_eq!(tokens["token_type"], "Bearer");
|
||||||
|
assert!(tokens["refresh_token"].is_string());
|
||||||
|
|
||||||
|
let revoked = app
|
||||||
|
.post_form("/oauth/revoke", "", &[("token", tokens["refresh_token"].as_str().unwrap()), ("client_id", "lore-cli")])
|
||||||
|
.await;
|
||||||
|
assert_eq!(revoked.status, StatusCode::OK);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn token_endpoint_wants_form_bodies() {
|
||||||
|
let app = app().await;
|
||||||
|
let reply = app
|
||||||
|
.send(
|
||||||
|
Request::post("/oauth/token")
|
||||||
|
.header(header::CONTENT_TYPE, "application/json")
|
||||||
|
.body(Body::from("{}"))
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(reply.status, StatusCode::BAD_REQUEST);
|
||||||
|
assert_eq!(reply.json()["error"], "invalid_request");
|
||||||
|
let unsupported = app.post_form("/oauth/token", "", &[("grant_type", "password")]).await;
|
||||||
|
assert_eq!(unsupported.json()["error"], "unsupported_grant_type");
|
||||||
|
}
|
||||||
|
|
||||||
|
impl App {
|
||||||
|
fn pool(&self) -> &forge_store::SqlitePool {
|
||||||
|
self.store.pool()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signs `username` in with a password and returns the browser's cookies.
|
||||||
|
async fn sign_in(&self, username: &str, password: &str) -> String {
|
||||||
|
let csrf = self.get("/login", "").await.cookie("lf_csrf").unwrap();
|
||||||
|
let reply = self
|
||||||
|
.post_form("/login", &format!("lf_csrf={csrf}"), &[("csrf", &csrf), ("username", username), ("password", password)])
|
||||||
|
.await;
|
||||||
|
assert_eq!(reply.status, StatusCode::SEE_OTHER, "{}", reply.body);
|
||||||
|
format!("lf_csrf={csrf}; lf_session={}", reply.cookie("lf_session").unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Posts a form as the browser with `cookies`, adding its CSRF token.
|
||||||
|
async fn post(&self, path: &str, cookies: &str, pairs: &[(&str, &str)]) -> Reply {
|
||||||
|
let csrf = csrf_of(cookies);
|
||||||
|
let mut all = vec![("csrf", csrf.as_str())];
|
||||||
|
all.extend_from_slice(pairs);
|
||||||
|
self.post_form(path, cookies, &all).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_user(&self, owner: &str, username: &str) {
|
||||||
|
let reply = self
|
||||||
|
.post("/admin/users", owner, &[("username", username), ("display_name", username), ("password", "a long password")])
|
||||||
|
.await;
|
||||||
|
assert_eq!(reply.status, StatusCode::SEE_OTHER, "{}", reply.body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn every_page_renders_without_inline_script_or_style() {
|
||||||
|
let app = app().await;
|
||||||
|
let owner = app.set_up().await;
|
||||||
|
let reply = app.post("/orgs", &owner, &[("name", "studio"), ("display_name", "Studio")]).await;
|
||||||
|
assert_eq!(reply.location(), "/studio?ok=created");
|
||||||
|
forge_access::repos::register(app.pool(), &alice_id(&app).await, &crate::fake_lore::REPO, "studio/game").await.unwrap();
|
||||||
|
for path in [
|
||||||
|
"/", "/alice", "/studio", "/studio/game", "/studio/game/access", "/orgs", "/orgs/studio/members",
|
||||||
|
"/orgs/studio/teams", "/orgs/studio/settings", "/orgs/studio/service-accounts", "/settings",
|
||||||
|
"/settings/sessions", "/settings/providers", "/settings/tokens", "/settings/service-accounts", "/admin",
|
||||||
|
"/admin/invites", "/admin/repos", "/admin/audit", "/admin/settings", "/admin/providers", "/licenses", "/device",
|
||||||
|
] {
|
||||||
|
let reply = app.get(path, &owner).await;
|
||||||
|
assert_eq!(reply.status, StatusCode::OK, "{path}: {}", reply.body);
|
||||||
|
assert!(!reply.body.contains("<script"), "{path} has a script");
|
||||||
|
assert!(!reply.body.contains(" style="), "{path} has an inline style");
|
||||||
|
}
|
||||||
|
assert_eq!(app.get("/nobody", &owner).await.status, StatusCode::NOT_FOUND);
|
||||||
|
assert_eq!(app.get("/studio/nothing", &owner).await.status, StatusCode::NOT_FOUND);
|
||||||
|
let font = app.get("/static/vga-8x16.ttf", "").await;
|
||||||
|
assert_eq!(font.headers.get(header::CONTENT_TYPE).unwrap(), "font/ttf");
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn alice_id(app: &App) -> String {
|
||||||
|
forge_id::users::find_by_username(app.pool(), "alice").await.unwrap().unwrap().id
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn members_cannot_reach_admin_pages_or_others_repositories() {
|
||||||
|
let app = app().await;
|
||||||
|
let owner = app.set_up().await;
|
||||||
|
app.create_user(&owner, "bob").await;
|
||||||
|
forge_access::repos::register(app.pool(), &alice_id(&app).await, &[4; 16], "alice/secret").await.unwrap();
|
||||||
|
let bob = app.sign_in("bob", "a long password").await;
|
||||||
|
assert_eq!(app.get("/admin", &bob).await.status, StatusCode::FORBIDDEN);
|
||||||
|
assert_eq!(app.get("/admin/providers", &bob).await.status, StatusCode::FORBIDDEN);
|
||||||
|
// A repository bob cannot reach does not show it exists.
|
||||||
|
assert_eq!(app.get("/alice/secret", &bob).await.status, StatusCode::NOT_FOUND);
|
||||||
|
assert_eq!(app.get("/alice/secret/access", &bob).await.status, StatusCode::NOT_FOUND);
|
||||||
|
// Signed out, pages send people to sign in and back.
|
||||||
|
assert_eq!(app.get("/settings/tokens", "").await.location(), "/login?next=%2Fsettings%2Ftokens");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn invite_links_open_signup_a_limited_number_of_times() {
|
||||||
|
let app = app().await;
|
||||||
|
let owner = app.set_up().await;
|
||||||
|
let fresh = app.get("/signup", "").await;
|
||||||
|
assert_eq!(fresh.status, StatusCode::FORBIDDEN);
|
||||||
|
app.post("/admin/settings", &owner, &[("signup", "invite"), ("orgs", "admins")]).await;
|
||||||
|
app.post("/admin/invites", &owner, &[("name", "artists"), ("max_uses", "1")]).await;
|
||||||
|
let invite = forge_id::invites::list(app.pool()).await.unwrap().remove(0);
|
||||||
|
let path = format!("/signup/{}", invite.invite_key);
|
||||||
|
|
||||||
|
let csrf = app.get(&path, "").await.cookie("lf_csrf").unwrap();
|
||||||
|
let cookies = format!("lf_csrf={csrf}");
|
||||||
|
let form = |username: &'static str| {
|
||||||
|
vec![
|
||||||
|
("csrf", csrf.clone()),
|
||||||
|
("username", username.to_owned()),
|
||||||
|
("display_name", username.to_owned()),
|
||||||
|
("password", "a long password".to_owned()),
|
||||||
|
("password_confirm", "a long password".to_owned()),
|
||||||
|
]
|
||||||
|
};
|
||||||
|
let pairs: Vec<(&str, String)> = form("dana");
|
||||||
|
let pairs: Vec<(&str, &str)> = pairs.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||||
|
let made = app.post_form(&path, &cookies, &pairs).await;
|
||||||
|
assert_eq!(made.status, StatusCode::SEE_OTHER, "{}", made.body);
|
||||||
|
assert!(made.cookie("lf_session").is_some());
|
||||||
|
|
||||||
|
let pairs: Vec<(&str, String)> = form("erin");
|
||||||
|
let pairs: Vec<(&str, &str)> = pairs.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||||
|
let again = app.post_form(&path, &cookies, &pairs).await;
|
||||||
|
assert_eq!(again.status, StatusCode::FORBIDDEN);
|
||||||
|
assert!(forge_id::users::find_by_username(app.pool(), "erin").await.unwrap().is_none());
|
||||||
|
// Open signup needs the open mode.
|
||||||
|
assert_eq!(app.get("/signup", "").await.status, StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn organisation_teams_and_grants_reach_tokens() {
|
||||||
|
let app = app().await;
|
||||||
|
let owner = app.set_up().await;
|
||||||
|
app.create_user(&owner, "bob").await;
|
||||||
|
app.post("/orgs", &owner, &[("name", "studio"), ("display_name", "Studio")]).await;
|
||||||
|
let repo = forge_access::repos::register(app.pool(), &alice_id(&app).await, &crate::fake_lore::REPO, "studio/game").await.unwrap();
|
||||||
|
let bob_id = forge_id::users::find_by_username(app.pool(), "bob").await.unwrap().unwrap().id;
|
||||||
|
|
||||||
|
let added = app.post("/orgs/studio/members", &owner, &[("username", "bob"), ("role", "member")]).await;
|
||||||
|
assert_eq!(added.location(), "/orgs/studio/members?ok=added");
|
||||||
|
let team = app.post("/orgs/studio/teams", &owner, &[("name", "artists")]).await;
|
||||||
|
assert_eq!(team.location(), "/orgs/studio/teams/artists?ok=created");
|
||||||
|
app.post("/orgs/studio/teams/artists/members", &owner, &[("name", "bob")]).await;
|
||||||
|
assert!(forge_access::resolve(app.pool(), &bob_id, &repo.id).await.unwrap().is_empty());
|
||||||
|
|
||||||
|
let granted = app
|
||||||
|
.post("/studio/game/access", &owner, &[("kind", "team"), ("name", "artists"), ("preset", "writer"), ("extra", "presign")])
|
||||||
|
.await;
|
||||||
|
assert_eq!(granted.location(), "/studio/game/access?ok=saved");
|
||||||
|
let actions = forge_access::resolve(app.pool(), &bob_id, &repo.id).await.unwrap();
|
||||||
|
assert_eq!(actions.names(), ["read", "write", "presign"]);
|
||||||
|
|
||||||
|
// Bob can now see the repository, but not manage its access.
|
||||||
|
let bob = app.sign_in("bob", "a long password").await;
|
||||||
|
assert_eq!(app.get("/studio/game", &bob).await.status, StatusCode::OK);
|
||||||
|
assert_eq!(app.get("/studio/game/access", &bob).await.status, StatusCode::FORBIDDEN);
|
||||||
|
let refused = app.post("/studio/game/access", &bob, &[("kind", "user"), ("name", "bob"), ("preset", "owner")]).await;
|
||||||
|
assert_eq!(refused.status, StatusCode::FORBIDDEN);
|
||||||
|
|
||||||
|
// The last owner cannot leave or be demoted.
|
||||||
|
let alice = alice_id(&app).await;
|
||||||
|
let demote = app.post(&format!("/orgs/studio/members/{alice}"), &owner, &[("action", "member")]).await;
|
||||||
|
assert_eq!(demote.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert!(demote.body.contains("at least one owner"), "{}", demote.body);
|
||||||
|
|
||||||
|
// Removing the team's grant takes the access away again.
|
||||||
|
let team_id = forge_access::orgs::find(app.pool(), "studio").await.unwrap().unwrap();
|
||||||
|
let team_id = forge_access::orgs::find_team(app.pool(), &team_id.id, "artists").await.unwrap().unwrap().id;
|
||||||
|
let removed = app.post("/studio/game/access", &owner, &[("kind", "team"), ("id", &team_id), ("preset", "")]).await;
|
||||||
|
assert_eq!(removed.location(), "/studio/game/access?ok=removed");
|
||||||
|
assert!(forge_access::resolve(app.pool(), &bob_id, &repo.id).await.unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn api_tokens_are_shown_once_and_read_the_api() {
|
||||||
|
let app = app().await;
|
||||||
|
let owner = app.set_up().await;
|
||||||
|
let created = app.post("/settings/tokens", &owner, &[("name", "script"), ("scope", "api"), ("days", "30")]).await;
|
||||||
|
assert_eq!(created.status, StatusCode::OK, "{}", created.body);
|
||||||
|
let start = created.body.find("lf_").expect("the new token is shown");
|
||||||
|
let secret: String = created.body[start..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-').collect();
|
||||||
|
let listed = app.get("/settings/tokens", &owner).await;
|
||||||
|
assert!(!listed.body.contains(&secret), "the secret is shown only once");
|
||||||
|
|
||||||
|
let call = |token: String| {
|
||||||
|
Request::get("/api/v1/user").header(header::AUTHORIZATION, format!("Bearer {token}")).body(Body::empty()).unwrap()
|
||||||
|
};
|
||||||
|
let me = app.send(call(secret.clone())).await;
|
||||||
|
assert_eq!(me.status, StatusCode::OK, "{}", me.body);
|
||||||
|
assert_eq!(me.json()["username"], "alice");
|
||||||
|
assert_eq!(app.send(call("lf_wrong".into())).await.status, StatusCode::UNAUTHORIZED);
|
||||||
|
assert_eq!(app.get("/api/v1/repos", "").await.status, StatusCode::UNAUTHORIZED);
|
||||||
|
|
||||||
|
let id = forge_id::api_tokens::list(app.pool(), &alice_id(&app).await).await.unwrap().remove(0).id;
|
||||||
|
app.post(&format!("/settings/tokens/{id}/revoke"), &owner, &[]).await;
|
||||||
|
assert_eq!(app.send(call(secret)).await.status, StatusCode::UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn repeated_wrong_passwords_lock_sign_in_for_a_while() {
|
||||||
|
let app = app().await;
|
||||||
|
app.set_up().await;
|
||||||
|
let csrf = app.get("/login", "").await.cookie("lf_csrf").unwrap();
|
||||||
|
let cookies = format!("lf_csrf={csrf}");
|
||||||
|
for _ in 0..10 {
|
||||||
|
let wrong = app.post_form("/login", &cookies, &[("csrf", &csrf), ("username", "alice"), ("password", "wrong")]).await;
|
||||||
|
assert_eq!(wrong.status, StatusCode::UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
let right = app.post_form("/login", &cookies, &[("csrf", &csrf), ("username", "alice"), ("password", "a long password")]).await;
|
||||||
|
assert_eq!(right.status, StatusCode::UNAUTHORIZED);
|
||||||
|
assert!(right.body.contains("Too many failed attempts"), "{}", right.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn disabling_an_account_ends_its_sessions() {
|
||||||
|
let app = app().await;
|
||||||
|
let owner = app.set_up().await;
|
||||||
|
app.create_user(&owner, "bob").await;
|
||||||
|
let bob = app.sign_in("bob", "a long password").await;
|
||||||
|
let bob_id = forge_id::users::find_by_username(app.pool(), "bob").await.unwrap().unwrap().id;
|
||||||
|
let disabled = app.post(&format!("/admin/users/{bob_id}"), &owner, &[("action", "disable")]).await;
|
||||||
|
assert_eq!(disabled.location(), "/admin?ok=saved");
|
||||||
|
assert!(app.get("/settings", &bob).await.location().starts_with("/login"));
|
||||||
|
let csrf = app.get("/login", "").await.cookie("lf_csrf").unwrap();
|
||||||
|
let again = app
|
||||||
|
.post_form("/login", &format!("lf_csrf={csrf}"), &[("csrf", &csrf), ("username", "bob"), ("password", "a long password")])
|
||||||
|
.await;
|
||||||
|
assert_eq!(again.status, StatusCode::UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fake GitHub: the token endpoint, the user endpoint and token revocation.
|
||||||
|
async fn fake_github(subject: u64, login: &'static str) -> (String, tokio::task::JoinHandle<()>) {
|
||||||
|
use axum::routing::delete;
|
||||||
|
use axum::routing::get;
|
||||||
|
use axum::routing::post;
|
||||||
|
let router = axum::Router::new()
|
||||||
|
.route(
|
||||||
|
"/github/token",
|
||||||
|
post(|body: String| async move {
|
||||||
|
if body.contains("code=good") && body.contains("code_verifier=") && body.contains("client_secret=shh") {
|
||||||
|
axum::Json(serde_json::json!({ "access_token": "gho_fake", "token_type": "bearer" }))
|
||||||
|
} else {
|
||||||
|
axum::Json(serde_json::json!({ "error": "bad_verification_code" }))
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/github/user",
|
||||||
|
get(move |headers: axum::http::HeaderMap| async move {
|
||||||
|
assert_eq!(headers.get("authorization").unwrap(), "Bearer gho_fake");
|
||||||
|
axum::Json(serde_json::json!({ "id": subject, "login": login, "name": "Alice A" }))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.route("/github/applications/{client}/token", delete(|| async { StatusCode::NO_CONTENT }));
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||||
|
let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
|
||||||
|
(base, server)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `state` parameter of a provider authorisation URL.
|
||||||
|
fn state_of(location: &str) -> String {
|
||||||
|
let url = url::Url::parse(location).unwrap();
|
||||||
|
url.query_pairs().find(|(k, _)| k == "state").unwrap().1.into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn github_links_explicitly_then_signs_in() {
|
||||||
|
let (base, _server) = fake_github(4242, "alice-gh").await;
|
||||||
|
let app = app_with(Some(&base)).await;
|
||||||
|
let owner = app.set_up().await;
|
||||||
|
let saved = app.post("/admin/providers/github", &owner, &[("client_id", "cid"), ("client_secret", "shh"), ("enabled", "on")]).await;
|
||||||
|
assert_eq!(saved.location(), "/admin/providers?ok=saved");
|
||||||
|
assert!(app.get("/login", "").await.body.contains("Sign in with GitHub"));
|
||||||
|
|
||||||
|
// Signing in before linking finds no account: links are never made by matching.
|
||||||
|
let csrf = app.get("/login", "").await.cookie("lf_csrf").unwrap();
|
||||||
|
let anon = format!("lf_csrf={csrf}");
|
||||||
|
let start = app.post_form("/oauth/github/start", &anon, &[("csrf", &csrf), ("stay_signed_in", "on")]).await;
|
||||||
|
assert!(start.location().starts_with(&format!("{base}/github/authorize?")), "{}", start.location());
|
||||||
|
let state = state_of(start.location());
|
||||||
|
let unlinked = app.get(&format!("/oauth/github/callback?code=good&state={state}"), &anon).await;
|
||||||
|
assert_eq!(unlinked.status, StatusCode::UNAUTHORIZED);
|
||||||
|
assert!(unlinked.body.contains("No account is linked"), "{}", unlinked.body);
|
||||||
|
|
||||||
|
// Link from settings.
|
||||||
|
let link = app.post("/settings/providers/github/link", &owner, &[]).await;
|
||||||
|
let state = state_of(link.location());
|
||||||
|
// The flow is bound to the session that started it.
|
||||||
|
let elsewhere = app.get(&format!("/oauth/github/callback?code=good&state={state}"), &anon).await;
|
||||||
|
assert!(elsewhere.body.contains("another session"), "{}", elsewhere.body);
|
||||||
|
let link = app.post("/settings/providers/github/link", &owner, &[]).await;
|
||||||
|
let state = state_of(link.location());
|
||||||
|
let linked = app.get(&format!("/oauth/github/callback?code=good&state={state}"), &owner).await;
|
||||||
|
assert_eq!(linked.location(), "/settings/providers?ok=linked");
|
||||||
|
assert!(app.get("/settings/providers", &owner).await.body.contains("alice-gh"));
|
||||||
|
// A flow's state works once.
|
||||||
|
let replay = app.get(&format!("/oauth/github/callback?code=good&state={state}"), &owner).await;
|
||||||
|
assert!(replay.body.contains("expired or was already used"), "{}", replay.body);
|
||||||
|
|
||||||
|
// Now GitHub signs alice in.
|
||||||
|
let start = app.post_form("/oauth/github/start", &anon, &[("csrf", &csrf), ("stay_signed_in", "on")]).await;
|
||||||
|
let state = state_of(start.location());
|
||||||
|
let signed_in = app.get(&format!("/oauth/github/callback?code=good&state={state}"), &anon).await;
|
||||||
|
assert_eq!(signed_in.location(), "/");
|
||||||
|
let session = signed_in.cookie("lf_session").unwrap();
|
||||||
|
let home = app.get("/", &format!("{anon}; lf_session={session}")).await;
|
||||||
|
assert!(home.body.contains("Your repositories"));
|
||||||
|
|
||||||
|
// A refused code is reported, not a crash.
|
||||||
|
let start = app.post_form("/oauth/github/start", &anon, &[("csrf", &csrf)]).await;
|
||||||
|
let state = state_of(start.location());
|
||||||
|
let bad = app.get(&format!("/oauth/github/callback?code=bad&state={state}"), &anon).await;
|
||||||
|
assert!(bad.body.contains("bad_verification_code"), "{}", bad.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_browser_reads_files_history_and_diffs_as_the_viewer() {
|
||||||
|
use crate::fake_lore::R1;
|
||||||
|
use crate::fake_lore::R2;
|
||||||
|
use forge_lore::reader::hex;
|
||||||
|
|
||||||
|
let app = app().await;
|
||||||
|
let owner = app.set_up().await;
|
||||||
|
forge_access::repos::register(app.pool(), &alice_id(&app).await, &crate::fake_lore::REPO, "alice/game").await.unwrap();
|
||||||
|
let ok = |reply: &Reply, path: &str| {
|
||||||
|
assert_eq!(reply.status, StatusCode::OK, "{path}: {}", reply.body);
|
||||||
|
assert!(!reply.body.contains(" style="), "{path} has an inline style");
|
||||||
|
};
|
||||||
|
|
||||||
|
// FILES: the default branch first, whatever order the server lists branches in.
|
||||||
|
let root = app.get("/alice/game", &owner).await;
|
||||||
|
ok(&root, "root");
|
||||||
|
assert!(root.body.contains(">README.md<") && root.body.contains(">src<"), "{}", root.body);
|
||||||
|
assert!(root.body.contains("Edit the readme"), "attribution: {}", root.body);
|
||||||
|
assert!(root.body.contains("<option value=\"main\" selected>"), "{}", root.body);
|
||||||
|
let readme = app.get("/alice/game?path=README.md", &owner).await;
|
||||||
|
ok(&readme, "readme");
|
||||||
|
assert!(readme.body.contains("<td class=\"text\">world</td>"), "{}", readme.body);
|
||||||
|
let src = app.get("/alice/game?path=src", &owner).await;
|
||||||
|
assert!(src.body.contains(">main.rs<") && src.body.contains(">..<"), "{}", src.body);
|
||||||
|
let logo = app.get("/alice/game?b=feature&path=art%2Flogo.png", &owner).await;
|
||||||
|
ok(&logo, "logo");
|
||||||
|
assert!(logo.body.contains("Binary file"), "{}", logo.body);
|
||||||
|
// The first revision, before the readme changed.
|
||||||
|
let old = app.get(&format!("/alice/game?rev={}&path=README.md", hex(&R1)), &owner).await;
|
||||||
|
assert!(old.body.contains("hello") && !old.body.contains(">world<"), "{}", old.body);
|
||||||
|
assert_eq!(app.get("/alice/game?path=nothing", &owner).await.status, StatusCode::NOT_FOUND);
|
||||||
|
assert_eq!(app.get("/alice/game?b=nope", &owner).await.status, StatusCode::NOT_FOUND);
|
||||||
|
|
||||||
|
// GRAPH: both branches, every revision once, drawn as SVG.
|
||||||
|
let graph = app.get("/alice/game/graph", &owner).await;
|
||||||
|
ok(&graph, "graph");
|
||||||
|
for text in ["First revision", "Edit the readme", "Add the logo", ">main<", ">feature<", "<svg class=\"graph\""] {
|
||||||
|
assert!(graph.body.contains(text), "graph lacks {text}: {}", graph.body);
|
||||||
|
}
|
||||||
|
assert_eq!(graph.body.matches("First revision").count(), 1);
|
||||||
|
|
||||||
|
// TREE: the open branch's revisions, and the open revision's changes.
|
||||||
|
let tree = app.get(&format!("/alice/game/tree?rev={}", hex(&R2)), &owner).await;
|
||||||
|
ok(&tree, "tree");
|
||||||
|
assert!(tree.body.contains("Edit the readme") && tree.body.contains(">M</span>"), "{}", tree.body);
|
||||||
|
|
||||||
|
// One revision: a diff computed here, since loreserver does not diff content.
|
||||||
|
let revision = app.get(&format!("/alice/game/revision/{}", hex(&R2)), &owner).await;
|
||||||
|
ok(&revision, "revision");
|
||||||
|
assert!(revision.body.contains("@@ -1,1 +1,2 @@"), "{}", revision.body);
|
||||||
|
assert!(revision.body.contains("<tr class=\"add\">") && revision.body.contains("+world"), "{}", revision.body);
|
||||||
|
let first = app.get(&format!("/alice/game/revision/{}", hex(&R1)), &owner).await;
|
||||||
|
assert!(first.body.contains("the first revision") && first.body.contains("+fn main() {}"), "{}", first.body);
|
||||||
|
assert_eq!(app.get("/alice/game/revision/00", &owner).await.status, StatusCode::NOT_FOUND);
|
||||||
|
|
||||||
|
// Someone without access sees nothing, not even that it exists.
|
||||||
|
app.create_user(&owner, "bob").await;
|
||||||
|
let bob = app.sign_in("bob", "a long password").await;
|
||||||
|
for path in ["/alice/game", "/alice/game/graph", "/alice/game/tree", &format!("/alice/game/revision/{}", hex(&R2))] {
|
||||||
|
assert_eq!(app.get(path, &bob).await.status, StatusCode::NOT_FOUND, "{path}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn the_browser_reports_an_unreachable_lore_server() {
|
||||||
|
let app = build(None, forge_lore::reader::Lore::new("http://127.0.0.1:9", "http://127.0.0.1:9").unwrap()).await;
|
||||||
|
let owner = app.set_up().await;
|
||||||
|
forge_access::repos::register(app.pool(), &alice_id(&app).await, &crate::fake_lore::REPO, "alice/game").await.unwrap();
|
||||||
|
let reply = app.get("/alice/game", &owner).await;
|
||||||
|
assert_eq!(reply.status, StatusCode::BAD_GATEWAY);
|
||||||
|
assert!(reply.body.contains("Could not read the repository from the Lore server"), "{}", reply.body);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
[package]
|
||||||
|
name = "lore-forge"
|
||||||
|
description = "Accounts, sign-in, per-repository tokens and a forge UI for Epic's Lore"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow.workspace = true
|
||||||
|
axum.workspace = true
|
||||||
|
clap.workspace = true
|
||||||
|
forge-id.workspace = true
|
||||||
|
forge-lore.workspace = true
|
||||||
|
forge-store.workspace = true
|
||||||
|
forge-web.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
tower.workspace = true
|
||||||
|
tower-http.workspace = true
|
||||||
|
tracing.workspace = true
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
|
url.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
@ -0,0 +1,240 @@
|
||||||
|
//! The lore-forge server.
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use anyhow::Context;
|
||||||
|
use anyhow::bail;
|
||||||
|
use clap::Args;
|
||||||
|
use clap::Parser;
|
||||||
|
use clap::Subcommand;
|
||||||
|
use forge_id::Issuer;
|
||||||
|
use forge_id::IssuerConfig;
|
||||||
|
use forge_id::crypto::SecretKey;
|
||||||
|
use forge_id::keys::Keys;
|
||||||
|
use forge_id::users;
|
||||||
|
use forge_id::users::InstanceRole;
|
||||||
|
use forge_id::users::NewUser;
|
||||||
|
use forge_lore::Directory;
|
||||||
|
use forge_store::Store;
|
||||||
|
use tower::ServiceExt;
|
||||||
|
use tower_http::trace::TraceLayer;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[derive(Parser)]
|
||||||
|
#[command(version, about)]
|
||||||
|
struct Cli {
|
||||||
|
#[command(subcommand)]
|
||||||
|
command: Command,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum Command {
|
||||||
|
/// Run the server.
|
||||||
|
Serve(ServeArgs),
|
||||||
|
/// Print the loreserver configuration that makes Lore trust this lore-forge.
|
||||||
|
LoreserverConfig(Urls),
|
||||||
|
/// Print a new secret key for LORE_FORGE_SECRET_KEY.
|
||||||
|
GenerateSecretKey,
|
||||||
|
/// Create an account directly in the database, reading its password from standard input.
|
||||||
|
CreateUser(CreateUserArgs),
|
||||||
|
/// Make a new token signing key current. The previous key keeps verifying; the one before
|
||||||
|
/// it is retired. A running server picks the change up within a minute.
|
||||||
|
RotateSigningKey(DataDir),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Args)]
|
||||||
|
struct DataDir {
|
||||||
|
/// Where the database lives.
|
||||||
|
#[arg(long, env = "LORE_FORGE_DATA_DIR", default_value = "./data")]
|
||||||
|
data_dir: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn rotate_signing_key(args: DataDir) -> anyhow::Result<()> {
|
||||||
|
let store = Store::open(&args.data_dir).await?;
|
||||||
|
let keys = Keys::load_or_create(store.pool().clone(), secret_key()?).await?;
|
||||||
|
keys.rotate().await?;
|
||||||
|
let (kid, _) = keys.current().await?.context("no current key after rotating")?;
|
||||||
|
println!("current signing key is now {kid}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Args)]
|
||||||
|
struct CreateUserArgs {
|
||||||
|
/// Where the database lives.
|
||||||
|
#[arg(long, env = "LORE_FORGE_DATA_DIR", default_value = "./data")]
|
||||||
|
data_dir: PathBuf,
|
||||||
|
#[arg(long)]
|
||||||
|
username: String,
|
||||||
|
#[arg(long)]
|
||||||
|
display_name: String,
|
||||||
|
/// Make the account an instance admin.
|
||||||
|
#[arg(long)]
|
||||||
|
admin: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_user(args: CreateUserArgs) -> anyhow::Result<()> {
|
||||||
|
let mut password = String::new();
|
||||||
|
std::io::stdin().read_line(&mut password).context("reading the password from stdin")?;
|
||||||
|
let password = password.trim_end_matches(['\r', '\n']);
|
||||||
|
let store = Store::open(&args.data_dir).await?;
|
||||||
|
let role = if args.admin { InstanceRole::Admin } else { InstanceRole::Member };
|
||||||
|
let user = users::create(store.pool(), NewUser {
|
||||||
|
username: &args.username,
|
||||||
|
display_name: &args.display_name,
|
||||||
|
password: Some(password),
|
||||||
|
role,
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
println!("created {} ({})", user.username, user.id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Args)]
|
||||||
|
struct Urls {
|
||||||
|
/// lore-forge's canonical public URL. It is the token issuer, so it must not change once
|
||||||
|
/// loreserver trusts it.
|
||||||
|
#[arg(long, env = "LORE_FORGE_PUBLIC_URL")]
|
||||||
|
public_url: Url,
|
||||||
|
/// The loreserver deployment's URL. It is the tokens' audience and the base of the
|
||||||
|
/// resource template.
|
||||||
|
#[arg(long, env = "LORE_FORGE_LORE_URL")]
|
||||||
|
lore_url: Url,
|
||||||
|
/// The public OAuth client ID the Lore CLI presents.
|
||||||
|
#[arg(long, env = "LORE_FORGE_CLIENT_ID", default_value = "lore-cli")]
|
||||||
|
client_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Urls {
|
||||||
|
fn issuer_config(&self) -> anyhow::Result<IssuerConfig> {
|
||||||
|
for (name, url) in [("public URL", &self.public_url), ("Lore URL", &self.lore_url)] {
|
||||||
|
if url.query().is_some() || url.fragment().is_some() || url.host_str().is_none() {
|
||||||
|
bail!("the {name} must be a plain http or https URL");
|
||||||
|
}
|
||||||
|
if !matches!(url.scheme(), "http" | "https") {
|
||||||
|
bail!("the {name} must use http or https");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.public_url.scheme() == "http" && !is_loopback(&self.public_url) {
|
||||||
|
tracing::warn!("the public URL is plain http: use https outside local development");
|
||||||
|
}
|
||||||
|
Ok(IssuerConfig::new(&self.public_url, &self.lore_url, &self.client_id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_loopback(url: &Url) -> bool {
|
||||||
|
matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Args)]
|
||||||
|
struct ServeArgs {
|
||||||
|
#[command(flatten)]
|
||||||
|
urls: Urls,
|
||||||
|
/// Where the database lives.
|
||||||
|
#[arg(long, env = "LORE_FORGE_DATA_DIR", default_value = "./data")]
|
||||||
|
data_dir: PathBuf,
|
||||||
|
/// Address to listen on. Web pages, the issuer and Lore's gRPC directory share it.
|
||||||
|
#[arg(long, env = "LORE_FORGE_LISTEN", default_value = "127.0.0.1:8080")]
|
||||||
|
listen: SocketAddr,
|
||||||
|
/// loreserver's public gRPC endpoint, which the repository browser reads. Plain http
|
||||||
|
/// unless loreserver's `[server.grpc]` has a certificate.
|
||||||
|
#[arg(long, env = "LORE_FORGE_LORE_GRPC_URL", default_value = "http://127.0.0.1:41337")]
|
||||||
|
lore_grpc_url: String,
|
||||||
|
/// loreserver's HTTP endpoint, from which the repository browser reads file content.
|
||||||
|
#[arg(long, env = "LORE_FORGE_LORE_HTTP_URL", default_value = "http://127.0.0.1:41339")]
|
||||||
|
lore_http_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a request is gRPC, which goes to Lore's directory services rather than the web
|
||||||
|
/// routes. Both share one port, so a deployment exposes one address as both lore-forge's
|
||||||
|
/// public URL and Lore's `user_url`.
|
||||||
|
fn is_grpc(request: &axum::extract::Request) -> bool {
|
||||||
|
request
|
||||||
|
.headers()
|
||||||
|
.get(axum::http::header::CONTENT_TYPE)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.is_some_and(|value| value.starts_with("application/grpc"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn secret_key() -> anyhow::Result<SecretKey> {
|
||||||
|
let text = std::env::var("LORE_FORGE_SECRET_KEY").context(
|
||||||
|
"LORE_FORGE_SECRET_KEY is not set. It encrypts the token signing keys; create one with \
|
||||||
|
`lore-forge generate-secret-key` and keep it outside the data directory",
|
||||||
|
)?;
|
||||||
|
SecretKey::from_base64(&text).context("LORE_FORGE_SECRET_KEY")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn serve(args: ServeArgs) -> anyhow::Result<()> {
|
||||||
|
let config = args.urls.issuer_config()?;
|
||||||
|
let secret = secret_key()?;
|
||||||
|
std::fs::create_dir_all(&args.data_dir)
|
||||||
|
.with_context(|| format!("creating {}", args.data_dir.display()))?;
|
||||||
|
let store = Store::open(&args.data_dir).await?;
|
||||||
|
let pool = store.pool().clone();
|
||||||
|
let keys = Arc::new(Keys::load_or_create(pool.clone(), secret.clone()).await?);
|
||||||
|
// Picks up rotations made with `rotate-signing-key` while the server runs.
|
||||||
|
let reloading = keys.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut every = tokio::time::interval(std::time::Duration::from_secs(60));
|
||||||
|
every.tick().await;
|
||||||
|
loop {
|
||||||
|
every.tick().await;
|
||||||
|
if let Err(error) = reloading.reload().await {
|
||||||
|
tracing::error!("reloading signing keys: {error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let issuer = Arc::new(Issuer::new(pool.clone(), keys, config));
|
||||||
|
let oauth = forge_id::oauth::OAuth::new(pool.clone(), secret);
|
||||||
|
|
||||||
|
let grpc = Directory::new(pool.clone(), issuer.clone()).routes().into_axum_router();
|
||||||
|
let lore = forge_lore::reader::Lore::new(&args.lore_grpc_url, &args.lore_http_url).map_err(anyhow::Error::msg)?;
|
||||||
|
let web = forge_web::router(forge_web::AppState::new(pool, issuer.clone(), oauth, lore));
|
||||||
|
let app = axum::Router::new()
|
||||||
|
.fallback_service(tower::service_fn(move |request: axum::extract::Request| {
|
||||||
|
let target = if is_grpc(&request) { grpc.clone() } else { web.clone() };
|
||||||
|
target.oneshot(request)
|
||||||
|
}))
|
||||||
|
.layer(TraceLayer::new_for_http());
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind(args.listen)
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("listening on {}", args.listen))?;
|
||||||
|
tracing::info!(
|
||||||
|
listen = %args.listen,
|
||||||
|
issuer = %issuer.config().issuer,
|
||||||
|
lore = %issuer.config().lore_url,
|
||||||
|
"lore-forge is serving"
|
||||||
|
);
|
||||||
|
axum::serve(listener, app)
|
||||||
|
.with_graceful_shutdown(async {
|
||||||
|
let _ = tokio::signal::ctrl_c().await;
|
||||||
|
tracing::info!("shutting down");
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(
|
||||||
|
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||||
|
.unwrap_or_else(|_| "info,sqlx=warn,tower_http=info".into()),
|
||||||
|
)
|
||||||
|
.init();
|
||||||
|
match Cli::parse().command {
|
||||||
|
Command::Serve(args) => serve(args).await,
|
||||||
|
Command::LoreserverConfig(urls) => {
|
||||||
|
print!("{}", forge_lore::loreserver_config(&urls.issuer_config()?));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Command::GenerateSecretKey => {
|
||||||
|
println!("{}", SecretKey::generate_base64());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Command::CreateUser(args) => create_user(args).await,
|
||||||
|
Command::RotateSigningKey(args) => rotate_signing_key(args).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
# The Lore release lore-forge is tested against, and the SHA-256 of each archive.
|
||||||
|
# Written by: scripts/fetch-lore.sh --pin v0.14.0
|
||||||
|
# Re-run scripts/e2e-lore.sh after changing it.
|
||||||
|
version v0.14.0
|
||||||
|
sha256 lore-v0.14.0-aarch64-apple-darwin.tar.gz 842ae60dd4dc6374c8a08da2c1d8c1b78cac9665802c73e0a4d7a341ef130d2d
|
||||||
|
sha256 lore-v0.14.0-aarch64-unknown-linux-gnu-neoverse-512tvb.tar.gz 87236a18a22fab3df49137316aa4a6fdb15f4d0b7e9df3ae938b695f2c3956c7
|
||||||
|
sha256 lore-v0.14.0-aarch64-unknown-linux-gnu.tar.gz fd50f322fa5aec3678606736d4953529a9047ac8a6ea658c35cc14f99d25c78d
|
||||||
|
sha256 lore-v0.14.0-x86_64-unknown-linux-gnu.tar.gz c2fe93b416a99fd7375ff9e94426c380bf3239fd4f9af9c9673000002fad52c3
|
||||||
|
sha256 loreserver-v0.14.0-aarch64-apple-darwin.tar.gz 38192a71c9341b4d2ab5891713d2b96e59a07b3a02be70ec918e6032b3bb97f6
|
||||||
|
sha256 loreserver-v0.14.0-aarch64-unknown-linux-gnu-neoverse-512tvb.tar.gz a25fba6be87529e6448180fec9d9af5b254d9ecadf4160f59ec7aad30801b077
|
||||||
|
sha256 loreserver-v0.14.0-aarch64-unknown-linux-gnu.tar.gz 1e05734bc99af913bf3643cce64dec97258adb6f892aae97b0f85df1ec15719a
|
||||||
|
sha256 loreserver-v0.14.0-x86_64-unknown-linux-gnu.tar.gz 900c0b508d2bb8856d9de1824c457b10bd3b33c1e0927fdecd9ed8511446cf81
|
||||||
|
|
@ -0,0 +1,340 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# End-to-end test of lore-forge against a real, unmodified loreserver and lore CLI.
|
||||||
|
#
|
||||||
|
# scripts/e2e-lore.sh
|
||||||
|
#
|
||||||
|
# Runs the Lore release pinned in lore.lock, fetched by scripts/fetch-lore.sh. To test another
|
||||||
|
# build, set LORE_BIN_DIR to a directory holding its `loreserver` and `lore`.
|
||||||
|
# Everything runs on localhost in a fresh temporary directory, which is kept on failure, or
|
||||||
|
# always with KEEP_WORK=1.
|
||||||
|
#
|
||||||
|
# It checks the whole phase 1 path: first-run setup, a device login approved in the browser
|
||||||
|
# flow, repository create through the registry, push and clone with repository-scoped tokens,
|
||||||
|
# name lookup through UserService, refusals for a second user, a login with an API token, a
|
||||||
|
# service account logging in with client credentials before and after a grant, and logout.
|
||||||
|
#
|
||||||
|
# LORE_PORT (default 41337) moves loreserver's QUIC and gRPC port, and its HTTP port to
|
||||||
|
# LORE_PORT+2, so the test can run beside a deployment started by scripts/start.sh; FORGE_PORT
|
||||||
|
# does the same for lore-forge.
|
||||||
|
#
|
||||||
|
# HOLD=1 keeps both servers running after the browser checks, for a look at the pages.
|
||||||
|
#
|
||||||
|
# SMOKE=1 stops after one user's login, create and push. On macOS the lore CLI keeps its token
|
||||||
|
# store key in the keychain and every lore process asks for it, so a smoke run is the place to
|
||||||
|
# answer "Always Allow" once.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
LORE_BIN_DIR="${LORE_BIN_DIR:-$("$ROOT/scripts/fetch-lore.sh")}"
|
||||||
|
LORE="$LORE_BIN_DIR/lore"
|
||||||
|
LORESERVER="$LORE_BIN_DIR/loreserver"
|
||||||
|
FORGE_PORT="${FORGE_PORT:-18080}"
|
||||||
|
FORGE="http://localhost:$FORGE_PORT"
|
||||||
|
LORE_PORT="${LORE_PORT:-41337}"
|
||||||
|
LORE_REMOTE="lore://localhost:$LORE_PORT"
|
||||||
|
WORK="$(mktemp -d "${TMPDIR:-/tmp}/lore-forge-e2e.XXXXXX")"
|
||||||
|
PIDS=()
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
local status=$?
|
||||||
|
for pid in ${PIDS[@]+"${PIDS[@]}"}; do kill "$pid" 2>/dev/null || true; done
|
||||||
|
wait 2>/dev/null || true
|
||||||
|
if [ "$status" -ne 0 ]; then
|
||||||
|
echo "FAILED; logs and state kept in $WORK" >&2
|
||||||
|
elif [ -n "${KEEP_WORK:-}" ]; then
|
||||||
|
echo "logs and state kept in $WORK"
|
||||||
|
else
|
||||||
|
rm -rf "$WORK"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
|
||||||
|
step() { printf '\n== %s\n' "$*"; }
|
||||||
|
fail() { echo "FAIL: $*" >&2; exit 1; }
|
||||||
|
|
||||||
|
wait_for() {
|
||||||
|
local what=$1 url=$2
|
||||||
|
for _ in $(seq 1 100); do
|
||||||
|
curl -fsS "$url" >/dev/null 2>&1 && return 0
|
||||||
|
sleep 0.2
|
||||||
|
done
|
||||||
|
fail "$what did not come up ($url)"
|
||||||
|
}
|
||||||
|
|
||||||
|
step "build lore-forge"
|
||||||
|
cargo build --quiet --manifest-path "$ROOT/Cargo.toml" -p lore-forge
|
||||||
|
FORGE_BIN="$ROOT/target/debug/lore-forge"
|
||||||
|
|
||||||
|
export LORE_FORGE_SECRET_KEY="$("$FORGE_BIN" generate-secret-key)"
|
||||||
|
export LORE_FORGE_PUBLIC_URL="$FORGE"
|
||||||
|
export LORE_FORGE_LORE_URL="https://localhost"
|
||||||
|
export LORE_FORGE_DATA_DIR="$WORK/forge-data"
|
||||||
|
export LORE_FORGE_LORE_GRPC_URL="http://127.0.0.1:$LORE_PORT"
|
||||||
|
export LORE_FORGE_LORE_HTTP_URL="http://127.0.0.1:$((LORE_PORT + 2))"
|
||||||
|
|
||||||
|
step "start lore-forge on $FORGE"
|
||||||
|
"$FORGE_BIN" serve --listen "127.0.0.1:$FORGE_PORT" >"$WORK/forge.log" 2>&1 &
|
||||||
|
PIDS+=($!)
|
||||||
|
wait_for lore-forge "$FORGE/.well-known/openid-configuration"
|
||||||
|
|
||||||
|
step "first-run setup in the browser flow"
|
||||||
|
JAR="$WORK/alice.cookies"
|
||||||
|
curl -fsS -c "$JAR" "$FORGE/setup" >/dev/null
|
||||||
|
csrf() { awk '$6 == "lf_csrf" { print $7 }' "$1"; }
|
||||||
|
curl -fsS -b "$JAR" -c "$JAR" -o /dev/null -H "Origin: $FORGE" \
|
||||||
|
--data-urlencode "csrf=$(csrf "$JAR")" \
|
||||||
|
--data-urlencode "username=alice" \
|
||||||
|
--data-urlencode "display_name=Alice Example" \
|
||||||
|
--data-urlencode "password=alice password" \
|
||||||
|
--data-urlencode "password_confirm=alice password" \
|
||||||
|
"$FORGE/setup"
|
||||||
|
grep -q lf_session "$JAR" || fail "setup did not sign alice in"
|
||||||
|
printf 'bob password\n' | "$FORGE_BIN" create-user --username bob --display-name "Bob Example" >/dev/null
|
||||||
|
|
||||||
|
step "start loreserver with the generated configuration"
|
||||||
|
mkdir -p "$WORK/lore-config"
|
||||||
|
{
|
||||||
|
"$FORGE_BIN" loreserver-config
|
||||||
|
cat <<EOF
|
||||||
|
|
||||||
|
[immutable_store.local]
|
||||||
|
path = "$WORK/lore-store"
|
||||||
|
|
||||||
|
[mutable_store.local]
|
||||||
|
path = "$WORK/lore-store"
|
||||||
|
|
||||||
|
[telemetry.logger]
|
||||||
|
format = "text"
|
||||||
|
|
||||||
|
[server.quic]
|
||||||
|
port = $LORE_PORT
|
||||||
|
|
||||||
|
[server.grpc]
|
||||||
|
port = $LORE_PORT
|
||||||
|
|
||||||
|
[server.http]
|
||||||
|
port = $((LORE_PORT + 2))
|
||||||
|
EOF
|
||||||
|
} >"$WORK/lore-config/forge.toml"
|
||||||
|
"$LORESERVER" --config "$WORK/lore-config" --env forge >"$WORK/loreserver.log" 2>&1 &
|
||||||
|
LORE_PID=$!
|
||||||
|
PIDS+=("$LORE_PID")
|
||||||
|
for _ in $(seq 1 150); do
|
||||||
|
grep -qiE 'listening|serving|started' "$WORK/loreserver.log" && break
|
||||||
|
kill -0 "$LORE_PID" 2>/dev/null || { cat "$WORK/loreserver.log" >&2; fail "loreserver exited"; }
|
||||||
|
sleep 0.2
|
||||||
|
done
|
||||||
|
sleep 1
|
||||||
|
|
||||||
|
# Logs `$1` (a user with cookie jar `$2`) into the Lore CLI by approving the device code.
|
||||||
|
lore_login() {
|
||||||
|
local user=$1 jar=$2
|
||||||
|
export LORE_AUTH_PATH="$WORK/auth-$user"
|
||||||
|
"$LORE" auth login --no-browser "$LORE_REMOTE" >"$WORK/login-$user.log" 2>&1 &
|
||||||
|
local pid=$!
|
||||||
|
local code=""
|
||||||
|
for _ in $(seq 1 100); do
|
||||||
|
code=$(grep -oE 'user_code=[A-Z]{4}-[A-Z]{4}' "$WORK/login-$user.log" | head -1 | cut -d= -f2 || true)
|
||||||
|
[ -z "$code" ] && code=$(grep -oE '\b[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}\b' "$WORK/login-$user.log" | head -1 || true)
|
||||||
|
[ -n "$code" ] && break
|
||||||
|
kill -0 "$pid" 2>/dev/null || { cat "$WORK/login-$user.log" >&2; fail "lore auth login exited early"; }
|
||||||
|
sleep 0.2
|
||||||
|
done
|
||||||
|
[ -n "$code" ] || { cat "$WORK/login-$user.log" >&2; fail "no user code printed"; }
|
||||||
|
echo "user code $code"
|
||||||
|
curl -fsS -b "$jar" -c "$jar" "$FORGE/device?user_code=$code" | grep -q "$code" \
|
||||||
|
|| fail "device page did not show $code"
|
||||||
|
curl -fsS -b "$jar" -c "$jar" -H "Origin: $FORGE" \
|
||||||
|
--data-urlencode "csrf=$(csrf "$jar")" \
|
||||||
|
--data-urlencode "user_code=$code" \
|
||||||
|
--data-urlencode "decision=approve" \
|
||||||
|
"$FORGE/device" | grep -q "Client signed in" || fail "approval failed"
|
||||||
|
wait "$pid" || { cat "$WORK/login-$user.log" >&2; fail "lore auth login failed for $user"; }
|
||||||
|
}
|
||||||
|
|
||||||
|
step "alice: lore auth login"
|
||||||
|
lore_login alice "$JAR"
|
||||||
|
|
||||||
|
step "alice: create alice/demo, commit and push"
|
||||||
|
export LORE_AUTH_PATH="$WORK/auth-alice"
|
||||||
|
mkdir -p "$WORK/alice-work"
|
||||||
|
(
|
||||||
|
cd "$WORK/alice-work"
|
||||||
|
"$LORE" repository create "$LORE_REMOTE/alice/demo"
|
||||||
|
echo one >a.txt
|
||||||
|
"$LORE" stage a.txt
|
||||||
|
"$LORE" commit "First revision"
|
||||||
|
"$LORE" push
|
||||||
|
)
|
||||||
|
|
||||||
|
if [ -n "${SMOKE:-}" ]; then
|
||||||
|
printf '\nPASS (smoke): one login, create and push against %s\n' "$("$LORESERVER" --version 2>/dev/null || echo loreserver)"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
step "alice: auth info resolves names through UserService and shows the scoped token"
|
||||||
|
(cd "$WORK/alice-work" && "$LORE" auth info --with-access-token) >"$WORK/info.log" 2>&1
|
||||||
|
sed -E 's/eyJ[A-Za-z0-9_.-]+/<token>/g' "$WORK/info.log"
|
||||||
|
grep -q 'Alice Example' "$WORK/info.log" || fail "auth info did not resolve alice's name"
|
||||||
|
# The payload of the repository token Lore stored, which must carry a `resources` entry for
|
||||||
|
# alice/demo.
|
||||||
|
jwt_payload() {
|
||||||
|
local part
|
||||||
|
part=$(cut -d. -f2 | tr '_-' '/+')
|
||||||
|
while [ $((${#part} % 4)) -ne 0 ]; do part="$part="; done
|
||||||
|
printf '%s' "$part" | base64 -d
|
||||||
|
}
|
||||||
|
TOKEN=$(grep -oE 'eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+' "$WORK/info.log" | tail -1)
|
||||||
|
[ -n "$TOKEN" ] || fail "auth info printed no access token"
|
||||||
|
printf '%s' "$TOKEN" | jwt_payload | tee "$WORK/claims.json"
|
||||||
|
echo
|
||||||
|
grep -q '"resources":\[{"resource_id":"urc-' "$WORK/claims.json" || fail "the repository token has no resources claim"
|
||||||
|
|
||||||
|
step "alice: lore repository list comes from the registry"
|
||||||
|
"$LORE" repository list "$LORE_REMOTE" 2>&1 | tee "$WORK/list.log"
|
||||||
|
grep -q "alice/demo" "$WORK/list.log" || fail "alice/demo not listed"
|
||||||
|
|
||||||
|
step "alice: clone alice/demo elsewhere"
|
||||||
|
(cd "$WORK" && "$LORE" clone "$LORE_REMOTE/alice/demo" alice-clone)
|
||||||
|
[ "$(cat "$WORK/alice-clone/a.txt")" = "one" ] || fail "clone content differs"
|
||||||
|
|
||||||
|
step "alice: names outside a namespace are refused"
|
||||||
|
# Each create runs in an empty directory, so only the registry can refuse it.
|
||||||
|
refused_create() {
|
||||||
|
local name=$1 expect=$2 dir="$WORK/refused-${1//\//-}"
|
||||||
|
mkdir -p "$dir"
|
||||||
|
if (cd "$dir" && "$LORE" repository create "$LORE_REMOTE/$name" >"$dir.log" 2>&1); then
|
||||||
|
fail "created $name"
|
||||||
|
fi
|
||||||
|
grep -qiE "$expect" "$dir.log" || { cat "$dir.log" >&2; fail "$name was refused for another reason"; }
|
||||||
|
}
|
||||||
|
refused_create nobody/x "not found|nobody"
|
||||||
|
refused_create flat "owner/name|invalid"
|
||||||
|
|
||||||
|
step "bob: lore auth login"
|
||||||
|
BOB_JAR="$WORK/bob.cookies"
|
||||||
|
curl -fsS -c "$BOB_JAR" "$FORGE/login" >/dev/null
|
||||||
|
curl -fsS -b "$BOB_JAR" -c "$BOB_JAR" -o /dev/null -H "Origin: $FORGE" \
|
||||||
|
--data-urlencode "csrf=$(csrf "$BOB_JAR")" \
|
||||||
|
--data-urlencode "username=bob" \
|
||||||
|
--data-urlencode "password=bob password" \
|
||||||
|
"$FORGE/login"
|
||||||
|
lore_login bob "$BOB_JAR"
|
||||||
|
export LORE_AUTH_PATH="$WORK/auth-bob"
|
||||||
|
|
||||||
|
step "bob: may not create in alice's namespace, clone her repository, or see it listed"
|
||||||
|
mkdir -p "$WORK/bob-work"
|
||||||
|
refused_create alice/stolen "not authorized|permission|denied"
|
||||||
|
(cd "$WORK" && ! "$LORE" clone "$LORE_REMOTE/alice/demo" bob-clone 2>"$WORK/bob-clone.log") \
|
||||||
|
|| fail "bob cloned alice's repository"
|
||||||
|
"$LORE" repository list "$LORE_REMOTE" >"$WORK/bob-list.log" 2>&1 || true
|
||||||
|
! grep -q "alice/demo" "$WORK/bob-list.log" || fail "bob sees alice/demo"
|
||||||
|
|
||||||
|
step "bob: creates bob/own"
|
||||||
|
(cd "$WORK/bob-work" && "$LORE" repository create "$LORE_REMOTE/bob/own")
|
||||||
|
|
||||||
|
# Posts a form as alice (CSRF added) and prints the page that answers it.
|
||||||
|
alice_post() {
|
||||||
|
local path=$1; shift
|
||||||
|
local args=()
|
||||||
|
for pair in "$@"; do args+=(--data-urlencode "$pair"); done
|
||||||
|
curl -fsS -L -b "$JAR" -c "$JAR" -H "Origin: $FORGE" \
|
||||||
|
--data-urlencode "csrf=$(csrf "$JAR")" ${args[@]+"${args[@]}"} "$FORGE$path"
|
||||||
|
}
|
||||||
|
secret_in() { grep -oE 'lf_[A-Za-z0-9_-]+' | head -1; }
|
||||||
|
|
||||||
|
step "alice: an API token logs the CLI in without a browser"
|
||||||
|
TOKEN=$(alice_post /settings/tokens name=e2e scope=lore days=1 | secret_in)
|
||||||
|
[ -n "$TOKEN" ] || fail "no API token shown"
|
||||||
|
export LORE_AUTH_PATH="$WORK/auth-alice-token"
|
||||||
|
LORE_TOKEN="$TOKEN" "$LORE" auth login --token-type api-key --no-browser "$LORE_REMOTE" >"$WORK/login-token.log" 2>&1 \
|
||||||
|
|| { cat "$WORK/login-token.log" >&2; fail "API token login failed"; }
|
||||||
|
(cd "$WORK" && "$LORE" clone "$LORE_REMOTE/alice/demo" token-clone) >/dev/null
|
||||||
|
[ "$(cat "$WORK/token-clone/a.txt")" = "one" ] || fail "clone with the API token login differs"
|
||||||
|
|
||||||
|
step "alice: a service account logs in with client credentials"
|
||||||
|
ACCOUNT_PATH=$(curl -fsS -o /dev/null -w '%{redirect_url}' -b "$JAR" -c "$JAR" -H "Origin: $FORGE" \
|
||||||
|
--data-urlencode "csrf=$(csrf "$JAR")" --data-urlencode name=ci --data-urlencode "display_name=CI" \
|
||||||
|
"$FORGE/settings/service-accounts" | sed -E 's|^https?://[^/]+||; s|\?.*$||')
|
||||||
|
[ -n "$ACCOUNT_PATH" ] || fail "service account not created"
|
||||||
|
SECRET=$(alice_post "$ACCOUNT_PATH/tokens" name=e2e days=1 | secret_in)
|
||||||
|
[ -n "$SECRET" ] || fail "no service account secret shown"
|
||||||
|
export LORE_AUTH_PATH="$WORK/auth-ci"
|
||||||
|
if (cd "$WORK" && "$LORE" clone "$LORE_REMOTE/alice/demo" ci-denied) >/dev/null 2>&1; then
|
||||||
|
fail "a service account cloned before any grant"
|
||||||
|
fi
|
||||||
|
LORE_CLIENT_SECRET="$SECRET" "$LORE" auth login --client-id alice.ci "$LORE_REMOTE" >"$WORK/login-ci.log" 2>&1 \
|
||||||
|
|| { cat "$WORK/login-ci.log" >&2; fail "client credentials login failed"; }
|
||||||
|
if (cd "$WORK" && "$LORE" clone "$LORE_REMOTE/alice/demo" ci-early) >/dev/null 2>&1; then
|
||||||
|
fail "a service account cloned without a grant"
|
||||||
|
fi
|
||||||
|
alice_post /alice/demo/access kind=user name=alice.ci preset=reader >/dev/null
|
||||||
|
LORE_CLIENT_SECRET="$SECRET" "$LORE" auth login --client-id alice.ci "$LORE_REMOTE" >>"$WORK/login-ci.log" 2>&1 \
|
||||||
|
|| { cat "$WORK/login-ci.log" >&2; fail "client credentials login failed after the grant"; }
|
||||||
|
(cd "$WORK" && "$LORE" clone "$LORE_REMOTE/alice/demo" ci-clone) >/dev/null
|
||||||
|
[ "$(cat "$WORK/ci-clone/a.txt")" = "one" ] || fail "clone as the service account differs"
|
||||||
|
|
||||||
|
step "alice: the web browser reads files, history and diffs from loreserver"
|
||||||
|
export LORE_AUTH_PATH="$WORK/auth-alice"
|
||||||
|
(
|
||||||
|
cd "$WORK/alice-work"
|
||||||
|
echo two >a.txt
|
||||||
|
mkdir -p sub && echo three >sub/b.txt
|
||||||
|
"$LORE" stage a.txt sub/b.txt
|
||||||
|
"$LORE" commit "Second revision"
|
||||||
|
"$LORE" push
|
||||||
|
) >"$WORK/second.log" 2>&1
|
||||||
|
(
|
||||||
|
cd "$WORK/alice-work"
|
||||||
|
"$LORE" branch create feature
|
||||||
|
"$LORE" branch switch feature
|
||||||
|
echo art >c.txt
|
||||||
|
"$LORE" stage c.txt
|
||||||
|
"$LORE" commit "Feature work"
|
||||||
|
"$LORE" push
|
||||||
|
"$LORE" branch switch main
|
||||||
|
echo four >d.txt
|
||||||
|
"$LORE" stage d.txt
|
||||||
|
"$LORE" commit "Main moves on"
|
||||||
|
"$LORE" push
|
||||||
|
"$LORE" branch merge feature # commits the merge itself
|
||||||
|
"$LORE" push
|
||||||
|
) >"$WORK/branch.log" 2>&1
|
||||||
|
page() { curl -fsS -b "$1" "$FORGE$2" || fail "GET $2 failed"; }
|
||||||
|
page "$JAR" /alice/demo >"$WORK/files.html"
|
||||||
|
grep -q '>a.txt<' "$WORK/files.html" && grep -q '>sub<' "$WORK/files.html" || fail "the file list lacks a.txt or sub"
|
||||||
|
grep -q 'Second revision' "$WORK/files.html" || fail "the file list does not attribute the last change"
|
||||||
|
page "$JAR" "/alice/demo?path=a.txt" | grep -q '<td class="text">two</td>' || fail "a.txt does not show its content"
|
||||||
|
page "$JAR" "/alice/demo?path=sub%2Fb.txt" | grep -q '<td class="text">three</td>' || fail "sub/b.txt does not show its content"
|
||||||
|
page "$JAR" /alice/demo/graph >"$WORK/graph.html"
|
||||||
|
grep -q 'First revision' "$WORK/graph.html" && grep -q 'Second revision' "$WORK/graph.html" || fail "the graph lacks a revision"
|
||||||
|
grep -q '>alice<' "$WORK/graph.html" || fail "the graph does not name the author"
|
||||||
|
grep -q 'Feature work' "$WORK/graph.html" && grep -q '>feature<' "$WORK/graph.html" || fail "the graph lacks the feature branch"
|
||||||
|
grep -q 'width="4" height="4"' "$WORK/graph.html" || fail "the graph draws no merge"
|
||||||
|
# The revision link in the row whose message is "Second revision".
|
||||||
|
SECOND=$(perl -ne 'print "$1\n" while m{(/alice/demo/revision/[0-9a-f]{64})(?:(?!</tr>).)*?Second revision}g' "$WORK/graph.html" | head -1)
|
||||||
|
MERGE=$(grep -oE '/alice/demo/revision/[0-9a-f]{64}' "$WORK/graph.html" | head -1)
|
||||||
|
[ "$(page "$JAR" "$MERGE" | grep -oE 'href="/alice/demo/revision/[0-9a-f]{64}"' | sort -u | wc -l | tr -d ' ')" = 2 ] \
|
||||||
|
|| fail "the merge does not show two parents"
|
||||||
|
page "$JAR" "$SECOND" >"$WORK/revision.html"
|
||||||
|
grep -q -- '+two' "$WORK/revision.html" && grep -q -- '-one' "$WORK/revision.html" || fail "the revision page lacks the diff of a.txt"
|
||||||
|
grep -q 'sub/b.txt' "$WORK/revision.html" || fail "the revision page lacks the added file"
|
||||||
|
page "$JAR" "/alice/demo/tree?rev=${SECOND##*/}" | grep -q '>M</span>' || fail "the tree does not open the revision's changes"
|
||||||
|
for path in /alice/demo /alice/demo/graph "$SECOND"; do
|
||||||
|
status=$(curl -s -o /dev/null -w '%{http_code}' -b "$BOB_JAR" "$FORGE$path")
|
||||||
|
[ "$status" = 404 ] || fail "bob got $status for $path"
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ -n "${HOLD:-}" ]; then
|
||||||
|
echo "holding both servers for a look: $FORGE (alice / alice password); Ctrl-C ends"
|
||||||
|
wait "$LORE_PID"
|
||||||
|
fi
|
||||||
|
|
||||||
|
step "alice: logout revokes the CLI login"
|
||||||
|
export LORE_AUTH_PATH="$WORK/auth-alice"
|
||||||
|
(cd "$WORK/alice-work" && "$LORE" auth logout)
|
||||||
|
grep -q "cli_login.revoke" <(sqlite3 "$LORE_FORGE_DATA_DIR/lore-forge.sqlite" "SELECT action FROM audit_log") \
|
||||||
|
|| fail "logout did not reach the revocation endpoint"
|
||||||
|
|
||||||
|
printf '\nPASS: lore-forge end to end against %s\n' "$("$LORESERVER" --version 2>/dev/null || echo loreserver)"
|
||||||
|
|
@ -0,0 +1,103 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Fetches the pinned Lore release (`lore` and `loreserver`) into .lore/<version>/.
|
||||||
|
#
|
||||||
|
# scripts/fetch-lore.sh download if needed, print the directory holding the binaries
|
||||||
|
# scripts/fetch-lore.sh --pin vX.Y.Z re-pin lore.lock to another release (needs `gh`)
|
||||||
|
#
|
||||||
|
# The version and the SHA-256 of every archive are pinned in lore.lock, so a download that does
|
||||||
|
# not match is refused. Needs curl, tar and shasum or sha256sum. Progress goes to stderr; the
|
||||||
|
# only line on stdout is the directory, so other scripts can run
|
||||||
|
# `LORE_BIN_DIR="$(scripts/fetch-lore.sh)"`.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
LOCK="$ROOT/lore.lock"
|
||||||
|
REPO="EpicGames/lore"
|
||||||
|
|
||||||
|
say() { echo "$*" >&2; }
|
||||||
|
die() { say "fetch-lore: $*"; exit 1; }
|
||||||
|
|
||||||
|
sha256() {
|
||||||
|
if command -v sha256sum >/dev/null; then
|
||||||
|
sha256sum "$1" | cut -d' ' -f1
|
||||||
|
elif command -v shasum >/dev/null; then
|
||||||
|
shasum -a 256 "$1" | cut -d' ' -f1
|
||||||
|
else
|
||||||
|
die "need sha256sum or shasum to verify downloads"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# The release's platform name for this machine.
|
||||||
|
target() {
|
||||||
|
case "$(uname -s)/$(uname -m)" in
|
||||||
|
Darwin/arm64) echo aarch64-apple-darwin ;;
|
||||||
|
Linux/x86_64) echo x86_64-unknown-linux-gnu ;;
|
||||||
|
Linux/aarch64 | Linux/arm64) echo aarch64-unknown-linux-gnu ;;
|
||||||
|
*) die "Lore publishes no release for $(uname -s)/$(uname -m). Build lore and loreserver from source and set LORE_BIN_DIR to their directory." ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
pin() {
|
||||||
|
local version=$1
|
||||||
|
command -v gh >/dev/null || die "--pin needs the GitHub CLI (gh)"
|
||||||
|
say "pinning $REPO $version"
|
||||||
|
{
|
||||||
|
echo "# The Lore release lore-forge is tested against, and the SHA-256 of each archive."
|
||||||
|
echo "# Written by: scripts/fetch-lore.sh --pin $version"
|
||||||
|
echo "# Re-run scripts/e2e-lore.sh after changing it."
|
||||||
|
echo "version $version"
|
||||||
|
gh release view "$version" --repo "$REPO" --json assets \
|
||||||
|
--jq '.assets[] | select(.name | test("^lore(server)?-v.*\\.tar\\.gz$")) | select(.name | test("-debug\\.") | not) | "sha256 \(.name) \(.digest | ltrimstr("sha256:"))"'
|
||||||
|
} >"$LOCK.tmp"
|
||||||
|
grep -q '^sha256 loreserver-' "$LOCK.tmp" || { rm -f "$LOCK.tmp"; die "$version has no loreserver archives"; }
|
||||||
|
mv "$LOCK.tmp" "$LOCK"
|
||||||
|
say "wrote $LOCK"
|
||||||
|
}
|
||||||
|
|
||||||
|
fetch() {
|
||||||
|
[ -f "$LOCK" ] || die "$LOCK is missing"
|
||||||
|
local version target dir
|
||||||
|
version=$(awk '$1 == "version" { print $2 }' "$LOCK")
|
||||||
|
[ -n "$version" ] || die "no version in $LOCK"
|
||||||
|
target=$(target)
|
||||||
|
dir="$ROOT/.lore/$version"
|
||||||
|
|
||||||
|
if [ -x "$dir/lore" ] && [ -x "$dir/loreserver" ]; then
|
||||||
|
echo "$dir"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
WORK_DIR=$(mktemp -d "${TMPDIR:-/tmp}/fetch-lore.XXXXXX")
|
||||||
|
trap 'rm -rf "$WORK_DIR"' EXIT
|
||||||
|
local work=$WORK_DIR
|
||||||
|
for name in lore loreserver; do
|
||||||
|
local archive="$name-$version-$target.tar.gz"
|
||||||
|
local expected
|
||||||
|
expected=$(awk -v a="$archive" '$1 == "sha256" && $2 == a { print $3 }' "$LOCK")
|
||||||
|
[ -n "$expected" ] || die "$LOCK pins no $archive"
|
||||||
|
say "downloading $archive"
|
||||||
|
curl -fsSL --retry 3 -o "$work/$archive" \
|
||||||
|
"https://github.com/$REPO/releases/download/$version/$archive"
|
||||||
|
local actual
|
||||||
|
actual=$(sha256 "$work/$archive")
|
||||||
|
[ "$actual" = "$expected" ] || die "$archive has SHA-256 $actual, but lore.lock pins $expected"
|
||||||
|
mkdir -p "$work/$name"
|
||||||
|
tar -xzf "$work/$archive" -C "$work/$name"
|
||||||
|
[ -x "$work/$name/$name" ] || die "$archive holds no $name binary"
|
||||||
|
done
|
||||||
|
|
||||||
|
mkdir -p "$dir"
|
||||||
|
cp "$work/lore/lore" "$work/loreserver/loreserver" "$dir/"
|
||||||
|
cp "$work/loreserver/LICENSE.txt" "$work/loreserver/THIRD-PARTY-NOTICES.txt" "$dir/" 2>/dev/null || true
|
||||||
|
# The release's sample server configuration, for reference.
|
||||||
|
[ -d "$work/loreserver/config" ] && cp -R "$work/loreserver/config" "$dir/config-examples"
|
||||||
|
say "Lore $version is in $dir"
|
||||||
|
echo "$dir"
|
||||||
|
}
|
||||||
|
|
||||||
|
case "${1:-}" in
|
||||||
|
--pin) [ -n "${2:-}" ] || die "usage: $0 --pin vX.Y.Z"; pin "$2" ;;
|
||||||
|
"") fetch ;;
|
||||||
|
*) die "usage: $0 [--pin vX.Y.Z]" ;;
|
||||||
|
esac
|
||||||
|
|
@ -0,0 +1,154 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Starts a lore-forge deployment: lore-forge, then the pinned loreserver configured to trust it.
|
||||||
|
#
|
||||||
|
# scripts/start.sh
|
||||||
|
#
|
||||||
|
# Everything the deployment keeps lives in run/ (git-ignored; set LORE_FORGE_RUN_DIR to move it):
|
||||||
|
#
|
||||||
|
# run/deployment.env settings, written with local defaults on the first run; edit it
|
||||||
|
# run/secret.key the key that encrypts token signing keys; back it up apart from the data
|
||||||
|
# run/forge-data/ lore-forge's database
|
||||||
|
# run/lore-config/ the loreserver configuration this script generates on every start
|
||||||
|
# run/lore-store/ loreserver's repository storage
|
||||||
|
# run/logs/ both processes' logs
|
||||||
|
#
|
||||||
|
# Needs Rust and protoc to build lore-forge, and curl and tar to fetch Lore. Ctrl-C stops both.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
RUN="${LORE_FORGE_RUN_DIR:-$ROOT/run}"
|
||||||
|
ENV_FILE="$RUN/deployment.env"
|
||||||
|
|
||||||
|
say() { echo "start: $*" >&2; }
|
||||||
|
die() { say "$*"; exit 1; }
|
||||||
|
|
||||||
|
mkdir -p "$RUN/logs"
|
||||||
|
|
||||||
|
if [ ! -f "$ENV_FILE" ]; then
|
||||||
|
cat >"$ENV_FILE" <<'EOF'
|
||||||
|
# lore-forge deployment settings, read by scripts/start.sh.
|
||||||
|
# The defaults run everything on this machine for trying lore-forge out.
|
||||||
|
|
||||||
|
# lore-forge's canonical public URL. It is the token issuer that loreserver trusts and Lore's
|
||||||
|
# user directory, so it must not change once people have logged in. Behind a reverse proxy,
|
||||||
|
# this is the proxy's https URL; the proxy must speak HTTP/2 to lore-forge so gRPC passes.
|
||||||
|
PUBLIC_URL=http://localhost:8080
|
||||||
|
|
||||||
|
# The address lore-forge listens on.
|
||||||
|
LISTEN=127.0.0.1:8080
|
||||||
|
|
||||||
|
# The URL identifying the loreserver deployment: the tokens' audience. Its host must be the
|
||||||
|
# host Lore clients connect to.
|
||||||
|
LORE_URL=https://localhost
|
||||||
|
|
||||||
|
# How people address the Lore server from the CLI, for the instructions printed at start.
|
||||||
|
LORE_REMOTE=lore://localhost:41337
|
||||||
|
|
||||||
|
# TLS certificate and key for loreserver's QUIC endpoint. Empty: loreserver generates a
|
||||||
|
# self-signed certificate for localhost on every start, which is fine only locally.
|
||||||
|
LORE_TLS_CERT=
|
||||||
|
LORE_TLS_KEY=
|
||||||
|
EOF
|
||||||
|
say "wrote $ENV_FILE with local defaults"
|
||||||
|
fi
|
||||||
|
# shellcheck source=/dev/null
|
||||||
|
. "$ENV_FILE"
|
||||||
|
: "${PUBLIC_URL:?set PUBLIC_URL in $ENV_FILE}" "${LISTEN:?}" "${LORE_URL:?}" "${LORE_REMOTE:?}"
|
||||||
|
|
||||||
|
if [ ! -s "$RUN/secret.key" ]; then
|
||||||
|
say "building lore-forge to generate the secret key"
|
||||||
|
cargo build --quiet --release --manifest-path "$ROOT/Cargo.toml" -p lore-forge
|
||||||
|
(umask 077 && "$ROOT/target/release/lore-forge" generate-secret-key >"$RUN/secret.key")
|
||||||
|
say "generated $RUN/secret.key; back it up somewhere other than run/"
|
||||||
|
fi
|
||||||
|
|
||||||
|
say "building lore-forge"
|
||||||
|
cargo build --quiet --release --manifest-path "$ROOT/Cargo.toml" -p lore-forge
|
||||||
|
FORGE="$ROOT/target/release/lore-forge"
|
||||||
|
|
||||||
|
LORE_BIN_DIR="$("$ROOT/scripts/fetch-lore.sh")"
|
||||||
|
|
||||||
|
export LORE_FORGE_SECRET_KEY="$(cat "$RUN/secret.key")"
|
||||||
|
export LORE_FORGE_PUBLIC_URL="$PUBLIC_URL"
|
||||||
|
export LORE_FORGE_LORE_URL="$LORE_URL"
|
||||||
|
export LORE_FORGE_DATA_DIR="$RUN/forge-data"
|
||||||
|
|
||||||
|
FORGE_PID=""
|
||||||
|
LORE_PID=""
|
||||||
|
stop() {
|
||||||
|
[ -n "$LORE_PID" ] && kill "$LORE_PID" 2>/dev/null || true
|
||||||
|
[ -n "$FORGE_PID" ] && kill "$FORGE_PID" 2>/dev/null || true
|
||||||
|
wait 2>/dev/null || true
|
||||||
|
}
|
||||||
|
trap stop EXIT
|
||||||
|
trap 'exit 130' INT TERM
|
||||||
|
|
||||||
|
say "starting lore-forge at $PUBLIC_URL (logs: run/logs/lore-forge.log)"
|
||||||
|
"$FORGE" serve --listen "$LISTEN" >>"$RUN/logs/lore-forge.log" 2>&1 &
|
||||||
|
FORGE_PID=$!
|
||||||
|
for _ in $(seq 1 100); do
|
||||||
|
curl -fsS "http://$LISTEN/.well-known/openid-configuration" >/dev/null 2>&1 && break
|
||||||
|
kill -0 "$FORGE_PID" 2>/dev/null || { tail -20 "$RUN/logs/lore-forge.log" >&2; die "lore-forge exited"; }
|
||||||
|
sleep 0.2
|
||||||
|
done
|
||||||
|
curl -fsS "http://$LISTEN/.well-known/openid-configuration" >/dev/null 2>&1 || die "lore-forge did not answer on $LISTEN"
|
||||||
|
|
||||||
|
# loreserver fetches lore-forge's keys at startup, so its configuration is written and it is
|
||||||
|
# started only once lore-forge answers.
|
||||||
|
mkdir -p "$RUN/lore-config"
|
||||||
|
{
|
||||||
|
"$FORGE" loreserver-config
|
||||||
|
cat <<EOF
|
||||||
|
|
||||||
|
[immutable_store.local]
|
||||||
|
path = "$RUN/lore-store"
|
||||||
|
|
||||||
|
[mutable_store.local]
|
||||||
|
path = "$RUN/lore-store"
|
||||||
|
|
||||||
|
[telemetry.logger]
|
||||||
|
format = "text"
|
||||||
|
EOF
|
||||||
|
if [ -n "${LORE_TLS_CERT:-}" ]; then
|
||||||
|
cat <<EOF
|
||||||
|
|
||||||
|
[server.quic.certificate]
|
||||||
|
cert_file = "$LORE_TLS_CERT"
|
||||||
|
pkey_file = "$LORE_TLS_KEY"
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
} >"$RUN/lore-config/forge.toml"
|
||||||
|
|
||||||
|
say "starting loreserver $("$LORE_BIN_DIR/loreserver" --version | awk '{print $2}') (logs: run/logs/loreserver.log)"
|
||||||
|
touch "$RUN/logs/loreserver.log"
|
||||||
|
LOG_FROM=$(($(wc -l <"$RUN/logs/loreserver.log") + 1))
|
||||||
|
"$LORE_BIN_DIR/loreserver" --config "$RUN/lore-config" --env forge >>"$RUN/logs/loreserver.log" 2>&1 &
|
||||||
|
LORE_PID=$!
|
||||||
|
for _ in $(seq 1 150); do
|
||||||
|
# Only lines written since this start count.
|
||||||
|
tail -n +"$LOG_FROM" "$RUN/logs/loreserver.log" | grep -qiE 'listening|serving|started' && break
|
||||||
|
kill -0 "$LORE_PID" 2>/dev/null || { tail -20 "$RUN/logs/loreserver.log" >&2; die "loreserver exited"; }
|
||||||
|
sleep 0.2
|
||||||
|
done
|
||||||
|
|
||||||
|
cat >&2 <<EOF
|
||||||
|
|
||||||
|
lore-forge and loreserver are running.
|
||||||
|
|
||||||
|
1. Open $PUBLIC_URL to create the owner account (first run only). Use exactly
|
||||||
|
this address: forms sent from another one, even 127.0.0.1 for localhost, are refused.
|
||||||
|
2. Sign the Lore CLI in and create a repository under your username:
|
||||||
|
|
||||||
|
$LORE_BIN_DIR/lore auth login $LORE_REMOTE
|
||||||
|
$LORE_BIN_DIR/lore repository create $LORE_REMOTE/<username>/<repository>
|
||||||
|
|
||||||
|
Ctrl-C stops both.
|
||||||
|
EOF
|
||||||
|
|
||||||
|
while kill -0 "$FORGE_PID" 2>/dev/null && kill -0 "$LORE_PID" 2>/dev/null; do
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
kill -0 "$FORGE_PID" 2>/dev/null || say "lore-forge stopped; see run/logs/lore-forge.log"
|
||||||
|
kill -0 "$LORE_PID" 2>/dev/null || say "loreserver stopped; see run/logs/loreserver.log"
|
||||||
|
exit 1
|
||||||
Loading…
Reference in New Issue