Compare commits
133 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 74746e409b | |||
| 70aed035a5 | |||
| 0264a62b22 | |||
| c212537163 | |||
| 391ad12afc | |||
| 622317b6da | |||
| aa17981c15 | |||
| 99fc0d2819 | |||
| 276629a587 | |||
| a26d54ec6f | |||
| 011d4b2975 | |||
| ecc9b62842 | |||
| e74c5cf11d | |||
| 4a592f9795 | |||
| aa2592ea4e | |||
| 9cf0ce34ca | |||
| 3b6d1ceda9 | |||
| e9b808d1c2 | |||
| 6c71c91ff6 | |||
| ac25084113 | |||
| a788a99e56 | |||
| bcd160cca2 | |||
| 724f5d8496 | |||
| 8fc7dd11f5 | |||
| e91ed6f1f7 | |||
| 874f7db037 | |||
| 013c21d4f0 | |||
| 42a61f8868 | |||
| b54da5c64c | |||
| 782ef69fb8 | |||
| 0e955abc73 | |||
| 69883836e1 | |||
| 17df21041a | |||
| c19fffe3c9 | |||
| b6abfe8f03 | |||
| 420ccfab3b | |||
| 8ed4505dc0 | |||
| 451054f0c2 | |||
| 3a46680c8b | |||
| 1b0418e42e | |||
| 4e3aa082d3 | |||
| 6cb8b259e2 | |||
| 2532c492f1 | |||
| fdc045e166 | |||
| 0c2f38f0fe | |||
| fcba782ac7 | |||
| 6162c6d8a1 | |||
| 3be8c7fde2 | |||
| 3852e9ba62 | |||
| 7f2c71299f | |||
| 18119d54aa | |||
| 487e38f1a4 | |||
| 2e011dd383 | |||
| 3c12ebba16 | |||
| ffb2e99199 | |||
| 9d5f106863 | |||
| 7f00d4c845 | |||
| 1d1d29d287 | |||
| 5665504bc1 | |||
| 2ac1c30112 | |||
| 04c18eaf30 | |||
| 6835074b8b | |||
| 59ae30897b | |||
| 94a7e07410 | |||
| a5de279bb4 | |||
| d8b6f6e7a3 | |||
| 208762f0d1 | |||
| b076498219 | |||
| fc0d9104d0 | |||
| 82da47cef7 | |||
| 39779f51dc | |||
| d9a3cb6044 | |||
| 0ee6825a01 | |||
| 14b6ed5ae0 | |||
| fd98854628 | |||
| 3babf18fe4 | |||
| d78f1dfabf | |||
| c3c206b830 | |||
| 0a21dce0d7 | |||
| 5940880d9b | |||
| 17fcf2fed0 | |||
| ec76054e41 | |||
| 5c0fc4f016 | |||
| 43dae2a3eb | |||
| 20c0a48199 | |||
| 12da7140c2 | |||
| dfd5f46095 | |||
| 5dcc75195c | |||
| 12a99b550c | |||
| 4ce5a5f492 | |||
| c84141b2f3 | |||
| f76d93d840 | |||
| e910a492ba | |||
| 1ef868e23c | |||
| e11e39c23a | |||
| b91089ad4c | |||
| 95ae50a924 | |||
| 0076784fae | |||
| c4d7a1a8e9 | |||
| a100f755ce | |||
| 81ad538e50 | |||
| 6ce36b4a14 | |||
| cda76d3889 | |||
| 2c11226793 | |||
| 80d88b083c | |||
| b4fa824609 | |||
| 5a8030fd7d | |||
| cf80c966eb | |||
| 07819a6254 | |||
| 1b3e842006 | |||
| efe3e514b0 | |||
| 37f2ece172 | |||
| b77704089b | |||
| 114d8c86ca | |||
| 3e87ad86ab | |||
| c5a2c0a71d | |||
| fe23d231be | |||
| 3a612dbed7 | |||
| f154bb8db0 | |||
| 9fc5abda2a | |||
| a6ee985de4 | |||
| 47a9f6c3ec | |||
| f6552cb741 | |||
| 4e7e29b35f | |||
| 4e5a2aa4f9 | |||
| 51784f2f27 | |||
| 4c59b1fabb | |||
| 099638057e | |||
| 077c41844d | |||
| 96adf60cf7 | |||
| 82f703f560 | |||
| 65b107d8ff | |||
| 5d7c0bd594 |
@@ -20,9 +20,9 @@
|
|||||||
!directory_spec.md
|
!directory_spec.md
|
||||||
!docs/**/*.md
|
!docs/**/*.md
|
||||||
|
|
||||||
# Tests
|
# Tests (excluded from production builds; test-runner Dockerfile copies them explicitly)
|
||||||
nodejs/tests/
|
# nodejs/tests/
|
||||||
nodejs/*.test.js
|
# nodejs/*.test.js
|
||||||
|
|
||||||
# Host dependency tree — let the image run a clean `npm ci`. Also avoids
|
# Host dependency tree — let the image run a clean `npm ci`. Also avoids
|
||||||
# copying platform-wrong native modules (e.g. bcrypt built for the host OS).
|
# copying platform-wrong native modules (e.g. bcrypt built for the host OS).
|
||||||
|
|||||||
@@ -136,6 +136,10 @@ jobs:
|
|||||||
# directory layout (dc=example,dc=com) -- only the admin password
|
# directory layout (dc=example,dc=com) -- only the admin password
|
||||||
# (normally supplied via a gitignored secrets.js) needs setting.
|
# (normally supplied via a gitignored secrets.js) needs setting.
|
||||||
app_ldap__bindPassword: your-ldap-password
|
app_ldap__bindPassword: your-ldap-password
|
||||||
|
# routes/oauth.js now refuses to start without a real jwtSecret.
|
||||||
|
# This is a non-secret test value; the container under test uses
|
||||||
|
# secrets.js.example's jwtSecret independently.
|
||||||
|
app_oauth__jwtSecret: ci-test-jwt-secret-do-not-use-in-production
|
||||||
run: npm test
|
run: npm test
|
||||||
|
|
||||||
test-summary:
|
test-summary:
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
# SSO Manager API Documentation
|
# SSO Manager API Documentation
|
||||||
|
|
||||||
|
> Looking for a plainer explanation of what API tokens are and when you'd
|
||||||
|
> want one, instead of a full endpoint reference? See
|
||||||
|
> [API Tokens](/docs/api-tokens) (in-app) or
|
||||||
|
> [concepts-api-tokens.md](docs/concepts-api-tokens.md) (repo).
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
API documentation for the SSO Manager Node application. Provides endpoints for authentication, user management, group management, token management, notifications, and OAuth 2.0 / OpenID Connect.
|
API documentation for the SSO Manager Node application. Provides endpoints for authentication, user management, group management, token management, notifications, and OAuth 2.0 / OpenID Connect.
|
||||||
@@ -698,6 +703,10 @@ The authenticated user is automatically set as the group owner.
|
|||||||
{ "results": true, "message": "Added user uid to group group." }
|
{ "results": true, "message": "Added user uid to group group." }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Returns `409` if the user is already a member — common in practice, since
|
||||||
|
`groupOfNames` requires at least one member and so seeds whoever created the
|
||||||
|
group into it.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Remove User from Group
|
### Remove User from Group
|
||||||
@@ -711,6 +720,66 @@ The authenticated user is automatically set as the group owner.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### Nest a Group Inside Another
|
||||||
|
|
||||||
|
**`PUT /api/group/:group/nested/:child`** — `app_sso_admin` or group owner
|
||||||
|
|
||||||
|
Makes `:child` a member of `:group`, so everyone in `:child` is a member of
|
||||||
|
`:group` at any depth.
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{ "results": { "cn": "group", "member": ["..."] }, "message": "Nested child inside group." }
|
||||||
|
```
|
||||||
|
|
||||||
|
**Errors:**
|
||||||
|
|
||||||
|
| Status | When |
|
||||||
|
|--------|------|
|
||||||
|
| `400` | `:group` and `:child` are the same group |
|
||||||
|
| `409` | already nested, or the nesting would create a loop (`:child` already contains `:group`, directly or transitively) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Un-nest a Group
|
||||||
|
|
||||||
|
**`DELETE /api/group/:group/nested/:child`** — `app_sso_admin` or group owner
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{ "results": { "cn": "group", "member": ["..."] }, "message": "Removed child from group." }
|
||||||
|
```
|
||||||
|
|
||||||
|
**Errors:**
|
||||||
|
|
||||||
|
| Status | When |
|
||||||
|
|--------|------|
|
||||||
|
| `409` | `:child` is the only member — `groupOfNames` requires at least one |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Effective Membership
|
||||||
|
|
||||||
|
**`GET /api/group/:group/effective`** — Any authenticated user
|
||||||
|
|
||||||
|
Who a group actually grants. `direct` is users listed on the group itself
|
||||||
|
(never groups); `nestedGroups` is what is nested into it; `effective` is every
|
||||||
|
user reachable through the whole chain.
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"results": {
|
||||||
|
"cn": "app_gitea_access",
|
||||||
|
"direct": ["cn=alice,ou=people,dc=example,dc=com"],
|
||||||
|
"nestedGroups": [{ "cn": "developers", "dn": "cn=developers,ou=groups,dc=example,dc=com" }],
|
||||||
|
"effective": ["cn=alice,ou=people,dc=example,dc=com", "cn=bob,ou=people,dc=example,dc=com"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### Delete Group
|
### Delete Group
|
||||||
|
|
||||||
**`DELETE /api/group/:group`** — `app_sso_admin` or group owner
|
**`DELETE /api/group/:group`** — `app_sso_admin` or group owner
|
||||||
|
|||||||
@@ -4,7 +4,325 @@ All notable changes to this project are documented here. Format loosely
|
|||||||
follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions
|
follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions
|
||||||
correspond to git tags (`vX.Y.Z`) and `nodejs/package.json`'s `version`.
|
correspond to git tags (`vX.Y.Z`) and `nodejs/package.json`'s `version`.
|
||||||
|
|
||||||
## [Unreleased]
|
## [1.11.0] - 2026-07-31
|
||||||
|
|
||||||
|
Closes the end-user half of the directory. The admin side could describe the lab; the user side could not tell anyone what they had or how to use it, and several of the paths meant to do so were silently returning nothing.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **`GET /api/discovery/me` returned only `isPublic` resources for every human caller.** It resolved the caller's groups from `req.user.groups`, which does not exist — `req.user` is a `User` carrying `memberOf` (DNs). The empty list failed open into "no group-granted resources", so "My Services" on the profile page and the portal's service list were blank for everyone. The same bug made `isDirectoryAdmin()` false for real directory admins, silently downgrading them to the public metadata projection. Group CNs now come from `utils/user_groups.js`.
|
||||||
|
- **The portal's "Discover More Services" was dead for every non-admin.** It called the admin-gated `directory-admin/resources` and swallowed the 403 into an empty array — so the one discovery feature never rendered for the audience it existed for. It now calls `/api/discovery/resources`.
|
||||||
|
- **Services reported no address.** `/api/discovery/me` had reimplemented `Resource.getMyAccess` without its parent-walking address resolution, leaving clients to guess `address || ip`, which is exactly wrong for a service that is reached at its host's IP. Both paths now share `Resource.withResolvedAddress()`.
|
||||||
|
- **Approving access for a user already in the target group threw a 500** and left the request stuck pending. `groupOfNames` requires at least one member, so a resource's auto-created groups are seeded with the creator's DN; the grant is now idempotent.
|
||||||
|
- **`DELETE /api/directory-admin/resources/:id` deleted the resource before its edges and group links.** With no transaction, a failure mid-way orphaned rows pointing at a nonexistent id — invisible in the UI and poisonous to `getGraph()`. Dependents go first now.
|
||||||
|
- `PUT /api/directory-admin/resources/:id` validated the body only after loading the row, and carried a dead if/else whose branches were identical.
|
||||||
|
- `/api/directory-admin/audit-logs` shelled out to `tail` three times via `execSync`; replaced with a bounded async file read (no `child_process`, at most the trailing 256 KB).
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **End-user catalog at `/`**, and the first ungated nav item — previously every nav entry was admin-only and a normal user had no signposted destination. Search/filter, per-kind icons, and a **how to reach it** block per card: the URL for a service, the SSH invocation for a host (using the jump-host `uid_-_slug@host` grammar when `directory.jumpHost` is configured).
|
||||||
|
- **Self-service access requests** — `AccessRequest` model plus `/api/access-requests` (create, list own, list decidable, approve, deny, withdraw). Approving performs the LDAP group add, so LDAP remains the access-control truth. Requests target a resource's `member`-level group, never its `_admin` one. Replaces the "coming soon" stub.
|
||||||
|
- **Admin access visibility**: an Access column on the directory table showing member and group counts (and flagging links whose LDAP group has been deleted), plus a "what can this user reach" lookup — the reverse question, which previously had no UI at all. Backed by `GET /api/directory-admin/access-summary` and `/user-access/:uid`.
|
||||||
|
- `conf.directory` — `jumpHost` and `defaultSshPort`, the connection conventions the catalog renders.
|
||||||
|
- `tests/access_request.test.js` — the request → approve → grant-is-real loop end to end, including the regression guard for the `user.groups` bug.
|
||||||
|
|
||||||
|
### Added — nested groups
|
||||||
|
- **A group can now contain another group.** `groupOfNames.member` accepts any DN, so nesting needs no new schema; what it needs is *resolution*, which no released OpenLDAP performs — `memberOf` and `(member=X)` both return direct membership only. Two halves:
|
||||||
|
- **Server-side**: the all-in-one image now builds slapd from a pinned OpenLDAP master commit (`350e9eb3`) to get the **`nestgroup`** overlay (ITS#10161), enabled with `member-filter memberof-filter memberof-values`. `member-values` is deliberately omitted — it expands `member` when reading a group, which destroys the distinction between "listed here" and "reachable via nesting" and is not recoverable afterwards. `pw-sha2` is built from contrib in the same stage; without it every existing `{SSHA512}` password would be unverifiable.
|
||||||
|
- **Client-side**: `Group.list(dn)` computes the transitive closure itself (cycle-detected, depth-capped) when the server can't, selected by `conf.ldap.nestedGroupsServerSide` — which `docker-entrypoint.sh` derives from probing for `nestgroup.so` rather than hardcoding. Both paths are covered by the full suite.
|
||||||
|
- `PUT`/`DELETE /api/group/:group/nested/:child` and `GET /api/group/:group/effective`, plus a **Nested** tab on each group card. Cycles are refused (409) rather than silently depth-truncated.
|
||||||
|
- **`app_super_admin` is now seeded** (it never was) and nested into `app_sso_admin` / `app_sso_invite` / `app_sso_oauth_admin`, so the privilege is real LDAP membership visible to SSSD and sudo — not just a special case in `utils/permission.js`. Not nested into `app_sso_service_account`, which marks non-person accounts rather than granting anything.
|
||||||
|
- Creating a directory resource nests `app_super_admin → <slug>_admin` and `<slug>_admin → <slug>_access`. Both previously required adding every super admin to every new group by hand, so they drifted.
|
||||||
|
- `ldap_group_nesting_level = 5` in ldap-client's SSSD template, for hosts pointed at a server without `nestgroup`. Against the bundled slapd the existing `memberof=` access filter is already transitive, so SSH login inherits nesting for free.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- `PUT /api/group/:group/:uid` returned a bare **500** when the user was already a member — common, since `groupOfNames` requires a member and so seeds whoever created the group. Now a 409 that says so.
|
||||||
|
- Un-nesting (or removing) the last member of a group returned a 500 `ObjectClassViolationError`; now a 409 explaining that a group must keep at least one member.
|
||||||
|
- `GET /api/user/me` derived `isAdmin` from `memberOf`, which is only transitive when `nestgroup` is present. Against a stock server an admin holding their group via nesting would get `isAdmin=false` and lose the entire admin UI while still passing every server-side permission check.
|
||||||
|
- `utils/permission.js`'s `byGroup` checked `group.member.includes(user.dn)` per group, seeing only direct membership.
|
||||||
|
- `/api/directory-admin/access-summary` counted `member` values; it now counts the transitive closure, which matters precisely because `app_super_admin` is nested into every resource's admin group.
|
||||||
|
- Broken `api.html` link in the published docs (`API.md` lives at the repo root, so Jekyll never rendered one); pointed at the source, and added an API entry to the docs nav.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- `@simpleworkjs/directory-schema` bumped to `^1.1.0`, which declares the ten metadata keys the admin form has always written but the schema never listed (`port`, `externalPort`, `isExternalReachable`, `os`, `gitRepo`, `isCurrentSite` as public; `vmid`, `macAddress`, `installPath`, `systemdService` as admin-only). Undeclared keys are dropped for non-admin callers, which blanked the portal's `OS:` field, hid every service's port from users, and left machine tokens unable to read the port mapping the firewall consumer exists to render.
|
||||||
|
- Resource metadata now includes `icon` and `tagline`, collected on the admin form (with a live icon preview) and rendered on the catalog cards.
|
||||||
|
|
||||||
|
## [1.10.0] - 2026-07-30
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **`app_super_admin` cross-app group**: members are full admins here regardless of `app_sso_admin` membership. Bypassed centrally in `utils/permission.js`'s `byGroup`, folded into `GET /api/user/me`'s `isAdmin` flag, and added to nav/`forceLogin` gates. The same group is now also recognized by proxy and jump-host, and by `ldap-client`'s SSSD access filter (SSH login on every host).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Renamed the Executive page to Overview** (route, view, `/api/metrics/overview`, nav label, docs). `/executive` kept as a 301 redirect alongside the existing `/admin`, `/notifications`, `/dashboard` legacy redirects.
|
||||||
|
|
||||||
|
## [1.9.0] - 2026-07-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Directory modal's Associated LDAP Groups tab now supports full membership management**: view, add, and remove members/owners of each associated group directly from the tab, reusing the same `PUT`/`DELETE group/:group/:uid` routes and member-mapping pattern already used on the Groups page.
|
||||||
|
- **`app.util.revealItem()`** (in the shared `app-base.js`, byte-identical across the 3 apps): scrolls a just-added/-edited element into view and flashes its background. Wired into the Directory table, the Groups tab's member list, and the Groups page's create-group flow.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Groups page's search/sort bar is now sticky**, staying visible while scrolling through a long group list. Introduces `--sw-content-offset` (set in `top.ejs` alongside `#spa-shell`'s margin-top) so an in-page sticky element can offset itself below the fixed navbar/update-banner instead of being hidden behind them.
|
||||||
|
- **Directory table**: Kind/Name/Env/Host merged into a single "Resource" column.
|
||||||
|
- `@simpleworkjs/frontend` bumped to `^0.2.7`.
|
||||||
|
|
||||||
|
## [1.8.3] - 2026-07-28
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **`profile.ejs`'s self-service API-token UI unified onto `app.modal`**, matching the pattern already shipped this round in `directory.ejs`, proxy, and jump-host: the static `#secretModal`/`#editModal` elements are retired in favor of the shared `app.modal` singleton, the always-visible inline create-form card becomes a "+ New Token" button + modal, and badge classes switch from `bg-*` to `text-bg-*`.
|
||||||
|
- Checkmark-flash copy feedback (silently broken by FontAwesome's `<i>`→`<svg>` replacement) replaced with toast-based `copyFieldValue`, matching proxy and jump-host.
|
||||||
|
|
||||||
|
## [1.8.2] - 2026-07-28
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Creating a new OAuth integration didn't reliably show the "save this client secret now" reveal modal** — `saveResource()` called `app.modal.close()` immediately before conditionally showing the secret via `app.modal.open()`. `app.modal` is a singleton, and `close()` immediately followed by `open()` collides with Bootstrap's hide-transition guard. An intervening `await loadResources()` made this race unlikely to lose in practice, but not guaranteed to — found while fixing the same, guaranteed-to-lose bug in jump-host and proxy's API-token create flows.
|
||||||
|
|
||||||
|
## [1.8.1] - 2026-07-28
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **The resource modal's "Associated LDAP Groups" autocomplete went empty after the first Add/Edit** — `loadLdapGroups()`'s fetch-once cache guard (`if (ldapGroupsCache) return;`) also skipped repopulating the `<datalist>` on every call after the first, but the modal body (including that `<datalist>`) is rebuilt fresh and empty on every `app.modal.open()`. Now the fetch is still cached, but the datalist is always repopulated.
|
||||||
|
|
||||||
|
## [1.8.0] - 2026-07-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Directory resource modal: General / Details / Associated LDAP Groups / Children tabs**, replacing one long form. The new Children tab lists a resource's existing children and lets you add another right from the modal.
|
||||||
|
- **Resource audit trail**: `created_by`/`created_on`/`updated_by`/`updated_on`, shown in the modal's new footer (mirrors the convention already used by proxy's `Host` and jump-host's `ApiToken`). Existing resources predating this change show "—" until next edited.
|
||||||
|
- **Linkable resource URLs**: `GET /directory/:slug` plus a client-side deep-link check make a resource's modal directly bookmarkable/shareable; the address bar updates to `/directory/{slug}` while its modal is open and reverts on close (including via the browser Back button).
|
||||||
|
- **Auto-created LDAP groups are now prefixed with their nearest ancestor Site's slug** (e.g. `site_local_myhost_access` instead of `myhost_access`), so groups for same-named hosts/services under different sites no longer collide or look identical. Resources with no Site ancestor keep the old unprefixed naming.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- `@simpleworkjs/frontend` bumped to 0.2.6: `app.modal` gained the `tabs`/`footer`/`url` options (all opt-in, existing callers unaffected) plus `showTab`/`on`/`deepLinkSlug`/`formatAudit`/`footerButtons` helpers — the shared building blocks behind this release's modal work, reusable by future entity modals in any of the 3 apps.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- The Directory's Associated LDAP Groups / Relationships lists no longer risk silently dropping their contents on a second modal open (a `jq-repeat`/DOM-rebuild timing race, now rendered manually instead).
|
||||||
|
|
||||||
|
### Operational note
|
||||||
|
The new `Resource` audit fields require a schema migration on any existing deployment: `ALTER TABLE Resource ADD COLUMN created_by VARCHAR(255); ALTER TABLE Resource ADD COLUMN created_on INTEGER; ALTER TABLE Resource ADD COLUMN updated_by VARCHAR(255); ALTER TABLE Resource ADD COLUMN updated_on INTEGER;` (adjust types for non-sqlite dialects) — `@simpleworkjs/orm`'s `sync()` only creates missing tables, it never alters existing ones.
|
||||||
|
|
||||||
|
## [1.7.0] - 2026-07-28
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **`formAJAX`'s loading indicator showed literal HTML** ("<div class=..."), not a spinner — it passed raw markup to `app.messages.action`, which HTML-escapes its message by design. Replaced with plain text.
|
||||||
|
- **`POST /api/user/` (create) and `PUT /api/user/password` had no `message` field** in their response, so the success notification rendered empty. Added messages matching every other route's convention.
|
||||||
|
- **The user landing on `/login` with a `?redirect=` had no explanation why** — happens whenever another app's "Log in with SSO" bounces an unauthenticated user through `/oauth/authorize`. Now shows a contextual banner explaining what's happening.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Directory: tree view is now the only view** (the list/tree toggle is gone) — simpler, one code path.
|
||||||
|
- **Directory: clicking a resource's name opens its detail modal**, not just the pencil/edit icon.
|
||||||
|
|
||||||
|
Found via a fresh production install's feedback — see the [theta-env v1.13.0 release](https://github.com/theta42/theta-env/releases) for the full cross-repo summary.
|
||||||
|
|
||||||
|
## [1.6.3] - 2026-07-28
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Group membership changes (`PUT`/`DELETE /api/group/:group/:uid`) didn't invalidate the User cache**, so `isServiceAccount` (and anything else derived from `memberOf`) could stay stale for up to 5 minutes after a change. This is what caused a real "lost user" report — the account had landed in `app_sso_service_account` (which `users.ejs`'s People tab filters out entirely) and looked exactly like data loss, though nothing was ever deleted.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **A confirmation before adding anyone to `app_sso_service_account`** via the Groups page — that group's whole purpose is to hide an account from the People tab, and there was no guardrail against doing that to a real person by mistake (which is how the bug above happened). Every other group's add-member flow is unchanged.
|
||||||
|
|
||||||
|
## [1.6.2] - 2026-07-28
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **`DELETE /api/oauth/client/:id` 500'd** (`client.remove is not a function`) — `OAuthClient` wraps `@simpleworkjs/orm`'s `Resource` model, whose instance delete method is `.delete()`, not `.remove()`. The Directory Management UI was unaffected (its own delete routes already used `.delete()` correctly); only this legacy/raw API endpoint was broken. Found live against a real deployment's SSO API.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Regression tests**: PUT/DELETE on `/api/oauth/client/:id` now verify persistence with a follow-up GET rather than trusting the mutating response alone (this is what would have caught the bug above). A static check across all views/client-side scripts fails CI if any native `alert()`/`confirm()`/`prompt()` call appears — these block all further browser events on the page and were fully removed in 1.6.1.
|
||||||
|
|
||||||
|
## [1.6.1] - 2026-07-27
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Removed every native `alert()`/`confirm()` call**, replacing them with `app.messages.action`/`confirm`/`toast`. Native `confirm()` blocks all further browser events on the page (discovered live, mid browser-verification of the 1.6.0 `app.messages`/`app.modal` adoption, on `directory.ejs`'s "Rotate Client Secret" — it froze the whole tab). Also deleted `app.user.remove`/`app.oauthClient.remove` in `public/js/app.js`, which had native `confirm()` guards and zero callers anywhere in the app.
|
||||||
|
|
||||||
|
## [1.6.0] - 2026-07-27
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Adopted `@simpleworkjs/frontend`'s `app.messages`, `app.modal`, and `app.validate` modules**, replacing the vendored `app.util.actionMessage`/`actionConfirm`/`alert` in `public/lib/js/app-base.js` and the vendored `public/lib/js/val.js`. Message content is now HTML-escaped (the vendored `alert()` this replaces had no escaping), and `app.messages.action` falls back to a page-wide toast when there's no inline `.actionMessage` target. `app.api`/`app.auth`/`app.pubsub`/`app.socket` are untouched — they're app-specific (dual-mode callback/promise API, `auth-token` header injection) and not something the frontend package's generic `app.js` provides.
|
||||||
|
|
||||||
|
## [1.5.1] - 2026-07-27
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **`PUT /api/user/:uid` 500'd with `ObjectClassViolationError` (LDAP `0x41`) when setting `sshPublicKey`** on any account created before the `ldapPublicKey` auxiliary objectClass was added to new-user creation (e.g. the bootstrap `admin` account). `User.update`'s `sshPublicKey` handling and `User.addSSHkey` (`nodejs/models/user_ldap.js`) now add the `ldapPublicKey` objectClass first (ignoring `TypeOrValueExistsError` if already present), the same pattern already used for `dateOfBirth`/`theta42Person`.
|
||||||
|
- **OAuth Integration parent dropdown was blank.** `populateHostDropdown` in `nodejs/views/directory.ejs` only built options for `kind === 'host'` and `kind === 'service'` — there was no branch for `kind === 'oauth'`, so choosing "OAuth Integration" in the Directory's add-resource modal left the parent-Service picker empty except the placeholder. Added the missing branch.
|
||||||
|
|
||||||
|
## [1.5.0] - 2026-07-26
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Unified the front-end UI shell across the three theta42 apps.** `views/top.ejs`, `views/bottom.ejs` and `public/lib/js/app-base.js` are now byte-identical in sso-manager-node, proxy and jump-host, so the apps look and behave the same and a shell change lands in one edit per repo instead of three divergent ones. Everything that differs between the apps moved into a new `nodejs/utils/ui.js`, exposed to every render as `ui` via `app.locals`: nav items and the groups that may see them, footer repo/license/docs/Terms links, favicon, the profile and post-logout targets, and whether the update banner exists at all.
|
||||||
|
- **One nav-gating model everywhere.** `app-base.js` reveals `.group-required-<cn>` elements for each group the current user is in, read from `GET /api/user/me`. sso-manager-node reports LDAP DNs in `memberOf` and the OIDC clients report CNs in `groups`; both normalise to CNs client-side, and the clients' effective-rights `isAdmin` flag is exposed as a synthetic `admin` group — so one gating model covers a group-based provider and boolean-admin clients without either app learning the other's response shape.
|
||||||
|
- **`GET /api/user/me` is fetched once per page load and cached** (`app.auth.loadUser`). The nav, per-view `forceLogin` and every group-gated element read that one promise instead of issuing their own request.
|
||||||
|
- `app.auth.isLoggedIn` is dual-mode: it returns a Promise **and** invokes an optional node-style callback, so the async and callback call styles both work against one shared `top.ejs`.
|
||||||
|
- `app.auth.forceLogin` no longer uses `$.holdReady` (removed in jQuery 4). An unauthenticated user is redirected to `/login?redirect=<path>`; group requirements are still enforced, and `logOut` now only clears the session, leaving the destination to the caller (`ui.logoutRedirect`).
|
||||||
|
- Dependency alignment across all three apps: `jquery` `^4.0.0` and `ejs` `^3.1.10`.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **`app.api.delete` dropped its callback when called by `formAJAX`.** `formAJAX` always passes the serialized form as the second argument, so a DELETE-method form's callback landed in the data slot and never ran. `delete` now accepts both `(url, callback)` and `(url, data, callback)`.
|
||||||
|
- **`app.api.post`/`put` referenced an undefined `callback2`** and threw when handed a non-function callback. Both are now dual-mode Promise/callback.
|
||||||
|
- **The login page's "reveal the card once we know you're logged out" branch threw** (`Cannot read properties of null`) whenever the logged-in check answered before the parser reached that element — which it always did without a stored token. It now runs on DOM ready.
|
||||||
|
- **`logInRedirect` on the legacy `/login/<path>` form kept only the path.** The OIDC provider routes an unauthenticated authorization request through `/login/oauth/authorize?client_id=…&state=…`; dropping the query there loses the entire authorization request. The suffix form now preserves its query string.
|
||||||
|
|
||||||
|
### Fixed (sso-manager-node)
|
||||||
|
- `public/lib/js/val.js` shadowed `message` with `let` inside `validateField`, so a custom rule's return value never reached `validateMessage` and the caller always saw the generic length message. Resolved by adopting the shared validator, which also brings the `target`/`hostname` rules and the real password policy (>= 8 chars, and either 12+ or 3 of 4 character classes) to this app.
|
||||||
|
- `public/js/app.js` used `$.isFunction`, removed in jQuery 4.
|
||||||
|
|
||||||
|
### Added (sso-manager-node)
|
||||||
|
- `GET /api/user/me` now also reports `isAdmin` (membership in `app_sso_admin`), the single effective-rights flag the shared UI shell gates the update banner on. Group-level gating still reads `memberOf`.
|
||||||
|
|
||||||
|
### Verified
|
||||||
|
- Browser-verified against a full theta-env stack (sso-manager + proxy + jump-host): every top-level page renders with a clean console; nav gating is correct for admin and non-admin; `forceLogin`'s onboarding and group gates fire; `val.js` blocks a weak password and accepts a strong one through a real form submit; the DELETE-method forms work; and the OIDC login round trip (authorize with PKCE -> login -> consent -> callback -> token fragment) completes on both OIDC clients.
|
||||||
|
|
||||||
|
## [1.4.0] - 2026-07-25
|
||||||
|
|
||||||
|
### Security
|
||||||
|
- **The directory discovery API leaked OAuth `client_secret_hash` (and any secret-ish metadata key) to every authenticated caller.** `Resource` doesn't override `toJSON`, so the ORM serialized `metadata` wholesale — including the `client_secret_hash` stored on `kind:'oauth'` resources — across `GET /api/discovery/resources`, `/graph`, `/me`, `/resources/:slug`, and the directory-admin `GET /api/directory-admin/resources`. Every discovery read endpoint and the admin list now route through `projectResource`/`projectResources` from `@simpleworkjs/directory-schema`, which unconditionally strips secret keys (anything matching `/secret|password|privatekey/i`, including `client_secret_hash`) and, for non-directory-admins, reduces metadata to a public allowlist. Admins never receive `client_secret_hash` either.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Directory discovery envelope drift.** `routes/discovery.js` (the `autoRouter(Resource)` mounted live at `app.js:87`) returned **bare arrays**, not the `{ results: [...] }` envelope the directory contract specifies — so jump-host's `data.results || []` collapsed every per-group query to `[]` and no user could bridge. Discovery is now served by explicit `/resources`, `/resources/:slug`, `/graph`, `/me` handlers that all return the `{ results }` envelope. The dead `routes/api_discovery.js` (mounted at `app.js:112`, *after* the 404 catcher) and its mount were removed.
|
||||||
|
- `GET /api/discovery/resources?group=<cn>` now returns 200 with `{ results: [...] }` instead of 404 (the autoRouter's `search` supported `?group=`, but the route was effectively unreachable for jump-host's call pattern).
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Adopted the shared `@simpleworkjs/*` packages published under the simpleworkjs org:
|
||||||
|
- `@simpleworkjs/directory-schema` — the directory contract: the `kind` enum, `Resource`/`ResourceEdge`/`ResourceGroup` field defs, the `{ results }` envelope, the security projection (`projectResource`/`projectResources`/`isDirectoryAdmin`), and the discovery client. `models/resource.js` imports the field defs; the discovery + directory-admin routes use the projection.
|
||||||
|
- `@simpleworkjs/ldap` — `models/user_ldap.js` and `models/group_ldap.js` now take `escapeFilter`/`escapeDN` and `makeClient`/`withClient` from the shared package (via local wrappers that pass `conf`); sso keeps its rich `User.get`/`Group.get`/`User.login`/`User.addSSHkey` (posix/write-side stays app-local). sso's `makeClient` passes no `tlsOptions`, so cert validation is unchanged.
|
||||||
|
- `@simpleworkjs/app-stack` — unified `build_info` (`{buildVersion, buildHash, buildYear}`) and the `static-modules` mounting helper. `utils/build_info.js` and the static-modules loop in `routes/index.js` use the shared helpers.
|
||||||
|
- New `tests/discovery.test.js` (jest + supertest, runs under the docker harness): locks in the `{ results }` envelope on `/resources`, `/graph`, `/me`, `/resources/:slug`, the `?group=` 200-regression, and the no-`client_secret_hash`/no-secret-key guarantee for every caller.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Dependency alignment: `ldapts` `^8.1.2` → `^8.1.8`. The new `@simpleworkjs/*` deps resolve from the npm registry (`^1.0.0`); no `file:`/`link:` entries in the lockfile, so `npm ci` is clean in docker builds.
|
||||||
|
- `build_info` export shape changed from `{commit, version}` to `{buildVersion, buildHash, buildYear}` (the shared shape used by all three apps).
|
||||||
|
|
||||||
|
## [1.3.2] - 2026-07-23
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **OAuth client management API returned `client_id: undefined` on every GET.** The ORM's `Model.toJSON()` only serializes schema fields, so the mapped `client_id`/`scopes`/`redirect_uris`/… that `OAuthClient.get()` attaches to the wrapped Resource were stripped from `GET /api/oauth/client` and `GET /api/oauth/client/:id` responses. The theta-env bootstrap (which lists clients and rotates by the returned `client_id`) then called `/api/oauth/client/undefined/rotate` and got a 500, aborting stack bring-up when `proxy-secrets.js` had no usable secret. `OAuthClient.get()` now emits an explicit public JSON shape (and deliberately omits `client_secret_hash`, so the secret hash no longer leaks over the API).
|
||||||
|
- `OAuthClient.get()` no longer 500s on an unknown/`undefined` client id: `Resource.get()` returns `null` (it doesn't throw), which was dereferenced as `r.kind`. It now returns a clean 404.
|
||||||
|
|
||||||
|
## [1.3.1] - 2026-07-23
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- The Directory documentation (`docs/directory.md`) is now surfaced: registered in-app at `/docs/directory` ("Directory & Inventory"), help-linked from the Directory page header, and linked from the docs-site index. Extended with the shared slug conventions (`site_<name>`, `host_<hostname>` — as used by ldap-client and the theta-env seed), the automatic-registration story (theta-env stack seeding, ldap-client Linux host enrollment), and the API surface (admin at `/api/directory-admin`, read-only graph at `/api/discovery`).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Direct LDAP binds are described as first-class, not "legacy", across README, DEPLOYMENT.md, docs, and the Dockerfile: Linux hosts are a primary consumer of the directory (PAM/SSSD login, LDAP-backed `sudo` via `sudoRole`, SSH public keys via openssh-lpk) — exactly what the custom schemas exist for.
|
||||||
|
|
||||||
|
## [1.3.0] - 2026-07-23
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **OAuth client management API** at `/api/oauth/client` (group `app_sso_oauth_admin`): list, create, update, delete, and rotate-secret for OAuth clients, backed by the Resource model. Accepts form-style string inputs (newline-separated `redirect_uris`/`allowed_groups`, space-separated `scopes`).
|
||||||
|
- **Dockerized test suite**: `docker-compose -f docker-compose.test.yml up --build` spins up OpenLDAP + Redis + a test-runner that seeds the test user and runs the full jest suite (174 tests) against them. `tests/globalSetup.js` honors `REDIS_URL`.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Completed the model-redis → `@simpleworkjs/orm` port that shipped half-finished in 1.2.1:
|
||||||
|
- `OtpToken.issue`/`verify` called nonexistent `find()`/`listDetail()` — every OTP login 500'd.
|
||||||
|
- Impersonation create/revoke called nonexistent `ImpersonationToken.listDetail()` — both endpoints 500'd.
|
||||||
|
- `OAuthClient` read `is_valid` from the Resource model, which has no such column — every client evaluated as disabled and **all `/oauth/authorize` requests were rejected with 400**. Client validity now lives in `metadata` (absent = valid).
|
||||||
|
- `OAuthClient.add` didn't set the required-unique `Resource.slug`; clients now get a slug derived from the client name.
|
||||||
|
- `GET /api/token/:name/:token` returned `{results: null}` with 200 for unknown tokens (orm `get()` returns null instead of throwing); now 404s.
|
||||||
|
- `User.login` returns a clean 401 instead of crashing when neither `uid` nor `username` is supplied.
|
||||||
|
- Depend on published `@simpleworkjs/orm` ^0.2.8 and `model-redis` ^1.6.0 instead of a local `file:` link that broke `npm ci` in docker builds.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Removed the Mobile Phone field from the user create/edit form.
|
||||||
|
|
||||||
|
## [1.2.1] - 2026-07-22
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Actionable Metrics**: New real-time metrics tracking for failed logins, top IPs, and service usage per user.
|
||||||
|
- **LDAP Monitor**: Background service to parse OpenLDAP binds over port 389 and track metrics for legacy apps.
|
||||||
|
- **UI Updates**: Executive dashboard now displays actionable metrics cards instead of raw logs. User profiles show individual service usage stats to admins.
|
||||||
|
- **Directory Management**: Integrated site/host/service abstractions into directory UI and allowed associating OAuth apps directly to services.
|
||||||
|
|
||||||
|
## [1.1.18] - 2026-07-21
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- N-Way Multi-Master LDAP replication: `LDAP_SERVER_ID` + `LDAP_REPLICATION_HOSTS` configure `syncrepl` peers in the bundled OpenLDAP, and a new `/sites` page (nav: **Sites**) shows each configured peer's LDAP URL and live reachability.
|
||||||
|
- A `location` property on users, editable from the profile and user-edit forms.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- `/sites` (added above) 500'd on every load: `views/sites.ejs` included nonexistent partials `header`/`footer` instead of this app's actual `top`/`bottom`. Fixed to match every other view.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Refreshed all README screenshots (dashboard, users, groups, OAuth apps) against the current UI, and added a new Sites & Replication screenshot.
|
||||||
|
|
||||||
|
## [1.1.17] - 2026-07-18
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `conf.ldap.ldapsHost` and `conf.ldap.ldapsPort` config options (also settable via `app_ldap__ldapsHost` / `app_ldap__ldapsPort`). When `ldapsHost` is set, the `/integrations` page advertises that hostname for direct LDAPS binds instead of deriving it from the public OAuth issuer. This lets operators use an internal-only hostname (e.g. `ldap.internal.example.com` or `sso-manager` on the Docker network) and avoid port-forwarding 636 to the internet.
|
||||||
|
- A contextual help panel on `/integrations` → LDAP explaining why LDAPS needs a hostname (not an IP), why 636 should not be publicly forwarded, and the recommended internal-DNS / Docker-internal alternatives.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- `routes/index.js` now computes the displayed LDAPS URL from `conf.ldap.ldapsHost`/`ldapsPort` with fallback to the OAuth issuer host for backward compatibility.
|
||||||
|
- `secrets.js.example`, `docs/configuration.md`, `docs/ldap.md`, and `DEPLOYMENT.md` document the new `ldapsHost`/`ldapsPort` options and recommended network layouts.
|
||||||
|
- Bumped version to `1.1.17` in `nodejs/package.json`.
|
||||||
|
|
||||||
|
## [1.1.16] - 2026-07-18
|
||||||
|
|
||||||
|
### Security
|
||||||
|
- Hardened LDAP filter and DN construction against injection. All user-supplied values interpolated into group filters (`models/group_ldap.js`) and RDN values used when adding users/groups (`models/user_ldap.js`) are now escaped before being sent to the LDAP server.
|
||||||
|
- Replaced `Math.random()`-based token generation in `models/token.js`, `models/oauth_code.js`, and `models/oauth_client.js` with `crypto.randomUUID()` for session tokens, OAuth codes, access/refresh tokens, and client IDs.
|
||||||
|
- Replaced `Math.random()`-based OTP generation in `OtpToken.issue()` with `crypto.randomInt()`.
|
||||||
|
- `routes/oauth.js` now refuses to start if `oauth.jwtSecret` is missing or still set to the placeholder value, instead of falling back to a hardcoded public string.
|
||||||
|
- Rendered docs and Terms-of-Service HTML in `routes/docs.js` and `routes/index.js` are now sanitized with `xss` to prevent stored XSS from malicious markdown.
|
||||||
|
- Removed a `console.log` that wrote new-user data (including password hashes) to the log in `models/user_ldap.js`; reduced login-path error logging to `error.name`/`error.message` only.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Public-release packaging: removed `"private": true` from `nodejs/package.json` and bumped version to `1.1.16`.
|
||||||
|
- CI workflow (`.github/workflows/pr-tests.yml`) now sets `app_oauth__jwtSecret` so the test suite can run against the new startup-time JWT validation.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- `models/email.js`: fixed a template bug where the rendered `from` address used `template.message` instead of `template.from`.
|
||||||
|
|
||||||
|
## [1.1.15] - 2026-07-18
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Rewrote `install.sh` as an idempotent git-clone installer, replacing the old flag-driven, copy-based one — `wget -O - .../install.sh | sudo bash` now works the same way it does for theta42/proxy. Installs to `/opt/theta42/sso-manager` (was `/opt/sso-manager`). First run only: bootstraps OpenLDAP with a generated admin password + JWT secret and seeds `/etc/sso-manager/secrets.js` (was `/opt/sso-manager/conf/secrets.js`, hand-filled from CLI flags); later runs never touch LDAP or the secrets file again. `ops/systemd/sso-manager.service` sets `CONF_SECRETS=/etc/sso-manager/secrets.js` to match.
|
||||||
|
- `install.sh` now prints the version it's updating from/to (or "Already up to date") on every run.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- `install.sh` could hang indefinitely on a fresh host if a base package pulled in `tzdata` as a new dependency (no TTY for the interactive timezone prompt), or if the debconf `slapd/domain` value was malformed (a raw DN fragment instead of a dotted domain) — slapd's postinst hangs rather than failing cleanly on a bad domain. Both fixed.
|
||||||
|
- `ops/ldap-setup.sh`'s ppolicy-overlay checks used an LDAP substring filter against an attribute that doesn't support substring matching, so they always reported the overlay as unconfigured even when it was correctly set up (stored as `{0}ppolicy`) — the final verification step always failed as a result. Fixed to filter on `(objectClass=olcOverlayConfig)` instead, matching every other check in that script.
|
||||||
|
|
||||||
|
## [1.1.14] - 2026-07-17
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Bumped `@simpleworkjs/conf` to 1.2.0 and `jq-repeat` to 2.2.0. The Docker entrypoint now sets the new `CONF_SECRETS` env var to point directly at a mounted `sso-secrets.js` instead of symlinking it into `/app/conf/secrets.js` — the app no longer needs write access to its own `conf/` directory to pick up mounted secrets.
|
||||||
|
|
||||||
|
## [1.1.13] - 2026-07-17
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- The new concept docs' cross-links (`concepts-accounts.html` etc.) are the correct, working URL on the Jekyll/GitHub Pages build (where the page's URL is its filename stem) but didn't resolve in the in-app docs viewer, which serves docs at a separate short slug (`/docs/accounts`). The in-app renderer now also resolves a doc's real filename as a fallback, so one link written in a doc works on both targets.
|
||||||
|
|
||||||
|
## [1.1.12] - 2026-07-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Three new plain-language docs aimed at less technical readers, replacing the schema-level LDAP/OAuth/API docs as the target of most card help links: **Accounts, Groups & Managers**, **Connecting Apps (SSO)**, and **API Tokens**. Each links onward to the deeper technical reference for readers who want it; the technical docs link back the other way too. The personal-access-token card (previously missed) now links to its own doc.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- The in-app docs viewer rendered every `docs/*.md` page with a garbled heading and a stray horizontal rule at the top — Jekyll front matter (meant only for the GitHub Pages build) was never stripped before being handed to the markdown renderer. Also fixed: cross-doc links (`ldap.html`, `index.html`, etc.) never resolved in-app, since this viewer serves docs at `/docs/<slug>` with no `.html` suffix — they're now rewritten to the correct in-app URL, the same way image paths already were.
|
||||||
|
|
||||||
|
## [1.1.11] - 2026-07-17
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Moved the help (❓) link out of the global header and onto each relevant card individually (Invite User, Add new user, User List, Service Accounts, group cards, OAuth/LDAP integration cards, My groups, Members of `<uid>`'s group, New API Token) — each now deep-links straight to the doc that actually covers it, instead of one generic header icon.
|
||||||
|
|
||||||
|
## [1.1.10] - 2026-07-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- A help icon (❓) in the top-right header now deep-links to the doc most relevant to the current page (falls back to the docs index elsewhere).
|
||||||
|
- The in-app docs viewer (`/docs`) is now searchable — a simple line-substring search over the same local doc set, no new dependency, still works with no internet access.
|
||||||
|
|
||||||
|
## [1.1.9] - 2026-07-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Every account's personal Unix group (its primary GID holder) can now have supplementary members managed from the account's profile page ("Members of `<uid>`'s group", admin-only) — e.g. to share write access to files owned by that group. Uses the standard `memberUid` attribute (RFC 2307 `posixGroup`).
|
||||||
|
|
||||||
|
## [1.1.8] - 2026-07-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Group membership is now editable directly from a user's profile page ("My groups" -- add via a group-name picker, remove with a button per row), instead of only from each group's own card on the Groups page. Admin-only, using the existing per-group member add/remove endpoints.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- The Edit Profile form's Mobile Phone field had a stray `validate=":9"` making it effectively required (submission was blocked with "Please fix the form errors" if left blank) -- it was always meant to be optional, matching the "Add user" form. Removed.
|
||||||
|
- A service account's profile always showed `Name: Service Account` -- every service account has the same literal filler given/last name (a schema-satisfying placeholder, not meant to be shown), making them indistinguishable by name. The Name line is now hidden for service accounts.
|
||||||
|
- The Users page's Service Accounts tab, and a freshly-created service account's own profile, could appear empty/not-a-service-account for up to 5 minutes right after creation. Creating a user caches it via `User.get()` *before* the route handler marks it as a service account (group membership), so the cached copy had `isServiceAccount` stuck wrong until the cache TTL expired. Now cleared and re-fetched immediately after marking.
|
||||||
|
- A user belonging to exactly one LDAP group had their `memberOf` attribute returned as a bare string instead of a one-element array (ldapts's normal behavior for single-valued attributes) -- client-side permission checks (`for(let group of user.memberOf)`) would then iterate the DN character-by-character instead of once, causing pages gated on that group (e.g. Groups) to incorrectly show "You do not have permission to be here." Normalized `memberOf` to always be an array, same fix already applied to `manager`.
|
||||||
|
|
||||||
## [1.1.7] - 2026-07-17
|
## [1.1.7] - 2026-07-17
|
||||||
|
|
||||||
@@ -61,7 +379,24 @@ First tagged release. Establishes the `vX.Y.Z` tag convention that the in-app up
|
|||||||
- Unix/POSIX and LDAP bind-only service account support, distinct from real-person accounts.
|
- Unix/POSIX and LDAP bind-only service account support, distinct from real-person accounts.
|
||||||
- Merged OAuth Apps + LDAP Info into a single Integrations page.
|
- Merged OAuth Apps + LDAP Info into a single Integrations page.
|
||||||
|
|
||||||
[Unreleased]: https://github.com/theta42/sso-manager-node/compare/v1.1.7...HEAD
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [1.14.0] - 2026-08-01
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Added Configuration page in the UI to manage SSO configurations stored securely in OpenBao Vault.
|
||||||
|
- Added Discovery plugin and Scheduler integration within the Directory.
|
||||||
|
- Re-routed Vault proxy under `/api/vault` and implemented Vault authentication headers.
|
||||||
|
|
||||||
|
[Unreleased]: https://github.com/theta42/sso-manager-node/compare/v1.1.16...HEAD
|
||||||
|
[1.1.15]: https://github.com/theta42/sso-manager-node/compare/v1.1.14...v1.1.15
|
||||||
|
[1.1.14]: https://github.com/theta42/sso-manager-node/compare/v1.1.13...v1.1.14
|
||||||
|
[1.1.13]: https://github.com/theta42/sso-manager-node/compare/v1.1.12...v1.1.13
|
||||||
|
[1.1.12]: https://github.com/theta42/sso-manager-node/compare/v1.1.11...v1.1.12
|
||||||
|
[1.1.11]: https://github.com/theta42/sso-manager-node/compare/v1.1.10...v1.1.11
|
||||||
|
[1.1.10]: https://github.com/theta42/sso-manager-node/compare/v1.1.9...v1.1.10
|
||||||
|
[1.1.9]: https://github.com/theta42/sso-manager-node/compare/v1.1.8...v1.1.9
|
||||||
|
[1.1.8]: https://github.com/theta42/sso-manager-node/compare/v1.1.7...v1.1.8
|
||||||
[1.1.7]: https://github.com/theta42/sso-manager-node/compare/v1.1.6...v1.1.7
|
[1.1.7]: https://github.com/theta42/sso-manager-node/compare/v1.1.6...v1.1.7
|
||||||
[1.1.6]: https://github.com/theta42/sso-manager-node/compare/v1.1.5...v1.1.6
|
[1.1.6]: https://github.com/theta42/sso-manager-node/compare/v1.1.5...v1.1.6
|
||||||
[1.1.5]: https://github.com/theta42/sso-manager-node/compare/v1.1.4...v1.1.5
|
[1.1.5]: https://github.com/theta42/sso-manager-node/compare/v1.1.4...v1.1.5
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ bare-metal / advanced standalone use; most deployments should use the file.
|
|||||||
- Health check: `http://localhost:3001/health` → `{"status":"ok"}`
|
- Health check: `http://localhost:3001/health` → `{"status":"ok"}`
|
||||||
- OIDC discovery: `http://localhost:3001/.well-known/openid-configuration`
|
- OIDC discovery: `http://localhost:3001/.well-known/openid-configuration`
|
||||||
- LDAP (internal, app↔slapd): `ldap://localhost:389` (not mapped to the host)
|
- LDAP (internal, app↔slapd): `ldap://localhost:389` (not mapped to the host)
|
||||||
- LDAPS (for legacy apps / direct binds): `ldaps://<host>:636` (TLS)
|
- LDAPS (direct binds: Linux hosts, LDAP-native apps): `ldaps://<host>:636` (TLS)
|
||||||
|
|
||||||
### API tokens (personal access tokens)
|
### API tokens (personal access tokens)
|
||||||
|
|
||||||
@@ -176,6 +176,8 @@ docker compose exec sso-manager ldapsearch -x -H ldap://localhost:389 \
|
|||||||
| `PORT` | `3001` | host port mapped to the UI |
|
| `PORT` | `3001` | host port mapped to the UI |
|
||||||
| `LDAPS_PORT` | `636` | host port mapped to LDAPS |
|
| `LDAPS_PORT` | `636` | host port mapped to LDAPS |
|
||||||
| `LDAP_PORT` | `389` | uncomment the host mapping in compose to expose plain LDAP (not recommended) |
|
| `LDAP_PORT` | `389` | uncomment the host mapping in compose to expose plain LDAP (not recommended) |
|
||||||
|
| `LDAP_SERVER_ID` | empty | Unique integer ID (e.g. 1, 2) required to enable Multi-Master replication |
|
||||||
|
| `LDAP_REPLICATION_HOSTS` | empty | Space-separated list of other sites' LDAP URLs for replication (e.g. `ldaps://site2:636`) |
|
||||||
|
|
||||||
Any `app_*` var may also be set directly to override any config value (see the
|
Any `app_*` var may also be set directly to override any config value (see the
|
||||||
table at the top).
|
table at the top).
|
||||||
@@ -188,6 +190,12 @@ valid 10 years, SAN includes the CN + `localhost` + `127.0.0.1`) and listens on
|
|||||||
`ldap-certs` volume so it persists across container recreation — clients don't need
|
`ldap-certs` volume so it persists across container recreation — clients don't need
|
||||||
to re-trust on every rebuild.
|
to re-trust on every rebuild.
|
||||||
|
|
||||||
|
The `/integrations` page derives its LDAPS URL from the OAuth issuer by default.
|
||||||
|
To advertise a separate, internal-only hostname (e.g. `ldap.internal.example.com`
|
||||||
|
or `sso-manager` for Docker-internal clients), set `conf.ldap.ldapsHost` in your
|
||||||
|
secrets file or pass `app_ldap__ldapsHost=...`. See `docs/ldap.md` for
|
||||||
|
recommended network layouts and how to match the cert SAN to the hostname.
|
||||||
|
|
||||||
- **Trusting the self-signed cert** (clients): copy `/etc/openldap/certs/ldap.crt`
|
- **Trusting the self-signed cert** (clients): copy `/etc/openldap/certs/ldap.crt`
|
||||||
out of the container and add it to the client's trusted CA store, or set
|
out of the container and add it to the client's trusted CA store, or set
|
||||||
`TLS_REQCERT never` for quick-and-dirty LAN use. Fetch it with:
|
`TLS_REQCERT never` for quick-and-dirty LAN use. Fetch it with:
|
||||||
@@ -328,14 +336,32 @@ OAuth client). Note: re-running bootstrap resets the bootstrap-admin and
|
|||||||
service-account passwords to the values in `./config/sso-secrets.js`; non-theta
|
service-account passwords to the values in `./config/sso-secrets.js`; non-theta
|
||||||
OAuth clients live in SSO Redis and are preserved by the volume.
|
OAuth clients live in SSO Redis and are preserved by the volume.
|
||||||
|
|
||||||
|
> **Note — the bundled slapd is built from source.** The all-in-one image
|
||||||
|
> compiles OpenLDAP from a pinned upstream commit to get the `nestgroup`
|
||||||
|
> overlay (nested groups; see `docs/directory.md`), because no 2.6.x release
|
||||||
|
> ships it. One consequence: master uses **LMDB 1.0.0**, whose on-disk format is
|
||||||
|
> mutually unreadable with the 0.9.x in OpenLDAP 2.6.x
|
||||||
|
> (`MDB_INVALID: File is not an LMDB file`). Moving a directory between a 2.6.x
|
||||||
|
> image and this one is a `slapcat` → `slapadd` reload, not a restart — the same
|
||||||
|
> shape as "Restore — LDAP only" above. Verify after a rebuild:
|
||||||
|
> `docker compose logs sso-manager | grep nestgroup` should report the overlay
|
||||||
|
> as available.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Method 2: Bare metal (Debian/Ubuntu)
|
## Method 2: Bare metal (Debian/Ubuntu)
|
||||||
|
|
||||||
`install.sh` is an idempotent installer: it installs Node.js 20.x, installs and
|
`install.sh` is an idempotent installer: it installs Node.js 22.x and Redis,
|
||||||
configures OpenLDAP (modules + overlays + custom schema + directory tree +
|
force-syncs the repo to `/opt/theta42/sso-manager`, and symlinks the systemd
|
||||||
required groups), deploys the app to `/opt/sso-manager`, and creates a systemd
|
config from the repo. Re-run it to update — it prints the version you're
|
||||||
unit. Configuration is written to `/opt/sso-manager/conf/secrets.js` (file-based).
|
updating from and to (or "Already up to date" if there's nothing new).
|
||||||
|
|
||||||
|
On the **first run only** it also installs and configures OpenLDAP (modules +
|
||||||
|
overlays + custom schema + directory tree + required groups — see
|
||||||
|
`ops/ldap-setup.sh`) and seeds `/etc/sso-manager/secrets.js` with a generated
|
||||||
|
LDAP admin password and JWT secret (SMTP is left as a placeholder). Once that
|
||||||
|
file exists it's never touched again, and LDAP is never re-bootstrapped —
|
||||||
|
edit the file and restart the service to change anything.
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
@@ -346,47 +372,50 @@ unit. Configuration is written to `/opt/sso-manager/conf/secrets.js` (file-based
|
|||||||
### Install
|
### Install
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo ./install.sh \
|
wget -O - https://raw.githubusercontent.com/theta42/sso-manager-node/master/install.sh | sudo bash
|
||||||
-p 'your-ldap-password' \
|
|
||||||
-b 'dc=yourdomain,dc=com' \
|
|
||||||
-n 'Your Org' \
|
|
||||||
-o 3001
|
|
||||||
```
|
```
|
||||||
|
|
||||||
| Flag | Env var | Description |
|
or, if you already have the repo checked out:
|
||||||
|------|---------|-------------|
|
|
||||||
| `-p, --admin-pass` | `LDAP_ADMIN_PASS` | LDAP admin password (required) |
|
```bash
|
||||||
| `-b, --base-dn` | `LDAP_BASE_DN` | Base DN (default `dc=example,dc=com`) |
|
sudo ./install.sh
|
||||||
| `-n, --org-name` | `ORG_NAME` | Org name (default `SSO Manager`) |
|
```
|
||||||
| `-o, --port` | `PORT` | HTTP port (default `3001`) |
|
|
||||||
| `-j, --jwt-secret` | `JWT_SECRET` | JWT secret (default auto-generated) |
|
| Env var | Description |
|
||||||
| `-s, --smtp-config` | `SMTP_*` | SMTP as `host:port:user:pass` |
|
|---------|-------------|
|
||||||
| `--skip-ldap` | `SKIP_LDAP` | Skip LDAP setup (use existing) |
|
| `LDAP_BASE_DN` | Base DN (default `dc=example,dc=com`) — first run only |
|
||||||
| `--skip-app` | `SKIP_APP` | LDAP setup only |
|
| `LDAP_ADMIN_PASS` | LDAP admin password (default auto-generated) — first run only |
|
||||||
| `--dry-run` | `DRY_RUN` | Show actions without making changes |
|
| `JWT_SECRET` | JWT secret (default auto-generated) — first run only |
|
||||||
|
| `ORG_NAME` | Org name (default `SSO Manager`) — first run only |
|
||||||
|
| `PORT` | HTTP port (default `3001`) — first run only |
|
||||||
|
| `SKIP_LDAP` | `true` to skip OpenLDAP bootstrap entirely (point at an existing server yourself) |
|
||||||
|
| `REPO_URL`, `REPO_DIR`, `BRANCH`, `SECRETS_FILE` | Override the defaults |
|
||||||
|
|
||||||
### Post-install
|
### Post-install
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo systemctl enable --now sso-manager
|
sudo systemctl status sso-manager
|
||||||
journalctl -fu sso-manager
|
journalctl -fu sso-manager
|
||||||
curl http://localhost:3001/health # -> {"status":"ok"}
|
curl http://localhost:3001/health # -> {"status":"ok"}
|
||||||
```
|
```
|
||||||
|
|
||||||
### What `install.sh` does
|
### What `install.sh` does
|
||||||
|
|
||||||
1. Installs Node.js 20.x (NodeSource).
|
1. Installs Node.js 22.x (NodeSource) and Redis.
|
||||||
2. Installs OpenLDAP (`slapd`) with: `pw-sha2`, `ppolicy`, `memberof`, `refint`
|
2. Clones/updates the repo at `/opt/theta42/sso-manager`.
|
||||||
modules + overlays; the custom `theta42Person` schema (`dateOfBirth`); indexes;
|
3. **First run only:** installs OpenLDAP (`slapd`) with `pw-sha2`, `ppolicy`,
|
||||||
`ou=people`/`ou=groups`/`ou=policies`; a default `pwdPolicy`; and the SSO groups.
|
`memberof`, `refint` modules + overlays; the custom `theta42Person` schema
|
||||||
3. Installs the app to `/opt/sso-manager` and runs `npm ci --omit=dev`.
|
(`dateOfBirth`); indexes; `ou=people`/`ou=groups`/`ou=policies`; a default
|
||||||
4. Generates `conf/secrets.js` (LDAP/SMTP/JWT) and `conf/base.js` (generic defaults).
|
`pwdPolicy`; and the SSO groups — then seeds `/etc/sso-manager/secrets.js`.
|
||||||
5. Installs `sso-manager.service` (systemd), enabled on boot.
|
4. Symlinks `ops/systemd/sso-manager.service` into `/etc/systemd/system` and
|
||||||
|
runs `npm ci --omit=dev`.
|
||||||
|
5. Enables and (re)starts the service.
|
||||||
|
|
||||||
> For an existing LDAP server, run `sudo ./install.sh --skip-ldap …` and point the
|
> For an existing LDAP server, run with `SKIP_LDAP=true` and write
|
||||||
> app at it. For LDAP-only setup on a host that already runs the app elsewhere, use
|
> `/etc/sso-manager/secrets.js` yourself (see `secrets.js.example`) before
|
||||||
> `--skip-app`. To (re)configure overlays on an already-installed slapd, prefer
|
> starting the service. To (re)configure overlays on an already-installed
|
||||||
> `ops/ldap-setup.sh` (idempotent, auto-detects the user database).
|
> slapd, use `ops/ldap-setup.sh` directly (idempotent, auto-detects the user
|
||||||
|
> database).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -465,8 +494,8 @@ netstat -tlnp | grep 389
|
|||||||
2. **Use LDAPS / StartTLS** for any LDAP connection that crosses the network. The
|
2. **Use LDAPS / StartTLS** for any LDAP connection that crosses the network. The
|
||||||
bundled slapd listens on `ldaps:///` (636, TLS) and `ldap:///` (389, plain +
|
bundled slapd listens on `ldaps:///` (636, TLS) and `ldap:///` (389, plain +
|
||||||
StartTLS); port 389 is not mapped to the host by default so LAN clients can't
|
StartTLS); port 389 is not mapped to the host by default so LAN clients can't
|
||||||
bind in cleartext. Direct-LDAP apps (legacy services, `theta42/proxy`) should
|
bind in cleartext. Direct-LDAP consumers (Linux hosts, LDAP-native apps,
|
||||||
use `ldaps://…:636` or StartTLS.
|
`theta42/proxy`) should use `ldaps://…:636` or StartTLS.
|
||||||
3. **Persist `JWT_SECRET`** — if the Docker image auto-generates one and you don't
|
3. **Persist `JWT_SECRET`** — if the Docker image auto-generates one and you don't
|
||||||
set `JWT_SECRET`, issued tokens invalidate on container recreation.
|
set `JWT_SECRET`, issued tokens invalidate on container recreation.
|
||||||
4. **Don't expose the UI's HTTP port to the internet** — terminate TLS at a front
|
4. **Don't expose the UI's HTTP port to the internet** — terminate TLS at a front
|
||||||
|
|||||||
@@ -33,37 +33,118 @@ RUN if [ -n "$GIT_COMMIT" ]; then \
|
|||||||
&& git rev-parse --short HEAD > /commit.txt; } 2>/dev/null || echo unknown > /commit.txt; \
|
&& git rev-parse --short HEAD > /commit.txt; } 2>/dev/null || echo unknown > /commit.txt; \
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# ── OpenLDAP from source ─────────────────────────────────────────────────────
|
||||||
|
# We build slapd from OpenLDAP master rather than installing Alpine's packages,
|
||||||
|
# for exactly one feature: the `nestgroup` overlay (ITS#10161, Howard Chu,
|
||||||
|
# 2024-03-21), which evaluates nested groups server-side. Nothing in any 2.6.x
|
||||||
|
# release can do this -- verified: 2.6.13 ships 26 overlay modules and
|
||||||
|
# nestgroup is not among them -- and the alternative is resolving nesting
|
||||||
|
# separately in every consumer (this app, SSSD on each host, jump-host, proxy),
|
||||||
|
# where any consumer that forgets silently under-grants access.
|
||||||
|
#
|
||||||
|
# Consequence to know about: master ships LMDB 1.0.0, whose on-disk format the
|
||||||
|
# 0.9.x used by 2.6.x cannot read, and vice versa
|
||||||
|
# ("MDB_INVALID: File is not an LMDB file"). Moving an existing directory onto
|
||||||
|
# this image is a slapcat/slapadd migration, not a restart. See DEPLOYMENT.md.
|
||||||
|
FROM node:20-alpine AS ldapbuild
|
||||||
|
|
||||||
|
# groff is not optional despite producing nothing we ship: the build descends
|
||||||
|
# into doc/man unconditionally and its Makefile calls soelim, which groff
|
||||||
|
# provides. Without it the whole `make` fails at the man-page stage
|
||||||
|
# ("soelim: not found") long after slapd itself has compiled fine.
|
||||||
|
RUN apk add --no-cache \
|
||||||
|
build-base autoconf automake libtool \
|
||||||
|
openssl-dev cyrus-sasl-dev \
|
||||||
|
git make pkgconf util-linux-dev groff
|
||||||
|
|
||||||
|
# Pinned to an exact commit, not a branch tip. This is the directory server the
|
||||||
|
# whole lab authenticates against; an unpinned `master` would mean every image
|
||||||
|
# rebuild silently ships whatever landed upstream that morning, and a bad day on
|
||||||
|
# master would take out logins with no way to tell what changed.
|
||||||
|
#
|
||||||
|
# TODO: drop this whole from-source stage once nestgroup ships in a release.
|
||||||
|
# It is master-only today (ITS#10161, 2024-03-21); the 2.7 roadmap has slipped
|
||||||
|
# from Fall 2024 to Fall 2025 and is still unreleased. When 2.7 lands with
|
||||||
|
# nestgroup, revert to `apk add openldap openldap-overlay-nestgroup ...` --
|
||||||
|
# the entrypoint already probes for nestgroup.so and needs no change, and the
|
||||||
|
# app already keys off app_ldap__nestedGroupsServerSide either way.
|
||||||
|
ARG OPENLDAP_COMMIT=350e9eb38b2270c2bad97c61ee02e85fb8f3196d
|
||||||
|
|
||||||
|
WORKDIR /src
|
||||||
|
RUN git init -q . \
|
||||||
|
&& git remote add origin https://git.openldap.org/openldap/openldap.git \
|
||||||
|
&& git fetch -q --depth 1 origin "${OPENLDAP_COMMIT}" \
|
||||||
|
&& git checkout -q FETCH_HEAD \
|
||||||
|
&& git rev-parse HEAD > /opt-openldap-commit.txt
|
||||||
|
|
||||||
|
# Overlays are built as loadable modules (=mod) because docker-entrypoint.sh
|
||||||
|
# `moduleload`s them individually; nestgroup joins that set.
|
||||||
|
RUN ./configure \
|
||||||
|
--prefix=/opt/openldap \
|
||||||
|
--enable-slapd \
|
||||||
|
--enable-modules \
|
||||||
|
--enable-mdb \
|
||||||
|
--enable-memberof=mod \
|
||||||
|
--enable-refint=mod \
|
||||||
|
--enable-ppolicy=mod \
|
||||||
|
--enable-dynlist=mod \
|
||||||
|
--enable-nestgroup=mod \
|
||||||
|
--enable-syncprov=mod \
|
||||||
|
--enable-auditlog=mod \
|
||||||
|
--with-tls=openssl \
|
||||||
|
--with-cyrus-sasl \
|
||||||
|
&& make depend \
|
||||||
|
&& make -j"$(nproc)" \
|
||||||
|
&& make install
|
||||||
|
|
||||||
|
# pw-sha2 provides {SSHA512}, which every existing user password is stored as.
|
||||||
|
# It lives in contrib and is not covered by the configure flags above, so it is
|
||||||
|
# built separately against the just-built tree -- omitting it would make every
|
||||||
|
# user password unverifiable.
|
||||||
|
RUN cd contrib/slapd-modules/passwd/sha2 \
|
||||||
|
&& make prefix=/opt/openldap OPENLDAP_SRC=/src \
|
||||||
|
&& cp .libs/pw-sha2.so* /opt/openldap/libexec/openldap/
|
||||||
|
|
||||||
FROM node:20-alpine
|
FROM node:20-alpine
|
||||||
|
|
||||||
# Install OpenLDAP and required packages.
|
# Runtime libraries the from-source slapd links against, plus the app's own
|
||||||
# Alpine splits OpenLDAP into many small subpackages; there is no catch-all
|
# deps. No openldap* packages here: everything LDAP comes from /opt/openldap.
|
||||||
# "openldap-overlays" package. We install exactly the backends/overlays/modules
|
# libltdl (module loading -- slapd is useless without it, since every overlay
|
||||||
# the app depends on:
|
# is a loadable module) and libuuid are pulled in by the source build but are
|
||||||
# openldap-back-mdb : the mdb backend (slapd.conf uses `database mdb`)
|
# NOT dependencies of anything else here, so they must be named explicitly;
|
||||||
# openldap-overlay-ppolicy : ppolicy module + overlay (account locking)
|
# omitting them fails at runtime with "Error relocating ... lt_dlopenext:
|
||||||
# openldap-overlay-memberof : reverse group membership
|
# symbol not found", not at build time.
|
||||||
# openldap-overlay-refint : referential integrity on group members
|
|
||||||
# openldap-passwd-sha2 : pw-sha2 module ({SSHA512} user password hashing)
|
|
||||||
# Note: Alpine does NOT ship a ppolicy.schema file — on OpenLDAP 2.6 the ppolicy
|
|
||||||
# schema is built into ppolicy.so and registered when the module loads, so
|
|
||||||
# docker-entrypoint.sh loads it via `moduleload ppolicy` (no schema include).
|
|
||||||
# openssl : used by docker-entrypoint.sh to generate a JWT secret
|
|
||||||
RUN apk add --no-cache \
|
RUN apk add --no-cache \
|
||||||
openldap \
|
openssl \
|
||||||
openldap-clients \
|
libsasl \
|
||||||
openldap-back-mdb \
|
libltdl \
|
||||||
openldap-overlay-ppolicy \
|
libuuid \
|
||||||
openldap-overlay-memberof \
|
|
||||||
openldap-overlay-refint \
|
|
||||||
openldap-passwd-sha2 \
|
|
||||||
dumb-init \
|
dumb-init \
|
||||||
bash \
|
bash \
|
||||||
openssl \
|
|
||||||
redis \
|
redis \
|
||||||
&& rm -rf /var/cache/apk/*
|
&& rm -rf /var/cache/apk/*
|
||||||
|
|
||||||
# The openldap package already creates the `ldap` user/group, which slapd runs
|
COPY --from=ldapbuild /opt/openldap /opt/openldap
|
||||||
# as (see -u ldap -g ldap in docker-entrypoint.sh). Nothing to add here.
|
# Which upstream commit this slapd was built from — so a running container can
|
||||||
|
# answer "what am I actually running" without rebuilding.
|
||||||
|
COPY --from=ldapbuild /opt-openldap-commit.txt /opt/openldap/COMMIT
|
||||||
|
|
||||||
|
# The Alpine openldap package used to create these; nothing does now, and
|
||||||
|
# docker-entrypoint.sh runs slapd as -u ldap -g ldap.
|
||||||
|
RUN addgroup -S ldap 2>/dev/null || true \
|
||||||
|
&& adduser -S -D -H -G ldap ldap 2>/dev/null || true
|
||||||
|
|
||||||
|
# docker-entrypoint.sh invokes slapd/slappasswd/ldapadd/ldapsearch by bare name
|
||||||
|
# and probes a list of candidate module directories, so putting the from-source
|
||||||
|
# tree first on PATH is all that is needed to redirect it. Schemas are symlinked
|
||||||
|
# into the conventional location because the entrypoint's slapd.conf includes
|
||||||
|
# /etc/openldap/schema/*.schema, and the app's own schemas (theta42, sudo,
|
||||||
|
# openssh-lpk) are copied there too.
|
||||||
|
ENV PATH="/opt/openldap/bin:/opt/openldap/sbin:/opt/openldap/libexec:${PATH}"
|
||||||
|
RUN mkdir -p /etc/openldap/schema \
|
||||||
|
&& for f in /opt/openldap/etc/openldap/schema/*.schema; do \
|
||||||
|
ln -sf "$f" "/etc/openldap/schema/$(basename "$f")"; \
|
||||||
|
done
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -88,6 +169,7 @@ COPY nodejs/services ./services
|
|||||||
COPY nodejs/utils ./utils
|
COPY nodejs/utils ./utils
|
||||||
COPY nodejs/views ./views
|
COPY nodejs/views ./views
|
||||||
COPY nodejs/public ./public
|
COPY nodejs/public ./public
|
||||||
|
COPY nodejs/plugins ./plugins
|
||||||
|
|
||||||
# routes/index.js reads path.join(__dirname, '../../tos.md') at boot. With the
|
# routes/index.js reads path.join(__dirname, '../../tos.md') at boot. With the
|
||||||
# app flattened into /app, __dirname is /app/routes and ../../ resolves to /,
|
# app flattened into /app, __dirname is /app/routes and ../../ resolves to /,
|
||||||
@@ -129,7 +211,8 @@ COPY ops/schema/openssh-lpk.schema /etc/openldap/schema/openssh-lpk.schema
|
|||||||
# 3001: SSO Manager web interface (HTTP — terminate TLS at the front proxy)
|
# 3001: SSO Manager web interface (HTTP — terminate TLS at the front proxy)
|
||||||
# 389: LDAP (plain + StartTLS) — used internally by the app; map to host only
|
# 389: LDAP (plain + StartTLS) — used internally by the app; map to host only
|
||||||
# if you want LAN clients to bind without TLS (not recommended).
|
# if you want LAN clients to bind without TLS (not recommended).
|
||||||
# 636: LDAPS — for legacy apps / direct LDAP binds over the network (TLS)
|
# 636: LDAPS — direct LDAP binds over the network (TLS): Linux host auth
|
||||||
|
# (PAM/SSSD, sudo, SSH keys) and LDAP-native apps
|
||||||
EXPOSE 3001 389 636
|
EXPOSE 3001 389 636
|
||||||
|
|
||||||
# Health check
|
# Health check
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Test-runner image for SSO Manager.
|
||||||
|
#
|
||||||
|
# Installs all dependencies (including dev) and bundles the app code plus
|
||||||
|
# the seed script. The entrypoint waits for LDAP + Redis, seeds the test
|
||||||
|
# user, then runs whatever command is given (default: npm test).
|
||||||
|
|
||||||
|
FROM node:20-alpine
|
||||||
|
|
||||||
|
# Install OpenLDAP clients (ldapadd, ldapsearch) and bash for the seed script
|
||||||
|
RUN apk add --no-cache openldap-clients bash
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy and install dependencies (including devDependencies for jest/supertest)
|
||||||
|
COPY nodejs/package*.json ./
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
# Copy the application source
|
||||||
|
COPY nodejs/app.js ./
|
||||||
|
COPY nodejs/bin ./bin
|
||||||
|
COPY nodejs/conf ./conf
|
||||||
|
COPY nodejs/controller ./controller
|
||||||
|
COPY nodejs/middleware ./middleware
|
||||||
|
COPY nodejs/models ./models
|
||||||
|
COPY nodejs/routes ./routes
|
||||||
|
COPY nodejs/services ./services
|
||||||
|
COPY nodejs/utils ./utils
|
||||||
|
COPY nodejs/views ./views
|
||||||
|
COPY nodejs/public ./public
|
||||||
|
COPY nodejs/tests ./tests
|
||||||
|
|
||||||
|
# SQLite database directory (config/inventory.sqlite for Resource model's ORM)
|
||||||
|
RUN mkdir -p /app/config
|
||||||
|
|
||||||
|
# Files expected at the flattened /app path (see Dockerfile.openldap notes)
|
||||||
|
COPY tos.md /tos.md
|
||||||
|
COPY README.md /README.md
|
||||||
|
COPY CHANGELOG.md /CHANGELOG.md
|
||||||
|
COPY DEPLOYMENT.md /DEPLOYMENT.md
|
||||||
|
COPY API.md /API.md
|
||||||
|
COPY directory_spec.md /directory_spec.md
|
||||||
|
COPY docs /docs
|
||||||
|
|
||||||
|
# Seed script and utility
|
||||||
|
COPY test_seed.js ./test_seed.js
|
||||||
|
COPY test/seed-test-user.sh /usr/local/bin/seed-test-user
|
||||||
|
RUN chmod +x /usr/local/bin/seed-test-user
|
||||||
|
|
||||||
|
# Default command: seed the test user, then run the test suite
|
||||||
|
CMD ["sh", "-c", "seed-test-user && npm test"]
|
||||||
@@ -25,6 +25,10 @@ phone-home, no hosted control plane, and no per-user pricing.
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| [](docs/images/groups.png) | [](docs/images/oauth-clients.png) |
|
| [](docs/images/groups.png) | [](docs/images/oauth-clients.png) |
|
||||||
|
|
||||||
|
| Sites & Replication |
|
||||||
|
| --- |
|
||||||
|
| [](docs/images/sites.png) |
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **OpenID Connect / OAuth 2.0 provider** — issue your own access, refresh, and
|
- **OpenID Connect / OAuth 2.0 provider** — issue your own access, refresh, and
|
||||||
@@ -37,13 +41,15 @@ phone-home, no hosted control plane, and no per-user pricing.
|
|||||||
- **Web management UI** — manage users, groups, and OAuth clients from a
|
- **Web management UI** — manage users, groups, and OAuth clients from a
|
||||||
browser; invite and password-reset flows over email; user self-service for
|
browser; invite and password-reset flows over email; user self-service for
|
||||||
profile and API tokens.
|
profile and API tokens.
|
||||||
- **LDAPS for legacy apps** — apps that bind LDAP directly (Gitea, Emby, and
|
- **Direct LDAP binds** — Linux hosts (PAM/SSSD login, LDAP-backed `sudo`
|
||||||
anything else that speaks LDAP) use LDAPS (636) or StartTLS against the same
|
rules, SSH public keys via openssh-lpk) and LDAP-native apps (Gitea, Emby,
|
||||||
directory, so you don't maintain a second user database for them.
|
and anything else that speaks LDAP) use LDAPS (636) or StartTLS against the
|
||||||
|
same directory, so you don't maintain a second user database for them.
|
||||||
- **Personal access tokens** — any user can mint a long-lived bearer token to
|
- **Personal access tokens** — any user can mint a long-lived bearer token to
|
||||||
drive the management API from scripts or CI, scoped to their own permissions.
|
drive the management API from scripts or CI, scoped to their own permissions.
|
||||||
- **All-in-one Docker image** — app + OpenLDAP + Redis in one container, or run
|
- **All-in-one Docker image** — app + OpenLDAP + Redis in one container, or run
|
||||||
the pieces separately against your own LDAP/Redis via `app_*` env config.
|
the pieces separately against your own LDAP/Redis via `app_*` env config.
|
||||||
|
- **Multi-Site Support (Geo-Location Scaling)** — built-in support for N-Way Multi-Master OpenLDAP replication across physical sites for HA and low latency.
|
||||||
|
|
||||||
## Why this over the alternatives
|
## Why this over the alternatives
|
||||||
|
|
||||||
@@ -107,23 +113,24 @@ vars, LDAPS/TLS, and backups.
|
|||||||
|
|
||||||
### 3. Bare metal on Debian/Ubuntu
|
### 3. Bare metal on Debian/Ubuntu
|
||||||
|
|
||||||
`install.sh` is an idempotent installer: it installs Node.js 20.x and OpenLDAP,
|
An automated installer installs Node.js, Redis, and (on first run) OpenLDAP —
|
||||||
configures the directory (modules, overlays, schema, the SSO groups), deploys
|
configuring the directory (modules, overlays, schema, the SSO groups) and
|
||||||
the app to `/opt/sso-manager`, and creates a systemd unit.
|
seeding `/etc/sso-manager/secrets.js` with a generated admin password and JWT
|
||||||
|
secret — then deploys the app to `/opt/theta42/sso-manager` and starts a
|
||||||
The only thing it requires is the LDAP admin password; the domain (base DN)
|
systemd service:
|
||||||
defaults to `dc=example,dc=com` if you don't pass one:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo ./install.sh -p 'your-ldap-password' -b 'dc=yourdomain,dc=com'
|
wget -O - https://raw.githubusercontent.com/theta42/sso-manager-node/master/install.sh | sudo bash
|
||||||
sudo systemctl enable --now sso-manager
|
|
||||||
curl http://localhost:3001/health # -> {"status":"ok"}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Run `sudo ./install.sh -h` for all flags (`-n` org name, `-o` port, `-j` JWT
|
That's it — LDAP and the app are both live afterward. Edit
|
||||||
secret, `-s` SMTP, `--skip-ldap` to use an existing LDAP, `--dry-run`). Re-run
|
`/etc/sso-manager/secrets.js` (org name, SMTP, a non-default base DN, ...) and
|
||||||
it to update. Full details in [DEPLOYMENT.md](DEPLOYMENT.md) under *Method 2:
|
restart the service to customize. It's idempotent and safe to re-run —
|
||||||
Bare metal*.
|
re-running it updates the app in place (never touching LDAP or the secrets
|
||||||
|
file again) and prints the version you're updating from and to (e.g. `Updated
|
||||||
|
v1.1.13 -> v1.1.14`), or `Already up to date` if there's nothing new. Full
|
||||||
|
details, including env var overrides (`LDAP_BASE_DN`, `SKIP_LDAP`, ...), in
|
||||||
|
[DEPLOYMENT.md](DEPLOYMENT.md) under *Method 2: Bare metal*.
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -145,7 +152,7 @@ Bare metal*.
|
|||||||
┌────────────────────────┐
|
┌────────────────────────┐
|
||||||
│ OpenLDAP (slapd) │
|
│ OpenLDAP (slapd) │
|
||||||
│ - users / groups │
|
│ - users / groups │
|
||||||
│ - LDAPS :636 │─── legacy apps bind directly
|
│ - LDAPS :636 │─── Linux hosts + LDAP apps bind directly
|
||||||
│ - StartTLS :389 │
|
│ - StartTLS :389 │
|
||||||
└────────────────────────┘
|
└────────────────────────┘
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
module.exports = {
|
||||||
|
oidc: {
|
||||||
|
clientId: '',
|
||||||
|
clientSecret: '',
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Local per-deployment configuration for this Theta42 instance.
|
||||||
|
// This file is gitignored — it contains real secrets and per-deployment
|
||||||
|
// values. The committed conf/base.js now ships generic defaults
|
||||||
|
// (example.com / localhost); the theta42-specific non-secret values that
|
||||||
|
// used to live in base.js have been migrated here so this instance keeps
|
||||||
|
// working. New deployments should put their own values here or in app_* env.
|
||||||
|
module.exports = {
|
||||||
|
port: 3001,
|
||||||
|
name: 'Theta42 SSO',
|
||||||
|
ldap: {
|
||||||
|
url: 'ldap://10.2.0.54',
|
||||||
|
bindDN: 'cn=admin,dc=theta42,dc=com',
|
||||||
|
bindPassword: 'Tomisgaypalm7',
|
||||||
|
userBase: 'ou=people,dc=theta42,dc=com',
|
||||||
|
groupBase: 'ou=groups,dc=theta42,dc=com',
|
||||||
|
},
|
||||||
|
smtp: {
|
||||||
|
host: 'mail.wgnode.com',
|
||||||
|
user: 'noreply@users.theta42.com',
|
||||||
|
// user: '',
|
||||||
|
pass: 'ZxAsQw!2',
|
||||||
|
from: 'Theta42 Accounts <noreply@users.theta42.com>',
|
||||||
|
},
|
||||||
|
voipms: {
|
||||||
|
username: 'wmantly@gmail.com',
|
||||||
|
password: 'EMjQvAuHhD!d5dm',
|
||||||
|
did: '9297353350',
|
||||||
|
},
|
||||||
|
oauth: {
|
||||||
|
issuer: 'https://sso.theta42.com',
|
||||||
|
jwtSecret: '09e2501a1c93aef4d5d713c7db17c800c6d7d6f5f9e9cf2efbdfa37549021bf9',
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
# Home-Lab Directory / Inventory — Design Spec
|
# Home-Lab Directory / Inventory — Design Spec
|
||||||
|
|
||||||
Status: **Draft / agreed direction** (no code yet)
|
Status: **Implemented** (v1.2.1+: model, admin API, UI; v1.3.x: automatic
|
||||||
|
registration from theta-env + ldap-client). §9 adds the planned-consumer
|
||||||
|
readiness review.
|
||||||
Owner: wmantly
|
Owner: wmantly
|
||||||
Last updated: 2026-07-02
|
Last updated: 2026-07-23
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -95,13 +97,24 @@ common query fields can be promoted to columns later.
|
|||||||
| column | type | notes |
|
| column | type | notes |
|
||||||
|--------------|-------------|-------|
|
|--------------|-------------|-------|
|
||||||
| `id` | uuid / pk | |
|
| `id` | uuid / pk | |
|
||||||
| `kind` | enum | `proxmox_node` \| `container` \| `vm` \| `bare_metal` \| `service` |
|
| `kind` | enum | `site` \| `host` \| `service` |
|
||||||
| `name` | text | display name ("Home Assistant", "ct101") |
|
| `name` | text | display name ("Home Assistant", "ct101") |
|
||||||
| `slug` | text unique | url-safe id used by the API |
|
| `slug` | text unique | url-safe id used by the API |
|
||||||
| `description`| text | free text |
|
| `description`| text | free text |
|
||||||
| `metadata` | jsonb | `{ url, icon, fqdn, ip, port, tags[], … }` |
|
| `metadata` | jsonb | `{ subType, ip, macAddress, address, vmid, port, externalPort, gitRepo, installPath, systemdService, os, kernel, isProduction, isExternalReachable, isPublic }` |
|
||||||
| `created_at` / `updated_at` | timestamptz | |
|
| `created_at` / `updated_at` | timestamptz | |
|
||||||
|
|
||||||
|
**Parent Enforcement Rules:**
|
||||||
|
- A **Host** MUST have a parent **Site** or **Host**.
|
||||||
|
- A **Service** MUST have a parent **Host**.
|
||||||
|
- An **OAuth Integration** MUST have a parent **Service**.
|
||||||
|
|
||||||
|
**LDAP Group Auto-Creation:**
|
||||||
|
When a Host or Service is created, the system will automatically create two LDAP groups in the directory (if they do not already exist):
|
||||||
|
- `<slug>_access` (for standard user access)
|
||||||
|
- `<slug>_admin` (for administrative access)
|
||||||
|
Additional groups can still be linked manually.
|
||||||
|
|
||||||
### `resource_edge` — directed relationships (the graph)
|
### `resource_edge` — directed relationships (the graph)
|
||||||
| column | type | notes |
|
| column | type | notes |
|
||||||
|--------------|--------|-------|
|
|--------------|--------|-------|
|
||||||
@@ -109,7 +122,7 @@ common query fields can be promoted to columns later.
|
|||||||
| `child_id` | fk → resource | |
|
| `child_id` | fk → resource | |
|
||||||
| `relation` | enum | `runs_on` \| `hosts` \| `exposes` \| `depends_on` |
|
| `relation` | enum | `runs_on` \| `hosts` \| `exposes` \| `depends_on` |
|
||||||
|
|
||||||
Represents host←container←service (`hosts`/`runs_on`) and service→service
|
Represents site←host←service (`hosts`/`runs_on`) and service→service
|
||||||
(`depends_on`). Directed edges (not a single `parent_id` column) so a node can have
|
(`depends_on`). Directed edges (not a single `parent_id` column) so a node can have
|
||||||
multiple parents/children and multiple relation types.
|
multiple parents/children and multiple relation types.
|
||||||
|
|
||||||
@@ -164,12 +177,7 @@ Write endpoints (POST/PUT/DELETE) are **out of scope for v1**; population is man
|
|||||||
|
|
||||||
- **Interactive users:** existing session auth — `middleware.auth` validating the
|
- **Interactive users:** existing session auth — `middleware.auth` validating the
|
||||||
`auth-token` header (an `AuthToken`, `models/token.js`). No change.
|
`auth-token` header (an `AuthToken`, `models/token.js`). No change.
|
||||||
- **CI/CD (machine) access:** the app does **not yet** have a long-lived service
|
- **CI/CD (machine) access:** scripts and external integrations (like jump hosts) will use the existing `ApiToken` system (Personal Access Tokens) passed in the `Authorization: Bearer sso_...` header. The `ApiToken` inherits the exact LDAP group permissions of the user who created it, seamlessly mapping to existing access controls.
|
||||||
token — `AuthToken` is session-oriented. **Proposed small addition:** a
|
|
||||||
`ServiceToken` subclass in `models/token.js` (mirrors `AuthToken`/`ImpersonationToken`),
|
|
||||||
long-lived, read-only, passed in the same `auth-token` header. Track as its own
|
|
||||||
task; the discovery API should assume it exists but degrade to normal auth tokens
|
|
||||||
until then.
|
|
||||||
- **Read visibility (decision to confirm):** either (a) any authenticated user may
|
- **Read visibility (decision to confirm):** either (a) any authenticated user may
|
||||||
read all resource metadata and only `/me` is filtered, or (b) list endpoints are
|
read all resource metadata and only `/me` is filtered, or (b) list endpoints are
|
||||||
themselves filtered to entitlement. Recommend **(a)** for a home lab — simpler,
|
themselves filtered to entitlement. Recommend **(a)** for a home lab — simpler,
|
||||||
@@ -195,7 +203,7 @@ Write endpoints (POST/PUT/DELETE) are **out of scope for v1**; population is man
|
|||||||
## 7. Roadmap
|
## 7. Roadmap
|
||||||
|
|
||||||
1. **v1 — Discovery API** (this spec's focus): SQL schema + migrations, read models,
|
1. **v1 — Discovery API** (this spec's focus): SQL schema + migrations, read models,
|
||||||
`/api/discovery/*` endpoints, `ServiceToken` for CI/CD.
|
`/api/discovery/*` endpoints, `ApiToken` for CI/CD.
|
||||||
2. **v2 — "My Access" dashboard**: swap `profile.ejs`'s static list for `/me`.
|
2. **v2 — "My Access" dashboard**: swap `profile.ejs`'s static list for `/me`.
|
||||||
3. **v3 — Admin CRUD UI**: manage resources/edges/group links (reusing `app.ui`
|
3. **v3 — Admin CRUD UI**: manage resources/edges/group links (reusing `app.ui`
|
||||||
widgets and the `oauth_clients.ejs` card+modal pattern); gated by
|
widgets and the `oauth_clients.ejs` card+modal pattern); gated by
|
||||||
@@ -213,4 +221,149 @@ Write endpoints (POST/PUT/DELETE) are **out of scope for v1**; population is man
|
|||||||
`description` so LDAP-only external consumers see it? **Default: no** — keep LDAP
|
`description` so LDAP-only external consumers see it? **Default: no** — keep LDAP
|
||||||
for auth, SQL for inventory.
|
for auth, SQL for inventory.
|
||||||
4. **Read-visibility policy:** confirm option (a) vs (b) in §5.
|
4. **Read-visibility policy:** confirm option (a) vs (b) in §5.
|
||||||
5. **Service token scope:** read-only globally, or per-token resource/kind scoping?
|
5. **Service token scope:** Currently `ApiToken` shares the creator's full permissions. A future enhancement could scope tokens specifically to the Directory API.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Planned consumers — data-model & API readiness
|
||||||
|
|
||||||
|
Five consumers the directory data should be able to power. None are being
|
||||||
|
built yet; this section records what each needs, what already exists, and the
|
||||||
|
gaps to close so the model/API never paints us into a corner.
|
||||||
|
|
||||||
|
The recurring theme: **the graph model itself (Resource / ResourceEdge /
|
||||||
|
ResourceGroup + LDAP groups) is sufficient for all five.** The gaps are
|
||||||
|
(a) one new model (access requests), (b) machine-to-machine auth for the read
|
||||||
|
API, (c) documented metadata conventions instead of new columns, and
|
||||||
|
(d) change detection for the drift/sync consumers.
|
||||||
|
|
||||||
|
### 9.1 End-user exploration ("Netflix-style" catalog + request access)
|
||||||
|
|
||||||
|
A user browses everything that exists — part advertisement, part
|
||||||
|
documentation — sees what they already have, and requests access to the rest.
|
||||||
|
|
||||||
|
Already there:
|
||||||
|
- `/api/discovery/me` (`getMyAccess`) — the "My Services" half.
|
||||||
|
- `Resource.owner` + `<slug>_access` / `<slug>_admin` ResourceGroup links —
|
||||||
|
who approves, and which group an approval means joining.
|
||||||
|
- The Notification model — the approval-request delivery mechanism.
|
||||||
|
|
||||||
|
Gaps:
|
||||||
|
1. **Catalog projection with metadata privacy.** `/api/discovery/resources`
|
||||||
|
returns full `metadata` to any authenticated user — including the OAuth
|
||||||
|
kind's `client_secret_hash`, and operator notes that may name internal
|
||||||
|
IPs. Needed: a per-kind public projection (name, description, kind,
|
||||||
|
subType, icon, address, hasAccess, requestable) and a private-key
|
||||||
|
convention for the rest (e.g. only `app_sso_directory_admin` sees full
|
||||||
|
metadata). This is a **fix worth doing before any catalog UI exists**.
|
||||||
|
2. **`AccessRequest` model** — the one genuinely new model:
|
||||||
|
`{id, uid, resourceId, groupCn, status: pending|approved|denied, note,
|
||||||
|
requestedOn, decidedBy, decidedOn}`. Approval = LDAP group add + notify.
|
||||||
|
Endpoints: user POST/GET own; resource owner / directory admin
|
||||||
|
list/approve/deny.
|
||||||
|
3. **Catalog metadata conventions**: `icon`, `tagline` (card-length blurb),
|
||||||
|
`requestable: false` for resources that shouldn't be advertised.
|
||||||
|
|
||||||
|
### 9.2 SSH jump host (`username_-_{hostname-or-ip}@publicHost`)
|
||||||
|
|
||||||
|
A public jump host parses the target out of the SSH username, checks the user
|
||||||
|
may reach that host, and proxies the connection (WinSCP-friendly: one
|
||||||
|
username string, no interactive menu needed — though an interactive picker on
|
||||||
|
plain `username@` login is the same query).
|
||||||
|
|
||||||
|
Already there:
|
||||||
|
- Hosts carry `ip` (and `host_<hostname>` slugs to resolve by name).
|
||||||
|
- Access is already group-based (`<slug>_access`), checkable via LDAP alone —
|
||||||
|
the jump host can run entirely off LDAP (SSSD) + one directory query.
|
||||||
|
- User SSH keys are in LDAP (openssh-lpk) — the jump host authenticates the
|
||||||
|
real user without local accounts.
|
||||||
|
|
||||||
|
Gaps:
|
||||||
|
1. **Machine auth for the access query.** The jump host must ask "may user X
|
||||||
|
reach host Y" / "list hosts user X may reach" *about another user*.
|
||||||
|
`getMyAccess` only answers for the calling user. Needed: a
|
||||||
|
service-token-authenticated endpoint (`GET
|
||||||
|
/api/discovery/access/:uid[/:slug]`). `ServiceToken` already exists and
|
||||||
|
is even linked to a resource (`resource_id`) — what's missing is an auth
|
||||||
|
middleware that accepts it and a permission rule ("service tokens may
|
||||||
|
read access info, scoped read-only").
|
||||||
|
2. **Connection metadata conventions** on hosts: `sshPort` (default 22),
|
||||||
|
optional `fqdn` (when IP is dynamic), optional `jumpVia` edge relation if
|
||||||
|
multi-hop topologies ever appear.
|
||||||
|
3. Document the username grammar (`{uid}_-_{host-slug-or-ip}`) here so the
|
||||||
|
seed/ldap-client keep host slugs DNS-safe (they already are: slugify
|
||||||
|
strips everything but `[a-z0-9-]`).
|
||||||
|
|
||||||
|
### 9.3 Firewall port-forward rules (build / update / drift-test)
|
||||||
|
|
||||||
|
An automation renders the public firewall's forwarding table from the
|
||||||
|
directory, applies it, and alerts on drift in either direction.
|
||||||
|
|
||||||
|
Already there:
|
||||||
|
- `metadata.port` / `metadata.externalPort` / `metadata.ip` /
|
||||||
|
`metadata.isExternalReachable` — the core mapping data, already seeded for
|
||||||
|
the stack's own services.
|
||||||
|
|
||||||
|
Gaps:
|
||||||
|
1. **Port-mapping convention is too thin for real rules**: no protocol, no
|
||||||
|
multi-port services. Adopt `metadata.portMappings: [{proto: "tcp"|"udp",
|
||||||
|
external: n, internal: n, comment}]` as the authoritative form
|
||||||
|
(`port`/`externalPort` stay as the simple single-mapping case).
|
||||||
|
2. **Drift detection needs cheap change polling**: an `updated_on` timestamp
|
||||||
|
on resources surfaced in the graph API, or a graph-level etag/hash, so
|
||||||
|
the runner can poll without diffing full payloads. (The ORM already
|
||||||
|
publishes create/update events internally — a future push feed can ride
|
||||||
|
that; polling comes first.)
|
||||||
|
3. Same **service-token read auth** as 9.2 — automation must not run on a
|
||||||
|
human's session token.
|
||||||
|
|
||||||
|
### 9.4 Local DNS / mDNS
|
||||||
|
|
||||||
|
A DNS (or mDNS advertiser) zone is generated from the directory: hosts get
|
||||||
|
A records from `metadata.ip`, services get CNAMEs/records from their
|
||||||
|
addresses, sites map to zones.
|
||||||
|
|
||||||
|
Already there:
|
||||||
|
- `host_<hostname>` + `ip` covers A records; `site_<name>` is a natural zone
|
||||||
|
boundary; service `address` yields names.
|
||||||
|
|
||||||
|
Gaps:
|
||||||
|
1. **Name conventions**: `metadata.dnsNames: []` for extra aliases, and a
|
||||||
|
documented rule for which name wins (slug vs `address` hostname). TTL
|
||||||
|
only if someone actually needs per-record TTLs — default is fine.
|
||||||
|
2. Same **change detection** as 9.3 (poll `updated_on` / etag; push later).
|
||||||
|
3. Nothing else — this consumer is nearly free once 9.3's conventions land.
|
||||||
|
|
||||||
|
### 9.5 Access control for hosts
|
||||||
|
|
||||||
|
Who may log in to / sudo on which machine, driven by the directory.
|
||||||
|
|
||||||
|
Already there — this is the original point of the system:
|
||||||
|
- `<slug>_access` / `<slug>_admin` groups are auto-provisioned per host;
|
||||||
|
ldap-client configures SSSD/PAM against the directory; `sudoRole` and
|
||||||
|
openssh-lpk schemas cover sudo and SSH keys.
|
||||||
|
|
||||||
|
Gaps:
|
||||||
|
1. **Close the loop in ldap-client**: joined hosts should set an SSSD access
|
||||||
|
filter (`access_provider = ldap`, filter on `host_<hostname>_access`
|
||||||
|
membership) so directory group membership *is* login permission, not just
|
||||||
|
identity. Today the registration exists but enforcement is host-side
|
||||||
|
convention.
|
||||||
|
2. **`accessLevel` granularity**: ResourceGroup's `member`/`owner` maps to
|
||||||
|
login/admin today; if finer roles emerge (e.g. `login` vs `sudo` vs
|
||||||
|
`admin`), extend the enum — the join-table shape already supports it.
|
||||||
|
|
||||||
|
### 9.6 Consolidated work list (model/API only, no consumers)
|
||||||
|
|
||||||
|
Ordered by how much they unblock:
|
||||||
|
|
||||||
|
1. **Metadata privacy projection** on the read API (blocks 9.1; fixes the
|
||||||
|
`client_secret_hash` exposure regardless of any consumer).
|
||||||
|
2. **Service-token auth for `/api/discovery/*`** + `access/:uid` endpoint
|
||||||
|
(blocks 9.2, 9.3; ServiceToken model already exists).
|
||||||
|
3. **`AccessRequest` model + endpoints** (blocks 9.1's request half).
|
||||||
|
4. **Metadata conventions doc entries** (`sshPort`, `portMappings`,
|
||||||
|
`dnsNames`, `icon`, `tagline`, `requestable`) in `docs/directory.md` —
|
||||||
|
conventions, not schema changes; the json column already holds them.
|
||||||
|
5. **`updated_on` in graph output / graph etag** (blocks drift/DNS
|
||||||
|
freshness; trivial once surfaced).
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
services:
|
||||||
|
site1:
|
||||||
|
build: .
|
||||||
|
container_name: sso_site1
|
||||||
|
environment:
|
||||||
|
- LDAP_SERVER_ID=1
|
||||||
|
- LDAP_REPLICATION_HOSTS=ldap://site2:389
|
||||||
|
- LDAP_BASE_DN=dc=test,dc=local
|
||||||
|
- LDAP_ADMIN_PASS=secret
|
||||||
|
ports:
|
||||||
|
- "3001:3001"
|
||||||
|
- "10389:389"
|
||||||
|
volumes:
|
||||||
|
- site1-ldap:/var/lib/ldap
|
||||||
|
- site1-redis:/data
|
||||||
|
|
||||||
|
site2:
|
||||||
|
build: .
|
||||||
|
container_name: sso_site2
|
||||||
|
environment:
|
||||||
|
- LDAP_SERVER_ID=2
|
||||||
|
- LDAP_REPLICATION_HOSTS=ldap://site1:389
|
||||||
|
- LDAP_BASE_DN=dc=test,dc=local
|
||||||
|
- LDAP_ADMIN_PASS=secret
|
||||||
|
ports:
|
||||||
|
- "3002:3001"
|
||||||
|
- "20389:389"
|
||||||
|
volumes:
|
||||||
|
- site2-ldap:/var/lib/ldap
|
||||||
|
- site2-redis:/data
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
site1-ldap:
|
||||||
|
site1-redis:
|
||||||
|
site2-ldap:
|
||||||
|
site2-redis:
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# Docker Compose for running the SSO Manager test suite.
|
||||||
|
#
|
||||||
|
# Spins up:
|
||||||
|
# ldap — OpenLDAP + Redis (all-in-one image, slapd + redis only, no app)
|
||||||
|
# redis — Standalone Redis for the app's model/token storage
|
||||||
|
# test-runner — Seeds the test user, then runs `npm test`
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# docker compose -f docker-compose.test.yml up --build
|
||||||
|
# # Or to run a specific test file:
|
||||||
|
# docker compose -f docker-compose.test.yml run --rm test-runner npx jest tests/auth.test.js
|
||||||
|
#
|
||||||
|
# The LDAP service uses the same Dockerfile.openldap image as production but
|
||||||
|
# overrides the command to only start slapd + redis (the entrypoint handles
|
||||||
|
# slapd.conf generation, directory initialization, and Redis startup before
|
||||||
|
# running the given command — "sleep infinity" keeps it alive).
|
||||||
|
#
|
||||||
|
# The test-runner connects to ldap:389 and redis:6379 via Docker networking.
|
||||||
|
# app_* env vars override conf/secrets.js (highest precedence in
|
||||||
|
# @simpleworkjs/conf), so the production secrets.js is never read.
|
||||||
|
|
||||||
|
services:
|
||||||
|
ldap:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile.openldap
|
||||||
|
environment:
|
||||||
|
- LDAP_BASE_DN=dc=test,dc=local
|
||||||
|
- LDAP_ADMIN_PASS=secret
|
||||||
|
- ORG_NAME=Test SSO
|
||||||
|
# The entrypoint starts slapd + redis, then runs whatever command is given.
|
||||||
|
# "sleep infinity" keeps the container alive so the test-runner can connect.
|
||||||
|
command: ["sleep", "infinity"]
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "ldapsearch -x -H ldap://localhost:389 -b '' -s base '(objectClass=*)' >/dev/null 2>&1"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
start_period: 5s
|
||||||
|
volumes:
|
||||||
|
- ldap-data:/var/lib/ldap
|
||||||
|
- ldap-certs:/etc/openldap/certs
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 15
|
||||||
|
|
||||||
|
test-runner:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile.test-runner
|
||||||
|
environment:
|
||||||
|
# Tell the app which environment it's in (loads conf/test.js for Redis prefix)
|
||||||
|
- NODE_ENV=test
|
||||||
|
# LDAP — point at the ldap service container
|
||||||
|
- app_ldap__url=ldap://ldap:389
|
||||||
|
- app_ldap__bindDN=cn=admin,dc=test,dc=local
|
||||||
|
- app_ldap__bindPassword=secret
|
||||||
|
- app_ldap__userBase=ou=people,dc=test,dc=local
|
||||||
|
- app_ldap__groupBase=ou=groups,dc=test,dc=local
|
||||||
|
# Redis — point at the redis service container
|
||||||
|
- app_redis__redisConf__url=redis://redis:6379
|
||||||
|
# Also used by tests/globalSetup.js (direct Redis client, not @simpleworkjs/conf)
|
||||||
|
- REDIS_URL=redis://redis:6379
|
||||||
|
# JWT secret (required by the app, not sensitive in test)
|
||||||
|
- app_oauth__jwtSecret=test-jwt-secret-for-testing-only
|
||||||
|
# App name
|
||||||
|
- app_name=Test SSO
|
||||||
|
depends_on:
|
||||||
|
ldap:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
ldap-data:
|
||||||
|
ldap-certs:
|
||||||
@@ -6,12 +6,12 @@
|
|||||||
# production, run a dedicated LDAP server and point the app at it via app_*
|
# production, run a dedicated LDAP server and point the app at it via app_*
|
||||||
# env vars (or a mounted conf/secrets.js) using the app-only image.
|
# env vars (or a mounted conf/secrets.js) using the app-only image.
|
||||||
#
|
#
|
||||||
# The app reads its configuration from conf/base.js + conf/secrets.js, deep-merged
|
# The app reads its configuration from conf/base.js + a secrets file, deep-merged
|
||||||
# by @simpleworkjs/conf, with `app_*` environment variables as the
|
# by @simpleworkjs/conf (requires >= 1.2.0, pinned in nodejs/package-lock.json),
|
||||||
# highest-precedence override layer. This entrypoint exports those `app_*`
|
# with `app_*` environment variables as the highest-precedence override layer.
|
||||||
# vars so the app connects to the bundled slapd without any mounted secrets
|
# This entrypoint exports those `app_*` vars so the app connects to the bundled
|
||||||
# file. Any `app_*` var already set in the environment wins (the values below
|
# slapd without any mounted secrets file. Any `app_*` var already set in the
|
||||||
# are defaults/fallbacks only).
|
# environment wins (the values below are defaults/fallbacks only).
|
||||||
|
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
@@ -33,14 +33,15 @@ error() { echo "[ERROR] $*" >&2; }
|
|||||||
# ── Optional: load operational config from a mounted secrets.js ──────────────
|
# ── Optional: load operational config from a mounted secrets.js ──────────────
|
||||||
# The unified theta-env stack mounts ./config/sso-secrets.js at /config and
|
# The unified theta-env stack mounts ./config/sso-secrets.js at /config and
|
||||||
# treats it as the authoritative source for the SSO's config (LDAP base, admin
|
# treats it as the authoritative source for the SSO's config (LDAP base, admin
|
||||||
# password, org name, JWT secret, ...). When present, symlink it into
|
# password, org name, JWT secret, ...). When present, point CONF_SECRETS at it
|
||||||
# /app/conf/secrets.js so @simpleworkjs/conf reads it, and override the
|
# so @simpleworkjs/conf reads it directly (no write access to /app/conf
|
||||||
# env-derived operational vars below with the file's values. When absent
|
# needed), and override the env-derived operational vars below with the
|
||||||
# (standalone / env-var deployments) the env vars set above stay in effect and
|
# file's values. When absent (standalone / env-var deployments) the env vars
|
||||||
# the app_* exports further down are emitted as before.
|
# set above stay in effect and the app_* exports further down are emitted as
|
||||||
|
# before.
|
||||||
SECRETS_JS_MODE=0
|
SECRETS_JS_MODE=0
|
||||||
if [[ -f /config/sso-secrets.js ]]; then
|
if [[ -f /config/sso-secrets.js ]]; then
|
||||||
ln -sf /config/sso-secrets.js /app/conf/secrets.js
|
export CONF_SECRETS=/config/sso-secrets.js
|
||||||
SECRETS_JS_MODE=1
|
SECRETS_JS_MODE=1
|
||||||
# Pull the entrypoint's operational vars out of secrets.js in one node call.
|
# Pull the entrypoint's operational vars out of secrets.js in one node call.
|
||||||
# Node emits `KEY<TAB>base64(value)` lines; we decode each with base64 -d and
|
# Node emits `KEY<TAB>base64(value)` lines; we decode each with base64 -d and
|
||||||
@@ -75,11 +76,22 @@ fi
|
|||||||
# ── Locate the OpenLDAP module directory ────────────────────────────────────
|
# ── Locate the OpenLDAP module directory ────────────────────────────────────
|
||||||
# slapd.conf needs `modulepath` to find pw-sha2/ppolicy/memberof/refint. The
|
# slapd.conf needs `modulepath` to find pw-sha2/ppolicy/memberof/refint. The
|
||||||
# path varies by distro; auto-detect rather than hardcode.
|
# path varies by distro; auto-detect rather than hardcode.
|
||||||
|
# /opt/openldap/libexec/openldap is first: that is the from-source build (see
|
||||||
|
# Dockerfile.openldap), which is the only one carrying the nestgroup overlay.
|
||||||
MODULE_PATH=""
|
MODULE_PATH=""
|
||||||
for p in /usr/lib/openldap /usr/lib/ldap /usr/local/lib/openldap /opt/local/lib/openldap; do
|
for p in /opt/openldap/libexec/openldap /usr/lib/openldap /usr/lib/ldap /usr/local/lib/openldap /opt/local/lib/openldap; do
|
||||||
if [[ -d "$p" ]]; then MODULE_PATH="$p"; break; fi
|
if [[ -d "$p" ]]; then MODULE_PATH="$p"; break; fi
|
||||||
done
|
done
|
||||||
|
|
||||||
|
# Nested-group support is only available when slapd was built with the
|
||||||
|
# nestgroup overlay. Detect rather than assume, so this entrypoint still
|
||||||
|
# produces a working slapd.conf against a distro OpenLDAP (where the app falls
|
||||||
|
# back to resolving nesting itself -- see nodejs/models/group_ldap.js).
|
||||||
|
NESTGROUP_AVAILABLE=0
|
||||||
|
if [[ -n "$MODULE_PATH" && -f "$MODULE_PATH/nestgroup.so" ]]; then
|
||||||
|
NESTGROUP_AVAILABLE=1
|
||||||
|
fi
|
||||||
|
|
||||||
# ── TLS certificate for LDAPS / StartTLS ────────────────────────────────────
|
# ── TLS certificate for LDAPS / StartTLS ────────────────────────────────────
|
||||||
# Legacy apps (e.g. the theta42/proxy, Gitea, Emby) bind to LDAP directly over the
|
# Legacy apps (e.g. the theta42/proxy, Gitea, Emby) bind to LDAP directly over the
|
||||||
# network. To keep password binds off the wire in cleartext we expose LDAPS
|
# network. To keep password binds off the wire in cleartext we expose LDAPS
|
||||||
@@ -124,6 +136,8 @@ include /etc/openldap/schema/theta42.schema
|
|||||||
include /etc/openldap/schema/sudo.schema
|
include /etc/openldap/schema/sudo.schema
|
||||||
include /etc/openldap/schema/openssh-lpk.schema
|
include /etc/openldap/schema/openssh-lpk.schema
|
||||||
|
|
||||||
|
SERVER_ID_PLACEHOLDER
|
||||||
|
|
||||||
# Module loading (pw-sha2 provides {SSHA512} used by the app for user passwords;
|
# Module loading (pw-sha2 provides {SSHA512} used by the app for user passwords;
|
||||||
# ppolicy/memberof/refint are the overlays the app depends on). On OpenLDAP 2.5+
|
# ppolicy/memberof/refint are the overlays the app depends on). On OpenLDAP 2.5+
|
||||||
# the ppolicy schema (pwdPolicy, pwdAccountLockedTime, ...) is built into
|
# the ppolicy schema (pwdPolicy, pwdAccountLockedTime, ...) is built into
|
||||||
@@ -136,6 +150,9 @@ moduleload pw-sha2
|
|||||||
moduleload ppolicy
|
moduleload ppolicy
|
||||||
moduleload memberof
|
moduleload memberof
|
||||||
moduleload refint
|
moduleload refint
|
||||||
|
moduleload auditlog
|
||||||
|
NESTGROUP_MODULE_PLACEHOLDER
|
||||||
|
SYNCPROV_MODULE_PLACEHOLDER
|
||||||
|
|
||||||
# TLS (LDAPS on 636 + StartTLS on 389). Cert/key paths are fixed; the files are
|
# TLS (LDAPS on 636 + StartTLS on 389). Cert/key paths are fixed; the files are
|
||||||
# generated/mounted above. We accept clients without their own cert (the common
|
# generated/mounted above. We accept clients without their own cert (the common
|
||||||
@@ -183,6 +200,14 @@ memberof-memberof-ad memberOf
|
|||||||
overlay refint
|
overlay refint
|
||||||
refint_attributes memberOf member manager owner
|
refint_attributes memberOf member manager owner
|
||||||
|
|
||||||
|
NESTGROUP_OVERLAY_PLACEHOLDER
|
||||||
|
|
||||||
|
# auditlog overlay (LDIF audit trail of all changes)
|
||||||
|
overlay auditlog
|
||||||
|
auditlog /var/lib/ldap/auditlog.ldif
|
||||||
|
|
||||||
|
REPLICATION_BLOCK_PLACEHOLDER
|
||||||
|
|
||||||
# Access controls
|
# Access controls
|
||||||
access to attrs=userPassword
|
access to attrs=userPassword
|
||||||
by dn="BIND_DN_PLACEHOLDER" write
|
by dn="BIND_DN_PLACEHOLDER" write
|
||||||
@@ -210,6 +235,61 @@ else
|
|||||||
sed -i "/^SLAPMODULEPATH$/d" /etc/openldap/slapd.conf
|
sed -i "/^SLAPMODULEPATH$/d" /etc/openldap/slapd.conf
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# ── Nested groups (nestgroup overlay) ──
|
||||||
|
# Three of the four flags, deliberately:
|
||||||
|
#
|
||||||
|
# member-filter (member=X) finds parent groups transitively. This is what
|
||||||
|
# Group.list(dn) rides on -- the core access question.
|
||||||
|
# memberof-filter (memberOf=X) matches members of nested groups. This is
|
||||||
|
# what SSSD's ldap_access_filter uses, so SSH/sudo inherit
|
||||||
|
# nesting without any client-side walking.
|
||||||
|
# memberof-values expands memberOf when reading a user, so anything that
|
||||||
|
# reads the attribute rather than searching still sees the
|
||||||
|
# full picture.
|
||||||
|
#
|
||||||
|
# member-values is deliberately NOT enabled. It expands the `member` attribute
|
||||||
|
# when reading a *group*, which sounds symmetric but destroys the distinction
|
||||||
|
# between "listed on this group" and "reachable through a nested one" -- and
|
||||||
|
# that distinction is not recoverable afterwards, because the raw values are
|
||||||
|
# simply not returned. The Groups UI needs it to show nested groups as nested
|
||||||
|
# rather than as a crowd of phantom users, and un-nesting needs it to know what
|
||||||
|
# it is actually removing. Transitive *answers* come from the filter flags and
|
||||||
|
# from Group.effectiveMembers(), which computes the closure explicitly.
|
||||||
|
if [[ "$NESTGROUP_AVAILABLE" == "1" ]]; then
|
||||||
|
info "nestgroup overlay available — nested groups resolved server-side"
|
||||||
|
sed -i "s|^NESTGROUP_MODULE_PLACEHOLDER$|moduleload nestgroup|" /etc/openldap/slapd.conf
|
||||||
|
NESTGROUP_BLOCK="# nestgroup overlay (server-side nested group evaluation)\noverlay nestgroup\nnestgroup-base ou=groups,${LDAP_BASE_DN}\nnestgroup-flags member-filter memberof-filter memberof-values"
|
||||||
|
sed -i "s|^NESTGROUP_OVERLAY_PLACEHOLDER$|${NESTGROUP_BLOCK}|" /etc/openldap/slapd.conf
|
||||||
|
else
|
||||||
|
info "nestgroup overlay not present in ${MODULE_PATH:-<no module path>} — nested groups will be resolved by the app instead"
|
||||||
|
sed -i "/^NESTGROUP_MODULE_PLACEHOLDER$/d" /etc/openldap/slapd.conf
|
||||||
|
sed -i "/^NESTGROUP_OVERLAY_PLACEHOLDER$/d" /etc/openldap/slapd.conf
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Multi-Master Replication Configuration ──
|
||||||
|
if [[ -n "${LDAP_SERVER_ID:-}" && -n "${LDAP_REPLICATION_HOSTS:-}" ]]; then
|
||||||
|
info "Configuring Multi-Master replication (Server ID: ${LDAP_SERVER_ID})"
|
||||||
|
sed -i "s|^SERVER_ID_PLACEHOLDER|ServerID ${LDAP_SERVER_ID}|" /etc/openldap/slapd.conf
|
||||||
|
sed -i "s|^SYNCPROV_MODULE_PLACEHOLDER|moduleload syncprov|" /etc/openldap/slapd.conf
|
||||||
|
|
||||||
|
# Generate syncrepl blocks
|
||||||
|
REPL_BLOCK="overlay syncprov\nsyncprov-checkpoint 100 10\nsyncprov-sessionlog 100\n\n"
|
||||||
|
RID=100
|
||||||
|
for HOST in ${LDAP_REPLICATION_HOSTS}; do
|
||||||
|
RID=$((RID + 1))
|
||||||
|
REPL_BLOCK="${REPL_BLOCK}syncrepl rid=${RID}\n provider=${HOST}\n type=refreshAndPersist\n retry=\"60 +\"\n searchbase=\"${LDAP_BASE_DN}\"\n bindmethod=simple\n binddn=\"${LDAP_BIND_DN}\"\n credentials=\"${LDAP_ADMIN_PASS}\"\n\n"
|
||||||
|
done
|
||||||
|
REPL_BLOCK="${REPL_BLOCK}mirrormode on\n"
|
||||||
|
|
||||||
|
# Replace placeholder (awk is safer for multiline replacements than sed)
|
||||||
|
awk -v repl="$(printf '%b' "$REPL_BLOCK")" '{gsub(/REPLICATION_BLOCK_PLACEHOLDER/, repl)}1' /etc/openldap/slapd.conf > /etc/openldap/slapd.conf.tmp
|
||||||
|
mv /etc/openldap/slapd.conf.tmp /etc/openldap/slapd.conf
|
||||||
|
else
|
||||||
|
sed -i "/^SERVER_ID_PLACEHOLDER/d" /etc/openldap/slapd.conf
|
||||||
|
sed -i "/^SYNCPROV_MODULE_PLACEHOLDER/d" /etc/openldap/slapd.conf
|
||||||
|
sed -i "/^REPLICATION_BLOCK_PLACEHOLDER/d" /etc/openldap/slapd.conf
|
||||||
|
fi
|
||||||
|
|
||||||
chown ldap:ldap /etc/openldap/slapd.conf 2>/dev/null || true
|
chown ldap:ldap /etc/openldap/slapd.conf 2>/dev/null || true
|
||||||
chown -R ldap:ldap /var/lib/ldap 2>/dev/null || true
|
chown -R ldap:ldap /var/lib/ldap 2>/dev/null || true
|
||||||
|
|
||||||
@@ -219,7 +299,7 @@ info "Starting OpenLDAP (base DN: ${LDAP_BASE_DN})..."
|
|||||||
# -h listens on ldap:/// (389: plain + StartTLS) and ldaps:/// (636: LDAPS).
|
# -h listens on ldap:/// (389: plain + StartTLS) and ldaps:/// (636: LDAPS).
|
||||||
# ldapi:/// is intentionally omitted: its default socket dir doesn't exist on
|
# ldapi:/// is intentionally omitted: its default socket dir doesn't exist on
|
||||||
# Alpine and the container only uses simple bind over ldap://localhost:389.
|
# Alpine and the container only uses simple bind over ldap://localhost:389.
|
||||||
slapd -d 0 -u ldap -g ldap -f /etc/openldap/slapd.conf -h "ldap:/// ldaps:///" &
|
slapd -d 256 -u ldap -g ldap -f /etc/openldap/slapd.conf -h "ldap:/// ldaps:///" >> /var/lib/ldap/slapd.log 2>&1 &
|
||||||
SLAPD_PID=$!
|
SLAPD_PID=$!
|
||||||
|
|
||||||
# Wait for slapd to answer the root DSE (means it's up, regardless of DB state).
|
# Wait for slapd to answer the root DSE (means it's up, regardless of DB state).
|
||||||
@@ -275,7 +355,7 @@ EOF
|
|||||||
# Required SSO groups. The app gates admin/invite/oauth-admin on these;
|
# Required SSO groups. The app gates admin/invite/oauth-admin on these;
|
||||||
# app_sso_service_account is a marker (not a permission gate) for
|
# app_sso_service_account is a marker (not a permission gate) for
|
||||||
# non-person accounts -- see the Users page.
|
# non-person accounts -- see the Users page.
|
||||||
for group in app_sso_admin app_sso_invite app_sso_oauth_admin app_sso_service_account; do
|
for group in app_super_admin app_sso_admin app_sso_invite app_sso_oauth_admin app_sso_service_account; do
|
||||||
ldapadd -x -D "$LDAP_BIND_DN" -w "$LDAP_ADMIN_PASS" -H ldap://localhost:389 << EOF || true
|
ldapadd -x -D "$LDAP_BIND_DN" -w "$LDAP_ADMIN_PASS" -H ldap://localhost:389 << EOF || true
|
||||||
dn: cn=${group},ou=groups,${LDAP_BASE_DN}
|
dn: cn=${group},ou=groups,${LDAP_BASE_DN}
|
||||||
objectClass: groupOfNames
|
objectClass: groupOfNames
|
||||||
@@ -286,6 +366,27 @@ member: ${LDAP_BIND_DN}
|
|||||||
EOF
|
EOF
|
||||||
done
|
done
|
||||||
|
|
||||||
|
# Nest app_super_admin into the SSO admin groups, so cross-app super admins
|
||||||
|
# hold those rights by membership rather than by a special case in app code.
|
||||||
|
# This is what makes the privilege visible to every consumer -- SSSD, sudo,
|
||||||
|
# anything binding LDAP directly -- instead of only to callers that happen
|
||||||
|
# to route through utils/permission.js.
|
||||||
|
#
|
||||||
|
# app_sso_service_account is deliberately excluded: it is a marker for
|
||||||
|
# non-person accounts, not a permission, and nesting admins into it would
|
||||||
|
# misclassify them as service accounts on the Users page.
|
||||||
|
if [[ "$NESTGROUP_AVAILABLE" == "1" ]]; then
|
||||||
|
for group in app_sso_admin app_sso_invite app_sso_oauth_admin; do
|
||||||
|
ldapmodify -x -D "$LDAP_BIND_DN" -w "$LDAP_ADMIN_PASS" -H ldap://localhost:389 >/dev/null 2>&1 << EOF || true
|
||||||
|
dn: cn=${group},ou=groups,${LDAP_BASE_DN}
|
||||||
|
changetype: modify
|
||||||
|
add: member
|
||||||
|
member: cn=app_super_admin,ou=groups,${LDAP_BASE_DN}
|
||||||
|
EOF
|
||||||
|
done
|
||||||
|
info "Nested app_super_admin into the SSO admin groups"
|
||||||
|
fi
|
||||||
|
|
||||||
info "LDAP directory initialized"
|
info "LDAP directory initialized"
|
||||||
else
|
else
|
||||||
info "LDAP directory already initialized — skipping seed"
|
info "LDAP directory already initialized — skipping seed"
|
||||||
@@ -345,6 +446,14 @@ if [[ "${SECRETS_JS_MODE:-0}" != 1 ]]; then
|
|||||||
export app_ldap__bindPassword="${app_ldap__bindPassword:-$LDAP_ADMIN_PASS}"
|
export app_ldap__bindPassword="${app_ldap__bindPassword:-$LDAP_ADMIN_PASS}"
|
||||||
export app_ldap__userBase="${app_ldap__userBase:-ou=people,${LDAP_BASE_DN}}"
|
export app_ldap__userBase="${app_ldap__userBase:-ou=people,${LDAP_BASE_DN}}"
|
||||||
export app_ldap__groupBase="${app_ldap__groupBase:-ou=groups,${LDAP_BASE_DN}}"
|
export app_ldap__groupBase="${app_ldap__groupBase:-ou=groups,${LDAP_BASE_DN}}"
|
||||||
|
# Tell the app whether slapd resolves nested groups for it. When true the app
|
||||||
|
# trusts a plain (member=) search to be transitive; when false it computes
|
||||||
|
# the closure itself. Getting this wrong in the "true" direction silently
|
||||||
|
# under-grants, so it is derived from the same nestgroup.so probe that
|
||||||
|
# decides whether the overlay is configured at all -- never hardcoded.
|
||||||
|
if [[ "$NESTGROUP_AVAILABLE" == "1" ]]; then
|
||||||
|
export app_ldap__nestedGroupsServerSide="${app_ldap__nestedGroupsServerSide:-true}"
|
||||||
|
fi
|
||||||
export app_oauth__jwtSecret="${app_oauth__jwtSecret:-$JWT_SECRET}"
|
export app_oauth__jwtSecret="${app_oauth__jwtSecret:-$JWT_SECRET}"
|
||||||
# OIDC issuer advertised in /.well-known/openid-configuration. Default to the
|
# OIDC issuer advertised in /.well-known/openid-configuration. Default to the
|
||||||
# public https URL on the SSO subdomain of the LDAP domain; override with
|
# public https URL on the SSO subdomain of the LDAP domain; override with
|
||||||
|
|||||||
@@ -31,6 +31,14 @@ nav:
|
|||||||
- title: LDAP
|
- title: LDAP
|
||||||
page: /ldap.html
|
page: /ldap.html
|
||||||
icon: fa-address-book
|
icon: fa-address-book
|
||||||
|
- title: Directory
|
||||||
|
page: /directory.html
|
||||||
|
icon: fa-server
|
||||||
|
# API.md lives at the repo root, not under docs/, so Jekyll never renders an
|
||||||
|
# api.html for it — link the source directly, same as the Changelog.
|
||||||
|
- title: API
|
||||||
|
url: https://github.com/theta42/sso-manager-node/blob/master/API.md
|
||||||
|
icon: fa-code
|
||||||
- title: Changelog
|
- title: Changelog
|
||||||
url: https://github.com/theta42/sso-manager-node/blob/master/CHANGELOG.md
|
url: https://github.com/theta42/sso-manager-node/blob/master/CHANGELOG.md
|
||||||
icon: fa-list
|
icon: fa-list
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
---
|
||||||
|
layout: default
|
||||||
|
title: Discovery Agents
|
||||||
|
nav_order: 5
|
||||||
|
---
|
||||||
|
|
||||||
|
# Discovery Agents
|
||||||
|
|
||||||
|
The SSO Manager supports a robust agent architecture for auto-discovering devices, hosts, and services across your home lab or data center. Agents run on a scheduled cron and feed their data into a central **Reconciliation Engine** that smartly merges information based on MAC addresses and IPs.
|
||||||
|
|
||||||
|
## Writing a Custom Agent
|
||||||
|
|
||||||
|
Agents are simple JavaScript files placed in `nodejs/agents/discovery/`.
|
||||||
|
|
||||||
|
A agent must export a single `discover` async function that returns a standardized graph of `resources` and `edges`.
|
||||||
|
|
||||||
|
### Agent Skeleton
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// nodejs/agents/discovery/my_custom_agent.js
|
||||||
|
module.exports = {
|
||||||
|
discover: async (config) => {
|
||||||
|
const { url, apiKey } = config; // Provided by your configuration
|
||||||
|
|
||||||
|
const resources = [];
|
||||||
|
const edges = [];
|
||||||
|
|
||||||
|
// 1. Fetch your data from an API
|
||||||
|
// const data = await fetch(...);
|
||||||
|
|
||||||
|
// 2. Map data to Resources
|
||||||
|
resources.push({
|
||||||
|
kind: 'network_device', // 'host', 'service', 'network_device', 'unmanaged_device'
|
||||||
|
name: 'My Switch',
|
||||||
|
slug: 'my-switch-01',
|
||||||
|
metadata: {
|
||||||
|
make: 'Vendor',
|
||||||
|
model: 'Model X',
|
||||||
|
interfaces: [
|
||||||
|
{ mac: '00:1A:2B:3C:4D:5E', ip: '10.0.0.5' }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 3. Map relations to Edges (optional)
|
||||||
|
edges.push({
|
||||||
|
parentSlug: 'my-switch-01',
|
||||||
|
childSlug: 'some-connected-client-slug',
|
||||||
|
relation: 'connected_to' // 'hosts', 'exposes', 'connected_to'
|
||||||
|
});
|
||||||
|
|
||||||
|
return { resources, edges };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Agents are automatically loaded and executed by the internal BullMQ job scheduler. You configure them in your `config/sso-secrets.js`:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
module.exports = {
|
||||||
|
// ... existing config ...
|
||||||
|
discovery: {
|
||||||
|
agents: {
|
||||||
|
my_custom_agent: {
|
||||||
|
enabled: true,
|
||||||
|
cron: '*/30 * * * *', // Run every 30 minutes
|
||||||
|
url: 'https://api.example.com',
|
||||||
|
apiKey: 'secret-key'
|
||||||
|
},
|
||||||
|
nmap: {
|
||||||
|
enabled: true,
|
||||||
|
cron: '0 * * * *',
|
||||||
|
targetRange: '192.168.1.0/24'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## The Reconciliation Engine
|
||||||
|
|
||||||
|
When your agent returns its graph, the Reconciliation Engine takes over:
|
||||||
|
1. **Matching:** It tries to find an existing device in the database matching any MAC address provided in the `interfaces` array. If no MAC matches, it falls back to IP address, and then to `slug`.
|
||||||
|
2. **Merging:** If it finds a match, it gracefully merges the metadata (so your agent can add CPU info to a host that NMAP previously found).
|
||||||
|
3. **Source Tracking:** It records your agent's filename in the `discovery_sources` array on the resource, and updates the `last_seen` timestamp.
|
||||||
|
4. **LDAP Spam Prevention:** Brand new devices are marked as `managed: false`. They will not pollute your LDAP directory until an admin explicitly promotes them.
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
---
|
||||||
|
layout: default
|
||||||
|
title: Accounts, Groups & Managers
|
||||||
|
description: A plain-language guide to users, service accounts, personal groups, and managers in SSO Manager.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Accounts, Groups & Managers
|
||||||
|
|
||||||
|
This page explains the concepts behind the Users and Groups pages in plain
|
||||||
|
language. If you want the technical schema/attribute-level detail instead,
|
||||||
|
see the [LDAP reference](ldap.html).
|
||||||
|
|
||||||
|
## What's an account?
|
||||||
|
|
||||||
|
Every person (or app) that can sign in through this SSO Manager has an
|
||||||
|
**account** — a username, a display name, maybe an email address, and a
|
||||||
|
password (or, for service accounts, no password at all — see below).
|
||||||
|
Accounts live in the directory this app manages, and any other app you've
|
||||||
|
connected (Gitea, Home Assistant, your Wi-Fi, whatever) checks against these
|
||||||
|
same accounts instead of keeping its own separate list of users and
|
||||||
|
passwords.
|
||||||
|
|
||||||
|
## Two kinds of account: people and service accounts
|
||||||
|
|
||||||
|
Most accounts belong to an actual person — check **Users → People** to see
|
||||||
|
them. But sometimes you need an account for something that *isn't* a
|
||||||
|
person: a media server, a backup script, a bind account another app uses to
|
||||||
|
look people up. These are **service accounts**, listed separately under
|
||||||
|
**Users → Service Accounts**, and they're different from a person's account
|
||||||
|
in two ways that matter:
|
||||||
|
|
||||||
|
- **No email required.** A service account doesn't need a mailbox, so the
|
||||||
|
form doesn't ask for one.
|
||||||
|
- **A password is optional.** If you leave it blank, nobody can log in as
|
||||||
|
that account — which is exactly what you want for something that only
|
||||||
|
ever gets used programmatically (a script authenticating with an API
|
||||||
|
token, or another app binding with a fixed, separately-configured
|
||||||
|
password you set yourself). Only give it a password if the account
|
||||||
|
genuinely needs to log in or bind somewhere as itself.
|
||||||
|
|
||||||
|
Aside from those two differences, a service account is a completely normal
|
||||||
|
account under the hood — it can belong to groups, have a manager, and so
|
||||||
|
on, just like anyone else's.
|
||||||
|
|
||||||
|
## Groups: who can do what
|
||||||
|
|
||||||
|
A **group** is just a named list of accounts, used to control access. This
|
||||||
|
app has a handful of built-in groups that grant admin powers (e.g. only
|
||||||
|
people in the `app_sso_admin` group can see the Users/Groups/Directory/Overview
|
||||||
|
pages at all), but you can also make your own groups for any app you
|
||||||
|
connect — say, a group listing everyone who should be allowed into your
|
||||||
|
photo server. Once a group exists, add or remove members from the
|
||||||
|
**Groups** page, and point the other app's "who's allowed in" setting at
|
||||||
|
that group's name.
|
||||||
|
|
||||||
|
### Groups inside groups
|
||||||
|
|
||||||
|
A group can contain another group, not just people — the *Nested* tab on any
|
||||||
|
group card. Everyone in the inner group counts as a member of the outer one,
|
||||||
|
however many levels deep it goes.
|
||||||
|
|
||||||
|
This is mostly a way to stop repeating yourself. Make one `developers` group,
|
||||||
|
nest it into the handful of things developers should reach, and adding a new
|
||||||
|
developer to that one group grants all of them at once — instead of adding them
|
||||||
|
to each individually and slowly drifting out of sync. The app already does this
|
||||||
|
for itself: super admins are nested into every resource's admin group, and each
|
||||||
|
admin group into its access group, so "can administer it" always implies "can
|
||||||
|
use it".
|
||||||
|
|
||||||
|
Two things it won't let you do: put a group inside itself (directly or round a
|
||||||
|
longer loop), and empty a group completely — every group must keep at least one
|
||||||
|
member.
|
||||||
|
|
||||||
|
A note if you also manage the directory by hand: a group's member list shows
|
||||||
|
what is *directly* listed on it. Someone who gets in through a nested group is
|
||||||
|
a real member but won't appear there — the **Nested** tab shows what is nested,
|
||||||
|
and the API's `effective` view lists everyone who actually gets in.
|
||||||
|
|
||||||
|
## Every account's personal group
|
||||||
|
|
||||||
|
Separately from the groups above, every single account — person or
|
||||||
|
service account — automatically gets its own small, personal group when
|
||||||
|
it's created, named after the account itself. Most of the time you'll
|
||||||
|
never think about this; it exists so that, on a Linux system connected to
|
||||||
|
this directory, each account "owns" its own files by default the same way
|
||||||
|
a normal Unix user account would.
|
||||||
|
|
||||||
|
Occasionally you'll want to share that ownership with someone else — for
|
||||||
|
example, letting a second account also have write access to files a
|
||||||
|
service account owns. That's what the **"Members of `<uid>`'s group"**
|
||||||
|
section on a profile page is for: add another account there, and the
|
||||||
|
underlying Linux permissions treat them as if they belong to that same
|
||||||
|
personal group too.
|
||||||
|
|
||||||
|
## What's a "manager"?
|
||||||
|
|
||||||
|
Every account has one or more **managers** — the people allowed to edit
|
||||||
|
that account's profile (phone number, SSH key, home directory, and so on)
|
||||||
|
without needing full admin rights. By default, whoever created an account
|
||||||
|
(the admin who added it, or whoever sent the invite) becomes its first
|
||||||
|
manager, but you can add or remove managers later from the account's Edit
|
||||||
|
form.
|
||||||
|
|
||||||
|
This is useful for service accounts especially: if a service account
|
||||||
|
belongs to a particular project or person, make them its manager so they
|
||||||
|
can maintain it — rotate its SSH key, adjust its description — without
|
||||||
|
needing to be a full SSO administrator.
|
||||||
|
|
||||||
|
## Inviting someone vs. adding them yourself
|
||||||
|
|
||||||
|
From the Users page you can either fill in someone's details yourself
|
||||||
|
("Add new user"), or send them an **invite** — an email (or a link you copy
|
||||||
|
and send however you like) that lets them pick their own username and
|
||||||
|
password. Either way, the resulting account is identical; invites are just
|
||||||
|
a convenience so you don't have to know someone's preferred username or
|
||||||
|
handle their password directly.
|
||||||
|
|
||||||
|
## Want more detail?
|
||||||
|
|
||||||
|
This page deliberately leaves out LDAP schema names, attribute types, and
|
||||||
|
protocol-level detail. If you're connecting a third-party app directly to
|
||||||
|
the LDAP directory, or you just want to know exactly what's stored where,
|
||||||
|
see the [LDAP reference](ldap.html).
|
||||||
|
|
||||||
|
[← Back to Home](index.html)
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
---
|
||||||
|
layout: default
|
||||||
|
title: API Tokens
|
||||||
|
description: A plain-language guide to personal access tokens in SSO Manager.
|
||||||
|
---
|
||||||
|
|
||||||
|
# API Tokens
|
||||||
|
|
||||||
|
This page explains what an API token is and when you'd want one. For the
|
||||||
|
full list of API endpoints a token can call, see the
|
||||||
|
[API reference](https://github.com/theta42/sso-manager-node/blob/master/API.md).
|
||||||
|
|
||||||
|
## What's an API token, in plain terms?
|
||||||
|
|
||||||
|
Normally, you interact with this app by logging in through a web browser.
|
||||||
|
An **API token** (also called a personal access token, or PAT) is an
|
||||||
|
alternative way in — a long, random string that a script, a scheduled job,
|
||||||
|
or another program can use instead of a username and password, to act on
|
||||||
|
your behalf without a human typing a login in each time.
|
||||||
|
|
||||||
|
If you've ever set up a script to talk to GitHub, GitLab, or a similar
|
||||||
|
service using a "token" instead of your real password, this is the same
|
||||||
|
idea.
|
||||||
|
|
||||||
|
## When would you actually need one?
|
||||||
|
|
||||||
|
Most people never need to create one of these — you'll only want a token
|
||||||
|
if you're automating something, for example:
|
||||||
|
|
||||||
|
- A script that syncs users or groups from somewhere else into this SSO
|
||||||
|
Manager on a schedule.
|
||||||
|
- A backup or monitoring job that checks this app's health via its API.
|
||||||
|
- A CI/CD pipeline that needs to register or update an OAuth client
|
||||||
|
automatically.
|
||||||
|
|
||||||
|
If you're not doing any of that, you don't need an API token — just log in
|
||||||
|
normally through the web UI.
|
||||||
|
|
||||||
|
## How it works
|
||||||
|
|
||||||
|
Create a token from your Profile page, give it a name so you remember what
|
||||||
|
it's for later, and optionally an expiry. You'll be shown the token's
|
||||||
|
value **exactly once** — copy it somewhere safe immediately, because it
|
||||||
|
can't be viewed again afterward (only revoked or rotated). Whatever script
|
||||||
|
or tool you're using it with sends it along with each request, the same
|
||||||
|
way a browser sends your login session.
|
||||||
|
|
||||||
|
A token acts **as you**, with **your** permissions — if you're not an
|
||||||
|
admin, a token you create can't do admin-only things either. If you ever
|
||||||
|
suspect a token has leaked (ended up somewhere it shouldn't have, like a
|
||||||
|
public script or log file), revoke it immediately from your Profile page;
|
||||||
|
it stops working right away.
|
||||||
|
|
||||||
|
## Want more detail?
|
||||||
|
|
||||||
|
This page doesn't attempt to list every API endpoint or show request/
|
||||||
|
response examples — for that, see the full [API reference](https://github.com/theta42/sso-manager-node/blob/master/API.md).
|
||||||
|
|
||||||
|
[← Back to Home](index.html)
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
---
|
||||||
|
layout: default
|
||||||
|
title: Connecting Apps (Single Sign-On)
|
||||||
|
description: A plain-language guide to OAuth/OIDC clients and single sign-on in SSO Manager.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Connecting Apps (Single Sign-On)
|
||||||
|
|
||||||
|
This page explains, in plain language, what happens when you "connect" an
|
||||||
|
app to your SSO Manager so people can log into it with their existing
|
||||||
|
account. For the technical endpoint/token detail, see the
|
||||||
|
[OAuth reference](oauth.html).
|
||||||
|
|
||||||
|
## What does "single sign-on" actually mean?
|
||||||
|
|
||||||
|
Instead of every app you run having its own separate list of usernames and
|
||||||
|
passwords, they all check with this SSO Manager instead. You log in once,
|
||||||
|
here, and any connected app trusts that login — no separate password to
|
||||||
|
remember or manage for each one. If you ever need to lock someone out
|
||||||
|
everywhere at once, you do it in one place (deactivate their account here)
|
||||||
|
instead of hunting down every app individually.
|
||||||
|
|
||||||
|
The technology behind this is called **OAuth 2.0** and **OpenID Connect
|
||||||
|
(OIDC)** — you'll see both names used, often together, referring to the
|
||||||
|
same thing. You don't need to understand the protocol to use this page;
|
||||||
|
what matters practically is the handful of concepts below.
|
||||||
|
|
||||||
|
## What's a "client"?
|
||||||
|
|
||||||
|
Every app you connect is registered here as a **client** — a single entry
|
||||||
|
in the Directory representing that one app. Registering a client
|
||||||
|
gives you a **Client ID** and **Client Secret**: think of these like a
|
||||||
|
username and password, but for the *app itself* rather than for a person.
|
||||||
|
You paste them into the other app's own "Single Sign-On" or "OIDC" setup
|
||||||
|
screen, along with the discovery URL shown at the top of this page, and
|
||||||
|
that app is now able to ask this SSO Manager to authenticate people on its
|
||||||
|
behalf.
|
||||||
|
|
||||||
|
**Treat the Client Secret like a password** — anyone who has it can
|
||||||
|
impersonate that app when talking to your SSO Manager. If you ever suspect
|
||||||
|
it's leaked, rotate it from the client's card.
|
||||||
|
|
||||||
|
## What are "scopes"?
|
||||||
|
|
||||||
|
**Scopes** control what information a connected app is allowed to ask for
|
||||||
|
about the person logging in — their username, email, group memberships,
|
||||||
|
and so on. Most apps tell you exactly which scopes they need in their own
|
||||||
|
setup instructions; when in doubt, the default set (`openid`, `profile`,
|
||||||
|
`email`, `groups`) covers what nearly every app expects.
|
||||||
|
|
||||||
|
## "Restrict to Groups"
|
||||||
|
|
||||||
|
By default, *any* account with an SSO Manager login can sign into a
|
||||||
|
connected app. If that's not what you want — say, a home automation
|
||||||
|
dashboard that only certain family members should reach — set **Restrict
|
||||||
|
to Groups** on that client to one of your [groups](concepts-accounts.html).
|
||||||
|
Only members of that group will be allowed to log into that particular
|
||||||
|
app; everyone else gets turned away at the login step, even though their
|
||||||
|
SSO Manager account still works everywhere else.
|
||||||
|
|
||||||
|
## Redirect URIs
|
||||||
|
|
||||||
|
A **Redirect URI** is the exact web address the connected app wants people
|
||||||
|
sent back to once they've logged in here — it's a security measure so an
|
||||||
|
attacker can't trick the login flow into redirecting somewhere else. The
|
||||||
|
app's own setup instructions will tell you this value; copy it in exactly
|
||||||
|
as given. If the app is reachable via more than one hostname (for example,
|
||||||
|
because it sits behind [theta42/proxy](https://theta42.github.io/proxy/)),
|
||||||
|
this field supports wildcard patterns — see the inline help under the
|
||||||
|
field itself for the exact syntax.
|
||||||
|
|
||||||
|
## Want more detail?
|
||||||
|
|
||||||
|
This page intentionally skips the protocol-level detail (exact endpoint
|
||||||
|
URLs, token formats, claim names). If you're troubleshooting a connection
|
||||||
|
or building something against the API directly, see the
|
||||||
|
[OAuth reference](oauth.html).
|
||||||
|
|
||||||
|
[← Back to Home](index.html)
|
||||||
@@ -32,6 +32,8 @@ raw strings otherwise.
|
|||||||
| `app_ldap__userBase=ou=people,dc=…` | `conf.ldap.userBase` | string |
|
| `app_ldap__userBase=ou=people,dc=…` | `conf.ldap.userBase` | string |
|
||||||
| `app_ldap__uidGidMin=1500` | `conf.ldap.uidGidMin` | number (new-user id floor) |
|
| `app_ldap__uidGidMin=1500` | `conf.ldap.uidGidMin` | number (new-user id floor) |
|
||||||
| `app_ldap__uidGidReservedFloor=9000` | `conf.ldap.uidGidReservedFloor` | number (ids at/above this are ignored when allocating) |
|
| `app_ldap__uidGidReservedFloor=9000` | `conf.ldap.uidGidReservedFloor` | number (ids at/above this are ignored when allocating) |
|
||||||
|
| `app_ldap__ldapsHost=ldap.internal.example.com` | `conf.ldap.ldapsHost` | string (hostname shown on `/integrations` for LDAPS binds; empty = derive from `oauth.issuer`) |
|
||||||
|
| `app_ldap__ldapsPort=636` | `conf.ldap.ldapsPort` | number (port shown on `/integrations`) |
|
||||||
| `app_oauth__jwtSecret=...` | `conf.oauth.jwtSecret` | string |
|
| `app_oauth__jwtSecret=...` | `conf.oauth.jwtSecret` | string |
|
||||||
| `app_oauth__issuer=https://sso.example.com` | `conf.oauth.issuer` | string |
|
| `app_oauth__issuer=https://sso.example.com` | `conf.oauth.issuer` | string |
|
||||||
| `app_oauth__token_lifetime__access_token=3600` | `conf.oauth.token_lifetime.access_token` | number |
|
| `app_oauth__token_lifetime__access_token=3600` | `conf.oauth.token_lifetime.access_token` | number |
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
---
|
||||||
|
layout: default
|
||||||
|
title: Directory Management
|
||||||
|
description: Managing your Home-Lab infrastructure, services, and LDAP access relationships via the SSO Directory API.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Directory Management
|
||||||
|
|
||||||
|
The SSO Manager ships with a built-in **Directory & Inventory Management** feature. Instead of just managing bare LDAP groups for your homelab, the Directory allows you to map out your infrastructure graph and assign rich metadata to your services.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
The Directory models your homelab infrastructure using a parent-child graph (e.g. `Site -> Host -> Service`).
|
||||||
|
|
||||||
|
There are three primary **Kinds** of resources you can define:
|
||||||
|
- **Site**: A physical location, datacenter, or root node (e.g., `us-east`). Sites do not require parents.
|
||||||
|
- **Host**: A physical machine, Proxmox node, virtual machine, or LXC container. A Host **must** have a parent Site or another Host.
|
||||||
|
- **Service (App)**: An application, web service. A Service **must** have a parent Host or another Service.
|
||||||
|
- **OAuth Integration**: An OAuth 2.0 / OpenID Connect client application. An OAuth integration **must** have a parent Service.
|
||||||
|
|
||||||
|
By defining this hierarchy, the SSO Manager builds a queryable graph of your infrastructure.
|
||||||
|
|
||||||
|
## Automatic LDAP Group Creation
|
||||||
|
|
||||||
|
When you create a new **Host** or **Service** in the Directory via the web UI (or API), the SSO Manager will automatically provision two LDAP groups in your directory to govern access to that resource:
|
||||||
|
|
||||||
|
1. `<slug>_access` (Member level access)
|
||||||
|
2. `<slug>_admin` (Owner level access)
|
||||||
|
|
||||||
|
For example, if you create a Service named "Emby" with the slug `app_emby`, the system will create the LDAP groups `app_emby_access` and `app_emby_admin`. You can then assign users to these groups, and they will immediately see the service populate on their "My Services" dashboard.
|
||||||
|
|
||||||
|
## Resource Metadata
|
||||||
|
|
||||||
|
Resources carry a flexible `metadata` JSON object that can store essential context for your applications. The UI natively supports the following metadata fields:
|
||||||
|
|
||||||
|
### Common Metadata
|
||||||
|
- **Sub Type**: Free-form text to categorize the resource (e.g., `proxmox_node`, `linux`, `lxc`, `web`).
|
||||||
|
- **IP Address**: The internal IP address of the resource.
|
||||||
|
- **MAC Address**: The hardware address of the primary interface.
|
||||||
|
- **Host / URI Address**: The FQDN or URL of the resource (e.g., `https://emby.home.arpa`).
|
||||||
|
- **Production Environment**: A boolean toggle indicating if the resource is in production.
|
||||||
|
|
||||||
|
### Host Metadata
|
||||||
|
- **VMID**: The hypervisor VM or Container ID (e.g. `101`).
|
||||||
|
- **OS**: The operating system name (e.g. `Ubuntu 22.04.3 LTS`).
|
||||||
|
- **Kernel**: The kernel version string (e.g. `5.15.0-100-generic`).
|
||||||
|
|
||||||
|
### Service Metadata
|
||||||
|
- **Internal Port**: The local port the service binds to (e.g. `8080`).
|
||||||
|
- **External Port**: The reverse-proxy or external port (defaults to Internal Port if left blank).
|
||||||
|
- **Public (No Auth)**: Indicates if the service is exposed publicly without authentication.
|
||||||
|
- **External Reachable**: Indicates if the service is accessible outside the VPN/local network.
|
||||||
|
- **Git Repo**: The source code repository for the service (e.g. `https://github.com/...`).
|
||||||
|
- **Install Path**: The filesystem path where the service is installed (e.g. `/opt/app`).
|
||||||
|
- **Systemd Service**: The systemd unit name for the service (e.g. `app.service`).
|
||||||
|
|
||||||
|
### Who sees which metadata
|
||||||
|
|
||||||
|
Metadata keys are declared in `@simpleworkjs/directory-schema` with an `admin` flag, and every API response is passed through its projection. There are three tiers:
|
||||||
|
|
||||||
|
- **Public** — returned to any authenticated caller, including machine (`ServiceToken`) callers: `ip`, `address`, `sshPort`, `fqdn`, `dnsNames`, `port`, `externalPort`, `portMappings`, `isExternalReachable`, `os`, `gitRepo`, `subType`, `icon`, `tagline`, `isPublic`, `isProduction`, `requestable`, `isCurrentSite`.
|
||||||
|
- **Admin-only** — only for members of `app_sso_directory_admin` / `app_sso_admin`: `vmid`, `macAddress`, `installPath`, `systemdService`, and the OAuth config keys (`redirect_uris`, `scopes`, `allowed_groups`, `token_lifetime`).
|
||||||
|
- **Never returned** — `client_secret_hash`, plus any key matching `/secret|password|privatekey/i`. Stripped on every path, admins included.
|
||||||
|
|
||||||
|
Note that machine tokens are deliberately *not* admins, so anything a machine consumer needs (the firewall generator reads `port` / `externalPort` / `isExternalReachable`) has to be in the public tier. A metadata key that isn't declared at all is treated as admin-only and will silently vanish for normal users — if you add a field to the admin form, declare it in the schema package too.
|
||||||
|
|
||||||
|
## Catalog & access requests
|
||||||
|
|
||||||
|
The site root (`/`) is the end-user catalog — the only ungated page in the nav. It shows:
|
||||||
|
|
||||||
|
- **My Access** — everything the signed-in user can reach (`GET /api/discovery/me`), each card carrying a **how to reach it** block: the URL for a service, or the SSH invocation for a host. When `directory.jumpHost` is set in the config, host cards render the jump-host form `ssh <uid>_-_<slug>@<jumpHost>`; otherwise they fall back to a direct `ssh <uid>@<ip>`.
|
||||||
|
- **Discover More** — everything else in the directory, with a **Request access** button.
|
||||||
|
- **My Requests** / **Awaiting My Approval** — pending requests, and the approve/deny queue for anyone who owns a requested resource.
|
||||||
|
|
||||||
|
A request is a proposal to join an LDAP group. It targets the resource's `member`-level group (the `_access` one, never `_admin`), and approving it performs the LDAP group add — so LDAP stays the single access-control truth and the table is just the audit trail. Approvals are idempotent: approving for someone already in the group succeeds rather than erroring.
|
||||||
|
|
||||||
|
Requests are decided by the resource's `owner`, or by any directory admin. Mark a resource `metadata.requestable = false` to keep it out of self-service.
|
||||||
|
|
||||||
|
## Navigating the UI
|
||||||
|
|
||||||
|
The Directory Management interface provides a **Tree View** toggle that visually nests your resources, making it easy to comprehend your network topography at a glance. You can also filter, search, and sort your entire infrastructure inventory. From the tree view, you can click the green `+` icon next to any resource to instantly add a child resource beneath it.
|
||||||
|
|
||||||
|
<a href="images/directory.png" target="_blank"><img src="images/directory.png" alt="Directory & inventory list view" width="80%"></a>
|
||||||
|
|
||||||
|
## Slug conventions
|
||||||
|
|
||||||
|
Slugs are the stable identifiers automation keys off, so the tooling around the SSO Manager follows a shared convention:
|
||||||
|
|
||||||
|
- **Sites**: `site_<name>` — e.g. `site_local`, `site_us-east`
|
||||||
|
- **Hosts**: `host_<hostname>` — e.g. `host_pve1`, `host_web01`
|
||||||
|
- **Services/apps**: a plain slug or `app_<name>` — e.g. `sso-manager`, `app_emby`
|
||||||
|
|
||||||
|
The auto-created LDAP groups derive from the slug (`<slug>_access` / `<slug>_admin`), so keep slugs stable once access groups are in use.
|
||||||
|
|
||||||
|
## Automatic registration
|
||||||
|
|
||||||
|
You don't have to build the graph by hand — the theta42 tooling registers itself:
|
||||||
|
|
||||||
|
### The stack itself (theta-env)
|
||||||
|
|
||||||
|
[theta-env](https://github.com/theta42/theta-env)'s `./setup.sh` seeds the directory on every run with the stack it deploys:
|
||||||
|
|
||||||
|
- a **site** (name from `CFG_SITE_NAME` in `setup.env`, default `local` → slug `site_local`) marked as the current site
|
||||||
|
- the **host** the stack runs on (`host_<hostname>`), with IP, MAC address, OS, and kernel collected from the machine
|
||||||
|
- the **services** it composes — SSO Manager, Proxy (management UI), OpenLDAP Directory (the LDAPS endpoint Linux hosts and LDAP-native apps bind to), and OpenResty Edge (the 80/443 data plane) — each with its address, internal port, and git repo
|
||||||
|
- the proxy's auto-registered **OAuth client**, linked under its service
|
||||||
|
|
||||||
|
The seed is idempotent and non-destructive: a resource whose slug already exists is considered operator-owned — the seed only fills in metadata fields you haven't set, and never overwrites your values.
|
||||||
|
|
||||||
|
### Linux hosts (ldap-client)
|
||||||
|
|
||||||
|
The `ldap-client` join script enrolls a Debian/Ubuntu machine for LDAP login (SSSD/PAM), LDAP-backed `sudo`, and SSH keys from the directory — and, when given an SSO API token, registers the machine as a `host_<hostname>` resource with its IP, MAC, OS, and kernel, parented to the site named by its configured location.
|
||||||
|
|
||||||
|
## Consumers of the directory
|
||||||
|
|
||||||
|
The inventory graph isn't just documentation — other components read it to make decisions:
|
||||||
|
|
||||||
|
- **[Jump Host](https://theta42.github.io/jump-host/)** — an SSH jump host that resolves which downstream machines a user may reach from their LDAP groups × the directory's `host` resources (`GET /api/discovery/resources?group=<cn>`), then bridges them in. The `host_<hostname>` slugs and `host_<slug>_access` groups this directory creates are exactly what it keys off; a host's `metadata.ip` / `metadata.sshPort` tell it where to connect. So a machine registered here (by theta-env or ldap-client) becomes reachable through the jump host the moment a user is in its access group.
|
||||||
|
|
||||||
|
Planned consumers (end-user catalog, firewall/DNS generation) and the model/API gaps they need are tracked in [`directory_spec.md`](https://github.com/theta42/sso-manager-node/blob/master/directory_spec.md) §9.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
All of the above uses the same admin API the UI does (group `app_sso_directory_admin` or `app_sso_admin`):
|
||||||
|
|
||||||
|
- `GET/POST /api/directory-admin/resources`, `PUT/DELETE /api/directory-admin/resources/:id`
|
||||||
|
- `GET/POST/DELETE /api/directory-admin/edges` — parent/child links (`hosts`, `oauth` relations)
|
||||||
|
- `GET/POST/DELETE /api/directory-admin/groups` — resource ↔ LDAP group links
|
||||||
|
- `GET /api/directory-admin/access-summary` — per-resource group + member counts (the Access column)
|
||||||
|
- `GET /api/directory-admin/user-access/:uid` — the reverse lookup: every resource a given user can reach, and via which group
|
||||||
|
- Read-only graph views (any authenticated user): `GET /api/discovery/resources`, `/api/discovery/resources/:slug`, `/api/discovery/graph`, `/api/discovery/me`
|
||||||
|
|
||||||
|
Access requests are open to any authenticated user; deciding is gated per-resource inside the router (resource owner or directory admin):
|
||||||
|
|
||||||
|
- `POST /api/access-requests` — `{slug | resourceId, groupCn?, note?}`
|
||||||
|
- `GET /api/access-requests/mine` — the caller's own history
|
||||||
|
- `GET /api/access-requests` — pending requests the caller may decide
|
||||||
|
- `POST /api/access-requests/:id/approve` · `POST /api/access-requests/:id/deny`
|
||||||
|
- `DELETE /api/access-requests/:id` — the requester withdraws their own pending request
|
||||||
|
Before Width: | Height: | Size: 118 KiB After Width: | Height: | Size: 141 KiB |
|
After Width: | Height: | Size: 392 KiB |
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 430 KiB |
|
Before Width: | Height: | Size: 174 KiB After Width: | Height: | Size: 313 KiB |
|
After Width: | Height: | Size: 123 KiB |
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 221 KiB |
@@ -22,10 +22,11 @@ one command).
|
|||||||
|
|
||||||
## Screenshots
|
## Screenshots
|
||||||
|
|
||||||
<a href="images/dashboard.png" target="_blank"><img src="images/dashboard.png" alt="Dashboard" width="49%"></a>
|
<a href="images/dashboard.png" target="_blank"><img src="images/dashboard.png" alt="Overview dashboard" width="49%"></a>
|
||||||
<a href="images/users.png" target="_blank"><img src="images/users.png" alt="User list" width="49%"></a>
|
<a href="images/users.png" target="_blank"><img src="images/users.png" alt="User list" width="49%"></a>
|
||||||
<a href="images/groups.png" target="_blank"><img src="images/groups.png" alt="Groups" width="49%"></a>
|
<a href="images/groups.png" target="_blank"><img src="images/groups.png" alt="Groups" width="49%"></a>
|
||||||
<a href="images/oauth-clients.png" target="_blank"><img src="images/oauth-clients.png" alt="OAuth clients" width="49%"></a>
|
<a href="images/directory.png" target="_blank"><img src="images/directory.png" alt="Directory & inventory" width="49%"></a>
|
||||||
|
<a href="images/oauth-clients.png" target="_blank"><img src="images/oauth-clients.png" alt="OAuth client (edit view)" width="49%"></a>
|
||||||
|
|
||||||
*(click any screenshot to view full size)*
|
*(click any screenshot to view full size)*
|
||||||
|
|
||||||
@@ -52,10 +53,13 @@ backend, that's the niche.
|
|||||||
- **Web management UI** — users, groups, and OAuth clients from a browser;
|
- **Web management UI** — users, groups, and OAuth clients from a browser;
|
||||||
invite and password-reset flows over email; self-service profile + API
|
invite and password-reset flows over email; self-service profile + API
|
||||||
tokens.
|
tokens.
|
||||||
- **LDAPS for legacy apps** — anything that binds LDAP directly (Gitea,
|
- **Direct LDAP binds** — anything that binds LDAP directly (Linux hosts
|
||||||
Emby, …) uses LDAPS/StartTLS against the same directory.
|
via PAM/SSSD, Gitea, Emby, …) uses LDAPS/StartTLS against the same
|
||||||
|
directory.
|
||||||
- **All-in-one Docker image** — app + OpenLDAP + Redis in one container, or
|
- **All-in-one Docker image** — app + OpenLDAP + Redis in one container, or
|
||||||
run the pieces separately via `app_*` env config.
|
run the pieces separately via `app_*` env config.
|
||||||
|
- **Geo-Location Scaling** — built-in support for N-Way Multi-Master OpenLDAP [replication](replication.html) across physical sites.
|
||||||
|
- **[Directory & Inventory](directory.html)** — map sites, hosts, and services as a graph with rich metadata (IP/MAC, OS/kernel, ports, git repos), auto-provisioned access groups, and automatic registration from theta-env and ldap-client. Drives directory-aware tools like the [SSH jump host](https://theta42.github.io/jump-host/).
|
||||||
|
|
||||||
## Get it
|
## Get it
|
||||||
|
|
||||||
@@ -75,5 +79,7 @@ That's the standalone quick start. For the full set of install options
|
|||||||
|
|
||||||
- **[Proxy](https://theta42.github.io/proxy/)** — an OIDC + LDAP-aware
|
- **[Proxy](https://theta42.github.io/proxy/)** — an OIDC + LDAP-aware
|
||||||
reverse proxy, designed to sit in front of this SSO.
|
reverse proxy, designed to sit in front of this SSO.
|
||||||
|
- **[Jump Host](https://theta42.github.io/jump-host/)** — an SSH jump host that
|
||||||
|
uses this SSO's directory to decide who may reach which machine.
|
||||||
- **[theta-env](https://theta42.github.io/theta-env/)** — runs this SSO
|
- **[theta-env](https://theta42.github.io/theta-env/)** — runs this SSO
|
||||||
Manager and the proxy together with one command.
|
Manager and the proxy together with one command.
|
||||||
|
|||||||
@@ -8,10 +8,15 @@ description: SSO Manager's bundled OpenLDAP directory — schema, service accoun
|
|||||||
|
|
||||||
[← Back to Home](index.html)
|
[← Back to Home](index.html)
|
||||||
|
|
||||||
|
> Looking for a plainer explanation of accounts, groups, and managers
|
||||||
|
> instead of schema/attribute detail? See
|
||||||
|
> [Accounts, Groups & Managers](concepts-accounts.html).
|
||||||
|
|
||||||
SSO Manager runs an OpenLDAP directory holding your users and groups. The app
|
SSO Manager runs an OpenLDAP directory holding your users and groups. The app
|
||||||
authenticates against it over `localhost:389` (inside the all-in-one container)
|
authenticates against it over `localhost:389` (inside the all-in-one container)
|
||||||
and exposes **LDAPS** (`ldaps://…:636`, TLS) for legacy apps that bind LDAP
|
and exposes **LDAPS** (`ldaps://…:636`, TLS) for anything that binds LDAP
|
||||||
directly — Gitea, Emby, the theta42/proxy, etc.
|
directly — Linux hosts (PAM/SSSD, sudo rules, SSH keys), Gitea, Emby, the
|
||||||
|
theta42/proxy, etc.
|
||||||
|
|
||||||
## Directory layout
|
## Directory layout
|
||||||
|
|
||||||
@@ -54,18 +59,64 @@ way or use `slappasswd -h '{SSHA512}'`.
|
|||||||
Groups are `cn=<name>,ou=groups,<base>` (`groupOfNames`) with a `member`
|
Groups are `cn=<name>,ou=groups,<base>` (`groupOfNames`) with a `member`
|
||||||
attribute listing member DNs. The `memberOf` overlay populates reverse
|
attribute listing member DNs. The `memberOf` overlay populates reverse
|
||||||
membership (`memberOf` on the user); `refint` keeps it consistent on
|
membership (`memberOf` on the user); `refint` keeps it consistent on
|
||||||
add/remove. **Admin permission checks read the group's `member` list**, not
|
add/remove.
|
||||||
`memberOf` on the user.
|
|
||||||
|
|
||||||
The SSO requires three groups (seeded automatically by the entrypoint /
|
Note that `groupOfNames` requires **at least one member**, which has two
|
||||||
`install.sh`):
|
consequences worth knowing: whoever creates a group is automatically seeded
|
||||||
|
into it, and removing the last member (user *or* nested group) is refused with
|
||||||
|
a 409 rather than leaving an invalid entry behind.
|
||||||
|
|
||||||
|
### Nested groups
|
||||||
|
|
||||||
|
A `member` DN may be another group's, not just a user's — that is how nesting
|
||||||
|
is stored, with no extra schema. Everyone in the nested group is a member of
|
||||||
|
the outer one, at any depth. Manage it on the **Groups** page under each
|
||||||
|
group's *Nested* tab, or via the API:
|
||||||
|
|
||||||
|
```
|
||||||
|
PUT /api/group/:group/nested/:child nest :child inside :group
|
||||||
|
DELETE /api/group/:group/nested/:child un-nest
|
||||||
|
GET /api/group/:group/effective direct users, nested groups, and the
|
||||||
|
full transitive set of users
|
||||||
|
```
|
||||||
|
|
||||||
|
Cycles are refused (409) rather than truncated — a loop makes "who is in this
|
||||||
|
group" unanswerable. Two standing relationships are wired automatically: the
|
||||||
|
cross-app `app_super_admin` is nested into every resource's `<slug>_admin`
|
||||||
|
group, and each `<slug>_admin` into its `<slug>_access` group, so administering
|
||||||
|
something implies being able to use it.
|
||||||
|
|
||||||
|
**Resolving nesting is a client-side job on stock OpenLDAP.** No 2.6.x release
|
||||||
|
can evaluate nested groups; `memberOf` and a `(member=X)` filter both return
|
||||||
|
direct membership only. The bundled slapd is therefore built from source with
|
||||||
|
the `nestgroup` overlay (see *Modules + overlays* below), and the app is told so
|
||||||
|
via `ldap.nestedGroupsServerSide`. Against any other server the app computes the
|
||||||
|
closure itself — same answers, more queries. Either way, **never read `memberOf`
|
||||||
|
directly to make an access decision**; use `utils/user_groups.js`'s `groupCns()`,
|
||||||
|
which is correct in both modes.
|
||||||
|
|
||||||
|
### Personal groups
|
||||||
|
|
||||||
|
Every user (person or service account) also gets a **personal Unix group**
|
||||||
|
at creation — `cn=<uid>,ou=groups,<base>`, `objectClass: posixGroup` (RFC
|
||||||
|
2307), holding just `cn` and `gidNumber` (the user's primary GID). This is a
|
||||||
|
different schema than the `groupOfNames` groups above — its membership
|
||||||
|
attribute is `memberUid` (a bare username, not a DN), and unlike
|
||||||
|
`groupOfNames` it's valid with zero members. It's excluded from the
|
||||||
|
`/groups` page (which filters on `objectClass=groupOfNames`) and managed
|
||||||
|
instead from the owning user's own profile page ("Members of `<uid>`'s
|
||||||
|
group", admin-only) — add other accounts as supplementary members, e.g. to
|
||||||
|
share write access to files owned by this group.
|
||||||
|
|
||||||
|
The SSO seeds these groups automatically (entrypoint / `install.sh`):
|
||||||
|
|
||||||
| Group | Grants |
|
| Group | Grants |
|
||||||
|-------|--------|
|
|-------|--------|
|
||||||
|
| `app_super_admin` | cross-app super admin. Nested into the three below, so its members hold those rights transitively rather than by a special case in app code — and the privilege is visible to LDAP-native consumers (SSSD, sudo) too. |
|
||||||
| `app_sso_admin` | full admin (users, groups, settings) |
|
| `app_sso_admin` | full admin (users, groups, settings) |
|
||||||
| `app_sso_oauth_admin` | OAuth client management |
|
| `app_sso_oauth_admin` | OAuth client management |
|
||||||
| `app_sso_invite` | invitation management |
|
| `app_sso_invite` | invitation management |
|
||||||
| `app_sso_service_account` | not a permission — marks a `posixAccount` as a non-person service account (see *Service accounts* below) |
|
| `app_sso_service_account` | not a permission — marks a `posixAccount` as a non-person service account (see *Service accounts* below). Deliberately **not** nested into, since it changes how an account is displayed rather than what it may do. |
|
||||||
|
|
||||||
## TLS (LDAPS / StartTLS)
|
## TLS (LDAPS / StartTLS)
|
||||||
|
|
||||||
@@ -101,6 +152,81 @@ volumes:
|
|||||||
|
|
||||||
The entrypoint leaves existing certs untouched (idempotent).
|
The entrypoint leaves existing certs untouched (idempotent).
|
||||||
|
|
||||||
|
## Choosing the LDAPS hostname
|
||||||
|
|
||||||
|
The `/integrations` page advertises an **LDAPS URL** for direct LDAP binds. By
|
||||||
|
default it derives that URL from the public OAuth issuer (e.g.
|
||||||
|
`https://sso.example.com` → `ldaps://sso.example.com:636`). That is convenient,
|
||||||
|
but it implies LDAP clients reach your directory through the same public
|
||||||
|
hostname — which usually means port-forwarding 636 through your router.
|
||||||
|
|
||||||
|
**Do not port-forward LDAPS (636) to the public internet.** LDAP simple binds
|
||||||
|
have no rate limiting and are a brute-force target. Instead, use one of these
|
||||||
|
internal-only patterns and set `conf.ldap.ldapsHost` (or
|
||||||
|
`app_ldap__ldapsHost`) so the `/integrations` page shows the right URL.
|
||||||
|
|
||||||
|
### 1. Same Docker / local network host (best for apps on this machine)
|
||||||
|
|
||||||
|
If the LDAP client runs on the same Docker network as the SSO Manager (for
|
||||||
|
example, the bundled `theta-env` stack), use the internal service name:
|
||||||
|
|
||||||
|
```
|
||||||
|
ldaps://sso-manager:636
|
||||||
|
```
|
||||||
|
|
||||||
|
In `conf/secrets.js`:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
ldap: {
|
||||||
|
ldapsHost: 'sso-manager',
|
||||||
|
ldapsPort: 636,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The proxy in theta-env already uses this internally. The bundled slapd cert
|
||||||
|
includes `sso-manager` in its SAN when `LDAP_CERT_CN` is left at its default,
|
||||||
|
so hostname verification works without extra setup.
|
||||||
|
|
||||||
|
### 2. LAN host behind your router (best for separate home-lan machines)
|
||||||
|
|
||||||
|
Create an internal-only DNS record — e.g. `ldap.internal.example.com` →
|
||||||
|
`192.168.1.10` — using your router, Pi-hole, or a local `hosts` file. Then get
|
||||||
|
or generate a cert whose SAN/CN matches that internal name:
|
||||||
|
|
||||||
|
- **Let's Encrypt wildcard** (`*.internal.example.com`) works if you own the
|
||||||
|
public domain and can complete DNS-01 challenge; the record itself can stay
|
||||||
|
private/routable only inside your LAN.
|
||||||
|
- **Internal CA** is fine for a pure LAN: run a small CA, issue a cert for
|
||||||
|
`ldap.internal.example.com`, and distribute the CA cert to clients.
|
||||||
|
- **Self-signed** with `LDAP_CERT_CN=ldap.internal.example.com` also works; copy
|
||||||
|
the generated `ldap.crt` to each client and trust it.
|
||||||
|
|
||||||
|
In `conf/secrets.js`:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
ldap: {
|
||||||
|
ldapsHost: 'ldap.internal.example.com',
|
||||||
|
ldapsPort: 636,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The URL on `/integrations` becomes `ldaps://ldap.internal.example.com:636`.
|
||||||
|
|
||||||
|
### 3. Public hostname (acceptable only behind a VPN/firewall)
|
||||||
|
|
||||||
|
If a remote host must bind LDAP, put it behind a VPN (Tailscale, WireGuard,
|
||||||
|
etc.) or a tightly locked-down firewall rule. In that case the public hostname
|
||||||
|
may be appropriate, but the LDAPS port should still not be reachable from the
|
||||||
|
open internet.
|
||||||
|
|
||||||
|
### Why not just use the LDAP server's IP address?
|
||||||
|
|
||||||
|
TLS clients verify the server name against the certificate. Connecting to
|
||||||
|
`ldaps://192.168.1.10:636` with a cert issued for `*.internal.example.com`
|
||||||
|
will fail hostname verification unless you disable cert checks — which removes
|
||||||
|
most of the security benefit of LDAPS. Always use a hostname that matches the
|
||||||
|
cert.
|
||||||
|
|
||||||
## Service accounts
|
## Service accounts
|
||||||
|
|
||||||
A service account is a normal `posixAccount` for something that isn't a
|
A service account is a normal `posixAccount` for something that isn't a
|
||||||
@@ -215,11 +341,37 @@ needs:
|
|||||||
|
|
||||||
- **Modules:** `pw-sha2` (the app stores user passwords as `{SSHA512}`),
|
- **Modules:** `pw-sha2` (the app stores user passwords as `{SSHA512}`),
|
||||||
`ppolicy`, `memberof`, `refint`.
|
`ppolicy`, `memberof`, `refint`.
|
||||||
|
- **Optional — `nestgroup`:** server-side nested-group evaluation. Not in any
|
||||||
|
released OpenLDAP (added to master as ITS#10161 in March 2024; 2.7 is still
|
||||||
|
unreleased), so the bundled image builds slapd from a pinned upstream commit.
|
||||||
|
Without it the app resolves nesting itself and everything still works — leave
|
||||||
|
`ldap.nestedGroupsServerSide` at `false`. With it, set that to `true` and
|
||||||
|
configure:
|
||||||
|
|
||||||
|
```
|
||||||
|
overlay nestgroup
|
||||||
|
nestgroup-base ou=groups,<base>
|
||||||
|
nestgroup-flags member-filter memberof-filter memberof-values
|
||||||
|
```
|
||||||
|
|
||||||
|
Flags are **space-separated**; the comma form the man page's `{a, b, c}`
|
||||||
|
notation suggests is rejected. `member-values` is deliberately omitted — it
|
||||||
|
expands the `member` attribute when reading a group, which destroys the
|
||||||
|
distinction between "listed here" and "reachable through a nested group", and
|
||||||
|
the raw values are then unrecoverable. Transitive answers come from the filter
|
||||||
|
flags and from `GET /api/group/:group/effective`.
|
||||||
|
|
||||||
|
One more consequence of building from master: it ships **LMDB 1.0.0**, whose
|
||||||
|
on-disk format is mutually unreadable with the 0.9.x in 2.6.x
|
||||||
|
(`MDB_INVALID: File is not an LMDB file`). Moving a directory between the two
|
||||||
|
is a `slapcat` → `slapadd` reload, not a restart.
|
||||||
- **Custom schema:** the `theta42Person` auxiliary objectClass with
|
- **Custom schema:** the `theta42Person` auxiliary objectClass with
|
||||||
`dateOfBirth` — see `ops/ldap-setup.sh` for the LDIF.
|
`dateOfBirth` — see `ops/ldap-setup.sh` for the LDIF.
|
||||||
- **Directory tree:** `ou=people`, `ou=groups`, `ou=policies` under the base DN,
|
- **Directory tree:** `ou=people`, `ou=groups`, `ou=policies` under the base DN,
|
||||||
a default `pwdPolicy` at `cn=ppolicy,ou=policies,<base>`.
|
a default `pwdPolicy` at `cn=ppolicy,ou=policies,<base>`.
|
||||||
- **Required groups:** `app_sso_admin`, `app_sso_invite`, `app_sso_oauth_admin`.
|
- **Required groups:** `app_sso_admin`, `app_sso_invite`, `app_sso_oauth_admin`,
|
||||||
|
and `app_super_admin` (the cross-app super-admin group; the bundled entrypoint
|
||||||
|
also nests it into the first three).
|
||||||
|
|
||||||
`ops/ldap-setup.sh -p <admin-password>` configures all of the above
|
`ops/ldap-setup.sh -p <admin-password>` configures all of the above
|
||||||
idempotently against a running slapd (auto-detects the database holding your
|
idempotently against a running slapd (auto-detects the database holding your
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ description: SSO Manager's OpenID Connect / OAuth 2.0 provider — discovery doc
|
|||||||
|
|
||||||
[← Back to Home](index.html)
|
[← Back to Home](index.html)
|
||||||
|
|
||||||
|
> Looking for a plainer explanation of clients/scopes/redirect URIs instead
|
||||||
|
> of endpoint-level detail? See
|
||||||
|
> [Connecting Apps (Single Sign-On)](concepts-oauth-apps.html).
|
||||||
|
|
||||||
SSO Manager is an **OpenID Connect / OAuth 2.0 provider**: it issues its own
|
SSO Manager is an **OpenID Connect / OAuth 2.0 provider**: it issues its own
|
||||||
access, refresh, and ID tokens that your apps can consume to authenticate
|
access, refresh, and ID tokens that your apps can consume to authenticate
|
||||||
users and authorize API calls. It also runs a full OpenLDAP directory, so it
|
users and authorize API calls. It also runs a full OpenLDAP directory, so it
|
||||||
@@ -49,20 +53,18 @@ An OAuth client represents an app that authenticates against the SSO. Each has:
|
|||||||
|
|
||||||
### Managing clients
|
### Managing clients
|
||||||
|
|
||||||
Clients are managed from the web UI (as a member of the `app_sso_oauth_admin`
|
Clients are managed directly from the **Directory** tab in the web UI. They are modeled as resources of `kind: oauth` and must belong to a parent Service.
|
||||||
group) or the HTTP API at `/api/oauth/client` (auth via the `auth-token` header
|
|
||||||
from a login):
|
|
||||||
|
|
||||||
| Method | Path | Action |
|
| Action | How to do it |
|
||||||
|--------|------|--------|
|
|--------|--------------|
|
||||||
| `GET` | `/api/oauth/client` | list clients |
|
| **Create** | Click the green **+** on a parent Service to add a child resource. Choose **OAuth Integration**. The raw `client_secret` is shown once upon creation. |
|
||||||
| `POST` | `/api/oauth/client` | create a client (returns the raw `client_secret` once) |
|
| **Edit** | Click the edit pencil on the OAuth resource in the Directory list or tree. You can update redirect URIs, scopes, allowed groups, and token TTLs. |
|
||||||
| `GET` | `/api/oauth/client/:id` | get one |
|
| **Delete** | Click the trash can on the OAuth resource in the Directory list. |
|
||||||
| `PUT` | `/api/oauth/client/:id` | update redirect URIs / scopes / groups |
|
| **Rotate Secret** | Open the edit modal for the OAuth resource and click **Rotate Client Secret**. The new raw secret is shown once. |
|
||||||
| `DELETE` | `/api/oauth/client/:id` | delete |
|
|
||||||
| `POST` | `/api/oauth/client/:id/rotate` | rotate the secret (returns the new raw secret once) |
|
|
||||||
|
|
||||||
> All client-management endpoints are gated by the `app_sso_oauth_admin` group.
|
> All client-management actions use the standard Directory API (`/api/directory-admin/resources`) and are gated by the `app_sso_directory_admin` group.
|
||||||
|
|
||||||
|
<a href="images/oauth-clients.png" target="_blank"><img src="images/oauth-clients.png" alt="Editing an OAuth client resource" width="80%"></a>
|
||||||
|
|
||||||
## Scopes
|
## Scopes
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
---
|
||||||
|
layout: default
|
||||||
|
title: Geo-Location Scaling (Replication)
|
||||||
|
---
|
||||||
|
|
||||||
|
# Geo-Location Scaling (Replication)
|
||||||
|
|
||||||
|
SSO Manager is built to be a self-contained identity provider, but if you have multiple physical sites, you may want a local copy of the directory at each site to ensure low latency and high availability.
|
||||||
|
|
||||||
|
## Why and when to use this?
|
||||||
|
- **High Availability (HA)**: If your primary site goes completely offline, your other sites can still authenticate users locally without depending on a WAN link.
|
||||||
|
- **Low Latency**: Applications at a remote site can bind directly to their local LDAP server (`localhost` or LAN IP) instead of traversing the internet to query the primary site, making logins blazing fast.
|
||||||
|
- **Independent Failure Domains**: By replicating only the LDAP directory (the source of truth) and keeping session state (Redis) independent, you prevent complex "split-brain" scenarios in the web UI. A failure at Site A won't bring down Site B.
|
||||||
|
|
||||||
|
By default, the `sso-manager` Docker container runs a single, independent OpenLDAP instance. However, you can enable **N-Way Multi-Master Replication** via environment variables.
|
||||||
|
|
||||||
|
## How it works
|
||||||
|
|
||||||
|
In an N-Way Multi-Master setup, every site runs a fully active OpenLDAP server (`slapd`).
|
||||||
|
- **Reads and Writes anywhere**: A user can change their password or update their profile at Site A, Site B, or Site C.
|
||||||
|
- **Conflict Resolution**: OpenLDAP's `syncrepl` engine uses Context Sequence Numbers (CSN) to track changes. If Site A goes offline and a user changes their password at Site B, Site A will automatically pull the newest changes the moment it rejoins the cluster.
|
||||||
|
- **Independent Redis**: Session data, API Tokens, and OAuth Clients are stored in Redis. By design, Redis is NOT replicated in this geographic setup. This ensures that a failure at Site A never causes Site B's Redis to become read-only, which would break the web UI at Site B. OAuth clients must be configured per-site.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
To enable replication, you must pass two environment variables to the `sso-manager` container:
|
||||||
|
|
||||||
|
1. `LDAP_SERVER_ID`: A unique integer for this node (e.g., `1`, `2`, `3`). This MUST be unique across the cluster.
|
||||||
|
2. `LDAP_REPLICATION_HOSTS`: A space-separated list of the LDAP URLs of all **other** nodes in the cluster.
|
||||||
|
|
||||||
|
### Example using `theta-env` / Docker Compose
|
||||||
|
|
||||||
|
**Site 1 (`setup.env` or `docker-compose.yml`)**
|
||||||
|
```env
|
||||||
|
LDAP_SERVER_ID=1
|
||||||
|
LDAP_REPLICATION_HOSTS="ldaps://sso.site2.com:636 ldaps://sso.site3.com:636"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Site 2 (`setup.env` or `docker-compose.yml`)**
|
||||||
|
```env
|
||||||
|
LDAP_SERVER_ID=2
|
||||||
|
LDAP_REPLICATION_HOSTS="ldaps://sso.site1.com:636 ldaps://sso.site3.com:636"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Site 3 (`setup.env` or `docker-compose.yml`)**
|
||||||
|
```env
|
||||||
|
LDAP_SERVER_ID=3
|
||||||
|
LDAP_REPLICATION_HOSTS="ldaps://sso.site1.com:636 ldaps://sso.site2.com:636"
|
||||||
|
```
|
||||||
|
|
||||||
|
Once configured, the container's entrypoint will automatically load the `syncprov` module, enable `mirrormode`, and generate the necessary `syncrepl` blocks in `/etc/openldap/slapd.conf`.
|
||||||
|
|
||||||
|
## User Locations
|
||||||
|
|
||||||
|
When creating or editing a user, you can specify their **Location (Site)**. This maps directly to the standard LDAP `l` (localityName) attribute, allowing you to track which physical site a user belongs to natively within the directory.
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
---
|
||||||
|
layout: default
|
||||||
|
title: Secrets Vault
|
||||||
|
nav_order: 6
|
||||||
|
---
|
||||||
|
|
||||||
|
# Secrets Vault
|
||||||
|
|
||||||
|
SSO Manager integrates natively with **OpenBao** (a Vault fork) to securely manage and store sensitive data, configuration, and API keys.
|
||||||
|
|
||||||
|
The Vault proxy endpoint is exposed directly through SSO Manager at `/api/vault/v1/`, which safely authenticates and authorizes requests before forwarding them to the internal OpenBao container.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
The secrets engine uses a persistent file backend (`/var/lib/docker/volumes/theta-env_openbao-data/_data`) to ensure high availability and durability.
|
||||||
|
|
||||||
|
When the environment is initialized via `setup.sh`, OpenBao is automatically unsealed and seeded with a root token that the application uses for authentication. The root token is kept securely inside the container environment.
|
||||||
|
|
||||||
|
## Accessing the Vault
|
||||||
|
|
||||||
|
The SSO Manager Vault can be accessed in two ways:
|
||||||
|
|
||||||
|
1. **Via the SSO Manager UI**: Go to the **Admin Configuration** page (`/conf`) to edit the application's configuration secrets directly.
|
||||||
|
2. **Via the REST API**: Send requests to `/api/vault/v1/...` with your SSO Manager session or API Token.
|
||||||
|
|
||||||
|
### API Example
|
||||||
|
|
||||||
|
To read secrets from the default key-value store, issue a `GET` request to:
|
||||||
|
`/api/vault/v1/secret/data/sso-manager/conf`
|
||||||
|
|
||||||
|
Only administrators with `app_sso_admin` or `admin` permissions can query the vault endpoints.
|
||||||
|
|
||||||
|
## Namespaces and Paths
|
||||||
|
|
||||||
|
Currently, secrets are maintained at `/v1/secret/data/sso-manager/conf` using the `kv-v2` backend. When configurations are edited via the admin UI, SSO Manager performs a deep-merge so that partial updates don't overwrite unrelated keys (such as SMTP vs OAuth configurations).
|
||||||
|
|
||||||
|
## Plugin Integration
|
||||||
|
|
||||||
|
When building custom Agents or integrations, they can utilize the local Vault to retrieve API tokens instead of hardcoding them. Always use the `/api/vault` proxy to ensure permissions are consistently enforced.
|
||||||
@@ -1,719 +1,230 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# install.sh - Idempotent standalone installer for Theta42 SSO Manager
|
|
||||||
# For Debian/Ubuntu systems
|
|
||||||
#
|
#
|
||||||
# This script:
|
# Install / update Theta42 SSO Manager on a fresh or existing host.
|
||||||
# 1. Installs Node.js 20.x
|
|
||||||
# 2. Installs and configures OpenLDAP with required schemas/overlays
|
|
||||||
# 3. Deploys the SSO Manager application
|
|
||||||
# 4. Sets up systemd services
|
|
||||||
#
|
#
|
||||||
# Usage:
|
# This script is idempotent: run it to install, and re-run it to update. It
|
||||||
# sudo ./install.sh [OPTIONS]
|
# installs system dependencies (Node, OpenLDAP, Redis), force-syncs the repo at
|
||||||
|
# $REPO_DIR to its remote branch, and symlinks the systemd config straight from
|
||||||
|
# the repo. Because the config is symlinked, an update is just "sync the repo +
|
||||||
|
# restart" -- the files under /etc/systemd always track the repo.
|
||||||
#
|
#
|
||||||
# Options:
|
# Secrets live at $SECRETS_FILE (/etc/sso-manager/secrets.js by default),
|
||||||
# -p, --admin-pass PASSWORD LDAP admin password (required, or set via LDAP_ADMIN_PASS env)
|
# outside the repo checkout so they survive the hard reset below. FIRST RUN
|
||||||
# -b, --base-dn DN Base DN (default: dc=example,dc=com)
|
# ONLY (no $SECRETS_FILE yet): installs and configures OpenLDAP (modules,
|
||||||
# -n, --org-name NAME Organization name shown in UI/email (default: SSO Manager)
|
# overlays, custom schema, directory tree, required SSO groups -- see
|
||||||
# -o, --port PORT HTTP port for SSO Manager (default: 3001)
|
# ops/ldap-setup.sh), generates an LDAP admin password + JWT secret unless
|
||||||
# -j, --jwt-secret SECRET JWT secret for OAuth (default: auto-generated)
|
# given via env, and seeds $SECRETS_FILE with those values plus SMTP
|
||||||
# -s, --smtp-config CONFIG SMTP config as host:port:user:pass
|
# placeholders. Edit that file (SMTP, org name, ...) and re-run this script to
|
||||||
# --skip-ldap Skip LDAP installation (use existing LDAP)
|
# apply changes -- once it exists it is never touched again, and LDAP is never
|
||||||
# --skip-app Skip application installation (LDAP setup only)
|
# re-bootstrapped.
|
||||||
# --dry-run Show what would be done without making changes
|
|
||||||
# -h, --help Show this help
|
|
||||||
#
|
#
|
||||||
# Environment variables (alternative to flags):
|
# Intended to be driven by CI/CD with no human writes on prod: the checkout is
|
||||||
# LDAP_ADMIN_PASS, LDAP_BASE_DN, PORT, JWT_SECRET, SMTP_*
|
# hard-reset to origin/$BRANCH on every run, so the box deterministically
|
||||||
|
# mirrors the repo (any drift on the box is discarded).
|
||||||
|
#
|
||||||
|
# Usage: sudo ./install.sh (override with REPO_URL=, REPO_DIR=, BRANCH=,
|
||||||
|
# SECRETS_FILE=, LDAP_BASE_DN=, LDAP_ADMIN_PASS=,
|
||||||
|
# JWT_SECRET=, ORG_NAME=, PORT=, SKIP_LDAP=true)
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
# Never block on an interactive git credential prompt in CI.
|
||||||
|
export GIT_TERMINAL_PROMPT=0
|
||||||
|
# Never block on an interactive debconf prompt (e.g. tzdata, pulled in as a
|
||||||
|
# dependency of redis-server/slapd on a box that's never configured it).
|
||||||
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
|
|
||||||
# ── Defaults ──────────────────────────────────────────────────────────────────
|
REPO_URL="${REPO_URL:-https://github.com/theta42/sso-manager-node.git}"
|
||||||
BASE_DN="${LDAP_BASE_DN:-dc=example,dc=com}"
|
REPO_DIR="${REPO_DIR:-/opt/theta42/sso-manager}"
|
||||||
ADMIN_PASS="${LDAP_ADMIN_PASS:-}"
|
BRANCH="${BRANCH:-master}"
|
||||||
|
NODE_MAJOR=22
|
||||||
|
SECRETS_FILE="${SECRETS_FILE:-/etc/sso-manager/secrets.js}"
|
||||||
|
|
||||||
|
LDAP_BASE_DN="${LDAP_BASE_DN:-dc=example,dc=com}"
|
||||||
ORG_NAME="${ORG_NAME:-SSO Manager}"
|
ORG_NAME="${ORG_NAME:-SSO Manager}"
|
||||||
PORT="${PORT:-3001}"
|
PORT="${PORT:-3001}"
|
||||||
JWT_SECRET="${JWT_SECRET:-}"
|
|
||||||
SMTP_HOST="${SMTP_HOST:-}"
|
|
||||||
SMTP_PORT="${SMTP_PORT:-587}"
|
|
||||||
SMTP_USER="${SMTP_USER:-}"
|
|
||||||
SMTP_PASS="${SMTP_PASS:-}"
|
|
||||||
SKIP_LDAP="${SKIP_LDAP:-false}"
|
SKIP_LDAP="${SKIP_LDAP:-false}"
|
||||||
SKIP_APP="${SKIP_APP:-false}"
|
|
||||||
DRY_RUN="${DRY_RUN:-false}"
|
|
||||||
|
|
||||||
INSTALL_DIR="/opt/sso-manager"
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
SYSTEMD_DIR="/etc/systemd/system"
|
echo "This script must be run as root (try: sudo $0)" >&2
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
exit 1
|
||||||
|
|
||||||
# Colors for output
|
|
||||||
RED='\033[0;31m'
|
|
||||||
GREEN='\033[0;32m'
|
|
||||||
YELLOW='\033[1;33m'
|
|
||||||
NC='\033[0m' # No Color
|
|
||||||
|
|
||||||
# ── Helper functions ──────────────────────────────────────────────────────────
|
|
||||||
info() { echo -e "${GREEN}[INFO]${NC} $*"; }
|
|
||||||
warn() { echo -e "${YELLOW}[WARN]${NC} $*" >&2; }
|
|
||||||
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
|
|
||||||
dry_run() { if [[ "$DRY_RUN" == "true" ]]; then echo "[DRY-RUN] $*"; fi; }
|
|
||||||
|
|
||||||
usage() {
|
|
||||||
grep '^#' "$0" | sed 's/^# \{0,1\}//'
|
|
||||||
exit 0
|
|
||||||
}
|
|
||||||
|
|
||||||
# Parse arguments
|
|
||||||
while [[ $# -gt 0 ]]; do
|
|
||||||
case $1 in
|
|
||||||
-p|--admin-pass)
|
|
||||||
ADMIN_PASS="$2"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-b|--base-dn)
|
|
||||||
BASE_DN="$2"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-n|--org-name)
|
|
||||||
ORG_NAME="$2"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-o|--port)
|
|
||||||
PORT="$2"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-j|--jwt-secret)
|
|
||||||
JWT_SECRET="$2"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
-s|--smtp-config)
|
|
||||||
IFS=':' read -r SMTP_HOST SMTP_PORT SMTP_USER SMTP_PASS <<< "$2"
|
|
||||||
shift 2
|
|
||||||
;;
|
|
||||||
--skip-ldap)
|
|
||||||
SKIP_LDAP="true"
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
--skip-app)
|
|
||||||
SKIP_APP="true"
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
--dry-run)
|
|
||||||
DRY_RUN="true"
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
-h|--help)
|
|
||||||
usage
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
error "Unknown option: $1"
|
|
||||||
usage
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
# Validate required parameters
|
|
||||||
if [[ -z "$ADMIN_PASS" ]]; then
|
|
||||||
error "LDAP admin password is required (-p or LDAP_ADMIN_PASS env)"
|
|
||||||
exit 1
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Generate JWT secret if not provided
|
# Symlink $1 -> $2, replacing whatever is already at $2 (idempotent).
|
||||||
if [[ -z "$JWT_SECRET" ]]; then
|
link(){
|
||||||
JWT_SECRET=$(openssl rand -hex 32)
|
ln -sfn "$1" "$2"
|
||||||
info "Generated JWT secret: ${JWT_SECRET:0:8}..."
|
echo "linked $2 -> $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Read the "version" field out of a package.json without depending on Node
|
||||||
|
# being installed yet (this runs before the Node.js install step below).
|
||||||
|
pkg_version(){
|
||||||
|
sed -n 's/^[[:space:]]*"version":[[:space:]]*"\([^"]*\)".*/\1/p' "$1" | head -1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Installed version before this run touches anything, for the upgrade banner
|
||||||
|
# at the end. Empty on a fresh install (no prior checkout).
|
||||||
|
CURRENT_VERSION=""
|
||||||
|
if [ -f "$REPO_DIR/nodejs/package.json" ]; then
|
||||||
|
CURRENT_VERSION="$(pkg_version "$REPO_DIR/nodejs/package.json")"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Derive the DNS domain from the base DN (dc=foo,dc=bar -> foo.bar) for email
|
# FIRST_RUN gates OpenLDAP bootstrap + secrets seeding below -- both only ever
|
||||||
# sender defaults. Override with LDAP_DOMAIN if set.
|
# happen once, the first time this script runs on a host (i.e. before
|
||||||
if [[ -z "${LDAP_DOMAIN:-}" ]]; then
|
# $SECRETS_FILE exists). Every later run only updates the code.
|
||||||
LDAP_DOMAIN=$(echo "$BASE_DN" | sed 's/^dc=//; s/,dc=/./g')
|
FIRST_RUN=0
|
||||||
|
[ -f "$SECRETS_FILE" ] || FIRST_RUN=1
|
||||||
|
|
||||||
|
echo "==> Base packages"
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y --no-install-recommends \
|
||||||
|
build-essential redis-server \
|
||||||
|
wget gnupg ca-certificates curl git
|
||||||
|
|
||||||
|
echo "==> Node.js ${NODE_MAJOR}.x apt source"
|
||||||
|
install -d -m 0755 /etc/apt/keyrings
|
||||||
|
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key \
|
||||||
|
| gpg --dearmor --yes -o /etc/apt/keyrings/nodesource.gpg
|
||||||
|
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_${NODE_MAJOR}.x nodistro main" \
|
||||||
|
> /etc/apt/sources.list.d/nodesource.list
|
||||||
|
|
||||||
|
echo "==> Install Node.js"
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y nodejs
|
||||||
|
|
||||||
|
echo "==> Redis"
|
||||||
|
systemctl enable --now redis-server
|
||||||
|
|
||||||
|
echo "==> Repo checkout at ${REPO_DIR} (branch ${BRANCH})"
|
||||||
|
install -d "$(dirname "$REPO_DIR")"
|
||||||
|
if [ -d "$REPO_DIR/.git" ]; then
|
||||||
|
# Force the box to match the remote branch exactly. No human edits configs
|
||||||
|
# on prod, so discarding local drift is the desired, deterministic behavior.
|
||||||
|
git -C "$REPO_DIR" fetch --prune origin
|
||||||
|
git -C "$REPO_DIR" checkout -B "$BRANCH" "origin/$BRANCH"
|
||||||
|
git -C "$REPO_DIR" reset --hard "origin/$BRANCH"
|
||||||
|
git -C "$REPO_DIR" clean -fd
|
||||||
|
else
|
||||||
|
git clone --branch "$BRANCH" "$REPO_URL" "$REPO_DIR"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ── System checks ─────────────────────────────────────────────────────────────
|
NEW_VERSION="$(pkg_version "$REPO_DIR/nodejs/package.json")"
|
||||||
check_root() {
|
|
||||||
if [[ $EUID -ne 0 ]]; then
|
if [ "$FIRST_RUN" -eq 1 ] && [ "$SKIP_LDAP" != "true" ]; then
|
||||||
error "This script must be run as root (sudo)"
|
echo "==> First run: bootstrapping OpenLDAP (base DN: ${LDAP_BASE_DN})"
|
||||||
exit 1
|
LDAP_ADMIN_PASS="${LDAP_ADMIN_PASS:-$(openssl rand -base64 24 | tr -d '=+/')}"
|
||||||
fi
|
JWT_SECRET="${JWT_SECRET:-$(openssl rand -hex 32)}"
|
||||||
}
|
BIND_DN="cn=admin,${LDAP_BASE_DN}"
|
||||||
|
# slapd/domain wants a dotted DNS domain (e.g. "example.com"), not the raw
|
||||||
check_os() {
|
# DN -- "dc=foo,dc=bar" -> "foo.bar". A malformed value here (e.g. the raw
|
||||||
if [[ ! -f /etc/debian_version ]]; then
|
# DN with only the leading "dc=" stripped) makes slapd's postinst hang
|
||||||
error "This script is for Debian/Ubuntu systems only"
|
# indefinitely instead of failing cleanly.
|
||||||
exit 1
|
LDAP_DOMAIN="$(echo "$LDAP_BASE_DN" | sed 's/^dc=//; s/,dc=/./g')"
|
||||||
fi
|
|
||||||
info "Detected $(cat /etc/os-release | grep PRETTY_NAME | cut -d'"' -f2)"
|
if ! command -v slapd >/dev/null 2>&1; then
|
||||||
}
|
debconf-set-selections <<-EOF
|
||||||
|
slapd slapd/internal/adminpw password ${LDAP_ADMIN_PASS}
|
||||||
# ── Package installation ──────────────────────────────────────────────────────
|
slapd slapd/password1 password ${LDAP_ADMIN_PASS}
|
||||||
install_package() {
|
slapd slapd/password2 password ${LDAP_ADMIN_PASS}
|
||||||
local pkg="$1"
|
slapd slapd/domain string ${LDAP_DOMAIN}
|
||||||
if dpkg -l | grep -q "^ii $pkg "; then
|
slapd shared/organization string ${ORG_NAME}
|
||||||
info "Package $pkg is already installed"
|
slapd slapd/purge_database boolean true
|
||||||
return 0
|
slapd slapd/move_old_database boolean true
|
||||||
fi
|
EOF
|
||||||
dry_run "Would install package: $pkg"
|
apt-get install -y slapd ldap-utils
|
||||||
[[ "$DRY_RUN" == "true" ]] && return 0
|
cat > /etc/ldap/ldap.conf <<-EOF
|
||||||
apt-get update -qq
|
BASE ${LDAP_BASE_DN}
|
||||||
apt-get install -y -qq "$pkg"
|
URI ldap://localhost
|
||||||
info "Installed $pkg"
|
EOF
|
||||||
}
|
systemctl enable --now slapd
|
||||||
|
else
|
||||||
install_nodejs() {
|
echo " slapd already installed -- assuming it already serves ${LDAP_BASE_DN}"
|
||||||
if command -v node &>/dev/null && node --version | grep -q "v20"; then
|
fi
|
||||||
info "Node.js 20.x is already installed"
|
|
||||||
return 0
|
echo "==> Directory structure (ou=people, ou=groups)"
|
||||||
fi
|
for ou in people groups; do
|
||||||
dry_run "Would install Node.js 20.x"
|
dn="ou=${ou},${LDAP_BASE_DN}"
|
||||||
[[ "$DRY_RUN" == "true" ]] && return 0
|
if ldapsearch -x -D "$BIND_DN" -w "$LDAP_ADMIN_PASS" -H ldap://localhost -b "$dn" -s base "(objectClass=*)" dn 2>/dev/null | grep -q "^dn:"; then
|
||||||
|
echo " ${dn} already exists"
|
||||||
info "Installing Node.js 20.x..."
|
else
|
||||||
# Use NodeSource repository for Node.js 20.x
|
ldapadd -x -D "$BIND_DN" -w "$LDAP_ADMIN_PASS" -H ldap://localhost <<-EOF
|
||||||
apt-get update -qq
|
dn: ${dn}
|
||||||
apt-get install -y -qq curl gnupg ca-certificates
|
objectClass: organizationalUnit
|
||||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash - >/dev/null 2>&1
|
ou: ${ou}
|
||||||
apt-get install -y -qq nodejs
|
EOF
|
||||||
info "Installed Node.js $(node --version)"
|
echo " ${dn} created"
|
||||||
}
|
fi
|
||||||
|
done
|
||||||
# ── OpenLDAP installation and configuration ───────────────────────────────────
|
|
||||||
install_openldap() {
|
echo "==> LDAP modules, overlays, schema, policy, SSO groups"
|
||||||
if command -v slapd &>/dev/null; then
|
"$REPO_DIR/ops/ldap-setup.sh" -p "$LDAP_ADMIN_PASS" -b "$LDAP_BASE_DN" -D "$BIND_DN"
|
||||||
info "OpenLDAP is already installed"
|
|
||||||
return 0
|
echo "==> Seeding ${SECRETS_FILE}"
|
||||||
fi
|
install -d -m 0750 "$(dirname "$SECRETS_FILE")"
|
||||||
dry_run "Would install OpenLDAP"
|
cat > "$SECRETS_FILE" <<-SECRETSEOF
|
||||||
[[ "$DRY_RUN" == "true" ]] && return 0
|
'use strict';
|
||||||
|
|
||||||
info "Installing OpenLDAP..."
|
// Generated by install.sh on $(date -u +%Y-%m-%dT%H:%M:%SZ). Edit freely --
|
||||||
|
// this file is never overwritten by a later run of install.sh.
|
||||||
# Pre-seed debconf for non-interactive installation
|
// LDAP admin password + JWT secret below were auto-generated; SMTP is a
|
||||||
debconf-set-selections << EOF
|
// placeholder (email delivery won't work until you fill it in).
|
||||||
slapd slapd/internal/adminpw string $ADMIN_PASS
|
|
||||||
slapd slapd/password1 string $ADMIN_PASS
|
module.exports = {
|
||||||
slapd slapd/password2 string $ADMIN_PASS
|
port: ${PORT},
|
||||||
slapd slapd/domain string ${BASE_DN#dc=}
|
name: '${ORG_NAME}',
|
||||||
slapd slapd/backend string MDB
|
ldap: {
|
||||||
slapd shared/organization string $ORG_NAME
|
url: 'ldap://localhost',
|
||||||
slapd slapd/purge_database boolean true
|
bindDN: '${BIND_DN}',
|
||||||
slapd slapd/move_old_database boolean true
|
bindPassword: '${LDAP_ADMIN_PASS}',
|
||||||
slapd slapd/invalid_config boolean true
|
userBase: 'ou=people,${LDAP_BASE_DN}',
|
||||||
EOF
|
groupBase: 'ou=groups,${LDAP_BASE_DN}',
|
||||||
|
},
|
||||||
apt-get update -qq
|
smtp: {
|
||||||
apt-get install -y -qq slapd ldap-utils
|
host: 'smtp.example.com',
|
||||||
|
port: 587,
|
||||||
# Configure ldap.conf
|
secure: false,
|
||||||
cat > /etc/ldap/ldap.conf << LDAPCONF
|
user: 'noreply@${LDAP_DOMAIN}',
|
||||||
BASE $BASE_DN
|
pass: 'set-me',
|
||||||
URI ldap://localhost
|
from: '${ORG_NAME} <noreply@${LDAP_DOMAIN}>',
|
||||||
LDAPCONF
|
},
|
||||||
|
oauth: {
|
||||||
# Set proper permissions
|
issuer: '',
|
||||||
chmod 644 /etc/ldap/ldap.conf
|
jwtSecret: '${JWT_SECRET}',
|
||||||
|
token_lifetime: {
|
||||||
info "OpenLDAP installed"
|
access_token: 3600,
|
||||||
}
|
refresh_token: 2592000,
|
||||||
|
},
|
||||||
configure_openldap() {
|
},
|
||||||
info "Configuring OpenLDAP..."
|
};
|
||||||
dry_run "Would configure OpenLDAP with base DN: $BASE_DN"
|
SECRETSEOF
|
||||||
[[ "$DRY_RUN" == "true" ]] && return 0
|
chmod 600 "$SECRETS_FILE"
|
||||||
|
echo " seeded ${SECRETS_FILE} (LDAP + JWT are live; SMTP is a placeholder)"
|
||||||
# Wait for slapd to be ready
|
echo " \$EDITOR ${SECRETS_FILE}"
|
||||||
for i in {1..10}; do
|
echo " then re-run this script (or: sudo systemctl restart sso-manager)"
|
||||||
if ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "cn=config" "(objectClass=*)" dn >/dev/null 2>&1; then
|
elif [ "$FIRST_RUN" -eq 1 ]; then
|
||||||
info "OpenLDAP is ready"
|
echo "==> SKIP_LDAP=true -- not bootstrapping OpenLDAP or seeding ${SECRETS_FILE}"
|
||||||
break
|
echo " Write it yourself (see secrets.js.example) before starting sso-manager."
|
||||||
fi
|
else
|
||||||
sleep 1
|
echo "==> ${SECRETS_FILE} already exists, leaving LDAP + secrets untouched"
|
||||||
done
|
fi
|
||||||
|
|
||||||
# Detect the database DN for our suffix
|
echo "==> Symlink systemd config from the repo"
|
||||||
DB_DN=$(ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "cn=config" \
|
link "$REPO_DIR/ops/systemd/sso-manager.service" /etc/systemd/system/sso-manager.service
|
||||||
"(&(objectClass=olcDatabaseConfig)(olcSuffix=${BASE_DN}))" dn 2>/dev/null \
|
|
||||||
| grep "^dn:" | head -1 | sed 's/^dn: //')
|
echo "==> Node dependencies"
|
||||||
|
# Deterministic, production-only install from the lockfile. Falls back to a
|
||||||
if [[ -z "$DB_DN" ]]; then
|
# plain install if the lockfile and manifest are out of step.
|
||||||
# Try to find any database and update its suffix
|
( cd "$REPO_DIR/nodejs" && { npm ci --omit=dev || npm install --omit=dev; } )
|
||||||
DB_DN=$(ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "cn=config" \
|
|
||||||
"(objectClass=olcDatabaseConfig)" dn 2>/dev/null \
|
echo "==> Services"
|
||||||
| grep "^dn:" | head -1 | sed 's/^dn: //')
|
systemctl daemon-reload
|
||||||
|
systemctl enable --now sso-manager.service
|
||||||
if [[ -n "$DB_DN" ]]; then
|
systemctl restart sso-manager.service
|
||||||
info "Updating database suffix to $BASE_DN"
|
|
||||||
ldapmodify -Q -Y EXTERNAL -H ldapi:/// << EOF
|
echo "==> Done."
|
||||||
dn: $DB_DN
|
if [ -z "$CURRENT_VERSION" ]; then
|
||||||
changetype: modify
|
echo " Installed v${NEW_VERSION}."
|
||||||
replace: olcSuffix
|
elif [ "$CURRENT_VERSION" = "$NEW_VERSION" ]; then
|
||||||
olcSuffix: $BASE_DN
|
echo " Already up to date (v${NEW_VERSION})."
|
||||||
EOF
|
else
|
||||||
fi
|
echo " Updated v${CURRENT_VERSION} -> v${NEW_VERSION}."
|
||||||
fi
|
fi
|
||||||
|
echo " Update later with: sudo BRANCH=${BRANCH} $0"
|
||||||
if [[ -z "$DB_DN" ]]; then
|
|
||||||
error "Could not detect OpenLDAP database configuration"
|
|
||||||
return 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
info "Using database: $DB_DN"
|
|
||||||
|
|
||||||
# 1. Load pw-sha2 module
|
|
||||||
if ! ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "cn=config" "(objectClass=olcModuleList)" olcModuleLoad 2>/dev/null | grep -q "pw-sha2"; then
|
|
||||||
info "Loading pw-sha2 module..."
|
|
||||||
ldapmodify -Q -Y EXTERNAL -H ldapi:/// << EOF
|
|
||||||
dn: cn=module{0},cn=config
|
|
||||||
changetype: modify
|
|
||||||
add: olcModuleLoad
|
|
||||||
olcModuleLoad: pw-sha2
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "pw-sha2 module already loaded"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 2. Load ppolicy module
|
|
||||||
if ! ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "cn=config" "(objectClass=olcModuleList)" olcModuleLoad 2>/dev/null | grep -q "ppolicy"; then
|
|
||||||
info "Loading ppolicy module..."
|
|
||||||
ldapmodify -Q -Y EXTERNAL -H ldapi:/// << EOF
|
|
||||||
dn: cn=module{0},cn=config
|
|
||||||
changetype: modify
|
|
||||||
add: olcModuleLoad
|
|
||||||
olcModuleLoad: ppolicy
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "ppolicy module already loaded"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 3. Load memberof module
|
|
||||||
if ! ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "cn=config" "(objectClass=olcModuleList)" olcModuleLoad 2>/dev/null | grep -q "memberof"; then
|
|
||||||
info "Loading memberof module..."
|
|
||||||
ldapmodify -Q -Y EXTERNAL -H ldapi:/// << EOF
|
|
||||||
dn: cn=module{1},cn=config
|
|
||||||
changetype: modify
|
|
||||||
add: olcModuleLoad
|
|
||||||
olcModuleLoad: memberof
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "memberof module already loaded"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 4. Load refint module
|
|
||||||
if ! ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "cn=config" "(objectClass=olcModuleList)" olcModuleLoad 2>/dev/null | grep -q "refint"; then
|
|
||||||
info "Loading refint module..."
|
|
||||||
ldapmodify -Q -Y EXTERNAL -H ldapi:/// << EOF
|
|
||||||
dn: cn=module{1},cn=config
|
|
||||||
changetype: modify
|
|
||||||
add: olcModuleLoad
|
|
||||||
olcModuleLoad: refint
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "refint module already loaded"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 5. Add ppolicy overlay
|
|
||||||
if ! ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "$DB_DN" "(olcOverlay=*ppolicy*)" dn 2>/dev/null | grep -qi "ppolicy"; then
|
|
||||||
info "Adding ppolicy overlay..."
|
|
||||||
ldapadd -Q -Y EXTERNAL -H ldapi:/// << EOF
|
|
||||||
dn: olcOverlay=ppolicy,$DB_DN
|
|
||||||
objectClass: olcOverlayConfig
|
|
||||||
objectClass: olcPPolicyConfig
|
|
||||||
olcOverlay: ppolicy
|
|
||||||
olcPPolicyDefault: cn=ppolicy,ou=policies,$BASE_DN
|
|
||||||
olcPPolicyUseLockout: TRUE
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "ppolicy overlay already configured"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 6. Add memberof overlay
|
|
||||||
if ! ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "$DB_DN" "(olcOverlay=*memberof*)" dn 2>/dev/null | grep -qi "memberof"; then
|
|
||||||
info "Adding memberof overlay..."
|
|
||||||
ldapadd -Q -Y EXTERNAL -H ldapi:/// << EOF
|
|
||||||
dn: olcOverlay=memberof,$DB_DN
|
|
||||||
objectClass: olcConfig
|
|
||||||
objectClass: olcMemberOf
|
|
||||||
objectClass: olcOverlayConfig
|
|
||||||
objectClass: top
|
|
||||||
olcOverlay: memberof
|
|
||||||
olcMemberOfDangling: ignore
|
|
||||||
olcMemberOfRefInt: TRUE
|
|
||||||
olcMemberOfGroupOC: groupOfNames
|
|
||||||
olcMemberOfMemberAD: member
|
|
||||||
olcMemberOfMemberOfAD: memberOf
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "memberof overlay already configured"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 7. Add refint overlay
|
|
||||||
if ! ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "$DB_DN" "(olcOverlay=*refint*)" dn 2>/dev/null | grep -qi "refint"; then
|
|
||||||
info "Adding refint overlay..."
|
|
||||||
ldapadd -Q -Y EXTERNAL -H ldapi:/// << EOF
|
|
||||||
dn: olcOverlay=refint,$DB_DN
|
|
||||||
objectClass: olcConfig
|
|
||||||
objectClass: olcOverlayConfig
|
|
||||||
objectClass: olcRefintConfig
|
|
||||||
objectClass: top
|
|
||||||
olcOverlay: refint
|
|
||||||
olcRefintAttribute: memberof member manager owner
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "refint overlay already configured"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 8. Add database indexes
|
|
||||||
info "Configuring database indexes..."
|
|
||||||
for index in "mail eq,sub" "uid eq,sub" "cn eq,sub" "member eq" "uidNumber eq" "gidNumber eq"; do
|
|
||||||
attr=$(echo "$index" | cut -d' ' -f1)
|
|
||||||
types=$(echo "$index" | cut -d' ' -f2)
|
|
||||||
ldapmodify -Q -Y EXTERNAL -H ldapi:/// << EOF || true
|
|
||||||
dn: $DB_DN
|
|
||||||
changetype: modify
|
|
||||||
add: olcDbIndex
|
|
||||||
olcDbIndex: $attr $types
|
|
||||||
EOF
|
|
||||||
done
|
|
||||||
|
|
||||||
# 9. Load custom theta42 schema
|
|
||||||
if ! ldapsearch -Q -Y EXTERNAL -H ldapi:/// -b "cn=schema,cn=config" "(olcObjectClasses=*theta42Person*)" olcObjectClasses 2>/dev/null | grep -q "theta42"; then
|
|
||||||
info "Loading custom theta42 schema..."
|
|
||||||
ldapadd -Q -Y EXTERNAL -H ldapi:/// << EOF
|
|
||||||
dn: cn=theta42,cn=schema,cn=config
|
|
||||||
objectClass: olcSchemaConfig
|
|
||||||
cn: theta42
|
|
||||||
olcAttributeTypes: ( 1.3.6.1.4.1.99999.1.1
|
|
||||||
NAME 'dateOfBirth'
|
|
||||||
DESC 'Date of birth in ISO 8601 format YYYY-MM-DD'
|
|
||||||
EQUALITY caseExactMatch
|
|
||||||
SUBSTR caseExactSubstringsMatch
|
|
||||||
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
|
|
||||||
SINGLE-VALUE )
|
|
||||||
olcObjectClasses: ( 1.3.6.1.4.1.99999.2.1
|
|
||||||
NAME 'theta42Person'
|
|
||||||
DESC 'Theta42 SSO extended person attributes'
|
|
||||||
AUXILIARY
|
|
||||||
MAY ( dateOfBirth ) )
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "theta42 schema already loaded"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 10. Create base directory structure
|
|
||||||
BIND_DN="cn=admin,$BASE_DN"
|
|
||||||
|
|
||||||
# Create base DN if it doesn't exist
|
|
||||||
if ! ldapsearch -x -D "$BIND_DN" -w "$ADMIN_PASS" -H ldapi:/// -b "$BASE_DN" -s base "(objectClass=*)" dn 2>/dev/null | grep -q "dn:"; then
|
|
||||||
info "Creating base DN structure..."
|
|
||||||
DC_VALUE="${BASE_DN#dc=}"
|
|
||||||
DC_VALUE="${DC_VALUE%%,*}"
|
|
||||||
|
|
||||||
ldapadd -x -D "$BIND_DN" -w "$ADMIN_PASS" -H ldapi:/// << EOF
|
|
||||||
dn: $BASE_DN
|
|
||||||
objectClass: dcObject
|
|
||||||
objectClass: organization
|
|
||||||
dc: $DC_VALUE
|
|
||||||
o: $ORG_NAME
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "Base DN already exists"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Create OUs
|
|
||||||
for ou in people groups policies; do
|
|
||||||
dn="ou=$ou,$BASE_DN"
|
|
||||||
if ! ldapsearch -x -D "$BIND_DN" -w "$ADMIN_PASS" -H ldapi:/// -b "$dn" -s base "(objectClass=*)" dn 2>/dev/null | grep -q "dn:"; then
|
|
||||||
info "Creating $ou OU..."
|
|
||||||
ldapadd -x -D "$BIND_DN" -w "$ADMIN_PASS" -H ldapi:/// << EOF
|
|
||||||
dn: ou=$ou,$BASE_DN
|
|
||||||
objectClass: organizationalUnit
|
|
||||||
ou: $ou
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "OU $ou already exists"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
# 11. Create default ppolicy
|
|
||||||
if ! ldapsearch -x -D "$BIND_DN" -w "$ADMIN_PASS" -H ldapi:/// -b "cn=ppolicy,ou=policies,$BASE_DN" -s base "(objectClass=*)" dn 2>/dev/null | grep -q "dn:"; then
|
|
||||||
info "Creating default ppolicy..."
|
|
||||||
ldapadd -x -D "$BIND_DN" -w "$ADMIN_PASS" -H ldapi:/// << EOF
|
|
||||||
dn: cn=ppolicy,ou=policies,$BASE_DN
|
|
||||||
objectClass: top
|
|
||||||
objectClass: organizationalRole
|
|
||||||
objectClass: pwdPolicy
|
|
||||||
cn: ppolicy
|
|
||||||
pwdAttribute: 2.5.4.35
|
|
||||||
pwdLockout: FALSE
|
|
||||||
pwdMustChange: FALSE
|
|
||||||
pwdAllowUserChange: TRUE
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "Default ppolicy already exists"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# 12. Create required SSO groups
|
|
||||||
for group in app_sso_admin app_sso_invite app_sso_oauth_admin; do
|
|
||||||
dn="cn=$group,ou=groups,$BASE_DN"
|
|
||||||
if ! ldapsearch -x -D "$BIND_DN" -w "$ADMIN_PASS" -H ldapi:/// -b "$dn" -s base "(objectClass=*)" dn 2>/dev/null | grep -q "dn:"; then
|
|
||||||
info "Creating group: $group"
|
|
||||||
ldapadd -x -D "$BIND_DN" -w "$ADMIN_PASS" -H ldapi:/// << EOF
|
|
||||||
dn: $dn
|
|
||||||
objectClass: groupOfNames
|
|
||||||
objectClass: top
|
|
||||||
cn: $group
|
|
||||||
description: $ORG_NAME $group group
|
|
||||||
member: $BIND_DN
|
|
||||||
EOF
|
|
||||||
else
|
|
||||||
info "Group $group already exists"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
info "OpenLDAP configuration complete"
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Application installation ──────────────────────────────────────────────────
|
|
||||||
install_app() {
|
|
||||||
info "Installing SSO Manager application..."
|
|
||||||
dry_run "Would install application to $INSTALL_DIR"
|
|
||||||
[[ "$DRY_RUN" == "true" ]] && return 0
|
|
||||||
|
|
||||||
# Create installation directory
|
|
||||||
mkdir -p "$INSTALL_DIR"
|
|
||||||
|
|
||||||
# Copy application files
|
|
||||||
info "Copying application files..."
|
|
||||||
cp -r "$SCRIPT_DIR/nodejs/"* "$INSTALL_DIR/"
|
|
||||||
|
|
||||||
# Install npm dependencies
|
|
||||||
info "Installing npm dependencies..."
|
|
||||||
cd "$INSTALL_DIR"
|
|
||||||
npm ci --only=production --quiet
|
|
||||||
|
|
||||||
# Create secrets configuration
|
|
||||||
info "Creating application configuration..."
|
|
||||||
cat > "$INSTALL_DIR/conf/secrets.js" << SECRETEOF
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
port: $PORT,
|
|
||||||
ldap: {
|
|
||||||
url: 'ldap://localhost',
|
|
||||||
bindDN: 'cn=admin,$BASE_DN',
|
|
||||||
bindPassword: '$ADMIN_PASS',
|
|
||||||
userBase: 'ou=people,$BASE_DN',
|
|
||||||
groupBase: 'ou=groups,$BASE_DN',
|
|
||||||
},
|
|
||||||
smtp: {
|
|
||||||
host: '${SMTP_HOST:-localhost}',
|
|
||||||
port: ${SMTP_PORT:-587},
|
|
||||||
user: '${SMTP_USER:-}',
|
|
||||||
pass: '${SMTP_PASS:-}',
|
|
||||||
from: '${ORG_NAME} <noreply@${LDAP_DOMAIN}>',
|
|
||||||
},
|
|
||||||
voipms: {
|
|
||||||
username: '${VOIPMS_USER:-}',
|
|
||||||
password: '${VOIPMS_PASS:-}',
|
|
||||||
did: '${VOIPMS_DID:-}',
|
|
||||||
},
|
|
||||||
oauth: {
|
|
||||||
issuer: '',
|
|
||||||
jwtSecret: '$JWT_SECRET',
|
|
||||||
token_lifetime: {
|
|
||||||
access_token: 3600,
|
|
||||||
refresh_token: 2592000
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
SECRETEOF
|
|
||||||
|
|
||||||
# Create base configuration
|
|
||||||
cat > "$INSTALL_DIR/conf/base.js" << BASEEOF
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
name: "$ORG_NAME",
|
|
||||||
userModel: 'ldap',
|
|
||||||
redis: {
|
|
||||||
prefix: 'sso_manager_'
|
|
||||||
},
|
|
||||||
ldap: {
|
|
||||||
url: 'ldap://localhost',
|
|
||||||
bindDN: 'cn=admin,$BASE_DN',
|
|
||||||
bindPassword: '__IN SECRETS FILE__',
|
|
||||||
userBase: 'ou=people,$BASE_DN',
|
|
||||||
groupBase: 'ou=groups,$BASE_DN',
|
|
||||||
userFilter: '(objectClass=posixAccount)',
|
|
||||||
userNameAttribute: 'uid'
|
|
||||||
},
|
|
||||||
oauth: {
|
|
||||||
issuer: '',
|
|
||||||
jwtSecret: '__in secrets file__',
|
|
||||||
token_lifetime: {
|
|
||||||
access_token: 3600,
|
|
||||||
refresh_token: 2592000
|
|
||||||
}
|
|
||||||
},
|
|
||||||
smtp: {
|
|
||||||
host: 'localhost',
|
|
||||||
port: 587,
|
|
||||||
secure: false,
|
|
||||||
from: '$ORG_NAME <noreply@$LDAP_DOMAIN>',
|
|
||||||
},
|
|
||||||
};
|
|
||||||
BASEEOF
|
|
||||||
|
|
||||||
# Set ownership
|
|
||||||
chown -R root:root "$INSTALL_DIR"
|
|
||||||
chmod -R 755 "$INSTALL_DIR"
|
|
||||||
|
|
||||||
info "Application installed to $INSTALL_DIR"
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Systemd service configuration ─────────────────────────────────────────────
|
|
||||||
install_systemd() {
|
|
||||||
info "Installing systemd service..."
|
|
||||||
dry_run "Would install systemd service"
|
|
||||||
[[ "$DRY_RUN" == "true" ]] && return 0
|
|
||||||
|
|
||||||
cat > "$SYSTEMD_DIR/sso-manager.service" << UNITEOF
|
|
||||||
[Unit]
|
|
||||||
Description=Theta42 SSO Manager
|
|
||||||
Documentation=file://$INSTALL_DIR/README.md
|
|
||||||
After=network.target slapd.service
|
|
||||||
Wants=slapd.service
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
User=root
|
|
||||||
WorkingDirectory=$INSTALL_DIR
|
|
||||||
ExecStart=/usr/bin/node $INSTALL_DIR/bin/www
|
|
||||||
Restart=on-failure
|
|
||||||
RestartSec=5
|
|
||||||
Environment=NODE_ENV=production
|
|
||||||
Environment=NODE_PORT=$PORT
|
|
||||||
|
|
||||||
# Security hardening
|
|
||||||
NoNewPrivileges=true
|
|
||||||
PrivateTmp=true
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
UNITEOF
|
|
||||||
|
|
||||||
systemctl daemon-reload
|
|
||||||
systemctl enable sso-manager.service
|
|
||||||
|
|
||||||
info "Systemd service installed"
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Verification ──────────────────────────────────────────────────────────────
|
|
||||||
verify_installation() {
|
|
||||||
info "Verifying installation..."
|
|
||||||
|
|
||||||
local errors=0
|
|
||||||
|
|
||||||
# Check OpenLDAP
|
|
||||||
if command -v slapd &>/dev/null; then
|
|
||||||
if systemctl is-active --quiet slapd; then
|
|
||||||
info "✓ OpenLDAP is running"
|
|
||||||
else
|
|
||||||
warn "✗ OpenLDAP is not running"
|
|
||||||
((errors++))
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
warn "✗ OpenLDAP is not installed"
|
|
||||||
((errors++))
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Check application
|
|
||||||
if [[ -d "$INSTALL_DIR" ]]; then
|
|
||||||
info "✓ Application is installed"
|
|
||||||
else
|
|
||||||
warn "✗ Application is not installed"
|
|
||||||
((errors++))
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Check systemd service
|
|
||||||
if systemctl is-enabled --quiet sso-manager.service 2>/dev/null; then
|
|
||||||
info "✓ Systemd service is enabled"
|
|
||||||
else
|
|
||||||
warn "✗ Systemd service is not enabled"
|
|
||||||
((errors++))
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ $errors -eq 0 ]]; then
|
|
||||||
info "Installation verified successfully"
|
|
||||||
else
|
|
||||||
warn "Installation completed with $errors issue(s)"
|
|
||||||
fi
|
|
||||||
|
|
||||||
return $errors
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Main execution ────────────────────────────────────────────────────────────
|
|
||||||
main() {
|
|
||||||
echo
|
|
||||||
echo "=============================================="
|
|
||||||
echo " Theta42 SSO Manager Installer"
|
|
||||||
echo "=============================================="
|
|
||||||
echo
|
|
||||||
echo "Configuration:"
|
|
||||||
echo " Base DN: $BASE_DN"
|
|
||||||
echo " Port: $PORT"
|
|
||||||
echo " Install dir: $INSTALL_DIR"
|
|
||||||
echo " Skip LDAP: $SKIP_LDAP"
|
|
||||||
echo " Skip App: $SKIP_APP"
|
|
||||||
echo
|
|
||||||
|
|
||||||
check_root
|
|
||||||
check_os
|
|
||||||
|
|
||||||
if [[ "$SKIP_LDAP" != "true" ]]; then
|
|
||||||
echo
|
|
||||||
info "=== Installing OpenLDAP ==="
|
|
||||||
install_openldap
|
|
||||||
configure_openldap
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "$SKIP_APP" != "true" ]]; then
|
|
||||||
echo
|
|
||||||
info "=== Installing SSO Manager ==="
|
|
||||||
install_nodejs
|
|
||||||
install_app
|
|
||||||
install_systemd
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo
|
|
||||||
verify_installation
|
|
||||||
|
|
||||||
echo
|
|
||||||
echo "=============================================="
|
|
||||||
echo " Installation Complete!"
|
|
||||||
echo "=============================================="
|
|
||||||
echo
|
|
||||||
|
|
||||||
if [[ "$SKIP_APP" != "true" ]]; then
|
|
||||||
info "Start the service with: systemctl start sso-manager"
|
|
||||||
info "View logs with: journalctl -fu sso-manager"
|
|
||||||
info "Access the UI at: http://localhost:$PORT"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "$SKIP_LDAP" != "true" ]]; then
|
|
||||||
echo
|
|
||||||
info "LDAP Configuration:"
|
|
||||||
info " Base DN: $BASE_DN"
|
|
||||||
info " Bind DN: cn=admin,$BASE_DN"
|
|
||||||
info " Admin pass: (set by you)"
|
|
||||||
echo
|
|
||||||
info "Required SSO groups created:"
|
|
||||||
info " - app_sso_admin"
|
|
||||||
info " - app_sso_invite"
|
|
||||||
info " - app_sso_oauth_admin"
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo
|
|
||||||
}
|
|
||||||
|
|
||||||
main
|
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ app.contoller = require('./controller');
|
|||||||
|
|
||||||
// Background services (self-initializing on require).
|
// Background services (self-initializing on require).
|
||||||
require('./services/update_check');
|
require('./services/update_check');
|
||||||
|
require('./services/ldap_monitor');
|
||||||
|
|
||||||
// Push pubsub over the socket and back.
|
// Push pubsub over the socket and back.
|
||||||
app.onListen.push(function(){
|
app.onListen.push(function(){
|
||||||
@@ -60,6 +61,11 @@ app.set('trust proxy', 1);
|
|||||||
app.set('views', path.join(__dirname, 'views'));
|
app.set('views', path.join(__dirname, 'views'));
|
||||||
app.set('view engine', 'ejs');
|
app.set('view engine', 'ejs');
|
||||||
|
|
||||||
|
// Per-app values for the shared UI shell (views/top.ejs + views/bottom.ejs).
|
||||||
|
// Set as an app local so every res.render has it, including routes that don't
|
||||||
|
// spread the routers' `values` object.
|
||||||
|
app.locals.ui = require('./utils/ui');
|
||||||
|
|
||||||
// Have express server static content( images, CSS, browser JS) from the public
|
// Have express server static content( images, CSS, browser JS) from the public
|
||||||
// local folder. maxAge is short since this is the app's own JS/CSS, which
|
// local folder. maxAge is short since this is the app's own JS/CSS, which
|
||||||
// changes on every deploy and isn't cache-busted/fingerprinted.
|
// changes on every deploy and isn't cache-busted/fingerprinted.
|
||||||
@@ -83,18 +89,37 @@ app.use('/api/token', middleware.auth, require('./routes/token'));
|
|||||||
|
|
||||||
app.use('/api/group', middleware.auth, require('./routes/group'));
|
app.use('/api/group', middleware.auth, require('./routes/group'));
|
||||||
app.use('/api/notification', middleware.auth, require('./routes/notification'));
|
app.use('/api/notification', middleware.auth, require('./routes/notification'));
|
||||||
|
app.use('/api/discovery', middleware.auth, require('./routes/discovery'));
|
||||||
|
app.use('/api/directory-admin', middleware.auth, require('./routes/api_directory_admin'));
|
||||||
|
// Self-service access requests — any authenticated user may ask; deciding is
|
||||||
|
// gated per-resource inside the router (owner or directory admin).
|
||||||
|
app.use('/api/access-requests', middleware.auth, require('./routes/access_request'));
|
||||||
app.use('/api/update-check', middleware.auth, require('./routes/update_check'));
|
app.use('/api/update-check', middleware.auth, require('./routes/update_check'));
|
||||||
app.use('/api/tos', middleware.auth, require('./routes/tos'));
|
app.use('/api/tos', middleware.auth, require('./routes/tos'));
|
||||||
|
app.use('/api/metrics', middleware.auth, require('./routes/api_metrics'));
|
||||||
|
app.use('/api/conf', middleware.auth, require('./routes/api_conf'));
|
||||||
// Self-service API tokens (PATs) — owner-scoped, no admin group required.
|
// Self-service API tokens (PATs) — owner-scoped, no admin group required.
|
||||||
app.use('/api/api-token', middleware.auth, require('./routes/api_token'));
|
app.use('/api/api-token', middleware.auth, require('./routes/api_token'));
|
||||||
|
|
||||||
// OAuth 2.0 / OpenID Connect
|
// OAuth 2.0 / OpenID Connect
|
||||||
app.use('/oauth', oauthRouter);
|
app.use('/oauth', oauthRouter);
|
||||||
app.use('/api/oauth/client', middleware.auth, require('./routes/oauth_client'));
|
|
||||||
app.use('/api/oauth', middleware.auth, oauthApiRouter);
|
app.use('/api/oauth', middleware.auth, oauthApiRouter);
|
||||||
|
app.use('/api/oauth/client', middleware.auth, require('./routes/oauth_client'));
|
||||||
app.get('/.well-known/openid-configuration', discovery);
|
app.get('/.well-known/openid-configuration', discovery);
|
||||||
|
app.use('/api/webhook', require('./routes/webhook'));
|
||||||
|
app.use('/api/plugins', middleware.auth, require('./routes/plugins'));
|
||||||
|
const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware');
|
||||||
|
|
||||||
|
const vaultApiProxy = createProxyMiddleware({
|
||||||
|
target: 'http://openbao:8200',
|
||||||
|
changeOrigin: true,
|
||||||
|
pathRewrite: { '^/': '/v1/' },
|
||||||
|
on: {
|
||||||
|
proxyReq: fixRequestBody
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.use('/api/vault', middleware.auth, vaultApiProxy);
|
||||||
|
|
||||||
// Catch 404 and forward to error handler. If none of the above routes are
|
// Catch 404 and forward to error handler. If none of the above routes are
|
||||||
// used, this is what will be called.
|
// used, this is what will be called.
|
||||||
@@ -105,7 +130,7 @@ app.use(function(req, res, next) {
|
|||||||
next(err);
|
next(err);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Error handler. This is where `next()` will go on error
|
// Error handling
|
||||||
app.use(function(err, req, res, next) {
|
app.use(function(err, req, res, next) {
|
||||||
const SILENT_404S = ['/.well-known/'];
|
const SILENT_404S = ['/.well-known/'];
|
||||||
const isSilent404 = err.status === 404 && SILENT_404S.some(p => req.url.startsWith(p));
|
const isSilent404 = err.status === 404 && SILENT_404S.some(p => req.url.startsWith(p));
|
||||||
@@ -117,5 +142,18 @@ app.use(function(err, req, res, next) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
res.status(err.status || 500);
|
res.status(err.status || 500);
|
||||||
res.json({name: err.name, message: err.message});
|
if (req.accepts('html') && !req.originalUrl.startsWith('/api/')) {
|
||||||
|
const conf = require('@simpleworkjs/conf');
|
||||||
|
const buildInfo = require('./utils/build_info');
|
||||||
|
res.render('error', {
|
||||||
|
name: conf.name,
|
||||||
|
title: 'Error',
|
||||||
|
titleIcon: '',
|
||||||
|
logo: conf.logo,
|
||||||
|
error: err,
|
||||||
|
...buildInfo
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
res.json({name: err.name, message: err.message});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -25,13 +25,27 @@ var server = http.createServer(app);
|
|||||||
var io = require('socket.io')(server);
|
var io = require('socket.io')(server);
|
||||||
app.io = io;
|
app.io = io;
|
||||||
|
|
||||||
/**
|
const models = require('../models');
|
||||||
* Listen on provided port, on all network interfaces.
|
|
||||||
*/
|
|
||||||
|
|
||||||
server.listen(port);
|
/**
|
||||||
server.on('error', onError);
|
* Initialize ORM, then Listen on provided port, on all network interfaces.
|
||||||
server.on('listening', onListening);
|
*/
|
||||||
|
models.initORM().then(() => {
|
||||||
|
return require('../utils/conf_manager').init();
|
||||||
|
}).then(() => {
|
||||||
|
server.listen(port);
|
||||||
|
server.on('error', onError);
|
||||||
|
server.on('listening', onListening);
|
||||||
|
|
||||||
|
// Initialize scheduler
|
||||||
|
const { initScheduler } = require('../services/scheduler');
|
||||||
|
initScheduler(conf.discovery).catch(err => {
|
||||||
|
console.error('Failed to initialize scheduler:', err);
|
||||||
|
});
|
||||||
|
}).catch(err => {
|
||||||
|
console.error('Failed to initialize ORM:', err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalize a port into a number, string, or false.
|
* Normalize a port into a number, string, or false.
|
||||||
|
|||||||
@@ -22,6 +22,18 @@ module.exports = {
|
|||||||
groupBase: 'ou=groups,dc=example,dc=com',
|
groupBase: 'ou=groups,dc=example,dc=com',
|
||||||
userFilter: '(objectClass=posixAccount)',
|
userFilter: '(objectClass=posixAccount)',
|
||||||
userNameAttribute: 'uid',
|
userNameAttribute: 'uid',
|
||||||
|
// Hostname/port advertised on the /integrations page for direct-LDAP
|
||||||
|
// clients. Leave ldapsHost empty to derive it from the OAuth issuer host.
|
||||||
|
// Set it to an internal-only name (e.g. 'ldap.internal.example.com' or
|
||||||
|
// 'sso-manager' on the Docker network) so external clients don't need a
|
||||||
|
// public 636 port forward. See docs/ldap.md.
|
||||||
|
ldapsHost: '',
|
||||||
|
ldapsPort: 636,
|
||||||
|
// True when slapd carries the `nestgroup` overlay, which resolves nested
|
||||||
|
// groups server-side. Set automatically by docker-entrypoint.sh for the
|
||||||
|
// all-in-one image; leave false when pointing at a stock OpenLDAP (no
|
||||||
|
// 2.6.x release ships nestgroup) and the app resolves nesting itself.
|
||||||
|
nestedGroupsServerSide: false,
|
||||||
// New users/personal groups (see addPosixAccount/addPosixGroup in
|
// New users/personal groups (see addPosixAccount/addPosixGroup in
|
||||||
// models/user_ldap.js) get the next uid/gidNumber >= uidGidMin.
|
// models/user_ldap.js) get the next uid/gidNumber >= uidGidMin.
|
||||||
// Existing entries >= uidGidReservedFloor are ignored when computing
|
// Existing entries >= uidGidReservedFloor are ignored when computing
|
||||||
@@ -53,6 +65,16 @@ module.exports = {
|
|||||||
pass: '__in secrets file__',
|
pass: '__in secrets file__',
|
||||||
from: 'SSO Manager <noreply@example.com>',
|
from: 'SSO Manager <noreply@example.com>',
|
||||||
},
|
},
|
||||||
|
directory: {
|
||||||
|
// Public SSH jump host fronting the lab, if there is one (the jump-host
|
||||||
|
// component). When set, a host card in the catalog shows the real
|
||||||
|
// invocation — `ssh <uid>_-_<slug>@<jumpHost>` — instead of a bare
|
||||||
|
// `ssh <uid>@<ip>` that only works from inside the LAN. Empty is fine;
|
||||||
|
// the card falls back to the direct form.
|
||||||
|
jumpHost: '',
|
||||||
|
// Default SSH port assumed when a host carries no metadata.sshPort.
|
||||||
|
defaultSshPort: 22,
|
||||||
|
},
|
||||||
service: {
|
service: {
|
||||||
updateCheck: {
|
updateCheck: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# Plugins & Scheduler
|
||||||
|
|
||||||
|
The SSO Manager includes a flexible background task runner and discovery system. Plugins are defined statically in your deployment configuration (`sso-secrets.js`) and run based on their defined `cron` schedule.
|
||||||
|
|
||||||
|
## Writing Custom Plugins
|
||||||
|
|
||||||
|
You can write custom plugins to discover resources, manage internal state, or run automated scripts. Plugins must be placed in the `plugins/discovery/` directory of the SSO Manager node codebase.
|
||||||
|
|
||||||
|
A plugin file must export a `discover` method.
|
||||||
|
|
||||||
|
**Example Plugin (`plugins/discovery/my_plugin.js`):**
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
module.exports = {
|
||||||
|
discover: async function(config) {
|
||||||
|
// The config object contains any keys passed in sso-secrets.js for this plugin.
|
||||||
|
|
||||||
|
// Perform discovery logic, hit external APIs, etc.
|
||||||
|
const resources = [
|
||||||
|
{
|
||||||
|
slug: 'my-custom-resource-1',
|
||||||
|
name: 'My Resource 1',
|
||||||
|
kind: 'Host',
|
||||||
|
metadata: {
|
||||||
|
ip: '10.0.0.100',
|
||||||
|
source: 'My Custom Plugin'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
// Return the discovered resources array. The discovery reconciler will
|
||||||
|
// automatically save these to the Network Discovery database.
|
||||||
|
return resources;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
## Configuring Plugins
|
||||||
|
|
||||||
|
In your `sso-secrets.js` file, add your plugin to the `discovery.plugins` object:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
module.exports = {
|
||||||
|
// ...
|
||||||
|
discovery: {
|
||||||
|
plugins: {
|
||||||
|
my_plugin: {
|
||||||
|
enabled: true,
|
||||||
|
cron: "0 * * * *", // Run every hour
|
||||||
|
my_custom_key: "my_custom_value" // Passed to the config argument in discover()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// ...
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Overriding Timing and Enable/Disable
|
||||||
|
|
||||||
|
From the **Plugins & Scheduler** tab in the Directory Dashboard, you can override the schedule and enable/disable state for each plugin. These overrides take precedence over `sso-secrets.js` and are stored internally.
|
||||||
|
|
||||||
|
## Scheduler Internals
|
||||||
|
|
||||||
|
The scheduler uses BullMQ backed by Redis to manage execution. It automatically performs garbage collection on stale network resources (resources not updated in > 7 days) and triggers your plugins at the defined intervals.
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Vault Secrets Management
|
||||||
|
|
||||||
|
The Vault Secrets feature integrates with OpenBao to provide a secure key-value store for your environment. It allows you to store sensitive information like passwords, API keys, and credentials, ensuring they are encrypted and access-controlled.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
You can access the Vault UI from the application's top navigation bar.
|
||||||
|
|
||||||
|
### Creating Secrets
|
||||||
|
|
||||||
|
1. Click on the **New Secret** button.
|
||||||
|
2. Enter a **Secret Path**. This acts as the name/identifier of your secret (e.g., `db-credentials`).
|
||||||
|
3. Enter the **Secret Data** in JSON format. For example:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"username": "admin",
|
||||||
|
"password": "supersecretpassword123"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
4. Click **Save Secret**.
|
||||||
|
|
||||||
|
### Reading and Editing Secrets
|
||||||
|
|
||||||
|
* To view a secret, click on its name in the **Secrets List**.
|
||||||
|
* To update an existing secret, select it and click the **Edit** button. You can then modify the JSON data and save your changes.
|
||||||
|
|
||||||
|
### OpenBao Integration
|
||||||
|
|
||||||
|
The secrets are stored in an OpenBao backend configured in development mode. The default KV (Key-Value) version 2 engine is mounted at `secret/`. The built-in UI uses the `/api/vault/secret/` API endpoints to interact with OpenBao.
|
||||||
|
|
||||||
|
## API Access
|
||||||
|
|
||||||
|
If you need to programmatically access the secrets, you can interact directly with the OpenBao API using the root token (in dev mode):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Example: Read a secret via the API
|
||||||
|
curl -H "X-Vault-Token: root" -H "Authorization: Bearer <your-sso-token>" http://<your-sso-host>/api/vault/secret/data/<your-secret-path>
|
||||||
|
```
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
const { Resource } = require('./models/resource');
|
||||||
|
const { initORM } = require('./models/index');
|
||||||
|
|
||||||
|
async function run() {
|
||||||
|
await initORM();
|
||||||
|
const all = await Resource.list();
|
||||||
|
console.log(`Found ${all.length} resources`);
|
||||||
|
|
||||||
|
const byIp = {};
|
||||||
|
const byName = {};
|
||||||
|
|
||||||
|
for (const r of all) {
|
||||||
|
if (!r.metadata) r.metadata = {};
|
||||||
|
|
||||||
|
// gather IPs
|
||||||
|
const ips = new Set();
|
||||||
|
if (r.metadata.address) ips.add(r.metadata.address);
|
||||||
|
if (r.metadata.interfaces) {
|
||||||
|
r.metadata.interfaces.forEach(i => { if (i.ip) ips.add(i.ip); });
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const ip of ips) {
|
||||||
|
if (!byIp[ip]) byIp[ip] = [];
|
||||||
|
byIp[ip].push(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
const nameLower = (r.name || '').toLowerCase();
|
||||||
|
if (nameLower) {
|
||||||
|
if (!byName[nameLower]) byName[nameLower] = [];
|
||||||
|
byName[nameLower].push(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find duplicates
|
||||||
|
const toDelete = new Set();
|
||||||
|
|
||||||
|
for (const ip in byIp) {
|
||||||
|
if (byIp[ip].length > 1) {
|
||||||
|
// Sort so managed/older is kept
|
||||||
|
const group = byIp[ip].sort((a, b) => {
|
||||||
|
const aM = a.metadata?.managed ? 1 : 0;
|
||||||
|
const bM = b.metadata?.managed ? 1 : 0;
|
||||||
|
if (aM !== bM) return bM - aM;
|
||||||
|
return a.created_on - b.created_on;
|
||||||
|
});
|
||||||
|
|
||||||
|
const primary = group[0];
|
||||||
|
for (let i = 1; i < group.length; i++) {
|
||||||
|
const sec = group[i];
|
||||||
|
if (toDelete.has(sec.id) || toDelete.has(primary.id)) continue;
|
||||||
|
console.log(`Merging ${sec.name} into ${primary.name} due to IP ${ip}`);
|
||||||
|
|
||||||
|
// merge metadata
|
||||||
|
const m1 = primary.metadata || {};
|
||||||
|
const m2 = sec.metadata || {};
|
||||||
|
|
||||||
|
const mergedMeta = { ...m2, ...m1 };
|
||||||
|
|
||||||
|
// merge interfaces
|
||||||
|
const intfs = [...(m1.interfaces||[]), ...(m2.interfaces||[])];
|
||||||
|
const uniqIntfs = [];
|
||||||
|
const seenIps = new Set();
|
||||||
|
for (const intf of intfs) {
|
||||||
|
if (intf.ip && seenIps.has(intf.ip)) continue;
|
||||||
|
if (intf.ip) seenIps.add(intf.ip);
|
||||||
|
uniqIntfs.push(intf);
|
||||||
|
}
|
||||||
|
mergedMeta.interfaces = uniqIntfs;
|
||||||
|
|
||||||
|
const sources = new Set([...(m1.discovery_sources||[]), ...(m2.discovery_sources||[])]);
|
||||||
|
mergedMeta.discovery_sources = [...sources];
|
||||||
|
|
||||||
|
await primary.update({
|
||||||
|
metadata: mergedMeta,
|
||||||
|
description: primary.description || sec.description
|
||||||
|
});
|
||||||
|
|
||||||
|
toDelete.add(sec.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const name in byName) {
|
||||||
|
if (byName[name].length > 1) {
|
||||||
|
// Sort so managed/older is kept
|
||||||
|
const group = byName[name].sort((a, b) => {
|
||||||
|
const aM = a.metadata?.managed ? 1 : 0;
|
||||||
|
const bM = b.metadata?.managed ? 1 : 0;
|
||||||
|
if (aM !== bM) return bM - aM;
|
||||||
|
return a.created_on - b.created_on;
|
||||||
|
});
|
||||||
|
|
||||||
|
const primary = group[0];
|
||||||
|
for (let i = 1; i < group.length; i++) {
|
||||||
|
const sec = group[i];
|
||||||
|
if (toDelete.has(sec.id) || toDelete.has(primary.id)) continue;
|
||||||
|
console.log(`Merging ${sec.name} into ${primary.name} due to name ${name}`);
|
||||||
|
|
||||||
|
// merge metadata
|
||||||
|
const m1 = primary.metadata || {};
|
||||||
|
const m2 = sec.metadata || {};
|
||||||
|
|
||||||
|
const mergedMeta = { ...m2, ...m1 };
|
||||||
|
|
||||||
|
// merge interfaces
|
||||||
|
const intfs = [...(m1.interfaces||[]), ...(m2.interfaces||[])];
|
||||||
|
const uniqIntfs = [];
|
||||||
|
const seenIps = new Set();
|
||||||
|
for (const intf of intfs) {
|
||||||
|
if (intf.ip && seenIps.has(intf.ip)) continue;
|
||||||
|
if (intf.ip) seenIps.add(intf.ip);
|
||||||
|
uniqIntfs.push(intf);
|
||||||
|
}
|
||||||
|
mergedMeta.interfaces = uniqIntfs;
|
||||||
|
|
||||||
|
const sources = new Set([...(m1.discovery_sources||[]), ...(m2.discovery_sources||[])]);
|
||||||
|
mergedMeta.discovery_sources = [...sources];
|
||||||
|
|
||||||
|
await primary.update({
|
||||||
|
metadata: mergedMeta,
|
||||||
|
description: primary.description || sec.description
|
||||||
|
});
|
||||||
|
|
||||||
|
toDelete.add(sec.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete merged items
|
||||||
|
for (const id of toDelete) {
|
||||||
|
console.log(`Deleting merged resource ${id}`);
|
||||||
|
const r = all.find(r => r.id === id);
|
||||||
|
if (r) await r.delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Merged ${toDelete.size} items.`);
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
run().catch(console.error);
|
||||||
@@ -9,10 +9,23 @@ async function auth(req, res, next){
|
|||||||
// the same /api/* routes the UI uses.
|
// the same /api/* routes the UI uses.
|
||||||
const authz = req.header('authorization') || '';
|
const authz = req.header('authorization') || '';
|
||||||
if(authz.slice(0, 7).toLowerCase() === 'bearer '){
|
if(authz.slice(0, 7).toLowerCase() === 'bearer '){
|
||||||
const user = await Auth.checkApiToken(authz.slice(7));
|
const tokenStr = authz.slice(7);
|
||||||
if(user && user.uid){
|
if (tokenStr.startsWith('sso_')) {
|
||||||
req.user = user;
|
const user = await Auth.checkApiToken(tokenStr);
|
||||||
return next();
|
if(user && user.uid){
|
||||||
|
req.user = user;
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Machine token (ServiceToken)
|
||||||
|
const { ServiceToken } = require('../models/token');
|
||||||
|
let svcToken;
|
||||||
|
try { svcToken = await ServiceToken.get(tokenStr); } catch(e) {}
|
||||||
|
if (svcToken && svcToken.is_valid) {
|
||||||
|
req.user = { uid: svcToken.resource_id, isMachine: true, name: 'Machine Account' };
|
||||||
|
req.resourceId = svcToken.resource_id;
|
||||||
|
return next();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Self-service access requests: the "request" half of the directory catalog.
|
||||||
|
//
|
||||||
|
// A request is a *proposal to join an LDAP group*. Approving one does exactly
|
||||||
|
// what an admin would have done by hand -- add the user to `groupCn` -- so LDAP
|
||||||
|
// remains the single access-control truth and this table is only the paper
|
||||||
|
// trail of who asked, who decided, and when. Nothing here grants anything on
|
||||||
|
// its own; a row with status 'approved' whose LDAP write failed is a row that
|
||||||
|
// grants no access, which is the safe direction.
|
||||||
|
|
||||||
|
const { Model } = require('@simpleworkjs/orm');
|
||||||
|
|
||||||
|
const STATUS = {
|
||||||
|
PENDING: 'pending',
|
||||||
|
APPROVED: 'approved',
|
||||||
|
DENIED: 'denied',
|
||||||
|
CANCELLED: 'cancelled',
|
||||||
|
};
|
||||||
|
|
||||||
|
class AccessRequest extends Model {
|
||||||
|
static fields = {
|
||||||
|
id: { type: 'uuid', primaryKey: true },
|
||||||
|
// The requesting user's uid (not dn): dn changes if the directory is
|
||||||
|
// restructured, uid is the stable handle used everywhere else in the app.
|
||||||
|
uid: { type: 'string', isRequired: true },
|
||||||
|
resource: { type: 'hasOne', model: 'Resource' }, // creates resourceId
|
||||||
|
// The group joining which satisfies this request. Captured at request time
|
||||||
|
// so a later re-link of the resource's groups can't silently redirect a
|
||||||
|
// pending approval at a different group than the one that was reviewed.
|
||||||
|
groupCn: { type: 'string', isRequired: true },
|
||||||
|
status: { type: 'string', isRequired: true, default: STATUS.PENDING },
|
||||||
|
note: { type: 'text' },
|
||||||
|
requestedOn: { type: 'integer' },
|
||||||
|
decidedBy: { type: 'string' },
|
||||||
|
decidedOn: { type: 'integer' },
|
||||||
|
decisionNote: { type: 'text' },
|
||||||
|
};
|
||||||
|
|
||||||
|
// The one request that blocks a new one: same user, same group, still open.
|
||||||
|
// Denied/cancelled requests deliberately do not block -- circumstances change
|
||||||
|
// and a user may ask again.
|
||||||
|
static async findOpen(uid, groupCn) {
|
||||||
|
const rows = await this.list({ where: { uid, groupCn, status: STATUS.PENDING } });
|
||||||
|
return rows[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async listForUser(uid) {
|
||||||
|
return this.list({ where: { uid } });
|
||||||
|
}
|
||||||
|
|
||||||
|
static async listPending() {
|
||||||
|
return this.list({ where: { status: STATUS.PENDING } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { AccessRequest, STATUS };
|
||||||
@@ -23,7 +23,7 @@ Auth.login = async function(data){
|
|||||||
|
|
||||||
return {user, token}
|
return {user, token}
|
||||||
}catch(error){
|
}catch(error){
|
||||||
console.error("AUTH LOGIN error:", error);
|
console.error("AUTH LOGIN error:", error.name, error.message);
|
||||||
throw this.errors.login();
|
throw this.errors.login();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ Mail.sendTemplate = async function(to, template, context, from){
|
|||||||
to,
|
to,
|
||||||
mustache.render(template.subject, context),
|
mustache.render(template.subject, context),
|
||||||
mustache.render(template.message, context),
|
mustache.render(template.message, context),
|
||||||
from || (template.from && mustache.render(template.message, context))
|
from || (template.from && mustache.render(template.from, context))
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -3,23 +3,22 @@
|
|||||||
const { Client, Attribute, Change } = require('ldapts');
|
const { Client, Attribute, Change } = require('ldapts');
|
||||||
const { LRUCache } = require('lru-cache');
|
const { LRUCache } = require('lru-cache');
|
||||||
const conf = require('@simpleworkjs/conf').ldap;
|
const conf = require('@simpleworkjs/conf').ldap;
|
||||||
|
// Connection + escaping from the shared @simpleworkjs/ldap package. Local
|
||||||
|
// wrappers preserve the no-arg call signatures; see user_ldap.js for rationale.
|
||||||
|
const { makeClient: _makeClient, withClient: _withClient, escapeFilter, escapeDN } = require('@simpleworkjs/ldap');
|
||||||
|
const escapeLDAPSearchValue = escapeFilter;
|
||||||
|
const escapeLDAPDNValue = escapeDN;
|
||||||
|
|
||||||
function makeClient() {
|
function makeClient() {
|
||||||
return new Client({ url: conf.url });
|
return _makeClient(conf);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function withClient(fn) {
|
async function withClient(fn) {
|
||||||
const client = makeClient();
|
return _withClient(conf, fn);
|
||||||
try {
|
|
||||||
await client.bind(conf.bindDN, conf.bindPassword);
|
|
||||||
return await fn(client);
|
|
||||||
} finally {
|
|
||||||
await client.unbind().catch(() => {});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getGroups(client, member){
|
async function getGroups(client, member){
|
||||||
let memberFilter = member ? `(member=${member})`: ''
|
let memberFilter = member ? `(member=${escapeLDAPSearchValue(member)})`: ''
|
||||||
|
|
||||||
let groups = (await client.search(conf.groupBase, {
|
let groups = (await client.search(conf.groupBase, {
|
||||||
scope: 'sub',
|
scope: 'sub',
|
||||||
@@ -35,7 +34,8 @@ async function getGroups(client, member){
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function addGroup(client, data){
|
async function addGroup(client, data){
|
||||||
await client.add(`cn=${data.name},${conf.groupBase}`, {
|
const safeName = escapeLDAPDNValue(data.name);
|
||||||
|
await client.add(`cn=${safeName},${conf.groupBase}`, {
|
||||||
cn: data.name,
|
cn: data.name,
|
||||||
member: data.owner,
|
member: data.owner,
|
||||||
description: data.description,
|
description: data.description,
|
||||||
@@ -112,18 +112,190 @@ async function cachedListDetail() {
|
|||||||
return promise;
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Nested groups -------------------------------------------------------
|
||||||
|
//
|
||||||
|
// `groupOfNames.member` holds DNs, and nothing says those DNs must be users --
|
||||||
|
// a group DN is a perfectly legal member. That is how nesting is stored here:
|
||||||
|
// as-is, no extra schema, no denormalization, the nesting visible in LDAP
|
||||||
|
// exactly as an admin entered it.
|
||||||
|
//
|
||||||
|
// What LDAP will NOT do is resolve it. The memberof overlay records only
|
||||||
|
// *direct* membership, and a `(member=<dn>)` filter likewise finds only the
|
||||||
|
// groups that list the DN literally. So transitivity is computed here, and
|
||||||
|
// every membership question in the app must go through these helpers or it
|
||||||
|
// will silently see one level and grant nothing for a nested group.
|
||||||
|
//
|
||||||
|
// The whole group set is one subtree search, so the closure is computed in
|
||||||
|
// memory rather than issuing a query per level. `resolverCache` keeps that
|
||||||
|
// search off the hot path for bursts; it is cleared by every write below, so
|
||||||
|
// the only staleness it can introduce is from edits made outside this app.
|
||||||
|
// Auth decisions ride on this, hence the deliberately short TTL.
|
||||||
|
|
||||||
|
const NESTING_TTL_MS = 15 * 1000;
|
||||||
|
const MAX_NESTING_DEPTH = Number(conf.groupNestingDepth) > 0 ? Number(conf.groupNestingDepth) : 10;
|
||||||
|
|
||||||
|
const resolverCache = new LRUCache({ max: 1, ttl: NESTING_TTL_MS, ttlAutopurge: true });
|
||||||
|
|
||||||
|
async function allGroupsForResolver() {
|
||||||
|
const hit = resolverCache.get('all');
|
||||||
|
if (hit) return hit;
|
||||||
|
const promise = withClient(async (client) => {
|
||||||
|
const groups = await getGroups(client);
|
||||||
|
return groups.map(g => ({ ...g }));
|
||||||
|
}).then(plain => {
|
||||||
|
resolverCache.set('all', plain);
|
||||||
|
return plain;
|
||||||
|
}).catch(err => {
|
||||||
|
resolverCache.delete('all');
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
|
resolverCache.set('all', promise);
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lc = dn => String(dn || '').toLowerCase();
|
||||||
|
|
||||||
|
// dn -> [groups that list dn as a member]. One pass, reused for every lookup.
|
||||||
|
function buildParentIndex(groups) {
|
||||||
|
const parents = new Map();
|
||||||
|
for (const group of groups) {
|
||||||
|
for (const member of [].concat(group.member || []).filter(Boolean)) {
|
||||||
|
const key = lc(member);
|
||||||
|
if (!parents.has(key)) parents.set(key, []);
|
||||||
|
parents.get(key).push(group);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parents;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every group `dn` belongs to, directly or through any chain of nested groups.
|
||||||
|
// Breadth-first with a visited set, so a cycle (A in B, B in A) terminates
|
||||||
|
// instead of hanging, and MAX_NESTING_DEPTH bounds a pathological chain.
|
||||||
|
function closureUp(dn, groups) {
|
||||||
|
const parents = buildParentIndex(groups);
|
||||||
|
const found = new Map(); // cn -> group
|
||||||
|
const seen = new Set([lc(dn)]);
|
||||||
|
let frontier = [lc(dn)];
|
||||||
|
|
||||||
|
for (let depth = 0; depth < MAX_NESTING_DEPTH && frontier.length; depth++) {
|
||||||
|
const next = [];
|
||||||
|
for (const current of frontier) {
|
||||||
|
for (const group of parents.get(current) || []) {
|
||||||
|
const groupDn = lc(group.dn);
|
||||||
|
if (seen.has(groupDn)) continue;
|
||||||
|
seen.add(groupDn);
|
||||||
|
found.set(group.cn, group);
|
||||||
|
// The group itself is now a member to look up: this is the step
|
||||||
|
// that makes the walk transitive rather than one-level.
|
||||||
|
next.push(groupDn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
frontier = next;
|
||||||
|
}
|
||||||
|
return [...found.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every member DN reachable from a group, split into the users it effectively
|
||||||
|
// grants and the groups it nests. `direct` is kept separate so the UI can show
|
||||||
|
// "3 members, 12 effective" and so removal stays unambiguous.
|
||||||
|
function closureDown(group, groups) {
|
||||||
|
const byDn = new Map(groups.map(g => [lc(g.dn), g]));
|
||||||
|
const users = new Set();
|
||||||
|
const nested = new Map();
|
||||||
|
const seen = new Set([lc(group.dn)]);
|
||||||
|
let frontier = [group];
|
||||||
|
|
||||||
|
for (let depth = 0; depth < MAX_NESTING_DEPTH && frontier.length; depth++) {
|
||||||
|
const next = [];
|
||||||
|
for (const current of frontier) {
|
||||||
|
for (const member of [].concat(current.member || []).filter(Boolean)) {
|
||||||
|
const key = lc(member);
|
||||||
|
const asGroup = byDn.get(key);
|
||||||
|
if (asGroup) {
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
nested.set(asGroup.cn, asGroup);
|
||||||
|
next.push(asGroup);
|
||||||
|
} else {
|
||||||
|
users.add(member);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
frontier = next;
|
||||||
|
}
|
||||||
|
return { users: [...users], nested: [...nested.values()] };
|
||||||
|
}
|
||||||
|
|
||||||
var Group = {};
|
var Group = {};
|
||||||
|
|
||||||
|
// Set when slapd carries the nestgroup overlay (docker-entrypoint.sh exports
|
||||||
|
// app_ldap__nestedGroupsServerSide=true after detecting nestgroup.so). With it,
|
||||||
|
// a plain `(member=<dn>)` search already returns the full transitive set and the
|
||||||
|
// in-app closure is redundant work on every request. Without it -- e.g. pointed
|
||||||
|
// at a stock 2.6.x server, which no release ships nestgroup in -- the app must
|
||||||
|
// compute the closure itself or nested groups silently grant nothing.
|
||||||
|
const SERVER_SIDE_NESTING = String(conf.nestedGroupsServerSide) === 'true';
|
||||||
|
|
||||||
|
// Transitive: every group CN this member belongs to, at any nesting depth.
|
||||||
|
// Callers making an access decision must use this rather than reading
|
||||||
|
// `memberOf`, which a server without nestgroup only ever populates one level
|
||||||
|
// deep.
|
||||||
Group.list = async function(member){
|
Group.list = async function(member){
|
||||||
if (member) {
|
if (member) {
|
||||||
return withClient(async (client) => {
|
if (SERVER_SIDE_NESTING) {
|
||||||
const groups = await getGroups(client, member);
|
return withClient(async (client) => {
|
||||||
return groups.map(group => group.cn);
|
const groups = await getGroups(client, member);
|
||||||
});
|
return groups.map(group => group.cn);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const groups = await allGroupsForResolver();
|
||||||
|
return closureUp(member, groups).map(group => group.cn);
|
||||||
}
|
}
|
||||||
return (await cachedListDetail()).map(group => group.cn);
|
return (await cachedListDetail()).map(group => group.cn);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The members a group effectively grants: users reached through any chain of
|
||||||
|
// nested groups, plus the nested groups themselves for display.
|
||||||
|
Group.effectiveMembers = async function(cn){
|
||||||
|
const groups = await allGroupsForResolver();
|
||||||
|
const group = groups.find(g => g.cn === cn);
|
||||||
|
if (!group) {
|
||||||
|
let error = new Error('GroupNotFound');
|
||||||
|
error.name = 'GroupNotFound';
|
||||||
|
error.message = `LDAP:${cn} does not exists`;
|
||||||
|
error.status = 404;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const { users, nested } = closureDown(group, groups);
|
||||||
|
const directMembers = [].concat(group.member || []).filter(Boolean);
|
||||||
|
const groupDns = new Set(groups.map(g => lc(g.dn)));
|
||||||
|
return {
|
||||||
|
cn: group.cn,
|
||||||
|
direct: directMembers.filter(dn => !groupDns.has(lc(dn))),
|
||||||
|
nestedGroups: nested.map(g => ({ cn: g.cn, dn: g.dn })),
|
||||||
|
effective: users,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Would adding `childDn` to `parentCn` create a cycle? A group may not contain
|
||||||
|
// itself, nor anything that already (transitively) contains it -- such a chain
|
||||||
|
// makes membership unanswerable, and callers would rely on the depth cap to
|
||||||
|
// stop rather than getting a real answer.
|
||||||
|
Group.wouldCycle = async function(parentCn, childDn){
|
||||||
|
const groups = await allGroupsForResolver();
|
||||||
|
const parent = groups.find(g => g.cn === parentCn);
|
||||||
|
if (!parent) return false;
|
||||||
|
if (lc(parent.dn) === lc(childDn)) return true;
|
||||||
|
const child = groups.find(g => lc(g.dn) === lc(childDn));
|
||||||
|
if (!child) return false; // a user DN can never close a cycle
|
||||||
|
// Adding child under parent is a cycle exactly when parent is already
|
||||||
|
// reachable downward from child.
|
||||||
|
const { nested } = closureDown(child, groups);
|
||||||
|
return nested.some(g => lc(g.dn) === lc(parent.dn));
|
||||||
|
};
|
||||||
|
|
||||||
|
Group.clearResolverCache = function(){ resolverCache.clear(); };
|
||||||
|
|
||||||
Group.listDetail = async function(member){
|
Group.listDetail = async function(member){
|
||||||
if (member) {
|
if (member) {
|
||||||
return withClient(async (client) => getGroups(client, member));
|
return withClient(async (client) => getGroups(client, member));
|
||||||
@@ -139,9 +311,10 @@ Group.get = async function(data){
|
|||||||
}
|
}
|
||||||
|
|
||||||
return withClient(async (client) => {
|
return withClient(async (client) => {
|
||||||
|
const safeName = escapeLDAPSearchValue(data.name);
|
||||||
let group = (await client.search(conf.groupBase, {
|
let group = (await client.search(conf.groupBase, {
|
||||||
scope: 'sub',
|
scope: 'sub',
|
||||||
filter: `(&(objectClass=groupOfNames)(cn=${data.name}))`,
|
filter: `(&(objectClass=groupOfNames)(cn=${safeName}))`,
|
||||||
attributes: ['cn', 'description', 'member', 'owner', 'createTimestamp', 'modifyTimestamp'],
|
attributes: ['cn', 'description', 'member', 'owner', 'createTimestamp', 'modifyTimestamp'],
|
||||||
})).searchEntries[0];
|
})).searchEntries[0];
|
||||||
|
|
||||||
@@ -165,6 +338,7 @@ Group.add = async function(data){
|
|||||||
return withClient(async (client) => {
|
return withClient(async (client) => {
|
||||||
await addGroup(client, data);
|
await addGroup(client, data);
|
||||||
cache.clear();
|
cache.clear();
|
||||||
|
resolverCache.clear();
|
||||||
return this.get(data);
|
return this.get(data);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -173,6 +347,7 @@ Group.addMember = async function(user){
|
|||||||
await withClient(async (client) => addMember(client, this, user));
|
await withClient(async (client) => addMember(client, this, user));
|
||||||
this.member = [].concat(this.member || []).concat([user.dn]);
|
this.member = [].concat(this.member || []).concat([user.dn]);
|
||||||
cache.clear();
|
cache.clear();
|
||||||
|
resolverCache.clear();
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -185,6 +360,7 @@ Group.removeMember = async function(user){
|
|||||||
}
|
}
|
||||||
this.member = [].concat(this.member || []).filter(dn => dn !== user.dn);
|
this.member = [].concat(this.member || []).filter(dn => dn !== user.dn);
|
||||||
cache.clear();
|
cache.clear();
|
||||||
|
resolverCache.clear();
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -192,6 +368,7 @@ Group.addOwner = async function(user){
|
|||||||
await withClient(async (client) => addOwner(client, this, user));
|
await withClient(async (client) => addOwner(client, this, user));
|
||||||
this.owner = [].concat(this.owner || []).concat([user.dn]);
|
this.owner = [].concat(this.owner || []).concat([user.dn]);
|
||||||
cache.clear();
|
cache.clear();
|
||||||
|
resolverCache.clear();
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -204,12 +381,14 @@ Group.removeOwner = async function(user){
|
|||||||
}
|
}
|
||||||
this.owner = [].concat(this.owner || []).filter(dn => dn !== user.dn);
|
this.owner = [].concat(this.owner || []).filter(dn => dn !== user.dn);
|
||||||
cache.clear();
|
cache.clear();
|
||||||
|
resolverCache.clear();
|
||||||
return this;
|
return this;
|
||||||
};
|
};
|
||||||
|
|
||||||
Group.remove = async function(){
|
Group.remove = async function(){
|
||||||
await withClient(async (client) => client.del(this.dn));
|
await withClient(async (client) => client.del(this.dn));
|
||||||
cache.clear();
|
cache.clear();
|
||||||
|
resolverCache.clear();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,44 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const conf = require('@simpleworkjs/conf');
|
const conf = require('@simpleworkjs/conf');
|
||||||
const {setUpTable} = require('model-redis');
|
const { setUpTable } = require('model-redis');
|
||||||
|
|
||||||
|
// Keep model-redis for the ones not yet ported
|
||||||
const Table = setUpTable(conf.redis);
|
const Table = setUpTable(conf.redis);
|
||||||
|
|
||||||
module.exports = Table;
|
module.exports = Table;
|
||||||
|
|
||||||
require('./token');
|
const { Token, AuthToken, InviteToken, ImpersonationToken, PasswordResetToken, OtpToken, ServiceToken } = require('./token');
|
||||||
require('./verification');
|
require('./verification');
|
||||||
require('./oauth_client');
|
|
||||||
require('./oauth_code');
|
require('./oauth_code');
|
||||||
require('./api_token');
|
require('./api_token');
|
||||||
|
|
||||||
|
const { init } = require('@simpleworkjs/orm');
|
||||||
|
const { Resource, ResourceEdge, ResourceGroup } = require('./resource');
|
||||||
|
const { AccessRequest } = require('./access_request');
|
||||||
|
const { Webhook } = require('./webhook');
|
||||||
|
async function initORM() {
|
||||||
|
const ormConf = conf.orm || {
|
||||||
|
dialect: 'sqlite',
|
||||||
|
storage: './config/inventory.sqlite',
|
||||||
|
logging: false
|
||||||
|
};
|
||||||
|
ormConf.redis = conf.redis;
|
||||||
|
|
||||||
|
console.log('[initORM] Starting ORM initialization...');
|
||||||
|
try {
|
||||||
|
await init({
|
||||||
|
conf: { orm: ormConf },
|
||||||
|
models: [
|
||||||
|
Resource, ResourceEdge, ResourceGroup, AccessRequest, Webhook,
|
||||||
|
Token, AuthToken, InviteToken, ImpersonationToken, PasswordResetToken, OtpToken, ServiceToken
|
||||||
|
]
|
||||||
|
});
|
||||||
|
console.log('[initORM] ORM initialized successfully');
|
||||||
|
console.log('[initORM] Resource.orm =', !!Resource.orm, 'Token.orm =', !!Token.orm);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[initORM] ORM initialization failed:', err.message);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports.initORM = initORM;
|
||||||
|
|||||||
@@ -1,50 +1,137 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const Table = require('.');
|
const { Resource } = require('./resource');
|
||||||
const bcrypt = require('bcrypt');
|
const bcrypt = require('bcrypt');
|
||||||
const UUID = function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)};
|
const crypto = require('crypto');
|
||||||
const conf = require('@simpleworkjs/conf');
|
const conf = require('@simpleworkjs/conf');
|
||||||
|
const UUID = () => crypto.randomUUID();
|
||||||
|
|
||||||
const defaultLifetime = (conf.oauth && conf.oauth.token_lifetime) || {
|
const defaultLifetime = (conf.oauth && conf.oauth.token_lifetime) || {
|
||||||
access_token: 3600,
|
access_token: 3600,
|
||||||
refresh_token: 2592000
|
refresh_token: 2592000
|
||||||
};
|
};
|
||||||
|
|
||||||
class OAuthClient extends Table {
|
class OAuthClient {
|
||||||
static _key = 'client_id';
|
|
||||||
static _keyMap = {
|
|
||||||
'client_id': {default: UUID, type: 'string'},
|
|
||||||
'client_secret_hash': {isRequired: true, type: 'string', isPrivate: true},
|
|
||||||
'name': {isRequired: true, type: 'string', min: 1, max: 255},
|
|
||||||
'description': {default: '', type: 'string'},
|
|
||||||
'redirect_uris': {default: [], type: 'object'},
|
|
||||||
'scopes': {default: ['openid', 'profile', 'email', 'groups'], type: 'object'},
|
|
||||||
'allowed_groups': {default: [], type: 'object'},
|
|
||||||
'token_lifetime': {default: function(){ return Object.assign({}, defaultLifetime) }, type: 'object'},
|
|
||||||
'created_by': {isRequired: true, type: 'string'},
|
|
||||||
'created_on': {default: function(){ return (new Date).getTime() }},
|
|
||||||
'is_valid': {default: true, type: 'boolean'},
|
|
||||||
}
|
|
||||||
|
|
||||||
static async add(data) {
|
static async add(data) {
|
||||||
const raw_secret = UUID();
|
const raw_secret = crypto.randomUUID();
|
||||||
data.client_secret_hash = await bcrypt.hash(raw_secret, 10);
|
const client_id = crypto.randomUUID();
|
||||||
data.client_id = UUID();
|
const client_secret_hash = await bcrypt.hash(raw_secret, 10);
|
||||||
const client = await this.create(data);
|
|
||||||
client._raw_secret = raw_secret;
|
// Generate a unique slug from the client name
|
||||||
return client;
|
let slug = data.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'oauth-client';
|
||||||
|
// Ensure uniqueness by appending a suffix if needed
|
||||||
|
const existing = await Resource.list({ where: { slug } });
|
||||||
|
if (existing.length) slug = `${slug}-${client_id.slice(0, 8)}`;
|
||||||
|
|
||||||
|
const r = await Resource.create({
|
||||||
|
id: client_id,
|
||||||
|
kind: 'oauth',
|
||||||
|
name: data.name,
|
||||||
|
slug: slug,
|
||||||
|
description: data.description || '',
|
||||||
|
owner: data.created_by,
|
||||||
|
metadata: {
|
||||||
|
client_secret_hash,
|
||||||
|
redirect_uris: data.redirect_uris || [],
|
||||||
|
scopes: data.scopes || ['openid', 'profile', 'email', 'groups'],
|
||||||
|
allowed_groups: data.allowed_groups || [],
|
||||||
|
token_lifetime: data.token_lifetime || { ...defaultLifetime }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
r._raw_secret = raw_secret;
|
||||||
|
r.client_id = client_id;
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
static async get(client_id) {
|
||||||
|
const notFound = () => {
|
||||||
|
const e = new Error('OAuthClient not found');
|
||||||
|
e.status = 404;
|
||||||
|
return e;
|
||||||
|
};
|
||||||
|
let r;
|
||||||
|
try {
|
||||||
|
r = await Resource.get(client_id);
|
||||||
|
} catch (_) {
|
||||||
|
throw notFound();
|
||||||
|
}
|
||||||
|
// Resource.get() returns null (does not throw) for a missing id —
|
||||||
|
// guard it so a bad/undefined client_id is a clean 404, not a
|
||||||
|
// "Cannot read properties of null (reading 'kind')" 500.
|
||||||
|
if (!r || r.kind !== 'oauth') throw notFound();
|
||||||
|
// Map metadata to top-level properties to satisfy routes/oauth.js without rewriting it
|
||||||
|
r.client_id = r.id;
|
||||||
|
r.client_secret_hash = r.metadata.client_secret_hash;
|
||||||
|
r.redirect_uris = r.metadata.redirect_uris || [];
|
||||||
|
r.scopes = r.metadata.scopes || ['openid', 'profile', 'email', 'groups'];
|
||||||
|
r.allowed_groups = r.metadata.allowed_groups || [];
|
||||||
|
r.token_lifetime = r.metadata.token_lifetime || { ...defaultLifetime };
|
||||||
|
// Resource has no is_valid column; validity lives in metadata (absent = valid)
|
||||||
|
r.is_valid = r.metadata.is_valid !== false;
|
||||||
|
r.verifySecret = async (secret) => bcrypt.compare(secret, r.client_secret_hash);
|
||||||
|
|
||||||
|
r.rotateSecret = async () => {
|
||||||
|
const raw_secret = crypto.randomUUID();
|
||||||
|
r.metadata.client_secret_hash = await bcrypt.hash(raw_secret, 10);
|
||||||
|
await r.update({ metadata: r.metadata });
|
||||||
|
return raw_secret;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The ORM Model.toJSON() only serializes schema fields, so the mapped
|
||||||
|
// properties above (client_id, scopes, redirect_uris, …) would be
|
||||||
|
// stripped from any res.json() — that's why GET /api/oauth/client
|
||||||
|
// returned client_id: undefined and the bootstrap's rotate blew up.
|
||||||
|
// Emit the public shape explicitly. client_secret_hash is deliberately
|
||||||
|
// omitted so it never leaks over the API.
|
||||||
|
r.toJSON = function () {
|
||||||
|
return {
|
||||||
|
client_id: r.id,
|
||||||
|
id: r.id,
|
||||||
|
kind: r.kind,
|
||||||
|
name: r.name,
|
||||||
|
slug: r.slug,
|
||||||
|
owner: r.owner,
|
||||||
|
description: r.description,
|
||||||
|
redirect_uris: r.redirect_uris,
|
||||||
|
scopes: r.scopes,
|
||||||
|
allowed_groups: r.allowed_groups,
|
||||||
|
token_lifetime: r.token_lifetime,
|
||||||
|
is_valid: r.is_valid,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// proxy update to handle metadata correctly
|
||||||
|
const originalUpdate = r.update.bind(r);
|
||||||
|
r.update = async (data) => {
|
||||||
|
if (data.redirect_uris !== undefined) r.metadata.redirect_uris = data.redirect_uris;
|
||||||
|
if (data.scopes !== undefined) r.metadata.scopes = data.scopes;
|
||||||
|
if (data.allowed_groups !== undefined) r.metadata.allowed_groups = data.allowed_groups;
|
||||||
|
if (data.token_lifetime !== undefined) r.metadata.token_lifetime = data.token_lifetime;
|
||||||
|
if (data.is_valid !== undefined) r.metadata.is_valid = data.is_valid;
|
||||||
|
|
||||||
|
const updateData = { metadata: r.metadata };
|
||||||
|
if (data.name !== undefined) updateData.name = data.name;
|
||||||
|
if (data.description !== undefined) updateData.description = data.description;
|
||||||
|
|
||||||
|
return originalUpdate(updateData);
|
||||||
|
};
|
||||||
|
|
||||||
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
async verifySecret(secret) {
|
static async list() {
|
||||||
return bcrypt.compare(secret, this.client_secret_hash);
|
const resources = await Resource.list({ where: { kind: 'oauth' } });
|
||||||
|
return Promise.all(resources.map(r => this.get(r.id)));
|
||||||
}
|
}
|
||||||
|
|
||||||
async rotateSecret() {
|
static async listDetail() {
|
||||||
const raw_secret = UUID();
|
return this.list();
|
||||||
await this.update({ client_secret_hash: await bcrypt.hash(raw_secret, 10) });
|
}
|
||||||
return raw_secret;
|
|
||||||
|
static async verifySecret(client_id, secret) {
|
||||||
|
const client = await this.get(client_id);
|
||||||
|
return client.verifySecret(secret);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
OAuthClient.register();
|
|
||||||
|
|
||||||
module.exports = { OAuthClient };
|
module.exports = { OAuthClient };
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const Table = require('.');
|
const Table = require('.');
|
||||||
const UUID = function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)};
|
const crypto = require('crypto');
|
||||||
|
const UUID = () => crypto.randomUUID();
|
||||||
|
|
||||||
// Shared base keyMap matching Token's schema so these behave as tokens
|
// Shared base keyMap matching Token's schema so these behave as tokens
|
||||||
const tokenKeyMap = {
|
const tokenKeyMap = {
|
||||||
|
|||||||
@@ -0,0 +1,216 @@
|
|||||||
|
const { Model } = require('@simpleworkjs/orm');
|
||||||
|
|
||||||
|
const { Group } = require('./group_ldap');
|
||||||
|
|
||||||
|
class Resource extends Model {
|
||||||
|
static exposedMethods = [
|
||||||
|
{ method: 'search', route: 'resources', verb: 'get', args: { from: 'query' } },
|
||||||
|
{ method: 'getBySlug', route: 'resources/:slug', verb: 'get', args: { from: 'params', names: ['slug'] } },
|
||||||
|
{ method: 'getGraph', route: 'graph', verb: 'get' },
|
||||||
|
{ method: 'getMyAccess', route: 'me', verb: 'get', args: { from: 'user' } }
|
||||||
|
];
|
||||||
|
|
||||||
|
static async search(query) {
|
||||||
|
const graph = await this.getGraph();
|
||||||
|
let resources = graph.resources;
|
||||||
|
|
||||||
|
if (query.kind) {
|
||||||
|
resources = resources.filter(r => r.kind === query.kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (query.group) {
|
||||||
|
const rgs = await ResourceGroup.list({ where: { groupCn: query.group } });
|
||||||
|
const allowedIds = new Set(rgs.map(rg => rg.resourceId));
|
||||||
|
resources = resources.filter(r => allowedIds.has(r.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (query.parent) {
|
||||||
|
const parents = graph.resources.filter(r => r.slug === query.parent);
|
||||||
|
if (parents.length > 0) {
|
||||||
|
const parentId = parents[0].id;
|
||||||
|
const childIds = new Set(graph.edges.filter(e => e.parentId === parentId).map(e => e.childId));
|
||||||
|
resources = resources.filter(r => childIds.has(r.id));
|
||||||
|
} else {
|
||||||
|
resources = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return resources;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getBySlug(slug) {
|
||||||
|
const graph = await this.getGraph();
|
||||||
|
const resource = graph.resources.find(r => r.slug === slug);
|
||||||
|
if (!resource) {
|
||||||
|
let err = new Error('Resource not found');
|
||||||
|
err.status = 404;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parents = graph.edges.filter(e => e.childId === resource.id);
|
||||||
|
const children = graph.edges.filter(e => e.parentId === resource.id);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...resource,
|
||||||
|
parents,
|
||||||
|
children
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getGraph() {
|
||||||
|
const resources = await this.list();
|
||||||
|
const edges = await ResourceEdge.list();
|
||||||
|
|
||||||
|
// Convert to simple objects so we can mutate metadata properties safely
|
||||||
|
const resObjs = resources.map(r => {
|
||||||
|
const obj = r.toJSON ? r.toJSON() : { ...r };
|
||||||
|
obj.metadata = obj.metadata || {};
|
||||||
|
return obj;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Bubble up production status: if any child is prod, parent is prod
|
||||||
|
const isProdCache = new Map();
|
||||||
|
function checkProd(resId, visited = new Set()) {
|
||||||
|
if (isProdCache.has(resId)) return isProdCache.get(resId);
|
||||||
|
if (visited.has(resId)) return false; // Cycle prevention
|
||||||
|
|
||||||
|
visited.add(resId);
|
||||||
|
const r = resObjs.find(x => x.id === resId);
|
||||||
|
if (!r) return false;
|
||||||
|
|
||||||
|
// If intrinsically prod, return true
|
||||||
|
if (r.metadata.isProduction) {
|
||||||
|
isProdCache.set(resId, true);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check children
|
||||||
|
const childrenIds = edges.filter(e => e.parentId === resId).map(e => e.childId);
|
||||||
|
for (const cid of childrenIds) {
|
||||||
|
if (checkProd(cid, visited)) {
|
||||||
|
isProdCache.set(resId, true);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
isProdCache.set(resId, false);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
resObjs.forEach(r => {
|
||||||
|
r.metadata.isProduction = checkProd(r.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
return { resources: resObjs, edges };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stamp `resolvedAddress` on each resource: its own address/ip if it has one,
|
||||||
|
// otherwise the nearest ancestor's. A service usually carries no address of
|
||||||
|
// its own -- it is reached at the host it runs on -- so "how do I reach this"
|
||||||
|
// is only answerable from the graph, never from the row alone. Every caller
|
||||||
|
// that answers that question for a user (getMyAccess, GET /api/discovery/me)
|
||||||
|
// must go through here, or services come back unreachable.
|
||||||
|
static async withResolvedAddress(resources) {
|
||||||
|
if (!resources || !resources.length) return [];
|
||||||
|
const graph = await this.getGraph();
|
||||||
|
|
||||||
|
const resolve = (resId, visited = new Set()) => {
|
||||||
|
if (visited.has(resId)) return null; // prevent cycles
|
||||||
|
visited.add(resId);
|
||||||
|
|
||||||
|
const res = graph.resources.find(r => r.id === resId);
|
||||||
|
if (!res) return null;
|
||||||
|
if (res.metadata && res.metadata.address) return res.metadata.address;
|
||||||
|
if (res.metadata && res.metadata.ip) return res.metadata.ip;
|
||||||
|
|
||||||
|
for (const edge of graph.edges.filter(e => e.childId === resId)) {
|
||||||
|
const found = resolve(edge.parentId, visited);
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
return resources.map(r => {
|
||||||
|
const data = r.toJSON ? r.toJSON() : { ...r };
|
||||||
|
data.metadata = data.metadata || {};
|
||||||
|
data.resolvedAddress = resolve(data.id);
|
||||||
|
return data;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static async getMyAccess(userDn) {
|
||||||
|
const userGroups = await Group.list(userDn);
|
||||||
|
if (!userGroups || userGroups.length === 0) return [];
|
||||||
|
|
||||||
|
const resourceGroups = await ResourceGroup.list({
|
||||||
|
where: { groupCn: { in: userGroups } }
|
||||||
|
});
|
||||||
|
|
||||||
|
const resourceIds = [...new Set(resourceGroups.map(rg => rg.resourceId))];
|
||||||
|
if (resourceIds.length === 0) return [];
|
||||||
|
|
||||||
|
return this.withResolvedAddress(await this.list({ where: { id: { in: resourceIds } } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
static fields = {
|
||||||
|
id: { type: 'uuid', primaryKey: true },
|
||||||
|
kind: { type: 'string', isRequired: true },
|
||||||
|
name: { type: 'string', isRequired: true },
|
||||||
|
slug: { type: 'string', isRequired: true, unique: true },
|
||||||
|
owner: { type: 'string' },
|
||||||
|
description: { type: 'text' },
|
||||||
|
metadata: { type: 'json', default: {} },
|
||||||
|
// Not isRequired: @simpleworkjs/orm has no auto-timestamp hook, so these
|
||||||
|
// are set explicitly by the route handler on every create/update (see
|
||||||
|
// routes/api_directory_admin.js). Existing rows predating this change
|
||||||
|
// simply read back undefined -- callers must render a fallback.
|
||||||
|
created_by: { type: 'string' },
|
||||||
|
created_on: { type: 'integer' },
|
||||||
|
updated_by: { type: 'string' },
|
||||||
|
updated_on: { type: 'integer' },
|
||||||
|
edgesAsParent: { type: 'hasMany', model: 'ResourceEdge', remoteKey: 'parentId' },
|
||||||
|
edgesAsChild: { type: 'hasMany', model: 'ResourceEdge', remoteKey: 'childId' },
|
||||||
|
groups: { type: 'hasMany', model: 'ResourceGroup', remoteKey: 'resourceId' }
|
||||||
|
};
|
||||||
|
|
||||||
|
// Walk parent ResourceEdges from resourceId up to the nearest ancestor
|
||||||
|
// whose kind === 'site', returning its slug (or null if none exists -- a
|
||||||
|
// top-level resource with no site parent keeps its unprefixed group name).
|
||||||
|
static async findAncestorSiteSlug(resourceId, visited = new Set()) {
|
||||||
|
if (visited.has(resourceId)) return null;
|
||||||
|
visited.add(resourceId);
|
||||||
|
|
||||||
|
const parentEdges = await ResourceEdge.list({ where: { childId: resourceId } });
|
||||||
|
for (const edge of parentEdges) {
|
||||||
|
const parent = await this.get(edge.parentId);
|
||||||
|
if (!parent) continue;
|
||||||
|
if (parent.kind === 'site') return parent.slug;
|
||||||
|
const found = await this.findAncestorSiteSlug(parent.id, visited);
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ResourceEdge extends Model {
|
||||||
|
static fields = {
|
||||||
|
id: { type: 'uuid', primaryKey: true },
|
||||||
|
parent: { type: 'hasOne', model: 'Resource' }, // Creates parentId
|
||||||
|
child: { type: 'hasOne', model: 'Resource' }, // Creates childId
|
||||||
|
relation: { type: 'string', isRequired: true }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class ResourceGroup extends Model {
|
||||||
|
static fields = {
|
||||||
|
id: { type: 'uuid', primaryKey: true },
|
||||||
|
resource: { type: 'hasOne', model: 'Resource' }, // Creates resourceId
|
||||||
|
groupCn: { type: 'string', isRequired: true },
|
||||||
|
accessLevel: { type: 'string', isRequired: true }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
Resource,
|
||||||
|
ResourceEdge,
|
||||||
|
ResourceGroup
|
||||||
|
};
|
||||||
@@ -1,21 +1,17 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const Table = require('.');
|
const { Model } = require('@simpleworkjs/orm');
|
||||||
const UUID = function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)};
|
const crypto = require('crypto');
|
||||||
|
const UUID = () => crypto.randomUUID();
|
||||||
|
|
||||||
|
class Token extends Model {
|
||||||
class Token extends Table{
|
static adapterName = 'redis';
|
||||||
static _key = 'token';
|
static fields = {
|
||||||
static _keyMap = {
|
token: { type: 'string', primaryKey: true, default: UUID, isPrivate: true, min: 36, max: 36 },
|
||||||
'created_by': {isRequired: true, type: 'string', min: 3, max: 500},
|
created_by: { isRequired: true, type: 'string', min: 3, max: 500 },
|
||||||
'created_on': {default: function(){return (new Date).getTime()}},
|
created_on: { type: 'integer', default: function(){return (new Date).getTime()} },
|
||||||
'updated_on': {default: function(){return (new Date).getTime()}, always: true},
|
updated_on: { type: 'integer', default: function(){return (new Date).getTime()}, always: true },
|
||||||
'token': {default: UUID, type: 'string', min: 36, max: 36, isPrivate: true},
|
is_valid: { default: true, type: 'boolean' }
|
||||||
'is_valid': {default: true, type: 'boolean'},
|
|
||||||
}
|
|
||||||
|
|
||||||
constructor(...args){
|
|
||||||
super(...args);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async check(){
|
async check(){
|
||||||
@@ -27,12 +23,10 @@ class Token extends Table{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Token.register();
|
|
||||||
|
|
||||||
class AuthToken extends Token{
|
class AuthToken extends Token{
|
||||||
static _keyMap = {
|
static fields = {
|
||||||
...super._keyMap,
|
...Token.fields,
|
||||||
user: {model: 'User', rel: 'one', localKey: 'created_by'},
|
user: {model: 'User', type: 'hasOne', localKey: 'created_by'},
|
||||||
}
|
}
|
||||||
|
|
||||||
static async create(data){
|
static async create(data){
|
||||||
@@ -41,11 +35,10 @@ class AuthToken extends Token{
|
|||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
AuthToken.register();
|
|
||||||
|
|
||||||
class InviteToken extends Token{
|
class InviteToken extends Token{
|
||||||
static _keyMap = {
|
static fields = {
|
||||||
...super._keyMap,
|
...Token.fields,
|
||||||
claimed_by: {default: '__NONE__', isRequired: false, type: 'string'},
|
claimed_by: {default: '__NONE__', isRequired: false, type: 'string'},
|
||||||
mail: {default: '__NONE__', type: 'string'},
|
mail: {default: '__NONE__', type: 'string'},
|
||||||
mail_token: {default: '__NONE__', type: 'string'},
|
mail_token: {default: '__NONE__', type: 'string'},
|
||||||
@@ -67,14 +60,13 @@ class InviteToken extends Token{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
InviteToken.register();
|
|
||||||
|
|
||||||
class ImpersonationToken extends Token {
|
class ImpersonationToken extends Token {
|
||||||
static _keyMap = {
|
static fields = {
|
||||||
...super._keyMap,
|
...Token.fields,
|
||||||
target_uid: {isRequired: true, type: 'string', min: 1, max: 200},
|
target_uid: {isRequired: true, type: 'string', min: 1, max: 200},
|
||||||
temp_hash: {isRequired: true, type: 'string', min: 1, max: 500},
|
temp_hash: {isRequired: true, type: 'string', min: 1, max: 500},
|
||||||
expires_at: {default: function(){ return (new Date).getTime() + 7200000 }, type: 'number'},
|
expires_at: {default: function(){ return (new Date).getTime() + 7200000 }, type: 'integer'},
|
||||||
}
|
}
|
||||||
|
|
||||||
get isExpired() {
|
get isExpired() {
|
||||||
@@ -86,42 +78,48 @@ class ImpersonationToken extends Token {
|
|||||||
return this.create(data);
|
return this.create(data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ImpersonationToken.register();
|
|
||||||
|
|
||||||
class PasswordResetToken extends Token {}
|
class PasswordResetToken extends Token {}
|
||||||
PasswordResetToken.register();
|
|
||||||
|
|
||||||
class OtpToken extends Token {
|
class OtpToken extends Token {
|
||||||
static _keyMap = {
|
static fields = {
|
||||||
...Token._keyMap,
|
...Token.fields,
|
||||||
uid: {isRequired: true, type: 'string'},
|
uid: {isRequired: true, type: 'string'},
|
||||||
code: {isRequired: true, type: 'string'},
|
code: {isRequired: true, type: 'string'},
|
||||||
method: {isRequired: true, type: 'string'},
|
method: {isRequired: true, type: 'string'},
|
||||||
expires_at: {default: function(){ return (new Date).getTime() + 600000 }, type: 'number'},
|
expires_at: {default: function(){ return (new Date).getTime() + 600000 }, type: 'integer'},
|
||||||
};
|
};
|
||||||
|
|
||||||
get isExpired() {
|
get isExpired() {
|
||||||
return (new Date).getTime() > this.expires_at;
|
return (new Date).getTime() > this.expires_at;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Factory method — named `issue` to avoid shadowing Token's `create(data)`
|
|
||||||
static async issue(uid, method) {
|
static async issue(uid, method) {
|
||||||
const existing = await this.listDetail({uid});
|
const existing = await this.list({where: {uid}});
|
||||||
for (const t of existing) {
|
for (const t of existing) {
|
||||||
if (t.is_valid) await t.update({is_valid: false});
|
if (t.is_valid) await t.update({is_valid: false});
|
||||||
}
|
}
|
||||||
const code = String(Math.floor(100000 + Math.random() * 900000));
|
const code = String(crypto.randomInt(100000, 1000000));
|
||||||
return this.create({uid, code, method, created_by: uid});
|
return this.create({uid, code, method, created_by: uid});
|
||||||
}
|
}
|
||||||
|
|
||||||
static async verify(uid, code) {
|
static async verify(uid, code) {
|
||||||
const tokens = await this.listDetail({uid});
|
const tokens = await this.list({where: {uid}});
|
||||||
const match = tokens.find(t => t.is_valid && !t.isExpired && t.code === code);
|
const match = tokens.find(t => t.is_valid && !t.isExpired && t.code === code);
|
||||||
if (!match) return null;
|
if (!match) return null;
|
||||||
await match.update({is_valid: false});
|
await match.update({is_valid: false});
|
||||||
return match;
|
return match;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
OtpToken.register();
|
class ServiceToken extends Token {
|
||||||
|
static fields = {
|
||||||
|
...Token.fields,
|
||||||
|
resource_id: {isRequired: true, type: 'string'}
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {Token, InviteToken, AuthToken, ImpersonationToken, PasswordResetToken, OtpToken};
|
static async issue(resource_id, created_by) {
|
||||||
|
return this.create({resource_id, created_by});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {Token, InviteToken, AuthToken, ImpersonationToken, PasswordResetToken, OtpToken, ServiceToken};
|
||||||
|
|||||||
@@ -9,6 +9,14 @@ const {Token, InviteToken, PasswordResetToken} = require('./token');
|
|||||||
const {Group} = require('./group_ldap');
|
const {Group} = require('./group_ldap');
|
||||||
const {UserVerification} = require('./verification');
|
const {UserVerification} = require('./verification');
|
||||||
const conf = require('@simpleworkjs/conf').ldap;
|
const conf = require('@simpleworkjs/conf').ldap;
|
||||||
|
// Connection + escaping come from the shared @simpleworkjs/ldap package. The
|
||||||
|
// wrappers below preserve this file's no-arg call signatures (makeClient() /
|
||||||
|
// withClient(fn)) so no call site changes; sso's makeClient passes no
|
||||||
|
// tlsOptions, which the shared client forwards as undefined — identical to the
|
||||||
|
// previous `new Client({ url: conf.url })`.
|
||||||
|
const { makeClient: _makeClient, withClient: _withClient, escapeFilter, escapeDN } = require('@simpleworkjs/ldap');
|
||||||
|
const escapeLDAPSearchValue = escapeFilter;
|
||||||
|
const escapeLDAPDNValue = escapeDN;
|
||||||
|
|
||||||
function hashPasswordSSHA512(password) {
|
function hashPasswordSSHA512(password) {
|
||||||
const salt = crypto.randomBytes(8);
|
const salt = crypto.randomBytes(8);
|
||||||
@@ -23,26 +31,11 @@ const cache = new LRUCache({
|
|||||||
});
|
});
|
||||||
|
|
||||||
function makeClient() {
|
function makeClient() {
|
||||||
return new Client({ url: conf.url });
|
return _makeClient(conf);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function withClient(fn) {
|
async function withClient(fn) {
|
||||||
const client = makeClient();
|
return _withClient(conf, fn);
|
||||||
try {
|
|
||||||
await client.bind(conf.bindDN, conf.bindPassword);
|
|
||||||
return await fn(client);
|
|
||||||
} finally {
|
|
||||||
await client.unbind().catch(() => {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper to escape LDAP filter values (crucial for security)
|
|
||||||
function escapeLDAPSearchValue(val) {
|
|
||||||
return val.replace(/\\/g, '\\5c')
|
|
||||||
.replace(/\*/g, '\\2a')
|
|
||||||
.replace(/\(/g, '\\28')
|
|
||||||
.replace(/\)/g, '\\29')
|
|
||||||
.replace(/\0/g, '\\00');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compute the next available uid/gidNumber: the highest existing value below
|
// Compute the next available uid/gidNumber: the highest existing value below
|
||||||
@@ -72,7 +65,8 @@ async function addPosixGroup(client, data){
|
|||||||
|
|
||||||
data.gidNumber = nextPosixId(groups, 'gidNumber');
|
data.gidNumber = nextPosixId(groups, 'gidNumber');
|
||||||
|
|
||||||
await client.add(`cn=${data.cn},${conf.groupBase}`, {
|
const safeCn = escapeLDAPDNValue(data.cn);
|
||||||
|
await client.add(`cn=${safeCn},${conf.groupBase}`, {
|
||||||
cn: data.cn,
|
cn: data.cn,
|
||||||
gidNumber: data.gidNumber,
|
gidNumber: data.gidNumber,
|
||||||
objectclass: [ 'posixGroup', 'top' ]
|
objectclass: [ 'posixGroup', 'top' ]
|
||||||
@@ -94,6 +88,7 @@ async function addPosixAccount(client, data){
|
|||||||
|
|
||||||
data.uidNumber = nextPosixId(people, 'uidNumber');
|
data.uidNumber = nextPosixId(people, 'uidNumber');
|
||||||
|
|
||||||
|
const safeCn = escapeLDAPDNValue(data.cn);
|
||||||
const entry = {
|
const entry = {
|
||||||
cn: data.cn,
|
cn: data.cn,
|
||||||
sn: data.sn,
|
sn: data.sn,
|
||||||
@@ -130,6 +125,10 @@ async function addPosixAccount(client, data){
|
|||||||
entry.dateOfBirth = data.dob;
|
entry.dateOfBirth = data.dob;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (data.location) {
|
||||||
|
entry.l = data.location;
|
||||||
|
}
|
||||||
|
|
||||||
// userPassword is optional -- a service account with no password set
|
// userPassword is optional -- a service account with no password set
|
||||||
// simply can't bind (no special enforcement needed, that's the default
|
// simply can't bind (no special enforcement needed, that's the default
|
||||||
// LDAP simple-bind behavior for an entry lacking the attribute).
|
// LDAP simple-bind behavior for an entry lacking the attribute).
|
||||||
@@ -143,7 +142,7 @@ async function addPosixAccount(client, data){
|
|||||||
entry.manager = [].concat(data.manager);
|
entry.manager = [].concat(data.manager);
|
||||||
}
|
}
|
||||||
|
|
||||||
await client.add(`cn=${data.cn},${conf.userBase}`, entry);
|
await client.add(`cn=${safeCn},${conf.userBase}`, entry);
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
@@ -171,7 +170,6 @@ async function addLdapUser(client, data){
|
|||||||
delete data.userPassword;
|
delete data.userPassword;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('addLdapUser', data)
|
|
||||||
group = await addPosixGroup(client, data);
|
group = await addPosixGroup(client, data);
|
||||||
data = await addPosixAccount(client, group);
|
data = await addPosixAccount(client, group);
|
||||||
|
|
||||||
@@ -206,14 +204,18 @@ const user_parse = function(data){
|
|||||||
data.username = data[conf.userNameAttribute]
|
data.username = data[conf.userNameAttribute]
|
||||||
data.userPassword = undefined;
|
data.userPassword = undefined;
|
||||||
}
|
}
|
||||||
|
data.location = data.l ? String(data.l) : '';
|
||||||
// Use truthy strings so jq-repeat section blocks ({{#isActive}}) fire correctly
|
// Use truthy strings so jq-repeat section blocks ({{#isActive}}) fire correctly
|
||||||
data.isActive = data.pwdAccountLockedTime ? '' : 'active';
|
data.isActive = data.pwdAccountLockedTime ? '' : 'active';
|
||||||
data.isInactive = data.pwdAccountLockedTime ? 'inactive' : '';
|
data.isInactive = data.pwdAccountLockedTime ? 'inactive' : '';
|
||||||
|
|
||||||
// manager (COSINE, SUP distinguishedName) is multi-valued; ldapts returns
|
// manager (COSINE, SUP distinguishedName) and memberOf (from the memberof
|
||||||
// a bare string for a single value and an array for multiple -- normalize
|
// overlay) are both multi-valued; ldapts returns a bare string for a
|
||||||
// to always be an array of DNs.
|
// single value and an array for multiple -- normalize both to always be
|
||||||
data.manager = [].concat(data.manager || []).filter(Boolean);
|
// an array, or app-base.js's `for(let group of user.memberOf)` silently
|
||||||
|
// iterates a single DN string character-by-character instead of once.
|
||||||
|
data.manager = [].concat(data.manager || []).filter(Boolean);
|
||||||
|
data.memberOf = [].concat(data.memberOf || []).filter(Boolean);
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
@@ -293,6 +295,9 @@ User.listDetail = async function(){
|
|||||||
obj.onboardingRequired = obj.onboardingNeeds.length > 0 ? 'yes' : '';
|
obj.onboardingRequired = obj.onboardingNeeds.length > 0 ? 'yes' : '';
|
||||||
obj.isServiceAccount = serviceAccountDNs.has(String(obj.dn).toLowerCase()) ? 'yes' : '';
|
obj.isServiceAccount = serviceAccountDNs.has(String(obj.dn).toLowerCase()) ? 'yes' : '';
|
||||||
obj.managerUids = obj.manager.map(dn => dnToUid.get(String(dn).toLowerCase()) || dn);
|
obj.managerUids = obj.manager.map(dn => dnToUid.get(String(dn).toLowerCase()) || dn);
|
||||||
|
// hasSshKey is a boolean flag for the UI -- sshPublicKey may be an array,
|
||||||
|
// and Mustache's {{#sshPublicKey}}...{{/sshPublicKey}} iterates over each item.
|
||||||
|
obj.hasSshKey = obj.sshPublicKey ? 'yes' : '';
|
||||||
|
|
||||||
return obj;
|
return obj;
|
||||||
}));
|
}));
|
||||||
@@ -348,6 +353,13 @@ User.get = async function(data, key) {
|
|||||||
|
|
||||||
const verif = await UserVerification.getOrCreate(obj.uid);
|
const verif = await UserVerification.getOrCreate(obj.uid);
|
||||||
|
|
||||||
|
// Same membership check as User.listDetail() -- see the comment there.
|
||||||
|
try{
|
||||||
|
const svcGroup = await Group.get('app_sso_service_account');
|
||||||
|
const serviceAccountDNs = new Set((svcGroup.member || []).map(dn => dn.toLowerCase()));
|
||||||
|
obj.isServiceAccount = serviceAccountDNs.has(String(obj.dn).toLowerCase()) ? 'yes' : '';
|
||||||
|
}catch(error){ obj.isServiceAccount = ''; }
|
||||||
|
|
||||||
// Auto-flag legacy MD5 password users — persist so subsequent cache hits see it
|
// Auto-flag legacy MD5 password users — persist so subsequent cache hits see it
|
||||||
if (isLegacyMD5 && !verif.password_must_change) {
|
if (isLegacyMD5 && !verif.password_must_change) {
|
||||||
await verif.update({ password_must_change: true });
|
await verif.update({ password_must_change: true });
|
||||||
@@ -464,6 +476,19 @@ User.update = async function(data){
|
|||||||
}
|
}
|
||||||
|
|
||||||
if(data.sshPublicKey){
|
if(data.sshPublicKey){
|
||||||
|
// Ensure the auxiliary objectClass is present before setting the attribute
|
||||||
|
// -- accounts created before ldapPublicKey was added to addPosixAccount's
|
||||||
|
// objectclass list (e.g. the bootstrap admin) won't have it yet.
|
||||||
|
try {
|
||||||
|
await client.modify(this.dn, [
|
||||||
|
new Change({
|
||||||
|
operation: 'add',
|
||||||
|
modification: new Attribute({ type: 'objectClass', values: ['ldapPublicKey'] }),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
} catch(e) {
|
||||||
|
if(e.name !== 'TypeOrValueExistsError') throw e;
|
||||||
|
}
|
||||||
await client.modify(this.dn, [
|
await client.modify(this.dn, [
|
||||||
new Change({
|
new Change({
|
||||||
operation: 'replace',
|
operation: 'replace',
|
||||||
@@ -494,6 +519,16 @@ User.update = async function(data){
|
|||||||
this.dateOfBirth = data.dateOfBirth;
|
this.dateOfBirth = data.dateOfBirth;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(data.location !== undefined){
|
||||||
|
await client.modify(this.dn, [
|
||||||
|
new Change({
|
||||||
|
operation: 'replace',
|
||||||
|
modification: new Attribute({ type: 'l', values: [data.location] }),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
this.location = data.location;
|
||||||
|
}
|
||||||
|
|
||||||
if(data.manager !== undefined){
|
if(data.manager !== undefined){
|
||||||
// Client sends uids; resolve each to a DN before writing --
|
// Client sends uids; resolve each to a DN before writing --
|
||||||
// manager (COSINE, SUP distinguishedName) stores DNs, not uids.
|
// manager (COSINE, SUP distinguishedName) stores DNs, not uids.
|
||||||
@@ -765,6 +800,19 @@ User.addSSHkey = async function(data) {
|
|||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
await withClient(async (client) => {
|
await withClient(async (client) => {
|
||||||
|
// Ensure the auxiliary objectClass is present before setting the attribute
|
||||||
|
// -- accounts created before ldapPublicKey was added to addPosixAccount's
|
||||||
|
// objectclass list (e.g. the bootstrap admin) won't have it yet.
|
||||||
|
try {
|
||||||
|
await client.modify(user.dn, [
|
||||||
|
new Change({
|
||||||
|
operation: 'add',
|
||||||
|
modification: new Attribute({ type: 'objectClass', values: ['ldapPublicKey'] }),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
} catch(e) {
|
||||||
|
if (e.name !== 'TypeOrValueExistsError') throw e;
|
||||||
|
}
|
||||||
await client.modify(user.dn, [
|
await client.modify(user.dn, [
|
||||||
new Change({
|
new Change({
|
||||||
operation: 'add',
|
operation: 'add',
|
||||||
@@ -784,6 +832,53 @@ User.addSSHkey = async function(data) {
|
|||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Every user gets a personal Unix group of the same name at creation (see
|
||||||
|
// addPosixGroup) -- just a GID holder, cn always equal to the user's uid.
|
||||||
|
// memberUid (RFC 2307, posixGroup) is a bare username, not a DN, unlike
|
||||||
|
// groupOfNames' `member` used by app_sso_* groups in group_ldap.js.
|
||||||
|
function personalGroupDN(uid){
|
||||||
|
return `cn=${escapeLDAPDNValue(uid)},${conf.groupBase}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
User.getPersonalGroupMembers = async function(uid) {
|
||||||
|
try {
|
||||||
|
return await withClient(async (client) => {
|
||||||
|
const res = await client.search(personalGroupDN(uid), {
|
||||||
|
scope: 'base',
|
||||||
|
filter: '(objectClass=posixGroup)',
|
||||||
|
attributes: ['memberUid'],
|
||||||
|
});
|
||||||
|
const entry = res.searchEntries[0];
|
||||||
|
return [].concat((entry && entry.memberUid) || []).filter(Boolean);
|
||||||
|
});
|
||||||
|
} catch(error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
User.addPersonalGroupMember = async function(uid, memberUid) {
|
||||||
|
await this.get(memberUid); // throws UserNotFound if the target uid doesn't exist
|
||||||
|
await withClient(async (client) => {
|
||||||
|
await client.modify(personalGroupDN(uid), [
|
||||||
|
new Change({
|
||||||
|
operation: 'add',
|
||||||
|
modification: new Attribute({ type: 'memberUid', values: [memberUid] }),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
User.removePersonalGroupMember = async function(uid, memberUid) {
|
||||||
|
await withClient(async (client) => {
|
||||||
|
await client.modify(personalGroupDN(uid), [
|
||||||
|
new Change({
|
||||||
|
operation: 'delete',
|
||||||
|
modification: new Attribute({ type: 'memberUid', values: [memberUid] }),
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
User.invite = async function(data = {}){
|
User.invite = async function(data = {}){
|
||||||
try{
|
try{
|
||||||
let token = await InviteToken.create({
|
let token = await InviteToken.create({
|
||||||
@@ -804,6 +899,12 @@ User.invite = async function(data = {}){
|
|||||||
|
|
||||||
User.login = async function(data){
|
User.login = async function(data){
|
||||||
try{
|
try{
|
||||||
|
if (!data.uid && !data.username) {
|
||||||
|
let error = new Error('Invalid Credentials, login failed.');
|
||||||
|
error.name = 'LDAPLoginFailed';
|
||||||
|
error.status = 401;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
let user = await this.get(data.uid || data.username);
|
let user = await this.get(data.uid || data.username);
|
||||||
|
|
||||||
const loginClient = makeClient();
|
const loginClient = makeClient();
|
||||||
@@ -816,7 +917,7 @@ User.login = async function(data){
|
|||||||
return user;
|
return user;
|
||||||
|
|
||||||
}catch(error){
|
}catch(error){
|
||||||
console.error("USER LOGIN error:", error);
|
console.error("USER LOGIN error:", error.name, error.message);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
const { Model } = require('@simpleworkjs/orm');
|
||||||
|
|
||||||
|
class Webhook extends Model {
|
||||||
|
static fields = {
|
||||||
|
id: { type: 'uuid', primaryKey: true },
|
||||||
|
name: { type: 'string', isRequired: true },
|
||||||
|
url: { type: 'string', isRequired: true },
|
||||||
|
events: { type: 'json', default: [] }, // e.g. ['discovery.new_device', 'resource.updated']
|
||||||
|
secret: { type: 'string' },
|
||||||
|
isActive: { type: 'boolean', default: true },
|
||||||
|
created_on: { type: 'integer' },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { Webhook };
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "t42-sso-manager",
|
"name": "t42-sso-manager",
|
||||||
"version": "1.1.7",
|
"version": "1.13.0",
|
||||||
"private": true,
|
"description": "A very simple LDAP management and SSO system",
|
||||||
"author": [
|
"author": [
|
||||||
{
|
{
|
||||||
"name": "William Mantly",
|
"name": "William Mantly",
|
||||||
@@ -23,26 +23,37 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fortawesome/fontawesome-free": "^7.3.0",
|
"@fortawesome/fontawesome-free": "^7.3.0",
|
||||||
"@popperjs/core": "^2.11.8",
|
"@popperjs/core": "^2.11.8",
|
||||||
"@simpleworkjs/conf": "^1.1.0",
|
"@simpleworkjs/app-stack": "^1.0.0",
|
||||||
|
"@simpleworkjs/conf": "^1.2.0",
|
||||||
|
"@simpleworkjs/directory-schema": "^1.1.0",
|
||||||
|
"@simpleworkjs/frontend": "^0.2.7",
|
||||||
|
"@simpleworkjs/ldap": "^1.0.0",
|
||||||
|
"@simpleworkjs/orm": "^0.2.8",
|
||||||
"bcrypt": "^6.0.0",
|
"bcrypt": "^6.0.0",
|
||||||
"bootstrap": "^5.3.8",
|
"bootstrap": "^5.3.8",
|
||||||
|
"bullmq": "^6.0.3",
|
||||||
"compression": "^1.8.1",
|
"compression": "^1.8.1",
|
||||||
"ejs": "^3.1.10",
|
"ejs": "^3.1.10",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
"express-rate-limit": "^8.5.2",
|
"express-rate-limit": "^8.5.2",
|
||||||
"extend": "^3.0.2",
|
"extend": "^3.0.2",
|
||||||
"jq-repeat": "^2.1.0",
|
"http-proxy-middleware": "^2.0.10",
|
||||||
"jquery": "^3.7.1",
|
"ioredis": "^6.0.0",
|
||||||
|
"jq-repeat": "^2.2.0",
|
||||||
|
"jquery": "^4.0.0",
|
||||||
"jsonwebtoken": "^9.0.3",
|
"jsonwebtoken": "^9.0.3",
|
||||||
"ldapts": "^8.1.2",
|
"ldapts": "^8.1.8",
|
||||||
"lru-cache": "^11.5.1",
|
"lru-cache": "^11.5.1",
|
||||||
"marked": "^9.1.6",
|
"marked": "^9.1.6",
|
||||||
"model-redis": "^0.4.0",
|
"model-redis": "^1.6.0",
|
||||||
"moment": "^2.30.1",
|
"moment": "^2.30.1",
|
||||||
"mustache": "^4.2.0",
|
"mustache": "^4.2.0",
|
||||||
|
"node-fetch": "^2.7.0",
|
||||||
|
"node-nmap": "^4.0.0",
|
||||||
"nodemailer": "^9.0.0",
|
"nodemailer": "^9.0.0",
|
||||||
"p2psub": "^0.2.0",
|
"p2psub": "^0.2.0",
|
||||||
"socket.io": "^4.8.3"
|
"socket.io": "^4.8.3",
|
||||||
|
"xss": "^1.0.15"
|
||||||
},
|
},
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"repository": {
|
"repository": {
|
||||||
|
|||||||
@@ -0,0 +1,328 @@
|
|||||||
|
diff --git a/nodejs/views/directory.ejs b/nodejs/views/directory.ejs
|
||||||
|
index c7646a4..411b56f 100644
|
||||||
|
--- a/nodejs/views/directory.ejs
|
||||||
|
+++ b/nodejs/views/directory.ejs
|
||||||
|
@@ -3,7 +3,26 @@
|
||||||
|
<div class="container mt-4">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-12">
|
||||||
|
- <div class="card shadow">
|
||||||
|
+ <ul class="nav nav-tabs mb-3" id="directoryTabs" role="tablist">
|
||||||
|
+ <li class="nav-item" role="presentation">
|
||||||
|
+ <button class="nav-link active" id="directory-tab" data-bs-toggle="tab" data-bs-target="#directory-tab-pane" type="button" role="tab" aria-controls="directory-tab-pane" aria-selected="true">
|
||||||
|
+ <i class="fa-solid fa-server"></i> Directory
|
||||||
|
+ </button>
|
||||||
|
+ </li>
|
||||||
|
+ <li class="nav-item" role="presentation">
|
||||||
|
+ <button class="nav-link" id="discovery-tab" data-bs-toggle="tab" data-bs-target="#discovery-tab-pane" type="button" role="tab" aria-controls="discovery-tab-pane" aria-selected="false">
|
||||||
|
+ <i class="fa-solid fa-network-wired"></i> Discovery
|
||||||
|
+ </button>
|
||||||
|
+ </li>
|
||||||
|
+ <li class="nav-item" role="presentation">
|
||||||
|
+ <button class="nav-link" id="plugins-tab" data-bs-toggle="tab" data-bs-target="#plugins-tab-pane" type="button" role="tab" aria-controls="plugins-tab-pane" aria-selected="false">
|
||||||
|
+ <i class="fa-solid fa-plug"></i> Plugins & Scheduler
|
||||||
|
+ </button>
|
||||||
|
+ </li>
|
||||||
|
+ </ul>
|
||||||
|
+ <div class="tab-content" id="directoryTabsContent">
|
||||||
|
+ <div class="tab-pane fade show active" id="directory-tab-pane" role="tabpanel" aria-labelledby="directory-tab">
|
||||||
|
+ <div class="card shadow border-top-0">
|
||||||
|
<div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
|
||||||
|
<div>
|
||||||
|
<i class="fa-solid fa-server"></i> Directory Management
|
||||||
|
@@ -74,6 +93,148 @@
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
+
|
||||||
|
+ <!-- Discovery Tab Pane -->
|
||||||
|
+ <div class="tab-pane fade" id="discovery-tab-pane" role="tabpanel" aria-labelledby="discovery-tab">
|
||||||
|
+ <div class="card shadow border-top-0">
|
||||||
|
+ <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
|
||||||
|
+ <div>
|
||||||
|
+ <i class="fa-solid fa-network-wired"></i> Network Discovery Dashboard
|
||||||
|
+ </div>
|
||||||
|
+ <div class="d-flex flex-wrap gap-2 align-items-center">
|
||||||
|
+ <input type="text" id="discovery-search-filter" class="form-control form-control-sm shadow-sm" placeholder="Search resources..." onkeyup="renderDiscoveryTable()" style="width: 250px;">
|
||||||
|
+ <select id="discovery-filter-managed" class="form-select form-select-sm shadow-sm" onchange="renderDiscoveryTable()" style="width: 150px;">
|
||||||
|
+ <option value="unmanaged">Unmanaged Only</option>
|
||||||
|
+ <option value="managed">Managed Only</option>
|
||||||
|
+ <option value="all">All Resources</option>
|
||||||
|
+ </select>
|
||||||
|
+ </div>
|
||||||
|
+ </div>
|
||||||
|
+ <div class="card-header actionMessage" style="display:none"></div>
|
||||||
|
+ <div class="p-3 pb-0 text-muted small border-bottom">
|
||||||
|
+ <i class="fa-solid fa-circle-info"></i> Auto-discovered network resources. Promote unmanaged devices to track them in the Directory.
|
||||||
|
+ <a href="/docs/discovery" class="text-reset float-end" title="Help"><i class="fa-solid fa-circle-question"></i></a>
|
||||||
|
+ </div>
|
||||||
|
+ <div class="table-responsive">
|
||||||
|
+ <table class="card-body table table-hover mb-0 align-middle">
|
||||||
|
+ <thead class="table-light">
|
||||||
|
+ <tr>
|
||||||
|
+ <th class="ps-3">Name / Source</th>
|
||||||
|
+ <th>Type</th>
|
||||||
|
+ <th>IP Address</th>
|
||||||
|
+ <th>Status</th>
|
||||||
|
+ <th class="text-end pe-3">Actions</th>
|
||||||
|
+ </tr>
|
||||||
|
+ </thead>
|
||||||
|
+ <tbody id="discovery-list" jq-repeat="discoveryResources">
|
||||||
|
+ <tr id="discovery-row-{{slug}}">
|
||||||
|
+ <td class="ps-3">
|
||||||
|
+ <div class="fw-bold">{{name}}</div>
|
||||||
|
+ <div class="text-muted small">
|
||||||
|
+ <i class="fa-solid fa-plug pe-1"></i> {{#metadata.source}}{{metadata.source}}{{/metadata.source}}{{^metadata.source}}Manual{{/metadata.source}}
|
||||||
|
+ </div>
|
||||||
|
+ </td>
|
||||||
|
+ <td>
|
||||||
|
+ <span class="badge bg-secondary">{{kind}}</span>
|
||||||
|
+ {{#metadata.subType}}
|
||||||
|
+ <span class="badge bg-light text-dark border">{{metadata.subType}}</span>
|
||||||
|
+ {{/metadata.subType}}
|
||||||
|
+ </td>
|
||||||
|
+ <td>
|
||||||
|
+ {{#metadata.ip}}<div class="font-monospace small"><i class="fa-solid fa-network-wired pe-1"></i>{{metadata.ip}}</div>{{/metadata.ip}}
|
||||||
|
+ {{^metadata.ip}}<span class="text-muted small fst-italic">Unknown IP</span>{{/metadata.ip}}
|
||||||
|
+ {{#metadata.interfaces.length}}
|
||||||
|
+ <div class="mt-1 small text-muted">
|
||||||
|
+ {{#metadata.interfaces}}
|
||||||
|
+ <div><i class="fa-solid fa-microchip pe-1"></i> {{mac}} {{#ip}}<span class="text-black-50">({{ip}})</span>{{/ip}}</div>
|
||||||
|
+ {{/metadata.interfaces}}
|
||||||
|
+ </div>
|
||||||
|
+ {{/metadata.interfaces.length}}
|
||||||
|
+ </td>
|
||||||
|
+ <td>
|
||||||
|
+ {{#metadata.managed}}
|
||||||
|
+ <span class="badge bg-success rounded-pill px-2"><i class="fa-solid fa-check"></i> Managed</span>
|
||||||
|
+ {{/metadata.managed}}
|
||||||
|
+ {{^metadata.managed}}
|
||||||
|
+ <span class="badge bg-warning text-dark rounded-pill px-2"><i class="fa-solid fa-ghost"></i> Unmanaged</span>
|
||||||
|
+ {{/metadata.managed}}
|
||||||
|
+ </td>
|
||||||
|
+ <td class="text-end pe-3">
|
||||||
|
+ {{^metadata.managed}}
|
||||||
|
+ <button class="btn btn-sm btn-outline-primary" onclick="promoteResource('{{slug}}')" title="Promote to Managed">
|
||||||
|
+ <i class="fa-solid fa-arrow-up-right-dots"></i> Promote
|
||||||
|
+ </button>
|
||||||
|
+ {{/metadata.managed}}
|
||||||
|
+ {{#metadata.managed}}
|
||||||
|
+ <button class="btn btn-sm btn-outline-secondary" disabled title="Already Managed">
|
||||||
|
+ Promoted
|
||||||
|
+ </button>
|
||||||
|
+ {{/metadata.managed}}
|
||||||
|
+ </td>
|
||||||
|
+ </tr>
|
||||||
|
+ </tbody>
|
||||||
|
+ <tbody id="discovery-empty-state" style="display: none;">
|
||||||
|
+ <tr>
|
||||||
|
+ <td colspan="5" class="text-center py-5 text-muted">
|
||||||
|
+ <i class="fa-solid fa-magnifying-glass fs-2 mb-3 text-black-50"></i>
|
||||||
|
+ <h5>No resources found</h5>
|
||||||
|
+ <p>Check your filters or ensure the discovery agents are running.</p>
|
||||||
|
+ </td>
|
||||||
|
+ </tr>
|
||||||
|
+ </tbody>
|
||||||
|
+ </table>
|
||||||
|
+ </div>
|
||||||
|
+ </div>
|
||||||
|
+ </div>
|
||||||
|
+
|
||||||
|
+ <!-- Plugins Tab Pane -->
|
||||||
|
+ <div class="tab-pane fade" id="plugins-tab-pane" role="tabpanel" aria-labelledby="plugins-tab">
|
||||||
|
+ <div class="card shadow border-top-0">
|
||||||
|
+ <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
|
||||||
|
+ <div>
|
||||||
|
+ <i class="fa-solid fa-plug"></i> Plugins & Scheduler
|
||||||
|
+ </div>
|
||||||
|
+ </div>
|
||||||
|
+ <div class="p-3 pb-0 text-muted small border-bottom">
|
||||||
|
+ <i class="fa-solid fa-circle-info"></i> Manage background tasks and schedules. <a href="/docs/plugins">Learn how to make and use custom plugins</a>.
|
||||||
|
+ </div>
|
||||||
|
+ <div class="table-responsive">
|
||||||
|
+ <table class="card-body table table-hover mb-0 align-middle">
|
||||||
|
+ <thead class="table-light">
|
||||||
|
+ <tr>
|
||||||
|
+ <th class="ps-3">Plugin Name</th>
|
||||||
|
+ <th>Cron Schedule</th>
|
||||||
|
+ <th>Status</th>
|
||||||
|
+ <th>Actions</th>
|
||||||
|
+ </tr>
|
||||||
|
+ </thead>
|
||||||
|
+ <tbody id="plugins-list" jq-repeat="plugins">
|
||||||
|
+ <tr>
|
||||||
|
+ <td class="ps-3 fw-bold">{{name}}</td>
|
||||||
|
+ <td><input type="text" class="form-control form-control-sm font-monospace" id="cron-{{name}}" value="{{cron}}" style="max-width: 150px;"></td>
|
||||||
|
+ <td>
|
||||||
|
+ {{#enabled}}<span class="badge bg-success">Enabled</span>{{/enabled}}
|
||||||
|
+ {{^enabled}}<span class="badge bg-secondary">Disabled</span>{{/enabled}}
|
||||||
|
+ </td>
|
||||||
|
+ <td>
|
||||||
|
+ <button class="btn btn-sm btn-outline-primary" onclick="updatePlugin('{{name}}')" title="Save Schedule">Save</button>
|
||||||
|
+ {{#enabled}}<button class="btn btn-sm btn-outline-danger" onclick="togglePlugin('{{name}}', false)">Disable</button>{{/enabled}}
|
||||||
|
+ {{^enabled}}<button class="btn btn-sm btn-outline-success" onclick="togglePlugin('{{name}}', true)">Enable</button>{{/enabled}}
|
||||||
|
+ </td>
|
||||||
|
+ </tr>
|
||||||
|
+ </tbody>
|
||||||
|
+ <tbody id="plugins-empty-state" style="display: none;">
|
||||||
|
+ <tr>
|
||||||
|
+ <td colspan="4" class="text-center py-4 text-muted">
|
||||||
|
+ No plugins configured.
|
||||||
|
+ </td>
|
||||||
|
+ </tr>
|
||||||
|
+ </tbody>
|
||||||
|
+ </table>
|
||||||
|
+ </div>
|
||||||
|
+ </div>
|
||||||
|
+ </div>
|
||||||
|
+
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@@ -413,14 +574,144 @@
|
||||||
|
const parentEdge = allEdges.find(e => e.childId === r.id);
|
||||||
|
if (parentEdge) {
|
||||||
|
r.parentId = parentEdge.parentId;
|
||||||
|
- const parent = resourcesById[parentEdge.parentId];
|
||||||
|
+ const parent = resourcesById[parentEdge.parentId];
|
||||||
|
if (parent) r.hostName = parent.name;
|
||||||
|
}
|
||||||
|
rawResources.push(r);
|
||||||
|
}
|
||||||
|
+ function openAddModal(parent_id, kind) {
|
||||||
|
+ if(parent_id){
|
||||||
|
+ $('#newResourceParent').val(parent_id);
|
||||||
|
+ $('#newResourceKind').val(kind);
|
||||||
|
+ var currentLabel = "Resource";
|
||||||
|
+ if(kind === 'Host'){ currentLabel = 'Host'; }
|
||||||
|
+ else if(kind === 'Site'){ currentLabel = 'Site'; }
|
||||||
|
+
|
||||||
|
+ $('#newResourceLabel').text('Add Child ' + currentLabel);
|
||||||
|
+ }else{
|
||||||
|
+ $('#newResourceParent').val('');
|
||||||
|
+ $('#newResourceKind').val('Host');
|
||||||
|
+ $('#newResourceLabel').text('Add Resource');
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ // Clear input
|
||||||
|
+ $('#newResourceName').val('');
|
||||||
|
+ $('#addResourceModal').modal('show');
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ // --- DISCOVERY SCRIPTS ---
|
||||||
|
+ let allDiscoveryResources = [];
|
||||||
|
+
|
||||||
|
+ function loadDiscoveryResources() {
|
||||||
|
+ app.api.get('discovery/resources', function(err, res) {
|
||||||
|
+ if(err) {
|
||||||
|
+ $('.actionMessage').html('<div class="alert alert-danger">' + (err.message || 'Error loading resources') + '</div>').show();
|
||||||
|
+ return;
|
||||||
|
+ }
|
||||||
|
+ allDiscoveryResources = res.results || [];
|
||||||
|
+ renderDiscoveryTable();
|
||||||
|
+ });
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ function renderDiscoveryTable() {
|
||||||
|
+ const search = $('#discovery-search-filter').val().toLowerCase();
|
||||||
|
+ const managedFilter = $('#discovery-filter-managed').val();
|
||||||
|
+
|
||||||
|
+ const filtered = allDiscoveryResources.filter(r => {
|
||||||
|
+ if(search && !r.name.toLowerCase().includes(search) && !r.slug.toLowerCase().includes(search)) return false;
|
||||||
|
+ const isManaged = !!(r.metadata && r.metadata.managed);
|
||||||
|
+ if(managedFilter === 'managed' && !isManaged) return false;
|
||||||
|
+ if(managedFilter === 'unmanaged' && isManaged) return false;
|
||||||
|
+ return true;
|
||||||
|
+ });
|
||||||
|
+
|
||||||
|
+ $.scope.discoveryResources.empty();
|
||||||
|
+ for(const r of filtered) {
|
||||||
|
+ $.scope.discoveryResources.push(r);
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ if(filtered.length === 0) {
|
||||||
|
+ $('#discovery-list').hide();
|
||||||
|
+ $('#discovery-empty-state').show();
|
||||||
|
+ } else {
|
||||||
|
+ $('#discovery-list').show();
|
||||||
|
+ $('#discovery-empty-state').hide();
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ function promoteResource(slug) {
|
||||||
|
+ if(!confirm("Are you sure you want to promote this resource? This will generate SSO LDAP groups for it.")) return;
|
||||||
|
+ app.api.post('discovery/promote/' + slug, {}, function(err, res) {
|
||||||
|
+ if(err) {
|
||||||
|
+ alert("Error promoting resource: " + (err.message || err));
|
||||||
|
+ return;
|
||||||
|
+ }
|
||||||
|
+ const resource = allDiscoveryResources.find(r => r.slug === slug);
|
||||||
|
+ if(resource) {
|
||||||
|
+ resource.metadata = resource.metadata || {};
|
||||||
|
+ resource.metadata.managed = true;
|
||||||
|
+ }
|
||||||
|
+ $('.actionMessage').html('<div class="alert alert-success alert-dismissible"><button type="button" class="btn-close" data-bs-dismiss="alert"></button>Successfully promoted! Created groups: ' + res.groups.join(', ') + '</div>').show();
|
||||||
|
+ renderDiscoveryTable();
|
||||||
|
+ renderTable(); // Also update directory tab
|
||||||
|
+ });
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ // --- PLUGINS SCRIPTS ---
|
||||||
|
+ function loadPlugins() {
|
||||||
|
+ app.api.get('plugins', function(err, res) {
|
||||||
|
+ if(err) {
|
||||||
|
+ alert("Error loading plugins: " + (err.message || err));
|
||||||
|
+ return;
|
||||||
|
+ }
|
||||||
|
+ const plugins = res.results || {};
|
||||||
|
+ const pluginNames = Object.keys(plugins);
|
||||||
|
|
||||||
|
- renderTable();
|
||||||
|
+ $.scope.plugins.empty();
|
||||||
|
+ if(pluginNames.length === 0) {
|
||||||
|
+ $('#plugins-list').hide();
|
||||||
|
+ $('#plugins-empty-state').show();
|
||||||
|
+ } else {
|
||||||
|
+ pluginNames.forEach(name => {
|
||||||
|
+ const config = plugins[name];
|
||||||
|
+ $.scope.plugins.push({
|
||||||
|
+ name: name,
|
||||||
|
+ cron: config.cron || '',
|
||||||
|
+ enabled: config.enabled
|
||||||
|
+ });
|
||||||
|
+ });
|
||||||
|
+ $('#plugins-list').show();
|
||||||
|
+ $('#plugins-empty-state').hide();
|
||||||
|
+ }
|
||||||
|
+ });
|
||||||
|
+ }
|
||||||
|
|
||||||
|
+ function updatePlugin(name) {
|
||||||
|
+ const cron = $('#cron-' + name).val();
|
||||||
|
+ app.api.put('plugins/' + name, {cron: cron}, function(err, res) {
|
||||||
|
+ if(err) { alert("Failed to save: " + err.message); return; }
|
||||||
|
+ alert("Saved schedule successfully.");
|
||||||
|
+ });
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ function togglePlugin(name, enable) {
|
||||||
|
+ app.api.put('plugins/' + name, {enabled: enable}, function(err, res) {
|
||||||
|
+ if(err) { alert("Failed to toggle: " + err.message); return; }
|
||||||
|
+ loadPlugins();
|
||||||
|
+ });
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ $(document).ready(function(){
|
||||||
|
+ renderTable();
|
||||||
|
+ loadDiscoveryResources();
|
||||||
|
+ loadPlugins();
|
||||||
|
+
|
||||||
|
+ // Auto-open modal if hash is present
|
||||||
|
+ if(window.location.hash && window.location.hash.startsWith('#modal-')) {
|
||||||
|
+ const slug = window.location.hash.replace('#modal-', '');
|
||||||
|
+ setTimeout(() => openEditModal(slug), 500);
|
||||||
|
+ }
|
||||||
|
+ });
|
||||||
|
// Type-ahead for the "what can this user reach" lookup. Non-blocking: the
|
||||||
|
// input accepts a free-typed uid whether or not the list ever arrives.
|
||||||
|
loadDirectoryUsers().then(function(users) {
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
const nmap = require('node-nmap');
|
||||||
|
nmap.nmapLocation = "nmap"; // default
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
discover: async (config) => {
|
||||||
|
const { targetRange } = config;
|
||||||
|
if (!targetRange) throw new Error("Missing targetRange for Nmap");
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const scan = new nmap.OsAndPortScan(targetRange);
|
||||||
|
scan.on('complete', function(data) {
|
||||||
|
const resources = [];
|
||||||
|
const edges = [];
|
||||||
|
|
||||||
|
for (const host of data) {
|
||||||
|
if (!host.mac || !host.ip) continue;
|
||||||
|
const hostSlug = `nmap-host-${host.mac.replace(/:/g, '')}`;
|
||||||
|
|
||||||
|
const interfaces = [{ mac: host.mac, ip: host.ip }];
|
||||||
|
|
||||||
|
resources.push({
|
||||||
|
kind: 'host',
|
||||||
|
name: host.hostname || host.ip,
|
||||||
|
slug: hostSlug,
|
||||||
|
metadata: { interfaces, os: host.osNmap }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (host.openPorts && host.openPorts.length > 0) {
|
||||||
|
for (const port of host.openPorts) {
|
||||||
|
const svcSlug = `nmap-svc-${host.mac.replace(/:/g, '')}-${port.port}`;
|
||||||
|
resources.push({
|
||||||
|
kind: 'service',
|
||||||
|
name: `${port.service} on ${port.port}`,
|
||||||
|
slug: svcSlug,
|
||||||
|
metadata: { port: port.port, protocol: port.protocol }
|
||||||
|
});
|
||||||
|
edges.push({ parentSlug: hostSlug, childSlug: svcSlug, relation: 'exposes' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resolve({ resources, edges });
|
||||||
|
});
|
||||||
|
|
||||||
|
scan.on('error', function(error) {
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
|
||||||
|
scan.startScan();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
const fetch = require('node-fetch');
|
||||||
|
const https = require('https');
|
||||||
|
|
||||||
|
// Custom agent to bypass self-signed certs typical in Proxmox
|
||||||
|
const agent = new https.Agent({
|
||||||
|
rejectUnauthorized: false
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
discover: async (config) => {
|
||||||
|
const { url, tokenId, tokenSecret } = config;
|
||||||
|
if (!url || !tokenId || !tokenSecret) {
|
||||||
|
throw new Error("Missing Proxmox config");
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = {
|
||||||
|
'Authorization': `PVEAPIToken=${tokenId}=${tokenSecret}`
|
||||||
|
};
|
||||||
|
|
||||||
|
const resources = [];
|
||||||
|
const edges = [];
|
||||||
|
|
||||||
|
// 1. Get Nodes
|
||||||
|
const resNodes = await fetch(`${url}/api2/json/nodes`, { headers, agent });
|
||||||
|
if(!resNodes.ok) throw new Error("Proxmox API error on nodes");
|
||||||
|
const nodes = (await resNodes.json()).data;
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (node.status !== 'online') continue;
|
||||||
|
|
||||||
|
const nodeSlug = `pve-node-${node.node}`;
|
||||||
|
resources.push({
|
||||||
|
kind: 'host',
|
||||||
|
name: node.node,
|
||||||
|
slug: nodeSlug,
|
||||||
|
metadata: {
|
||||||
|
subType: 'hypervisor',
|
||||||
|
os: 'Proxmox VE',
|
||||||
|
isProduction: true,
|
||||||
|
interfaces: []
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. Get VMs for this node
|
||||||
|
const resVms = await fetch(`${url}/api2/json/nodes/${node.node}/qemu`, { headers, agent });
|
||||||
|
const vms = resVms.ok ? ((await resVms.json()).data || []) : [];
|
||||||
|
|
||||||
|
for (const vm of vms) {
|
||||||
|
const vmSlug = `vm-${vm.vmid}`;
|
||||||
|
const isTemplate = vm.template === 1;
|
||||||
|
|
||||||
|
let ips = [];
|
||||||
|
let macs = [];
|
||||||
|
|
||||||
|
// Enrich from QEMU guest agent if running
|
||||||
|
if (vm.status === 'running') {
|
||||||
|
try {
|
||||||
|
const agentRes = await fetch(`${url}/api2/json/nodes/${node.node}/qemu/${vm.vmid}/agent/network-get-interfaces`, { headers, agent });
|
||||||
|
if (agentRes.ok) {
|
||||||
|
const agentData = (await agentRes.json()).data;
|
||||||
|
if (agentData && agentData.result) {
|
||||||
|
for (const iface of agentData.result) {
|
||||||
|
if (iface['hardware-address'] && iface['hardware-address'] !== '00:00:00:00:00:00') macs.push(iface['hardware-address']);
|
||||||
|
if (iface['ip-addresses']) {
|
||||||
|
for (const ip of iface['ip-addresses']) {
|
||||||
|
if (ip['ip-address-type'] === 'ipv4' && ip['ip-address'] !== '127.0.0.1') {
|
||||||
|
ips.push(ip['ip-address']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch(e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enrich from VM config to at least get MAC if agent failed/stopped
|
||||||
|
try {
|
||||||
|
const configRes = await fetch(`${url}/api2/json/nodes/${node.node}/qemu/${vm.vmid}/config`, { headers, agent });
|
||||||
|
if (configRes.ok) {
|
||||||
|
const confData = (await configRes.json()).data;
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
if (confData[`net${i}`]) {
|
||||||
|
const m = confData[`net${i}`].match(/(?:virtio|e1000|rtl8139|vmxnet3)=([0-9a-fA-F:]+)/);
|
||||||
|
if(m) macs.push(m[1].toLowerCase());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch(e) {}
|
||||||
|
|
||||||
|
const interfaces = [...new Set(macs)].map((mac, i) => ({ mac, ip: ips[i] || null }));
|
||||||
|
|
||||||
|
resources.push({
|
||||||
|
kind: isTemplate ? 'template' : 'host',
|
||||||
|
name: vm.name || `VM ${vm.vmid}`,
|
||||||
|
slug: vmSlug,
|
||||||
|
metadata: {
|
||||||
|
subType: isTemplate ? 'template' : 'vm',
|
||||||
|
vmid: vm.vmid,
|
||||||
|
isProduction: vm.status === 'running',
|
||||||
|
interfaces,
|
||||||
|
ip: ips[0] || null
|
||||||
|
}
|
||||||
|
});
|
||||||
|
edges.push({ parentSlug: nodeSlug, childSlug: vmSlug, relation: 'hosts' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Get LXCs for this node
|
||||||
|
const resLxcs = await fetch(`${url}/api2/json/nodes/${node.node}/lxc`, { headers, agent });
|
||||||
|
const lxcs = resLxcs.ok ? ((await resLxcs.json()).data || []) : [];
|
||||||
|
|
||||||
|
for (const lxc of lxcs) {
|
||||||
|
const lxcSlug = `lxc-${lxc.vmid}`;
|
||||||
|
const isTemplate = lxc.template === 1;
|
||||||
|
|
||||||
|
let ips = [];
|
||||||
|
let macs = [];
|
||||||
|
|
||||||
|
// Enrich from LXC config
|
||||||
|
try {
|
||||||
|
const configRes = await fetch(`${url}/api2/json/nodes/${node.node}/lxc/${lxc.vmid}/config`, { headers, agent });
|
||||||
|
if (configRes.ok) {
|
||||||
|
const confData = (await configRes.json()).data;
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
if (confData[`net${i}`]) {
|
||||||
|
const hwMatch = confData[`net${i}`].match(/hwaddr=([0-9a-fA-F:]+)/);
|
||||||
|
const ipMatch = confData[`net${i}`].match(/ip=([0-9\.]+)/); // Ignores dhcp
|
||||||
|
if(hwMatch) macs.push(hwMatch[1].toLowerCase());
|
||||||
|
if(ipMatch) ips.push(ipMatch[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch(e) {}
|
||||||
|
|
||||||
|
const interfaces = [...new Set(macs)].map((mac, i) => ({ mac, ip: ips[i] || null }));
|
||||||
|
|
||||||
|
resources.push({
|
||||||
|
kind: isTemplate ? 'template' : 'host',
|
||||||
|
name: lxc.name || `LXC ${lxc.vmid}`,
|
||||||
|
slug: lxcSlug,
|
||||||
|
metadata: {
|
||||||
|
subType: isTemplate ? 'template' : 'lxc',
|
||||||
|
vmid: lxc.vmid,
|
||||||
|
isProduction: lxc.status === 'running',
|
||||||
|
interfaces,
|
||||||
|
ip: ips[0] || null
|
||||||
|
}
|
||||||
|
});
|
||||||
|
edges.push({ parentSlug: nodeSlug, childSlug: lxcSlug, relation: 'hosts' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { resources, edges };
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
const fetch = require('node-fetch');
|
||||||
|
const https = require('https');
|
||||||
|
|
||||||
|
const agent = new https.Agent({
|
||||||
|
rejectUnauthorized: false
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
discover: async (config) => {
|
||||||
|
const { url, user, password } = config;
|
||||||
|
if (!url || !user || !password) {
|
||||||
|
throw new Error("Missing Unifi config");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Authenticate
|
||||||
|
let loginRes = await fetch(`${url}/api/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ username: user, password }),
|
||||||
|
agent
|
||||||
|
});
|
||||||
|
|
||||||
|
let isUdm = true;
|
||||||
|
if (!loginRes.ok) {
|
||||||
|
loginRes = await fetch(`${url}/api/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ username: user, password }),
|
||||||
|
agent
|
||||||
|
});
|
||||||
|
isUdm = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!loginRes.ok) {
|
||||||
|
throw new Error(`Unifi auth failed: ${loginRes.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cookie = loginRes.headers.get('set-cookie');
|
||||||
|
// UniFi often requires the CSRF token from the cookie
|
||||||
|
let csrf = '';
|
||||||
|
if (cookie) {
|
||||||
|
const match = cookie.match(/csrf_token=([^;]+)/);
|
||||||
|
if (match) csrf = match[1];
|
||||||
|
}
|
||||||
|
const headers = { 'Cookie': cookie, 'X-Csrf-Token': csrf };
|
||||||
|
|
||||||
|
const resources = [];
|
||||||
|
const edges = [];
|
||||||
|
|
||||||
|
const basePath = isUdm ? '/proxy/network' : '';
|
||||||
|
|
||||||
|
// 2. Get Devices (Switches/APs)
|
||||||
|
const devRes = await fetch(`${url}${basePath}/api/s/default/stat/device`, { headers, agent });
|
||||||
|
const devData = (await devRes.json()).data || [];
|
||||||
|
|
||||||
|
for (const dev of devData) {
|
||||||
|
const devSlug = `unifi-device-${dev.mac.replace(/:/g, '')}`;
|
||||||
|
resources.push({
|
||||||
|
kind: 'network_device',
|
||||||
|
name: dev.name || dev.model,
|
||||||
|
slug: devSlug,
|
||||||
|
metadata: {
|
||||||
|
make: 'Ubiquiti',
|
||||||
|
model: dev.model,
|
||||||
|
firmware: dev.version,
|
||||||
|
interfaces: [{ mac: dev.mac, ip: dev.ip }]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Get Clients
|
||||||
|
const clientRes = await fetch(`${url}${basePath}/api/s/default/stat/sta`, { headers, agent });
|
||||||
|
const clientData = (await clientRes.json()).data || [];
|
||||||
|
|
||||||
|
for (const client of clientData) {
|
||||||
|
const clientSlug = `unifi-client-${client.mac.replace(/:/g, '')}`;
|
||||||
|
resources.push({
|
||||||
|
kind: 'host', // Or unmanaged_device initially
|
||||||
|
name: client.hostname || client.name || client.mac,
|
||||||
|
slug: clientSlug,
|
||||||
|
metadata: {
|
||||||
|
interfaces: [{ mac: client.mac, ip: client.ip }]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// If we know which switch/AP it's on
|
||||||
|
if (client.ap_mac) {
|
||||||
|
const apSlug = `unifi-device-${client.ap_mac.replace(/:/g, '')}`;
|
||||||
|
edges.push({ parentSlug: apSlug, childSlug: clientSlug, relation: 'connected_to' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { resources, edges };
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -7,6 +7,12 @@ body {
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
|
/* Height of the fixed navbar (plus the update banner, while shown --
|
||||||
|
see top.ejs's showUpdateBanner/dismissUpdateBanner). Lets an in-page
|
||||||
|
sticky element offset itself below both fixed elements via
|
||||||
|
`top: var(--sw-content-offset)` instead of colliding with them at the
|
||||||
|
viewport's true top:0. */
|
||||||
|
--sw-content-offset: 4.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
#spa-shell {
|
#spa-shell {
|
||||||
|
|||||||
@@ -67,13 +67,6 @@ app.user = (function(app){
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function remove(args, callack){
|
|
||||||
if(!confirm('Delete '+ args.uid+ 'user?')) return false;
|
|
||||||
app.api.delete('user/'+ args.uid, function(error, data){
|
|
||||||
callack(error, data);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function changePassword(args, callack){
|
function changePassword(args, callack){
|
||||||
app.api.put('users/'+ arg.uid || '', args, function(error, data){
|
app.api.put('users/'+ arg.uid || '', args, function(error, data){
|
||||||
callack(error, data);
|
callack(error, data);
|
||||||
@@ -110,7 +103,7 @@ app.user = (function(app){
|
|||||||
return m ? m[1] : dn;
|
return m ? m[1] : dn;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {list, remove, createInvite, setActive, dnToUid};
|
return {list, createInvite, setActive, dnToUid};
|
||||||
|
|
||||||
})(app);
|
})(app);
|
||||||
|
|
||||||
@@ -306,13 +299,6 @@ app.oauthClient = (function(app){
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function remove(args, callack){
|
|
||||||
if(!confirm('Delete OAuth client "' + args.client_id + '"?')) return false;
|
|
||||||
app.api.delete('oauth/client/' + args.client_id, function(error, data){
|
|
||||||
callack(error, data);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function update(args, callack){
|
function update(args, callack){
|
||||||
app.api.put('oauth/client/' + args.client_id, args, function(error, data){
|
app.api.put('oauth/client/' + args.client_id, args, function(error, data){
|
||||||
callack(error, data);
|
callack(error, data);
|
||||||
@@ -325,7 +311,7 @@ app.oauthClient = (function(app){
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return { list, add, remove, update, rotateSecret };
|
return { list, add, update, rotateSecret };
|
||||||
})(app);
|
})(app);
|
||||||
|
|
||||||
app.tos = (function(app){
|
app.tos = (function(app){
|
||||||
@@ -396,7 +382,7 @@ app.impersonate = (function(app){
|
|||||||
|
|
||||||
app.token = (function(app){
|
app.token = (function(app){
|
||||||
function list(name, callack){
|
function list(name, callack){
|
||||||
if($.isFunction(name)){
|
if(typeof name === 'function'){
|
||||||
callack = name;
|
callack = name;
|
||||||
name = '';
|
name = '';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
// Shared client framework for the theta42 apps.
|
||||||
|
//
|
||||||
|
// This file is byte-identical across sso-manager-node, proxy and jump-host —
|
||||||
|
// per-app behaviour comes from the server (the `ui` locals in views/top.ejs and
|
||||||
|
// the /api/user/me response), never from edits to this file. Edit all three
|
||||||
|
// copies together.
|
||||||
|
//
|
||||||
|
// jQuery 4 safe: no $.isFunction, no $.holdReady.
|
||||||
|
|
||||||
var app = {};
|
var app = {};
|
||||||
|
|
||||||
app.pubsub = (function(){
|
app.pubsub = (function(){
|
||||||
@@ -75,11 +84,17 @@ app.socket = (function(app){
|
|||||||
app.api = (function(app){
|
app.api = (function(app){
|
||||||
var baseURL = '/api/'
|
var baseURL = '/api/'
|
||||||
|
|
||||||
function post(url, data, callback){
|
// post/put/delete are dual-mode: pass a callback for the node-style
|
||||||
if (!$.isFunction(callback)) {
|
// (error, data, status) form, or omit it to get a Promise that resolves
|
||||||
return new Promise((resolve, reject) => {
|
// with the parsed body and rejects with the error body. get/options return
|
||||||
|
// the jqXHR, which is itself thenable, so `await app.api.get(...)` works.
|
||||||
|
|
||||||
|
function body(method, url, data, callback){
|
||||||
|
if(typeof callback !== 'function'){
|
||||||
|
return new Promise(function(resolve, reject){
|
||||||
$.ajax({
|
$.ajax({
|
||||||
type: 'POST', url: baseURL+url,
|
type: method,
|
||||||
|
url: baseURL+url,
|
||||||
headers: { 'auth-token': app.auth.getToken() },
|
headers: { 'auth-token': app.auth.getToken() },
|
||||||
data: JSON.stringify(data),
|
data: JSON.stringify(data),
|
||||||
contentType: 'application/json; charset=utf-8',
|
contentType: 'application/json; charset=utf-8',
|
||||||
@@ -88,9 +103,11 @@ app.api = (function(app){
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
return $.ajax({
|
return $.ajax({
|
||||||
type: 'POST',
|
type: method,
|
||||||
url: baseURL+url,
|
url: baseURL+url,
|
||||||
headers:{ 'auth-token': app.auth.getToken() },
|
headers:{
|
||||||
|
'auth-token': app.auth.getToken()
|
||||||
|
},
|
||||||
data: JSON.stringify(data),
|
data: JSON.stringify(data),
|
||||||
contentType: "application/json; charset=utf-8",
|
contentType: "application/json; charset=utf-8",
|
||||||
dataType: "json",
|
dataType: "json",
|
||||||
@@ -104,40 +121,27 @@ app.api = (function(app){
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function post(url, data, callback){
|
||||||
|
return body('POST', url, data, callback);
|
||||||
|
}
|
||||||
|
|
||||||
function put(url, data, callback){
|
function put(url, data, callback){
|
||||||
if (!$.isFunction(callback)) {
|
return body('PUT', url, data, callback);
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
$.ajax({
|
|
||||||
type: 'PUT', url: baseURL+url,
|
|
||||||
headers: { 'auth-token': app.auth.getToken() },
|
|
||||||
data: JSON.stringify(data),
|
|
||||||
contentType: 'application/json; charset=utf-8',
|
|
||||||
dataType: 'json',
|
|
||||||
}).done(resolve).fail(function(xhr){ reject(xhr.responseJSON || {}); });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return $.ajax({
|
|
||||||
type: 'PUT',
|
|
||||||
url: baseURL+url,
|
|
||||||
headers:{ 'auth-token': app.auth.getToken() },
|
|
||||||
data: JSON.stringify(data),
|
|
||||||
contentType: "application/json; charset=utf-8",
|
|
||||||
dataType: "json",
|
|
||||||
complete: function(res, text){
|
|
||||||
callback(
|
|
||||||
text !== 'success' ? res.statusText : null,
|
|
||||||
JSON.parse(res.responseText),
|
|
||||||
res.status
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function remove(url, callback){
|
// Called both as (url, callback) and — from formAJAX, which always passes
|
||||||
if (!$.isFunction(callback)) {
|
// the serialized form as the second argument — as (url, data, callback).
|
||||||
return new Promise((resolve, reject) => {
|
// No request body is sent either way.
|
||||||
|
function remove(url, data, callback){
|
||||||
|
if(typeof data === 'function'){
|
||||||
|
callback = data;
|
||||||
|
data = undefined;
|
||||||
|
}
|
||||||
|
if(typeof callback !== 'function'){
|
||||||
|
return new Promise(function(resolve, reject){
|
||||||
$.ajax({
|
$.ajax({
|
||||||
type: 'DELETE', url: baseURL+url,
|
type: 'DELETE',
|
||||||
|
url: baseURL+url,
|
||||||
headers: { 'auth-token': app.auth.getToken() },
|
headers: { 'auth-token': app.auth.getToken() },
|
||||||
contentType: 'application/json; charset=utf-8',
|
contentType: 'application/json; charset=utf-8',
|
||||||
dataType: 'json',
|
dataType: 'json',
|
||||||
@@ -147,7 +151,9 @@ app.api = (function(app){
|
|||||||
return $.ajax({
|
return $.ajax({
|
||||||
type: 'DELETE',
|
type: 'DELETE',
|
||||||
url: baseURL+url,
|
url: baseURL+url,
|
||||||
headers:{ 'auth-token': app.auth.getToken() },
|
headers:{
|
||||||
|
'auth-token': app.auth.getToken()
|
||||||
|
},
|
||||||
contentType: "application/json; charset=utf-8",
|
contentType: "application/json; charset=utf-8",
|
||||||
dataType: "json",
|
dataType: "json",
|
||||||
complete: function(res, text){
|
complete: function(res, text){
|
||||||
@@ -202,7 +208,10 @@ app.api = (function(app){
|
|||||||
})(app)
|
})(app)
|
||||||
|
|
||||||
app.auth = (function(app){
|
app.auth = (function(app){
|
||||||
var user = {};
|
// One in-flight/cached GET /api/user/me per page load. Every gating
|
||||||
|
// decision (nav items, per-view forceLogin, group-required elements) reads
|
||||||
|
// this same promise instead of re-fetching.
|
||||||
|
var userPromise = null;
|
||||||
|
|
||||||
function setToken(token){
|
function setToken(token){
|
||||||
localStorage.setItem('APIToken', token);
|
localStorage.setItem('APIToken', token);
|
||||||
@@ -216,35 +225,70 @@ app.auth = (function(app){
|
|||||||
try{
|
try{
|
||||||
return await app.api.get('user/me');
|
return await app.api.get('user/me');
|
||||||
}catch(error){
|
}catch(error){
|
||||||
if(error?.status === 401) return null;
|
if(error && error.status === 401) return null;
|
||||||
throw error
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cached current user, or false when there's no token at all. Callers that
|
||||||
|
// need a fresh copy (after a login or a profile change) pass force.
|
||||||
|
function loadUser(force){
|
||||||
|
if(force || !userPromise){
|
||||||
|
userPromise = getToken() ? getUser() : Promise.resolve(null);
|
||||||
|
userPromise = userPromise.then(function(user){
|
||||||
|
app.auth.user = app.auth.perms = user || null;
|
||||||
|
return user;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return userPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The apps report group membership two ways: sso-manager-node returns LDAP
|
||||||
|
// DNs in `memberOf`, the OIDC clients return plain CNs in `groups`. Both
|
||||||
|
// normalise to a list of CNs. `isAdmin` (the clients' effective-rights flag)
|
||||||
|
// is exposed as a synthetic `admin` group so one gating model covers both.
|
||||||
|
function groupCNs(user){
|
||||||
|
var raw = (user && (user.memberOf || user.groups)) || [];
|
||||||
|
if(!Array.isArray(raw)) raw = [raw];
|
||||||
|
var names = raw.map(function(group){
|
||||||
|
return String(group).split(',')[0].replace(/^cn=/i, '');
|
||||||
|
});
|
||||||
|
if(user && user.isAdmin && names.indexOf('admin') === -1) names.push('admin');
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
|
||||||
async function memberOf(groupNameToFind, user){
|
async function memberOf(groupNameToFind, user){
|
||||||
try{
|
user = user || await loadUser();
|
||||||
user = user || await app.auth.asyncUser;
|
if(!user) return false;
|
||||||
groupNameToFind = Array.isArray(groupNameToFind) ? groupNameToFind : [groupNameToFind]
|
groupNameToFind = Array.isArray(groupNameToFind) ? groupNameToFind : [groupNameToFind];
|
||||||
|
|
||||||
for(let group of user.memberOf){
|
return groupCNs(user).some(function(group){
|
||||||
group = group.split(',ou=groups')[0].replace('cn=', '');
|
return groupNameToFind.includes(group);
|
||||||
if(groupNameToFind.includes(group)) return true;
|
});
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
|
|
||||||
}catch(error){
|
|
||||||
throw(error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function isLoggedIn(){
|
// True when the logged-in user is a global admin (per user/me). Sync — only
|
||||||
if(getToken()){
|
// meaningful once isLoggedIn/forceLogin has resolved.
|
||||||
user = await app.auth.asyncUser;
|
function isAdmin(){
|
||||||
return user;
|
return !!(app.auth.perms && app.auth.perms.isAdmin);
|
||||||
}else{
|
}
|
||||||
return false;
|
|
||||||
|
// Dual-mode: returns a Promise resolving to the user (or false), and calls
|
||||||
|
// an optional node-style callback with the same result.
|
||||||
|
function isLoggedIn(callback){
|
||||||
|
var promise = loadUser().then(function(user){
|
||||||
|
return user || false;
|
||||||
|
});
|
||||||
|
|
||||||
|
if(typeof callback === 'function'){
|
||||||
|
promise.then(function(user){
|
||||||
|
callback(null, user);
|
||||||
|
}, function(error){
|
||||||
|
callback(error, false);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
function logIn(args, callback){
|
function logIn(args, callback){
|
||||||
@@ -252,62 +296,125 @@ app.auth = (function(app){
|
|||||||
if(data.login){
|
if(data.login){
|
||||||
setToken(data.token);
|
setToken(data.token);
|
||||||
}
|
}
|
||||||
|
loadUser(true);
|
||||||
callback(error, !!data.token);
|
callback(error, !!data.token);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clears the session only — the caller decides where to go next (the nav's
|
||||||
|
// Log Out button uses ui.logoutRedirect).
|
||||||
function logOut(callback){
|
function logOut(callback){
|
||||||
localStorage.removeItem('APIToken');
|
localStorage.removeItem('APIToken');
|
||||||
location.replace(`/login${location.href.replace(location.origin, '')}`);
|
userPromise = null;
|
||||||
callback();
|
app.auth.user = app.auth.perms = null;
|
||||||
|
if(typeof callback === 'function') callback();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Constrain a redirect target to a same-origin absolute path. Rejects
|
||||||
|
// absolute URLs (open redirect), protocol-relative "//host" and "/\host",
|
||||||
|
// and non-path schemes like "javascript:" (XSS). Falls back to "/".
|
||||||
|
function safeInternalPath(path){
|
||||||
|
if(typeof path !== 'string' || path.charAt(0) !== '/'
|
||||||
|
|| path.charAt(1) === '/' || path.charAt(1) === '\\'){
|
||||||
|
return '/';
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Consume an app token handed back by the OIDC callback via the URL
|
||||||
|
// fragment (#token=…&redirect=…). Stores it, strips the fragment, and
|
||||||
|
// forwards to the intended page. Returns true if a token was consumed.
|
||||||
|
function consumeTokenFragment(){
|
||||||
|
if(!location.hash) return false;
|
||||||
|
var params = new URLSearchParams(location.hash.replace(/^#/, ''));
|
||||||
|
var token = params.get('token');
|
||||||
|
if(!token) return false;
|
||||||
|
|
||||||
|
setToken(token);
|
||||||
|
// redirect comes from the URL fragment (attacker-controllable); only
|
||||||
|
// allow a same-origin path so it can't become an open redirect / XSS.
|
||||||
|
var redirect = safeInternalPath(params.get('redirect') || '/');
|
||||||
|
// Drop the token from the address bar before navigating on.
|
||||||
|
history.replaceState(null, '', location.pathname + location.search);
|
||||||
|
window.location.href = redirect;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Page-level gate. jQuery 4 removed $.holdReady, so an unauthenticated or
|
||||||
|
// unauthorised user is kept off the page by a redirect / an error panel
|
||||||
|
// rather than by pausing document ready.
|
||||||
|
//
|
||||||
|
// `requiredGroups` is a group CN or an OR-list of them; the synthetic
|
||||||
|
// `admin` group covers the OIDC clients' isAdmin flag.
|
||||||
async function forceLogin(requiredGroups){
|
async function forceLogin(requiredGroups){
|
||||||
$.holdReady(true);
|
var user = await loadUser();
|
||||||
if(!await app.auth.isLoggedIn()) app.auth.logOut(function(){});
|
|
||||||
|
if(!user){
|
||||||
|
logOut(function(){});
|
||||||
|
location.replace('/login?redirect=' + encodeURIComponent(
|
||||||
|
location.pathname + location.search
|
||||||
|
));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if(user.onboardingRequired && location.pathname !== '/onboarding'){
|
if(user.onboardingRequired && location.pathname !== '/onboarding'){
|
||||||
location.replace('/onboarding');
|
location.replace('/onboarding');
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if(requiredGroups){
|
if(requiredGroups && !await memberOf(requiredGroups, user)){
|
||||||
if(!await memberOf(requiredGroups)){
|
app.messages.action(
|
||||||
console.log("Does not have permission!!!")
|
`<h1>
|
||||||
app.util.actionMessage(
|
<i class="fa-solid fa-triangle-exclamation"></i>
|
||||||
`<h1>
|
<b>You do not have permission to be here.</b>
|
||||||
<i class="fa-solid fa-triangle-exclamation"></i>
|
<i class="fa-solid fa-triangle-exclamation"></i>
|
||||||
<b>You do not have permission to be here.</b>
|
</h1>`,
|
||||||
<i class="fa-solid fa-triangle-exclamation"></i>
|
$('#spa-shell'),
|
||||||
</h1>`,
|
'danger',
|
||||||
$('#spa-shell'),
|
);
|
||||||
'danger',
|
throw new Error("User does not have permission");
|
||||||
);
|
|
||||||
throw new Error("User does not have permission");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$.holdReady(false);
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Where to go after a successful login: the ?redirect= query param, or the
|
||||||
|
// legacy /login/<path> suffix form, constrained to a same-origin path. The
|
||||||
|
// suffix form keeps its query string — /login/oauth/authorize?client_id=…
|
||||||
|
// is how the OIDC provider sends an unauthenticated user through login.
|
||||||
function logInRedirect(){
|
function logInRedirect(){
|
||||||
window.location.href = location.href.replace(location.origin+'/login', '') || '/'
|
var params = new URLSearchParams(location.search);
|
||||||
|
var target = params.get('redirect')
|
||||||
|
|| location.href.replace(location.origin + '/login', '')
|
||||||
|
|| '/';
|
||||||
|
window.location.href = safeInternalPath(target);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getToken: getToken,
|
getToken: getToken,
|
||||||
setToken: setToken,
|
setToken: setToken,
|
||||||
|
getUser: getUser,
|
||||||
|
loadUser: loadUser,
|
||||||
|
groupCNs: groupCNs,
|
||||||
|
memberOf: memberOf,
|
||||||
|
isAdmin: isAdmin,
|
||||||
isLoggedIn: isLoggedIn,
|
isLoggedIn: isLoggedIn,
|
||||||
|
safeInternalPath: safeInternalPath,
|
||||||
|
consumeTokenFragment: consumeTokenFragment,
|
||||||
|
user: null,
|
||||||
|
perms: null,
|
||||||
logIn: logIn,
|
logIn: logIn,
|
||||||
logOut: logOut,
|
logOut: logOut,
|
||||||
forceLogin,
|
forceLogin,
|
||||||
logInRedirect,
|
logInRedirect,
|
||||||
getUser,
|
|
||||||
memberOf,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
})(app);
|
})(app);
|
||||||
app.auth.asyncUser = app.auth.getUser();
|
|
||||||
|
|
||||||
|
// Back-compat alias for views that awaited the cached user directly.
|
||||||
|
Object.defineProperty(app.auth, 'asyncUser', {
|
||||||
|
get: function(){ return app.auth.loadUser(); },
|
||||||
|
});
|
||||||
|
|
||||||
app.user = (function(app){
|
app.user = (function(app){
|
||||||
function list(callback){
|
function list(callback){
|
||||||
@@ -338,6 +445,72 @@ app.user = (function(app){
|
|||||||
|
|
||||||
})(app);
|
})(app);
|
||||||
|
|
||||||
|
// Local (app-managed) permissions and groups. Only the OIDC-client apps serve
|
||||||
|
// these endpoints; the calls are inert elsewhere.
|
||||||
|
app.permission = (function(app){
|
||||||
|
function list(callback){
|
||||||
|
app.api.get('permission/', function(error, data){
|
||||||
|
callback(error, data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function subjects(callback){
|
||||||
|
app.api.get('permission/subjects', function(error, data){
|
||||||
|
callback(error, data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function add(args, callback){
|
||||||
|
app.api.post('permission/', args, function(error, data){
|
||||||
|
callback(error, data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function remove(id, callback){
|
||||||
|
app.api.delete('permission/' + encodeURIComponent(id), function(error, data){
|
||||||
|
callback(error, data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {list, subjects, add, remove};
|
||||||
|
|
||||||
|
})(app);
|
||||||
|
|
||||||
|
app.group = (function(app){
|
||||||
|
function list(callback){
|
||||||
|
app.api.get('group/', function(error, data){
|
||||||
|
callback(error, data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function add(args, callback){
|
||||||
|
app.api.post('group/', args, function(error, data){
|
||||||
|
callback(error, data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function remove(name, callback){
|
||||||
|
app.api.delete('group/' + encodeURIComponent(name), function(error, data){
|
||||||
|
callback(error, data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function addMember(name, username, callback){
|
||||||
|
app.api.post('group/' + encodeURIComponent(name) + '/members', {username}, function(error, data){
|
||||||
|
callback(error, data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeMember(name, username, callback){
|
||||||
|
app.api.delete('group/' + encodeURIComponent(name) + '/members/' + encodeURIComponent(username), function(error, data){
|
||||||
|
callback(error, data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {list, add, remove, addMember, removeMember};
|
||||||
|
|
||||||
|
})(app);
|
||||||
|
|
||||||
app.util = (function(app){
|
app.util = (function(app){
|
||||||
|
|
||||||
function getUrlParameter(name){
|
function getUrlParameter(name){
|
||||||
@@ -347,65 +520,15 @@ app.util = (function(app){
|
|||||||
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
|
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
|
||||||
};
|
};
|
||||||
|
|
||||||
function actionMessage(message, $targetPassed, type, callback){
|
// escapeHtml/actionMessage/actionConfirm moved to @simpleworkjs/frontend's
|
||||||
message = message || '';
|
// app.util.escapeHtml and app.messages.action/confirm.
|
||||||
|
function escapeHtml(s){
|
||||||
let $target = $targetPassed.closest('div.card').find('.actionMessage');
|
return String(s == null ? '' : s)
|
||||||
if(!$target.length) $target = $($targetPassed.find('.actionMessage')[0]);
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
type = type || 'info';
|
.replace(/>/g, '>')
|
||||||
callback = callback || function(){};
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
if($target.html() === message) return;
|
|
||||||
|
|
||||||
if($target.html()){
|
|
||||||
$target.slideUp('fast', function(){
|
|
||||||
$target.html('')
|
|
||||||
$target.removeClass (function(index, className){
|
|
||||||
return (className.match (/(^|\s)bg-\S+/g) || []).join(' ');
|
|
||||||
});
|
|
||||||
if(message) return actionMessage(message, $target, type, callback);
|
|
||||||
$target.hide()
|
|
||||||
})
|
|
||||||
}else{
|
|
||||||
if(type) $target.addClass('bg-' + type);
|
|
||||||
|
|
||||||
if(!message.includes('<button')) message += `
|
|
||||||
<button class="action-close btn btn-sm btn-outline-dark float-end">
|
|
||||||
<i class="fa-solid fa-xmark"></i>
|
|
||||||
</button>
|
|
||||||
`
|
|
||||||
$target.html(message).slideDown('fast');
|
|
||||||
}
|
|
||||||
setTimeout(callback,10)
|
|
||||||
}
|
|
||||||
|
|
||||||
function actionConfirm(message, $target, type, callback){
|
|
||||||
return new Promise((resolve, reject) =>{
|
|
||||||
let id = crypto.randomUUID();
|
|
||||||
message = `
|
|
||||||
<h4 class"align-middle" >
|
|
||||||
<i class="fa-solid fa-triangle-exclamation"></i>
|
|
||||||
<b>${message}</b>
|
|
||||||
<span class="float-end">
|
|
||||||
<button type="button" class="btn btn-success confirm-${id}" data-confirm="true">
|
|
||||||
<i class="fa-solid fa-circle-check"></i>
|
|
||||||
Confirm
|
|
||||||
</button>
|
|
||||||
<button type="button" class="btn btn-danger confirm-${id}">
|
|
||||||
<i class="fa-solid fa-circle-stop"></i>
|
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
</h4>
|
|
||||||
`
|
|
||||||
actionMessage(message, $target, type);
|
|
||||||
$("body").on('click', `.confirm-${id}`, function(){
|
|
||||||
actionMessage('', $target, type);
|
|
||||||
resolve(!!$(this).data('confirm'));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$.fn.serializeObject = function() {
|
$.fn.serializeObject = function() {
|
||||||
@@ -417,6 +540,9 @@ app.util = (function(app){
|
|||||||
if (obj[name] === undefined) {
|
if (obj[name] === undefined) {
|
||||||
if (!value
|
if (!value
|
||||||
&& !$(this).parent().find(`[name="${name}"]`).attr('value')
|
&& !$(this).parent().find(`[name="${name}"]`).attr('value')
|
||||||
|
// Keep empty <textarea>s so a cleared field is submitted (and
|
||||||
|
// can reset a list, e.g. the per-host IP/header controls).
|
||||||
|
&& !$(this).filter(`textarea[name="${name}"]`).length
|
||||||
){
|
){
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -458,29 +584,64 @@ app.util = (function(app){
|
|||||||
document.body.removeChild(element);
|
document.body.removeChild(element);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Scroll a just-added/-edited element into view and flash its
|
||||||
|
// background, so the user's eye lands on the row that changed instead of
|
||||||
|
// it silently appearing/updating somewhere off-screen. Takes a jQuery
|
||||||
|
// object or a raw DOM node (e.g. jq-repeat's `item.__jq_$el`).
|
||||||
|
function revealItem(el){
|
||||||
|
var node = el && el.jquery ? el[0] : el;
|
||||||
|
if (!node) return;
|
||||||
|
if (typeof node.scrollIntoView === 'function') {
|
||||||
|
node.scrollIntoView({behavior: 'smooth', block: 'center'});
|
||||||
|
}
|
||||||
|
var prevTransition = node.style.transition;
|
||||||
|
var prevBg = node.style.backgroundColor;
|
||||||
|
node.style.transition = 'background-color 1.5s ease';
|
||||||
|
node.style.backgroundColor = 'var(--bs-success-bg-subtle, #d1e7dd)';
|
||||||
|
setTimeout(function(){
|
||||||
|
node.style.backgroundColor = prevBg;
|
||||||
|
setTimeout(function(){ node.style.transition = prevTransition; }, 1500);
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
downloadFile: downloadFile,
|
downloadFile: downloadFile,
|
||||||
getUrlParameter: getUrlParameter,
|
getUrlParameter: getUrlParameter,
|
||||||
actionMessage: actionMessage,
|
escapeHtml: escapeHtml,
|
||||||
actionConfirm,
|
revealItem: revealItem,
|
||||||
}
|
}
|
||||||
})(app);
|
})(app);
|
||||||
|
|
||||||
$( document ).ready(async function(){
|
// Reveal every .group-required-<cn> element the current user's groups entitle
|
||||||
|
// them to. Elements carrying .group-required start hidden (styles.css), so a
|
||||||
|
// user who is in no groups — or who isn't logged in — simply never sees them.
|
||||||
|
app.auth.applyGroupVisibility = function(user){
|
||||||
|
var groups = app.auth.groupCNs(user);
|
||||||
|
if(!groups.length) return;
|
||||||
|
|
||||||
// Show content if the user has the correct group
|
var style = document.getElementById('group-required-rules');
|
||||||
for(let group of (await app.auth.asyncUser)?.memberOf || []){
|
if(!style){
|
||||||
|
style = document.createElement('style');
|
||||||
|
style.id = 'group-required-rules';
|
||||||
|
document.head.appendChild(style);
|
||||||
|
}
|
||||||
|
|
||||||
|
for(var group of groups){
|
||||||
try{
|
try{
|
||||||
group = group.split(',ou=groups')[0].replace('cn=', '');
|
style.sheet.insertRule(
|
||||||
|
`.group-required-${CSS.escape(group)} { display: revert !important; }`,
|
||||||
const sheet = document.styleSheets[0];
|
style.sheet.cssRules.length
|
||||||
const selector = `.group-required-${group}`;
|
);
|
||||||
const cssText = `${selector} { display: revert !important; }`;
|
|
||||||
sheet.insertRule(cssText, sheet.cssRules.length);
|
|
||||||
}catch(error){
|
}catch(error){
|
||||||
|
// A group whose CN isn't a usable CSS identifier just gates nothing.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
$( document ).ready(async function(){
|
||||||
|
|
||||||
|
// Show content the user's groups entitle them to.
|
||||||
|
app.auth.applyGroupVisibility(await app.auth.loadUser());
|
||||||
|
|
||||||
$('div.row').fadeIn('slow'); //show the page
|
$('div.row').fadeIn('slow'); //show the page
|
||||||
|
|
||||||
@@ -502,9 +663,9 @@ $( document ).ready(async function(){
|
|||||||
$(this).closest('.card').slideUp('fast');
|
$(this).closest('.card').slideUp('fast');
|
||||||
});
|
});
|
||||||
|
|
||||||
$('.actionMessage').on('click', 'button.action-close', function(event){
|
// action-close click handling is wired by @simpleworkjs/frontend's
|
||||||
app.util.actionMessage(null, $(this));
|
// app.messages.js (delegated on document, so it also covers messages
|
||||||
});
|
// rendered after this ready handler runs).
|
||||||
|
|
||||||
setInterval(()=>{
|
setInterval(()=>{
|
||||||
$('.momentFromNow').each((idx, el)=>{
|
$('.momentFromNow').each((idx, el)=>{
|
||||||
@@ -535,20 +696,17 @@ function formAJAX(btn){
|
|||||||
var method = ($form.attr('method') || 'post').toLowerCase();
|
var method = ($form.attr('method') || 'post').toLowerCase();
|
||||||
|
|
||||||
if($form.validate && !$form.validate()){
|
if($form.validate && !$form.validate()){
|
||||||
app.util.actionMessage('Please fix the form errors.', $form, 'danger')
|
app.messages.action('Please fix the form errors.', $form, 'danger')
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
app.util.actionMessage(
|
// Plain text: app.messages.action HTML-escapes its message (by design,
|
||||||
`<div class="spinner-border" role="status">
|
// see @simpleworkjs/frontend), so raw markup like a spinner <div> would
|
||||||
<span class="visually-hidden">Loading...</span>
|
// render literally instead of as an element.
|
||||||
</div>`,
|
app.messages.action('Saving…', $form, 'info');
|
||||||
$form,
|
|
||||||
'info'
|
|
||||||
);
|
|
||||||
|
|
||||||
app.api[method]($form.attr('action'), formData, function(error, data){
|
app.api[method]($form.attr('action'), formData, function(error, data){
|
||||||
app.util.actionMessage(data.message, $form, error ? 'danger' : 'success'); //re-populate table
|
app.messages.action(data.message, $form, error ? 'danger' : 'success'); //re-populate table
|
||||||
$form.validateClear();
|
$form.validateClear();
|
||||||
if(!error){
|
if(!error){
|
||||||
$form.trigger("reset");
|
$form.trigger("reset");
|
||||||
@@ -556,7 +714,7 @@ function formAJAX(btn){
|
|||||||
}else{
|
}else{
|
||||||
console.log('formAJAX res error', error, data)
|
console.log('formAJAX res error', error, data)
|
||||||
if(data && data.name === 'ObjectValidateError'){
|
if(data && data.name === 'ObjectValidateError'){
|
||||||
app.util.actionMessage('Please fix the form errors', $form, 'danger'); //re-populate table
|
app.messages.action('Please fix the form errors', $form, 'danger'); //re-populate table
|
||||||
}
|
}
|
||||||
if(data && data.keys){
|
if(data && data.keys){
|
||||||
console.log('form key errors', data.keys)
|
console.log('form key errors', data.keys)
|
||||||
@@ -567,4 +725,3 @@ function formAJAX(btn){
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,133 +0,0 @@
|
|||||||
( function( $ ) {
|
|
||||||
var settings = {
|
|
||||||
rule: {
|
|
||||||
eq: function(value, options){
|
|
||||||
var compare = $('[name=' + options + ']').val();
|
|
||||||
|
|
||||||
if ( value != compare ) {
|
|
||||||
return "Miss-match";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
$.fn.validate = function(event) {
|
|
||||||
// let thisSettings = $.extend(true, settings, settingsObj);
|
|
||||||
let hasErrors = false;
|
|
||||||
|
|
||||||
if(this.is('[validate]')) return this.validateField(event);
|
|
||||||
|
|
||||||
if(!this.attr('isValid')){
|
|
||||||
console.log('adding reset event')
|
|
||||||
this.on('reset', function(){
|
|
||||||
$(this).attr('isValid', false);
|
|
||||||
$(this).validateClear();
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
this.find('[validate]').each(function(){
|
|
||||||
if(!$(this).validateField()) hasErrors = true;
|
|
||||||
});
|
|
||||||
|
|
||||||
this.attr('isValid', !hasErrors);
|
|
||||||
|
|
||||||
if(hasErrors && event) event.preventDefault();
|
|
||||||
|
|
||||||
return !hasErrors;
|
|
||||||
};
|
|
||||||
|
|
||||||
$.fn.validateClear = function(){
|
|
||||||
$(this).find('input').each(function(){
|
|
||||||
$(this).removeClass('is-invalid');
|
|
||||||
$(this).removeClass('is-valid');
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
$.fn.validateField = function(){
|
|
||||||
var attr = this.attr('validate').split(':'); //array of params
|
|
||||||
var rule = attr[0];
|
|
||||||
var options = attr[1];
|
|
||||||
var value = this.val(); //link to input value
|
|
||||||
var message;
|
|
||||||
|
|
||||||
if(this.prop('disabled')) return true;
|
|
||||||
|
|
||||||
|
|
||||||
//checks if field is required, and length
|
|
||||||
if(!isNaN(options) && value.length < options){
|
|
||||||
message = `Must be ${options} characters`;
|
|
||||||
}
|
|
||||||
|
|
||||||
//checks if empty to stop processing
|
|
||||||
if(!isNaN(options) && value.length === 0) {
|
|
||||||
}else if(rule in settings.rule){
|
|
||||||
let message = settings.rule[rule].apply(this, [value, options]);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.validateMessage(message)
|
|
||||||
return !message;
|
|
||||||
}
|
|
||||||
|
|
||||||
$.fn.validateMessage = function(message){
|
|
||||||
if(message && message !== true){
|
|
||||||
this.closest('.form-group').find('b.invalid-feedback').html(message);
|
|
||||||
this.addClass('is-invalid');
|
|
||||||
}else{
|
|
||||||
this.removeClass('is-invalid');
|
|
||||||
this.addClass('is-valid');
|
|
||||||
}
|
|
||||||
return this;
|
|
||||||
};
|
|
||||||
|
|
||||||
jQuery.extend({
|
|
||||||
validateSettings: function( settingsObj ) {
|
|
||||||
$.extend( true, settings, settingsObj );
|
|
||||||
},
|
|
||||||
|
|
||||||
validateInit: function( ettingsObj ) {
|
|
||||||
$( '[action]' ).on( 'submit', function ( event, settingsObj ){
|
|
||||||
$( this ).validate( settingsObj, event );
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
}( jQuery ));
|
|
||||||
|
|
||||||
$.validateSettings({
|
|
||||||
rule:{
|
|
||||||
ip: function( value ) {
|
|
||||||
value = value.split( '.' );
|
|
||||||
|
|
||||||
if ( value.length != 4 ) {
|
|
||||||
return "Malformed IP";
|
|
||||||
}
|
|
||||||
|
|
||||||
$.each( value, function( key, value ) {
|
|
||||||
if( value > 255 || value < 0 ) {
|
|
||||||
return "Malformed IP";
|
|
||||||
}
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
host: function( value ) {
|
|
||||||
var reg = /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/;
|
|
||||||
if ( reg.test( value ) === false ) {
|
|
||||||
return "Invalid";
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
user: function( value ) {
|
|
||||||
var reg = /^[a-z0-9\_\-\@\.]{1,32}$/;
|
|
||||||
if ( reg.test( value ) === false ) {
|
|
||||||
return "Invalid";
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
password: function( value ) {
|
|
||||||
var reg = /^(?=[^\d_].*?\d)\w(\w|[!@#$%]){1,48}/;
|
|
||||||
if ( reg.test( value ) === false ) {
|
|
||||||
return "Weak password, Try again";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Self-service access requests. Mounted at /api/access-requests (app.js).
|
||||||
|
//
|
||||||
|
// The loop this closes: a user browses the catalog, finds something they cannot
|
||||||
|
// reach, asks for it; the resource's owner (or a directory admin) approves; the
|
||||||
|
// approval performs the LDAP group add. LDAP stays the access-control truth --
|
||||||
|
// this router never invents a permission, it only automates the group add an
|
||||||
|
// admin would otherwise do by hand, and records who decided.
|
||||||
|
|
||||||
|
const router = require('express').Router();
|
||||||
|
const { Resource, ResourceGroup } = require('../models/resource');
|
||||||
|
const { AccessRequest, STATUS } = require('../models/access_request');
|
||||||
|
const { Group } = require('../models/group_ldap');
|
||||||
|
const { User } = require('../models/user_ldap');
|
||||||
|
const { Mail } = require('../models/email');
|
||||||
|
const { groupCns } = require('../utils/user_groups');
|
||||||
|
const { envelope, projectResource } = require('@simpleworkjs/directory-schema');
|
||||||
|
|
||||||
|
const DIRECTORY_ADMIN_GROUPS = ['app_sso_directory_admin', 'app_sso_admin', 'app_super_admin'];
|
||||||
|
|
||||||
|
function httpError(status, message) {
|
||||||
|
const err = new Error(message);
|
||||||
|
err.status = status;
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
// May `user` decide requests against `resource`? The resource's own owner is
|
||||||
|
// the primary approver -- that is the point of Resource.owner -- with directory
|
||||||
|
// admins as the catch-all so an unowned or orphaned resource is never stuck.
|
||||||
|
async function canDecide(user, resource, callerGroups) {
|
||||||
|
if (resource && resource.owner && resource.owner === user.uid) return true;
|
||||||
|
return callerGroups.some(g => DIRECTORY_ADMIN_GROUPS.includes(g));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The group that satisfies a request for this resource. Prefers an explicit
|
||||||
|
// choice, else the `member`-level link (the "just let me use it" group) over an
|
||||||
|
// `owner`-level one -- requesting a resource should never silently escalate to
|
||||||
|
// its admin group.
|
||||||
|
async function resolveGroupCn(resourceId, requested) {
|
||||||
|
const links = await ResourceGroup.list({ where: { resourceId } });
|
||||||
|
if (!links.length) {
|
||||||
|
throw httpError(409, 'This resource has no access group linked, so it cannot be requested.');
|
||||||
|
}
|
||||||
|
if (requested) {
|
||||||
|
const match = links.find(l => l.groupCn === requested);
|
||||||
|
if (!match) throw httpError(400, `"${requested}" is not an access group for this resource.`);
|
||||||
|
return match.groupCn;
|
||||||
|
}
|
||||||
|
const member = links.find(l => l.accessLevel === 'member');
|
||||||
|
return (member || links[0]).groupCn;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Best-effort notification. A mail failure must never fail the request itself --
|
||||||
|
// the row is the source of truth and the approver can find it in the UI.
|
||||||
|
async function notify(uid, subject, message) {
|
||||||
|
try {
|
||||||
|
const user = await User.get({ uid });
|
||||||
|
if (!user || !user.mail) return;
|
||||||
|
await Mail.sendTemplate(user.mail, 'notification', {
|
||||||
|
givenName: user.givenName || uid,
|
||||||
|
subject,
|
||||||
|
message,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`access-request: notification to ${uid} failed:`, err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/access-requests { slug | resourceId, groupCn?, note? }
|
||||||
|
router.post('/', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
if (req.user.isMachine) throw httpError(403, 'Machine accounts cannot request access.');
|
||||||
|
|
||||||
|
let resource;
|
||||||
|
if (req.body.slug) {
|
||||||
|
const found = await Resource.list({ where: { slug: req.body.slug } });
|
||||||
|
resource = found[0];
|
||||||
|
} else if (req.body.resourceId) {
|
||||||
|
resource = await Resource.get(req.body.resourceId);
|
||||||
|
}
|
||||||
|
if (!resource) throw httpError(404, 'Resource not found');
|
||||||
|
|
||||||
|
const md = resource.metadata || {};
|
||||||
|
// Opt-out, not opt-in: everything in the catalog is requestable unless an
|
||||||
|
// admin has explicitly marked it otherwise.
|
||||||
|
if (md.requestable === false) {
|
||||||
|
throw httpError(409, 'This resource is not available for self-service requests.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const groupCn = await resolveGroupCn(resource.id, req.body.groupCn);
|
||||||
|
|
||||||
|
const callerGroups = await groupCns(req.user);
|
||||||
|
if (callerGroups.includes(groupCn)) {
|
||||||
|
throw httpError(409, 'You already have access to this resource.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await AccessRequest.findOpen(req.user.uid, groupCn);
|
||||||
|
if (existing) throw httpError(409, 'You already have a pending request for this resource.');
|
||||||
|
|
||||||
|
const request = await AccessRequest.create({
|
||||||
|
uid: req.user.uid,
|
||||||
|
resourceId: resource.id,
|
||||||
|
groupCn,
|
||||||
|
status: STATUS.PENDING,
|
||||||
|
note: req.body.note || '',
|
||||||
|
requestedOn: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (resource.owner) {
|
||||||
|
await notify(
|
||||||
|
resource.owner,
|
||||||
|
`Access request: ${resource.name}`,
|
||||||
|
`<p><strong>${req.user.uid}</strong> has requested access to <strong>${resource.name}</strong> (group <code>${groupCn}</code>).</p>` +
|
||||||
|
(req.body.note ? `<p>Their note: ${req.body.note}</p>` : '') +
|
||||||
|
`<p>Review it on the Directory page.</p>`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(envelope(request));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/access-requests/mine — the caller's own request history.
|
||||||
|
router.get('/mine', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const rows = await AccessRequest.listForUser(req.user.uid);
|
||||||
|
res.json(envelope(await decorate(rows)));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/access-requests — pending requests the caller may decide.
|
||||||
|
router.get('/', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const callerGroups = await groupCns(req.user);
|
||||||
|
const isAdmin = callerGroups.some(g => DIRECTORY_ADMIN_GROUPS.includes(g));
|
||||||
|
const pending = await AccessRequest.listPending();
|
||||||
|
|
||||||
|
let visible = pending;
|
||||||
|
if (!isAdmin) {
|
||||||
|
// A plain resource owner sees only requests against resources they own.
|
||||||
|
const owned = await Resource.list({ where: { owner: req.user.uid } });
|
||||||
|
const ownedIds = new Set(owned.map(r => r.id));
|
||||||
|
visible = pending.filter(r => ownedIds.has(r.resourceId));
|
||||||
|
}
|
||||||
|
res.json(envelope(await decorate(visible)));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Attach the resource name/slug each row refers to. The UI needs it on every
|
||||||
|
// list and would otherwise issue one lookup per row.
|
||||||
|
async function decorate(rows) {
|
||||||
|
if (!rows.length) return [];
|
||||||
|
const resources = await Resource.list();
|
||||||
|
const byId = new Map(resources.map(r => [r.id, r]));
|
||||||
|
return rows.map(row => {
|
||||||
|
const data = row.toJSON ? row.toJSON() : { ...row };
|
||||||
|
const resource = byId.get(data.resourceId);
|
||||||
|
data.resource = resource
|
||||||
|
? { id: resource.id, name: resource.name, slug: resource.slug, kind: resource.kind }
|
||||||
|
: null;
|
||||||
|
return data;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/access-requests/:id/approve { decisionNote? }
|
||||||
|
router.post('/:id/approve', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const request = await AccessRequest.get(req.params.id);
|
||||||
|
if (!request) throw httpError(404, 'Request not found');
|
||||||
|
if (request.status !== STATUS.PENDING) {
|
||||||
|
throw httpError(409, `This request was already ${request.status}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const resource = await Resource.get(request.resourceId);
|
||||||
|
const callerGroups = await groupCns(req.user);
|
||||||
|
if (!(await canDecide(req.user, resource, callerGroups))) {
|
||||||
|
throw httpError(403, 'You do not have permission to decide this request.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// The LDAP write happens FIRST and is allowed to throw. Marking a request
|
||||||
|
// approved without the group add would show the user a grant they do not
|
||||||
|
// actually have -- a pending row is recoverable, a lying one is not.
|
||||||
|
const group = await Group.get(request.groupCn);
|
||||||
|
const user = await User.get({ uid: request.uid });
|
||||||
|
try {
|
||||||
|
await group.addMember(user);
|
||||||
|
} catch (err) {
|
||||||
|
// "already a member" is the goal state, not a failure. This happens
|
||||||
|
// routinely: groupOfNames requires at least one member, so creating a
|
||||||
|
// resource seeds its auto-created groups with the creator's DN, and an
|
||||||
|
// admin may also grant access by hand while a request sits pending.
|
||||||
|
// Without this the request would 500 and stay pending forever.
|
||||||
|
const alreadyMember = err.name === 'TypeOrValueExistsError' || err.code === 20;
|
||||||
|
if (!alreadyMember) throw err;
|
||||||
|
}
|
||||||
|
User.clearCache(); // membership feeds cached isAdmin / group-gated nav
|
||||||
|
|
||||||
|
const updated = await request.update({
|
||||||
|
status: STATUS.APPROVED,
|
||||||
|
decidedBy: req.user.uid,
|
||||||
|
decidedOn: Date.now(),
|
||||||
|
decisionNote: req.body.decisionNote || '',
|
||||||
|
});
|
||||||
|
|
||||||
|
await notify(
|
||||||
|
request.uid,
|
||||||
|
`Access approved: ${resource ? resource.name : request.groupCn}`,
|
||||||
|
`<p>Your request for <strong>${resource ? resource.name : request.groupCn}</strong> was approved by ${req.user.uid}.</p>` +
|
||||||
|
`<p>You may need to sign out and back in for the change to take effect everywhere.</p>`
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json(envelope(updated));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/access-requests/:id/deny { decisionNote? }
|
||||||
|
router.post('/:id/deny', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const request = await AccessRequest.get(req.params.id);
|
||||||
|
if (!request) throw httpError(404, 'Request not found');
|
||||||
|
if (request.status !== STATUS.PENDING) {
|
||||||
|
throw httpError(409, `This request was already ${request.status}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const resource = await Resource.get(request.resourceId);
|
||||||
|
const callerGroups = await groupCns(req.user);
|
||||||
|
if (!(await canDecide(req.user, resource, callerGroups))) {
|
||||||
|
throw httpError(403, 'You do not have permission to decide this request.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await request.update({
|
||||||
|
status: STATUS.DENIED,
|
||||||
|
decidedBy: req.user.uid,
|
||||||
|
decidedOn: Date.now(),
|
||||||
|
decisionNote: req.body.decisionNote || '',
|
||||||
|
});
|
||||||
|
|
||||||
|
await notify(
|
||||||
|
request.uid,
|
||||||
|
`Access request declined: ${resource ? resource.name : request.groupCn}`,
|
||||||
|
`<p>Your request for <strong>${resource ? resource.name : request.groupCn}</strong> was declined.</p>` +
|
||||||
|
(req.body.decisionNote ? `<p>Reason: ${req.body.decisionNote}</p>` : '')
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json(envelope(updated));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// DELETE /api/access-requests/:id — requester withdraws their own pending request.
|
||||||
|
router.delete('/:id', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const request = await AccessRequest.get(req.params.id);
|
||||||
|
if (!request) throw httpError(404, 'Request not found');
|
||||||
|
if (request.uid !== req.user.uid) {
|
||||||
|
throw httpError(403, 'You can only withdraw your own requests.');
|
||||||
|
}
|
||||||
|
if (request.status !== STATUS.PENDING) {
|
||||||
|
throw httpError(409, `This request was already ${request.status}.`);
|
||||||
|
}
|
||||||
|
const updated = await request.update({ status: STATUS.CANCELLED, decidedOn: Date.now() });
|
||||||
|
res.json(envelope(updated));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
const router = require('express').Router();
|
||||||
|
const confManager = require('../utils/conf_manager');
|
||||||
|
const permission = require('../utils/permission');
|
||||||
|
const conf = require('@simpleworkjs/conf');
|
||||||
|
|
||||||
|
router.use(async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
await permission.byGroup(req.user, ['app_sso_admin']);
|
||||||
|
next();
|
||||||
|
} catch(err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/', async (req, res) => {
|
||||||
|
const editable = {
|
||||||
|
smtp: conf.smtp || {},
|
||||||
|
discovery: conf.discovery || {},
|
||||||
|
oauth: conf.oauth || {}
|
||||||
|
};
|
||||||
|
res.json(editable);
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const existing = await confManager.getVaultConf() || {};
|
||||||
|
// Deep merge req.body into existing
|
||||||
|
for (const key of Object.keys(req.body)) {
|
||||||
|
if (typeof req.body[key] === 'object' && req.body[key] !== null && !Array.isArray(req.body[key])) {
|
||||||
|
existing[key] = { ...(existing[key] || {}), ...req.body[key] };
|
||||||
|
} else {
|
||||||
|
existing[key] = req.body[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await confManager.setVaultConf(existing);
|
||||||
|
res.json({ success: true });
|
||||||
|
} catch(err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -0,0 +1,407 @@
|
|||||||
|
'use strict';
|
||||||
|
const router = require('express').Router();
|
||||||
|
const permission = require('../utils/permission');
|
||||||
|
const { Resource, ResourceEdge, ResourceGroup } = require('../models/resource');
|
||||||
|
const { Group } = require('../models/group_ldap');
|
||||||
|
const { User } = require('../models/user_ldap');
|
||||||
|
const { cnFromDn } = require('../utils/user_groups');
|
||||||
|
const { projectResources } = require('@simpleworkjs/directory-schema');
|
||||||
|
|
||||||
|
const SUPER_ADMIN_GROUP = permission.SUPER_ADMIN_GROUP;
|
||||||
|
|
||||||
|
// Make `childCn` a member of `parentCn`, i.e. everyone in the child is
|
||||||
|
// transitively in the parent. Idempotent and non-fatal: "already a member" is
|
||||||
|
// the goal state, and a missing group (e.g. app_super_admin absent on a
|
||||||
|
// directory seeded by an older entrypoint) is a reason to skip, not to fail the
|
||||||
|
// caller's real work.
|
||||||
|
async function nestGroup(childCn, parentCn) {
|
||||||
|
try {
|
||||||
|
const parent = await Group.get(parentCn);
|
||||||
|
const child = await Group.get(childCn);
|
||||||
|
if (await Group.wouldCycle(parentCn, child.dn)) {
|
||||||
|
console.error(`nestGroup: refusing ${childCn} -> ${parentCn} (would create a cycle)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await parent.addMember({ dn: child.dn });
|
||||||
|
} catch (err) {
|
||||||
|
const benign = err.name === 'TypeOrValueExistsError' || err.code === 20 || err.name === 'GroupNotFound';
|
||||||
|
if (!benign) console.error(`nestGroup: ${childCn} -> ${parentCn} failed:`, err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Require the admin group
|
||||||
|
router.use(async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
await permission.byGroup(req.user, ['app_sso_directory_admin', 'app_sso_admin']);
|
||||||
|
next();
|
||||||
|
} catch(err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Resources ---
|
||||||
|
router.get('/resources', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
let resources = await Resource.list();
|
||||||
|
resources = resources.filter(r => {
|
||||||
|
const isAuto = r.metadata?.discovery_sources?.length > 0 && !r.metadata.discovery_sources.includes('manual');
|
||||||
|
const isManaged = r.metadata?.managed === true;
|
||||||
|
return !isAuto || isManaged;
|
||||||
|
});
|
||||||
|
// Even admins never receive secret metadata (e.g. client_secret_hash) over
|
||||||
|
// the wire; projectResources strips it unconditionally.
|
||||||
|
res.json({ results: projectResources(resources, { fullMetadata: true }) });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/resources', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
if (!req.body.hostId && req.body.parentSlug) {
|
||||||
|
const parents = await Resource.list({ where: { slug: req.body.parentSlug } });
|
||||||
|
if (parents.length > 0) req.body.hostId = parents[0].id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.body.kind === 'host' && !req.body.hostId) {
|
||||||
|
return res.status(400).json({ error: 'Hosts must have a parent Site or Host' });
|
||||||
|
}
|
||||||
|
if (req.body.kind === 'service' && !req.body.hostId) {
|
||||||
|
return res.status(400).json({ error: 'Services must have a parent Host' });
|
||||||
|
}
|
||||||
|
if (req.body.kind === 'oauth' && !req.body.hostId) {
|
||||||
|
return res.status(400).json({ error: 'OAuth Integrations must have a parent Service' });
|
||||||
|
}
|
||||||
|
|
||||||
|
req.body.owner = req.body.owner || req.user.uid;
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
req.body.created_by = req.body.created_by || req.user.uid;
|
||||||
|
req.body.created_on = now;
|
||||||
|
req.body.updated_by = req.user.uid;
|
||||||
|
req.body.updated_on = now;
|
||||||
|
|
||||||
|
let r;
|
||||||
|
if (req.body.kind === 'oauth') {
|
||||||
|
const { OAuthClient } = require('../models/oauth_client');
|
||||||
|
// Pass created_by explicitly for the wrapper (overrides the generic
|
||||||
|
// assignment above -- this is OAuthClient-wrapper-specific behavior).
|
||||||
|
req.body.created_by = req.body.owner;
|
||||||
|
// In the UI we might pass slug, but OAuthClient wrapper expects name
|
||||||
|
r = await OAuthClient.add(req.body);
|
||||||
|
} else {
|
||||||
|
r = await Resource.create(req.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((r.kind === 'host' || r.kind === 'service' || r.kind === 'oauth') && req.body.hostId) {
|
||||||
|
await ResourceEdge.create({ parentId: req.body.hostId, childId: r.id, relation: r.kind === 'oauth' ? 'oauth' : 'hosts' });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (r.kind === 'host' || r.kind === 'service') {
|
||||||
|
const siteSlug = await Resource.findAncestorSiteSlug(r.id);
|
||||||
|
const groupCn = suffix => (siteSlug ? `${siteSlug}_${r.slug}_${suffix}` : `${r.slug}_${suffix}`);
|
||||||
|
|
||||||
|
const createGroup = async (suffix, accessLevel) => {
|
||||||
|
const cn = groupCn(suffix);
|
||||||
|
try {
|
||||||
|
await Group.add({
|
||||||
|
name: cn,
|
||||||
|
owner: req.user.dn,
|
||||||
|
description: `${suffix === 'admin' ? 'Admin' : 'Access'} group for ${r.name}`
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
if (err.name !== 'EntryAlreadyExistsError' && err.code !== 68) {
|
||||||
|
console.error(`Failed to create LDAP group ${cn}:`, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await ResourceGroup.create({ resourceId: r.id, groupCn: cn, accessLevel });
|
||||||
|
} catch(err) { /* ignore duplicate links */ }
|
||||||
|
};
|
||||||
|
await createGroup('access', 'member');
|
||||||
|
await createGroup('admin', 'owner');
|
||||||
|
|
||||||
|
// Wire up the two standing relationships every resource has, as nesting
|
||||||
|
// rather than as membership that has to be maintained per resource:
|
||||||
|
//
|
||||||
|
// app_super_admin -> <slug>_admin cross-app super admins administer
|
||||||
|
// every resource, automatically
|
||||||
|
// <slug>_admin -> <slug>_access administering something implies
|
||||||
|
// being able to use it
|
||||||
|
//
|
||||||
|
// Before nesting, both of these could only be expressed by adding every
|
||||||
|
// super admin to every new group by hand -- which nobody does, so the
|
||||||
|
// groups drifted. A failure here must not fail resource creation: the
|
||||||
|
// resource and its groups already exist and the nesting is repairable.
|
||||||
|
await nestGroup(groupCn('admin'), groupCn('access'));
|
||||||
|
await nestGroup(SUPER_ADMIN_GROUP, groupCn('admin'));
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ results: r });
|
||||||
|
} catch (err) {
|
||||||
|
if (err.name === 'SequelizeUniqueConstraintError') {
|
||||||
|
return res.status(400).json({ error: 'A resource with this slug already exists.' });
|
||||||
|
}
|
||||||
|
if (err.name === 'SequelizeValidationError') {
|
||||||
|
return res.status(400).json({ error: err.message });
|
||||||
|
}
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.put('/resources/:id', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
// Validate before loading anything -- a rejected body should never have
|
||||||
|
// touched the store.
|
||||||
|
if (req.body.kind === 'host' && !req.body.hostId) {
|
||||||
|
return res.status(400).json({ error: 'Hosts must have a parent Site or Host' });
|
||||||
|
}
|
||||||
|
if (req.body.kind === 'service' && !req.body.hostId) {
|
||||||
|
return res.status(400).json({ error: 'Services must have a parent Host' });
|
||||||
|
}
|
||||||
|
if (req.body.kind === 'oauth' && !req.body.hostId) {
|
||||||
|
return res.status(400).json({ error: 'OAuth Integrations must have a parent Service' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// OAuthClient is a wrapper over the same `resource` row, but its .update()
|
||||||
|
// handles the oauth-specific body fields (redirect_uris, scopes,
|
||||||
|
// token_lifetime) that a bare Resource would drop into metadata unvalidated.
|
||||||
|
const { OAuthClient } = require('../models/oauth_client');
|
||||||
|
const model = req.body.kind === 'oauth' ? OAuthClient : Resource;
|
||||||
|
const r = await model.get(req.params.id);
|
||||||
|
if (!r) return res.status(404).json({ error: 'Not found' });
|
||||||
|
|
||||||
|
req.body.updated_by = req.user.uid;
|
||||||
|
req.body.updated_on = Date.now();
|
||||||
|
|
||||||
|
const updated = await r.update(req.body);
|
||||||
|
|
||||||
|
if ((updated.kind === 'host' || updated.kind === 'service' || updated.kind === 'oauth') && req.body.hostId !== undefined) {
|
||||||
|
const existingEdges = await ResourceEdge.list({ where: { childId: r.id } });
|
||||||
|
for (const e of existingEdges) {
|
||||||
|
if (e.relation === 'hosts' || e.relation === 'oauth') await e.delete();
|
||||||
|
}
|
||||||
|
if (req.body.hostId) {
|
||||||
|
await ResourceEdge.create({ parentId: req.body.hostId, childId: r.id, relation: updated.kind === 'oauth' ? 'oauth' : 'hosts' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ results: updated });
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/resources/:id/rotate-secret', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { OAuthClient } = require('../models/oauth_client');
|
||||||
|
const client = await OAuthClient.get(req.params.id);
|
||||||
|
const secret = await client.rotateSecret();
|
||||||
|
res.json({ secret });
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete('/resources/:id', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const r = await Resource.get(req.params.id);
|
||||||
|
if (!r) return res.status(404).json({ error: 'Not found' });
|
||||||
|
// Clear the dependents FIRST. There is no transaction here, so ordering is
|
||||||
|
// the only thing protecting us: if a dependent delete throws after the
|
||||||
|
// resource row is gone, the leftovers are edges/links pointing at a
|
||||||
|
// nonexistent id -- invisible in the UI and poisonous to getGraph(). Failing
|
||||||
|
// with the resource still present is the recoverable direction (retry the
|
||||||
|
// delete); the caller sees the error either way.
|
||||||
|
const edgesParent = await ResourceEdge.list({ where: { parentId: req.params.id } });
|
||||||
|
const edgesChild = await ResourceEdge.list({ where: { childId: req.params.id } });
|
||||||
|
const groups = await ResourceGroup.list({ where: { resourceId: req.params.id } });
|
||||||
|
for (const e of [...edgesParent, ...edgesChild]) await e.delete();
|
||||||
|
for (const g of groups) await g.delete();
|
||||||
|
await r.delete();
|
||||||
|
res.json({ results: true });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Edges ---
|
||||||
|
router.get('/edges', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const edges = await ResourceEdge.list();
|
||||||
|
res.json({ results: edges });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/edges', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const edge = await ResourceEdge.create(req.body);
|
||||||
|
res.json({ results: edge });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete('/edges/:id', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const edge = await ResourceEdge.get(req.params.id);
|
||||||
|
if (!edge) return res.status(404).json({ error: 'Not found' });
|
||||||
|
await edge.delete();
|
||||||
|
res.json({ results: true });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Groups ---
|
||||||
|
router.get('/groups', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const groups = await ResourceGroup.list();
|
||||||
|
res.json({ results: groups });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/groups', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const g = await ResourceGroup.create(req.body);
|
||||||
|
res.json({ results: g });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete('/groups/:id', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const g = await ResourceGroup.get(req.params.id);
|
||||||
|
if (!g) return res.status(404).json({ error: 'Not found' });
|
||||||
|
await g.delete();
|
||||||
|
res.json({ results: true });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Access visibility ---
|
||||||
|
//
|
||||||
|
// The two questions an access-control pane has to answer, neither of which the
|
||||||
|
// directory could answer before: "who can reach this resource" (a column on the
|
||||||
|
// table, rather than three clicks into a modal) and "what can this user reach"
|
||||||
|
// (which had no UI at all). Both are joins of the same two sets, so both are
|
||||||
|
// served from one cached Group.listDetail() rather than a lookup per row.
|
||||||
|
|
||||||
|
// dn -> uid, so member DNs can be reported as the uids admins actually think in.
|
||||||
|
async function dnToUidMap() {
|
||||||
|
const users = await User.listDetail();
|
||||||
|
return new Map(users.map(u => [String(u.dn).toLowerCase(), u.uid]));
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /access-summary — { resourceId: { groups: [...], memberCount } }
|
||||||
|
router.get('/access-summary', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const [links, groups, uidByDn] = await Promise.all([
|
||||||
|
ResourceGroup.list(),
|
||||||
|
Group.listDetail(),
|
||||||
|
dnToUidMap(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const groupByCn = new Map(groups.map(g => [g.cn, g]));
|
||||||
|
const summary = {};
|
||||||
|
|
||||||
|
for (const link of links) {
|
||||||
|
const group = groupByCn.get(link.groupCn);
|
||||||
|
// A link whose LDAP group has been deleted out from under it: report it
|
||||||
|
// rather than skipping, since a dangling link grants nothing and the
|
||||||
|
// admin needs to see that it is dead.
|
||||||
|
//
|
||||||
|
// Counts come from the transitive closure, not from `member`. Reading the
|
||||||
|
// attribute would report only who is listed on the group, missing anyone
|
||||||
|
// who reaches it through a nested group -- and since app_super_admin is
|
||||||
|
// nested into every resource's _admin group, that is not an edge case.
|
||||||
|
let members = [];
|
||||||
|
if (group) {
|
||||||
|
const eff = await Group.effectiveMembers(link.groupCn);
|
||||||
|
members = eff.effective.map(dn => uidByDn.get(String(dn).toLowerCase()) || cnFromDn(dn));
|
||||||
|
}
|
||||||
|
|
||||||
|
const entry = summary[link.resourceId] || (summary[link.resourceId] = { groups: [], members: [] });
|
||||||
|
entry.groups.push({
|
||||||
|
cn: link.groupCn,
|
||||||
|
accessLevel: link.accessLevel,
|
||||||
|
exists: !!group,
|
||||||
|
memberCount: members.length,
|
||||||
|
});
|
||||||
|
for (const uid of members) {
|
||||||
|
if (!entry.members.includes(uid)) entry.members.push(uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const id of Object.keys(summary)) {
|
||||||
|
summary[id].memberCount = summary[id].members.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ results: summary });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /user-access/:uid — every resource a given user can reach, and via which
|
||||||
|
// group. This is the reverse lookup; previously an admin could only see their
|
||||||
|
// own access, via /api/discovery/me.
|
||||||
|
router.get('/user-access/:uid', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const user = await User.get({ uid: req.params.uid });
|
||||||
|
if (!user) return res.status(404).json({ error: 'User not found' });
|
||||||
|
|
||||||
|
const dn = String(user.dn).toLowerCase();
|
||||||
|
const groups = await Group.listDetail();
|
||||||
|
const memberOf = groups
|
||||||
|
.filter(g => [].concat(g.member || []).some(m => String(m).toLowerCase() === dn))
|
||||||
|
.map(g => g.cn);
|
||||||
|
|
||||||
|
const [links, resources] = await Promise.all([ResourceGroup.list(), Resource.list()]);
|
||||||
|
const byId = new Map(resources.map(r => [r.id, r]));
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
for (const link of links) {
|
||||||
|
if (!memberOf.includes(link.groupCn)) continue;
|
||||||
|
const resource = byId.get(link.resourceId);
|
||||||
|
if (!resource) continue;
|
||||||
|
results.push({
|
||||||
|
id: resource.id,
|
||||||
|
name: resource.name,
|
||||||
|
slug: resource.slug,
|
||||||
|
kind: resource.kind,
|
||||||
|
groupCn: link.groupCn,
|
||||||
|
accessLevel: link.accessLevel,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ results: { uid: user.uid, groups: memberOf, resources: results } });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Tail the last `lines` lines of a log file without shelling out. Reads at most
|
||||||
|
// the trailing MAX_TAIL_BYTES so an unrotated multi-GB log can't blow up the
|
||||||
|
// heap. A missing/unreadable file is normal (the log only exists once slapd has
|
||||||
|
// written to it), so it yields '' rather than an error.
|
||||||
|
const MAX_TAIL_BYTES = 256 * 1024;
|
||||||
|
|
||||||
|
async function tailFile(filePath, lines = 100) {
|
||||||
|
const fs = require('fs/promises');
|
||||||
|
let fh;
|
||||||
|
try {
|
||||||
|
fh = await fs.open(filePath, 'r');
|
||||||
|
const { size } = await fh.stat();
|
||||||
|
const start = Math.max(0, size - MAX_TAIL_BYTES);
|
||||||
|
const buf = Buffer.alloc(Math.min(size, MAX_TAIL_BYTES));
|
||||||
|
await fh.read(buf, 0, buf.length, start);
|
||||||
|
const text = buf.toString('utf8');
|
||||||
|
// A partial first line when we started mid-file; drop it.
|
||||||
|
const rows = (start > 0 ? text.slice(text.indexOf('\n') + 1) : text).split('\n');
|
||||||
|
return rows.slice(-lines).join('\n');
|
||||||
|
} catch (err) {
|
||||||
|
return '';
|
||||||
|
} finally {
|
||||||
|
if (fh) await fh.close().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
router.get('/audit-logs', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const [ldap, oauth, audit] = await Promise.all([
|
||||||
|
tailFile('/var/lib/ldap/slapd.log'),
|
||||||
|
tailFile('/var/lib/ldap/oauth.log'),
|
||||||
|
tailFile('/var/lib/ldap/auditlog.ldif'),
|
||||||
|
]);
|
||||||
|
res.json({ results: { ldap, oauth, audit } });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
'use strict';
|
||||||
|
const router = require('express').Router();
|
||||||
|
const permission = require('../utils/permission');
|
||||||
|
const metrics = require('../utils/metrics');
|
||||||
|
|
||||||
|
// /api/metrics/overview
|
||||||
|
router.get('/overview', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
await permission.byGroup(req.user, ['app_sso_admin']);
|
||||||
|
|
||||||
|
const topIps = await metrics.getTopN('metrics:failed_ips', 7, 5);
|
||||||
|
const topUsers = await metrics.getTopN('metrics:failed_users', 7, 5);
|
||||||
|
const topServices = await metrics.getTopN('metrics:service_usage', 7, 5);
|
||||||
|
|
||||||
|
res.json({ results: { ips: topIps, users: topUsers, services: topServices } });
|
||||||
|
} catch(e) {
|
||||||
|
next(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// /api/metrics/user/:uid
|
||||||
|
router.get('/user/:uid', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
// Can only view if admin or self
|
||||||
|
if (req.user.uid !== req.params.uid) {
|
||||||
|
await permission.byGroup(req.user, ['app_sso_admin']);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Failed logins for user is hard if we didn't track it by user, but wait, we did! metrics:failed_users:YYYY-MM-DD
|
||||||
|
// However, we didn't track failed IPs per user. We tracked failed_users as a sorted set.
|
||||||
|
// To get the user's failures, we just query their score from the union.
|
||||||
|
|
||||||
|
// Wait, for services we have user_service_usage:<uid>:<date>. No, in metrics.js I wrote:
|
||||||
|
// `metrics:user_service_usage:${username}:${date}`
|
||||||
|
|
||||||
|
const topServices = await metrics.getTopN('metrics:user_service_usage', 7, 5, req.params.uid);
|
||||||
|
|
||||||
|
res.json({ results: { services: topServices } });
|
||||||
|
} catch(e) {
|
||||||
|
next(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -13,6 +13,7 @@ const middleware = require('../middleware/auth');
|
|||||||
const rateLimit = require('../middleware/rate_limit');
|
const rateLimit = require('../middleware/rate_limit');
|
||||||
const permission = require('../utils/permission');
|
const permission = require('../utils/permission');
|
||||||
const conf = require('@simpleworkjs/conf');
|
const conf = require('@simpleworkjs/conf');
|
||||||
|
const metrics = require('../utils/metrics');
|
||||||
|
|
||||||
async function findUserByLogin(login) {
|
async function findUserByLogin(login) {
|
||||||
try {
|
try {
|
||||||
@@ -37,12 +38,16 @@ router.get('/username-suggestions', async function(req, res, next) {
|
|||||||
router.post('/login', rateLimit.login, async function(req, res, next){
|
router.post('/login', rateLimit.login, async function(req, res, next){
|
||||||
try{
|
try{
|
||||||
let auth = await Auth.login(req.body);
|
let auth = await Auth.login(req.body);
|
||||||
|
metrics.recordServiceUsage('SSO Web UI', req.body.uid);
|
||||||
return res.json({
|
return res.json({
|
||||||
login: true,
|
login: true,
|
||||||
token: auth.token.token,
|
token: auth.token.token,
|
||||||
message:`${req.body.uid} logged in!`,
|
message:`${req.body.uid} logged in!`,
|
||||||
});
|
});
|
||||||
}catch(error){
|
}catch(error){
|
||||||
|
if (error.name === 'LDAPLoginFailed' || error.status === 401 || error.name === 'UserNotFound') {
|
||||||
|
metrics.recordFailedLogin(req.ip, req.body.uid);
|
||||||
|
}
|
||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -198,7 +203,7 @@ router.post('/impersonate/:uid', middleware.auth, async function(req, res, next)
|
|||||||
const target = await User.get(req.params.uid);
|
const target = await User.get(req.params.uid);
|
||||||
|
|
||||||
// Clean up any existing impersonation for this target
|
// Clean up any existing impersonation for this target
|
||||||
const existing = await ImpersonationToken.listDetail({ target_uid: target.uid });
|
const existing = await ImpersonationToken.list({ where: { target_uid: target.uid } });
|
||||||
for (const old of existing) {
|
for (const old of existing) {
|
||||||
if (old.is_valid && !old.isExpired) {
|
if (old.is_valid && !old.isExpired) {
|
||||||
try { await target.removeTempPassword(old.temp_hash); } catch(_) {}
|
try { await target.removeTempPassword(old.temp_hash); } catch(_) {}
|
||||||
@@ -232,7 +237,7 @@ router.delete('/impersonate/:uid', middleware.auth, async function(req, res, nex
|
|||||||
await permission.byGroup(req.user, ['app_sso_admin']);
|
await permission.byGroup(req.user, ['app_sso_admin']);
|
||||||
|
|
||||||
const target = await User.get(req.params.uid);
|
const target = await User.get(req.params.uid);
|
||||||
const existing = await ImpersonationToken.listDetail({ target_uid: target.uid });
|
const existing = await ImpersonationToken.list({ where: { target_uid: target.uid } });
|
||||||
|
|
||||||
let revoked = 0;
|
let revoked = 0;
|
||||||
for (const token of existing) {
|
for (const token of existing) {
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
const express = require('express');
|
||||||
|
|
||||||
|
// Parses arguments according to the exposed method config.
|
||||||
|
// Extended to support { from: 'user' } which injects `req.user.dn` (LDAP integration).
|
||||||
|
function extractArgs(req, cfg) {
|
||||||
|
const args = cfg.args;
|
||||||
|
if (!args) return [];
|
||||||
|
if (args.from === 'user') return [req.user.dn];
|
||||||
|
|
||||||
|
const source = args.from === 'params' ? req.params
|
||||||
|
: args.from === 'query' ? req.query
|
||||||
|
: req.body;
|
||||||
|
|
||||||
|
if (Array.isArray(args.names)) return args.names.map(name => source[name]);
|
||||||
|
return [source || {}];
|
||||||
|
}
|
||||||
|
|
||||||
|
// A mini-auto-router that reads `static exposedMethods` from a @simpleworkjs/orm Model
|
||||||
|
// and maps them directly into Express endpoints.
|
||||||
|
function autoRouter(Model) {
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
if (Model.getExposedMethods) {
|
||||||
|
for (const cfg of Model.getExposedMethods()) {
|
||||||
|
router[cfg.verb](cfg.routePath, async function(req, res, next) {
|
||||||
|
try {
|
||||||
|
// In a full implementation, we'd load the instance if cfg.kind === 'instance'.
|
||||||
|
// For now, our methods are all static class methods.
|
||||||
|
const target = Model;
|
||||||
|
const result = await target[cfg.method](...extractArgs(req, cfg));
|
||||||
|
res.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return router;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = autoRouter;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
const router = require('express').Router();
|
||||||
|
const permission = require('../utils/permission');
|
||||||
|
|
||||||
|
router.use(async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
await permission.byGroup(req.user, ['app_sso_admin']);
|
||||||
|
next();
|
||||||
|
} catch(err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/', (req, res) => {
|
||||||
|
res.render('conf', {
|
||||||
|
title: 'Configuration',
|
||||||
|
user: req.user
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Public directory discovery API. Mounted at /api/discovery (app.js, before
|
||||||
|
// the 404 catcher). Every response uses the `{ results }` envelope and the
|
||||||
|
// security projection from @simpleworkjs/directory-schema, so secrets (e.g. an
|
||||||
|
// OAuth client's client_secret_hash) never leave the server and non-admins only
|
||||||
|
// see the public metadata allowlist.
|
||||||
|
//
|
||||||
|
// This replaces the autoRouter mount (which returned bare arrays — the shape
|
||||||
|
// jump-host's `data.results || []` silently collapsed to `[]`, so no user could
|
||||||
|
// bridge) and absorbs the dead /me handler that used to live in
|
||||||
|
// routes/api_discovery.js (mounted after the 404, so unreachable).
|
||||||
|
//
|
||||||
|
// Group CNs come from utils/user_groups — `req.user` has `memberOf` (DNs) and
|
||||||
|
// no `.groups`, so reading `.groups` off it directly yields [] for every human
|
||||||
|
// caller. See that file for what that silently broke.
|
||||||
|
|
||||||
|
const router = require('express').Router();
|
||||||
|
const { Resource, ResourceGroup } = require('../models/resource');
|
||||||
|
const { withGroups } = require('../utils/user_groups');
|
||||||
|
const {
|
||||||
|
envelope,
|
||||||
|
projectResource,
|
||||||
|
projectResources,
|
||||||
|
isDirectoryAdmin,
|
||||||
|
} = require('@simpleworkjs/directory-schema');
|
||||||
|
|
||||||
|
// Resolve the caller's groups once per request and hand back the projection
|
||||||
|
// flag. Every handler needs both, and both are wrong if taken off req.user raw.
|
||||||
|
async function callerView(req) {
|
||||||
|
const user = await withGroups(req.user);
|
||||||
|
return { user, fullMetadata: isDirectoryAdmin(user) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /api/discovery/resources[?kind=&group=&parent=]
|
||||||
|
router.get('/resources', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { fullMetadata } = await callerView(req);
|
||||||
|
const resources = await Resource.search(req.query);
|
||||||
|
res.json(envelope(projectResources(resources, { fullMetadata })));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/discovery/resources/:slug
|
||||||
|
router.get('/resources/:slug', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { fullMetadata } = await callerView(req);
|
||||||
|
const resource = await Resource.getBySlug(req.params.slug);
|
||||||
|
// parents/children are edges (no secrets); project only the resource body.
|
||||||
|
const projected = projectResource(resource, { fullMetadata });
|
||||||
|
projected.parents = resource.parents;
|
||||||
|
projected.children = resource.children;
|
||||||
|
res.json(envelope(projected));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/discovery/graph
|
||||||
|
router.get('/graph', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { fullMetadata } = await callerView(req);
|
||||||
|
const graph = await Resource.getGraph();
|
||||||
|
res.json(envelope({
|
||||||
|
resources: projectResources(graph.resources, { fullMetadata }),
|
||||||
|
edges: graph.edges,
|
||||||
|
}));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/discovery/me
|
||||||
|
// Returns the resources the current caller can reach. Machines see only their
|
||||||
|
// own resource; humans get the union of their LDAP groups' resources plus
|
||||||
|
// anything flagged isPublic.
|
||||||
|
router.get('/me', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { user, fullMetadata } = await callerView(req);
|
||||||
|
let accessible;
|
||||||
|
if (req.user && req.user.isMachine) {
|
||||||
|
accessible = await Resource.list({ where: { id: req.resourceId } });
|
||||||
|
} else {
|
||||||
|
const ids = new Set();
|
||||||
|
if (user.groups.length) {
|
||||||
|
const rgs = await ResourceGroup.list({ where: { groupCn: { in: user.groups } } });
|
||||||
|
for (const rg of rgs) ids.add(rg.resourceId);
|
||||||
|
}
|
||||||
|
const all = await Resource.list();
|
||||||
|
accessible = all.filter(r => {
|
||||||
|
const isAuto = r.metadata?.discovery_sources?.length > 0 && !r.metadata.discovery_sources.includes('manual');
|
||||||
|
const isManaged = r.metadata?.managed === true;
|
||||||
|
if (isAuto && !isManaged) return false;
|
||||||
|
return ids.has(r.id) || (r.metadata && r.metadata.isPublic);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// resolvedAddress is the whole point of /me ("how do I reach it") and a
|
||||||
|
// service inherits it from its host, so it must be computed here rather
|
||||||
|
// than left to each caller to guess at address || ip.
|
||||||
|
accessible = await Resource.withResolvedAddress(accessible);
|
||||||
|
res.json(envelope(projectResources(accessible, { fullMetadata })));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/discovery/sync
|
||||||
|
// Used by external agents (e.g. ldap-client) to push discovery data.
|
||||||
|
router.post('/sync', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { DiscoveryReconciler } = require('../services/discovery_reconciler');
|
||||||
|
// Assuming the caller provides a source name and payload
|
||||||
|
const source = req.body.source || 'agent';
|
||||||
|
await DiscoveryReconciler.reconcile(source, req.body.payload || req.body);
|
||||||
|
res.json(envelope({ success: true }));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/discovery/promote/:slug
|
||||||
|
// Promotes an unmanaged device to managed by creating its LDAP groups.
|
||||||
|
router.post('/promote/:slug', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const resource = await Resource.getBySlug(req.params.slug);
|
||||||
|
if (!resource) return res.status(404).json(envelope({ error: 'Not found' }));
|
||||||
|
|
||||||
|
const { Group } = require('../models/group_ldap');
|
||||||
|
|
||||||
|
const accessGroup = `${resource.slug}_access`;
|
||||||
|
const adminGroup = `${resource.slug}_admin`;
|
||||||
|
|
||||||
|
// Create groups if they don't exist
|
||||||
|
try { await Group.get(accessGroup); } catch (e) {
|
||||||
|
if (e.status === 404) await Group.add({ name: accessGroup, description: `Access to ${resource.name}`, owner: req.user.dn });
|
||||||
|
else throw e;
|
||||||
|
}
|
||||||
|
try { await Group.get(adminGroup); } catch (e) {
|
||||||
|
if (e.status === 404) await Group.add({ name: adminGroup, description: `Admin access to ${resource.name}`, owner: req.user.dn });
|
||||||
|
else throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Link them
|
||||||
|
const crypto = require('crypto');
|
||||||
|
await ResourceGroup.create({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
resourceId: resource.id,
|
||||||
|
groupCn: accessGroup,
|
||||||
|
accessLevel: 'user'
|
||||||
|
});
|
||||||
|
await ResourceGroup.create({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
resourceId: resource.id,
|
||||||
|
groupCn: adminGroup,
|
||||||
|
accessLevel: 'admin'
|
||||||
|
});
|
||||||
|
|
||||||
|
const meta = resource.metadata || {};
|
||||||
|
meta.managed = true;
|
||||||
|
await resource.update({ metadata: meta });
|
||||||
|
|
||||||
|
res.json(envelope({ success: true, groups: [accessGroup, adminGroup] }));
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -4,6 +4,7 @@ const fs = require('fs');
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
const router = require('express').Router();
|
const router = require('express').Router();
|
||||||
const {marked} = require('marked');
|
const {marked} = require('marked');
|
||||||
|
const xss = require('xss');
|
||||||
const conf = require('@simpleworkjs/conf');
|
const conf = require('@simpleworkjs/conf');
|
||||||
const buildInfo = require('../utils/build_info');
|
const buildInfo = require('../utils/build_info');
|
||||||
const rateLimit = require('../middleware/rate_limit');
|
const rateLimit = require('../middleware/rate_limit');
|
||||||
@@ -25,6 +26,17 @@ const values = {
|
|||||||
// back at the root DEPLOYMENT.md (see docs/deployment.md itself), which is
|
// back at the root DEPLOYMENT.md (see docs/deployment.md itself), which is
|
||||||
// already covered by the "deployment" entry.
|
// already covered by the "deployment" entry.
|
||||||
const DOCS = {
|
const DOCS = {
|
||||||
|
// Plain-language "what is this and why would I use it" guides -- linked
|
||||||
|
// directly from the relevant card in the UI (see the help icon on each
|
||||||
|
// card). Each links onward to the deeper technical doc below for readers
|
||||||
|
// who want the schema/protocol-level detail.
|
||||||
|
accounts: {title: 'Accounts, Groups & Managers', file: path.join(__dirname, '../../docs/concepts-accounts.md')},
|
||||||
|
'oauth-apps': {title: 'Connecting Apps (SSO)', file: path.join(__dirname, '../../docs/concepts-oauth-apps.md')},
|
||||||
|
'api-tokens': {title: 'API Tokens', file: path.join(__dirname, '../../docs/concepts-api-tokens.md')},
|
||||||
|
directory: {title: 'Directory & Inventory', file: path.join(__dirname, '../../docs/directory.md')},
|
||||||
|
agents: {title: 'Agents & Scheduler', file: path.join(__dirname, '../../docs/agents.md')},
|
||||||
|
vault: {title: 'Vault Secrets', file: path.join(__dirname, '../../docs/vault.md')},
|
||||||
|
|
||||||
overview: {title: 'Overview', file: path.join(__dirname, '../../README.md')},
|
overview: {title: 'Overview', file: path.join(__dirname, '../../README.md')},
|
||||||
changelog: {title: 'Changelog', file: path.join(__dirname, '../../CHANGELOG.md')},
|
changelog: {title: 'Changelog', file: path.join(__dirname, '../../CHANGELOG.md')},
|
||||||
deployment: {title: 'Deployment', file: path.join(__dirname, '../../DEPLOYMENT.md')},
|
deployment: {title: 'Deployment', file: path.join(__dirname, '../../DEPLOYMENT.md')},
|
||||||
@@ -46,24 +58,84 @@ function fixImagePaths(html) {
|
|||||||
return html.replace(/(["(])docs\/images\//g, '$1/docs/images/');
|
return html.replace(/(["(])docs\/images\//g, '$1/docs/images/');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Docs cross-link each other as "<slug>.html" (correct for the Jekyll/GitHub
|
||||||
|
// Pages build, which is what these same .md files also feed) and
|
||||||
|
// "index.html" for the docs home -- neither resolves here, where a doc lives
|
||||||
|
// at /docs/<slug> with no .html suffix. Rewrite known doc links to the
|
||||||
|
// in-app route, same idea as fixImagePaths() above. Only touches slugs that
|
||||||
|
// actually exist, so an unrelated "foo.html" link is left alone.
|
||||||
|
// Docs are also linked by their real filename stem (e.g. "concepts-accounts.html"
|
||||||
|
// for docs/concepts-accounts.md) -- the correct, working link on the Jekyll/
|
||||||
|
// GitHub Pages build, where the URL IS the filename stem. That doesn't match
|
||||||
|
// this viewer's own short slugs (DOCS keys, e.g. "accounts"), so also resolve
|
||||||
|
// by filename as a fallback -- one link written in a doc works correctly on
|
||||||
|
// both targets, rather than needing two different link forms.
|
||||||
|
const slugByFilename = Object.fromEntries(
|
||||||
|
Object.entries(DOCS).map(([slug, d]) => [path.basename(d.file, '.md'), slug])
|
||||||
|
);
|
||||||
|
function fixDocLinks(html) {
|
||||||
|
return html
|
||||||
|
.replace(/href="index\.html"/g, 'href="/docs"')
|
||||||
|
.replace(/href="([a-z0-9-]+)\.html"/g, (match, name) => {
|
||||||
|
const slug = DOCS[name] ? name : slugByFilename[name];
|
||||||
|
return slug ? `href="/docs/${slug}"` : match;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// docs/*.md files (not the repo-root README/CHANGELOG/API.md) carry Jekyll
|
||||||
|
// front matter for the GitHub Pages build and a "← Back to Home" link back
|
||||||
|
// to that site's index -- both meaningless here (this viewer has its own
|
||||||
|
// doc-list sidebar, docs_page.ejs) and, worse, marked() doesn't know front
|
||||||
|
// matter isn't regular markdown: it rendered as a garbled heading + stray
|
||||||
|
// <hr> at the top of every page. Strip both before rendering.
|
||||||
|
function stripJekyllCruft(content) {
|
||||||
|
return content
|
||||||
|
.replace(/^---\n[\s\S]*?\n---\n/, '')
|
||||||
|
.replace(/^\s*\[← Back to Home\]\([^)]*\)\s*\n/m, '');
|
||||||
|
}
|
||||||
|
|
||||||
router.use(rateLimit.docs);
|
router.use(rateLimit.docs);
|
||||||
|
|
||||||
router.get('/', function(req, res) {
|
router.get('/', function(req, res) {
|
||||||
res.render('docs_index', {...values, docs: docList});
|
res.render('docs_index', {...values, docs: docList});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Plain, dependency-free line-substring search over the same allowlisted
|
||||||
|
// doc set -- no separate index to build/maintain, no new dependency, and it
|
||||||
|
// keeps working with no internet access (same reasoning as the rest of this
|
||||||
|
// route). Must be registered before the /:slug catch-all below, or "search"
|
||||||
|
// would be treated as a (nonexistent) doc slug and 404.
|
||||||
|
router.get('/search', function(req, res) {
|
||||||
|
const q = (req.query.q || '').trim();
|
||||||
|
if (!q) return res.json({results: []});
|
||||||
|
const qLower = q.toLowerCase();
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
for (const [slug, doc] of Object.entries(DOCS)) {
|
||||||
|
try {
|
||||||
|
const content = stripJekyllCruft(fs.readFileSync(doc.file, 'utf8'));
|
||||||
|
const matchLine = content.split('\n').find(line => line.toLowerCase().includes(qLower));
|
||||||
|
if (matchLine) {
|
||||||
|
results.push({slug, title: doc.title, snippet: matchLine.trim().slice(0, 200)});
|
||||||
|
}
|
||||||
|
} catch (error) { /* unreadable doc file -- skip it */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({results});
|
||||||
|
});
|
||||||
|
|
||||||
router.get('/:slug', function(req, res, next) {
|
router.get('/:slug', function(req, res, next) {
|
||||||
const doc = DOCS[req.params.slug];
|
const doc = DOCS[req.params.slug];
|
||||||
if (!doc) return next({status: 404, message: 'Doc not found'});
|
if (!doc) return next({status: 404, message: 'Doc not found'});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const content = fs.readFileSync(doc.file, 'utf8');
|
const content = stripJekyllCruft(fs.readFileSync(doc.file, 'utf8'));
|
||||||
res.render('docs_page', {
|
res.render('docs_page', {
|
||||||
...values,
|
...values,
|
||||||
docs: docList,
|
docs: docList,
|
||||||
currentSlug: req.params.slug,
|
currentSlug: req.params.slug,
|
||||||
docTitle: doc.title,
|
docTitle: doc.title,
|
||||||
docHtml: fixImagePaths(marked(content)),
|
docHtml: xss(fixDocLinks(fixImagePaths(marked(content)))),
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
next(error);
|
next(error);
|
||||||
|
|||||||
@@ -43,6 +43,87 @@ router.get('/:name', async function(req, res, next){
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── Nested groups ───────────────────────────────────────────────────────────
|
||||||
|
// A groupOfNames `member` may be any DN, including another group's, which is
|
||||||
|
// how nesting is stored. These routes are mounted before /:group/:uid so the
|
||||||
|
// literal "nested"/"effective" path segments are not swallowed by that
|
||||||
|
// wildcard, which would otherwise try to resolve them as a uid.
|
||||||
|
|
||||||
|
// GET /api/group/:group/effective — who this group actually grants, split into
|
||||||
|
// directly-listed users, the groups nested into it, and the full transitive set
|
||||||
|
// of users. The UI shows "3 direct, 12 effective"; a plain member read cannot
|
||||||
|
// answer that, and on a server with nestgroup it silently returns the expanded
|
||||||
|
// list with no indication which entries are direct.
|
||||||
|
router.get('/:group/effective', async function(req, res, next){
|
||||||
|
try{
|
||||||
|
return res.json({ results: await Group.effectiveMembers(req.params.group) });
|
||||||
|
}catch(error){
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// PUT /api/group/:group/nested/:child — nest :child inside :group.
|
||||||
|
router.put('/:group/nested/:child', async function(req, res, next){
|
||||||
|
try{
|
||||||
|
await permission.byGroup(req.user, ['app_sso_admin'], [req.params.group]);
|
||||||
|
|
||||||
|
const parent = await Group.get(req.params.group);
|
||||||
|
const child = await Group.get(req.params.child);
|
||||||
|
|
||||||
|
if(parent.dn === child.dn){
|
||||||
|
return res.status(400).json({message: 'A group cannot contain itself.'});
|
||||||
|
}
|
||||||
|
// Refuse rather than rely on the resolver's depth cap: a cycle makes
|
||||||
|
// "who is in this group" unanswerable, and the cap would quietly return
|
||||||
|
// a truncated answer instead of an error anyone would notice.
|
||||||
|
if(await Group.wouldCycle(req.params.group, child.dn)){
|
||||||
|
return res.status(409).json({
|
||||||
|
message: `"${req.params.child}" already contains "${req.params.group}" — nesting them would create a loop.`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = await parent.addMember({dn: child.dn});
|
||||||
|
User.clearCache();
|
||||||
|
return res.json({
|
||||||
|
results,
|
||||||
|
message: `Nested ${req.params.child} inside ${req.params.group}.`
|
||||||
|
});
|
||||||
|
}catch(error){
|
||||||
|
if(error.name === 'TypeOrValueExistsError' || error.code === 20){
|
||||||
|
return res.status(409).json({message: `"${req.params.child}" is already nested in "${req.params.group}".`});
|
||||||
|
}
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// DELETE /api/group/:group/nested/:child — un-nest.
|
||||||
|
router.delete('/:group/nested/:child', async function(req, res, next){
|
||||||
|
try{
|
||||||
|
await permission.byGroup(req.user, ['app_sso_admin'], [req.params.group]);
|
||||||
|
|
||||||
|
const parent = await Group.get(req.params.group);
|
||||||
|
const child = await Group.get(req.params.child);
|
||||||
|
const results = await parent.removeMember({dn: child.dn});
|
||||||
|
User.clearCache();
|
||||||
|
return res.json({
|
||||||
|
results,
|
||||||
|
message: `Removed ${req.params.child} from ${req.params.group}.`
|
||||||
|
});
|
||||||
|
}catch(error){
|
||||||
|
// groupOfNames requires at least one member, so emptying a group is a
|
||||||
|
// schema violation rather than a permission problem. Surfacing the raw
|
||||||
|
// error as a 500 makes it look like a bug in the server; it is really a
|
||||||
|
// "you cannot do that, and here is why" -- the same reason the last user
|
||||||
|
// cannot be removed from a group either.
|
||||||
|
if(error.name === 'ObjectClassViolationError' || error.code === 65){
|
||||||
|
return res.status(409).json({
|
||||||
|
message: `"${req.params.child}" is the only member of "${req.params.group}". A group must keep at least one member — add another first.`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
router.put('/owner/:group/:uid', async function(req, res, next){
|
router.put('/owner/:group/:uid', async function(req, res, next){
|
||||||
try{
|
try{
|
||||||
|
|
||||||
@@ -82,11 +163,25 @@ router.put('/:group/:uid', async function(req, res, next){
|
|||||||
|
|
||||||
var group = await Group.get(req.params.group);
|
var group = await Group.get(req.params.group);
|
||||||
var user = await User.get(req.params.uid);
|
var user = await User.get(req.params.uid);
|
||||||
|
const results = await group.addMember(user);
|
||||||
|
// Group membership feeds directly into cached-User-derived state
|
||||||
|
// (isServiceAccount, isAdmin, group-gated nav/UI) -- without this,
|
||||||
|
// a membership change here is invisible for up to the cache's TTL.
|
||||||
|
User.clearCache();
|
||||||
return res.json({
|
return res.json({
|
||||||
results: await group.addMember(user),
|
results,
|
||||||
message: `Added user ${req.params.uid} to ${req.params.group} group.`
|
message: `Added user ${req.params.uid} to ${req.params.group} group.`
|
||||||
});
|
});
|
||||||
}catch(error){
|
}catch(error){
|
||||||
|
// Already a member -- surfaced as a plain 500 before, which read as a
|
||||||
|
// server fault for what is really a no-op. Common in practice because
|
||||||
|
// groupOfNames needs at least one member, so whoever creates a group is
|
||||||
|
// seeded into it and is then "added" again by the obvious next click.
|
||||||
|
if(error.name === 'TypeOrValueExistsError' || error.code === 20){
|
||||||
|
return res.status(409).json({
|
||||||
|
message: `"${req.params.uid}" is already a member of "${req.params.group}".`
|
||||||
|
});
|
||||||
|
}
|
||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -98,8 +193,10 @@ router.delete('/:group/:uid', async function(req, res, next){
|
|||||||
|
|
||||||
var group = await Group.get(req.params.group);
|
var group = await Group.get(req.params.group);
|
||||||
var user = await User.get(req.params.uid);
|
var user = await User.get(req.params.uid);
|
||||||
|
const results = await group.removeMember(user);
|
||||||
|
User.clearCache();
|
||||||
return res.json({
|
return res.json({
|
||||||
results: await group.removeMember(user),
|
results,
|
||||||
message: `Removed user ${req.params.uid} from ${req.params.group} group.`
|
message: `Removed user ${req.params.uid} from ${req.params.group} group.`
|
||||||
});
|
});
|
||||||
}catch(error){
|
}catch(error){
|
||||||
|
|||||||
@@ -5,38 +5,39 @@ var express = require('express');
|
|||||||
var router = express.Router();
|
var router = express.Router();
|
||||||
const moment = require('moment');
|
const moment = require('moment');
|
||||||
const {marked} = require('marked');
|
const {marked} = require('marked');
|
||||||
|
const xss = require('xss');
|
||||||
const {InviteToken, PasswordResetToken} = require('./../models/token');
|
const {InviteToken, PasswordResetToken} = require('./../models/token');
|
||||||
const {Tos} = require('../models/tos');
|
const {Tos} = require('../models/tos');
|
||||||
const conf = require('@simpleworkjs/conf');
|
const conf = require('@simpleworkjs/conf');
|
||||||
const buildInfo = require('../utils/build_info');
|
const buildInfo = require('../utils/build_info');
|
||||||
|
const { mountStaticModules } = require('@simpleworkjs/app-stack');
|
||||||
|
|
||||||
const values ={
|
const values ={
|
||||||
title: conf.environment !== 'production' ? `dev` : '',
|
title: conf.environment !== 'production' ? `dev` : '',
|
||||||
titleIcon: conf.environment !== 'production' ? `<i class="fa-brands fa-dev"></i>` : '',
|
titleIcon: conf.environment !== 'production' ? `<i class="fa-brands fa-dev"></i>` : '',
|
||||||
name: conf.name,
|
name: conf.name,
|
||||||
logo: conf.logo,
|
logo: conf.logo,
|
||||||
|
// Connection conventions the catalog needs to render "how to reach this"
|
||||||
|
// (conf/base.js `directory`). Safe to expose: a jump-host name and a default
|
||||||
|
// port are public connection info, not credentials.
|
||||||
|
directoryConf: {
|
||||||
|
jumpHost: (conf.directory && conf.directory.jumpHost) || '',
|
||||||
|
defaultSshPort: (conf.directory && conf.directory.defaultSshPort) || 22,
|
||||||
|
},
|
||||||
...buildInfo,
|
...buildInfo,
|
||||||
}
|
}
|
||||||
|
|
||||||
// List of front end node modules to be served
|
// List of front end node modules to be served
|
||||||
const frontEndModules = ['bootstrap', 'mustache', 'jquery', '@fortawesome',
|
|
||||||
'moment', '@popper', 'jq-repeat',
|
|
||||||
];
|
|
||||||
|
|
||||||
// Server front end modules
|
|
||||||
// https://stackoverflow.com/a/55700773/3140931
|
|
||||||
// Vendor libraries only change when package versions are bumped (a rebuild),
|
// Vendor libraries only change when package versions are bumped (a rebuild),
|
||||||
// so they're safe to cache aggressively; ETag/Last-Modified (on by default)
|
// so they're safe to cache aggressively; ETag/Last-Modified (on by default)
|
||||||
// still cover that rare case with a cheap 304 instead of a stale asset.
|
// still cover that rare case with a cheap 304 instead of a stale asset. The
|
||||||
frontEndModules.forEach(dep => {
|
// app's own JS/CSS/img from public/ gets a shorter maxAge since it changes on
|
||||||
router.use(`/static-modules/${dep}`, express.static(path.join(__dirname, `../node_modules/${dep}`), {maxAge: '7d'}))
|
// every deploy and isn't cache-busted/fingerprinted.
|
||||||
|
mountStaticModules(router, {
|
||||||
|
root: path.join(__dirname, '..'),
|
||||||
|
deps: ['bootstrap', 'mustache', 'jquery', '@fortawesome', 'moment', '@popper', 'jq-repeat', '@simpleworkjs/frontend'],
|
||||||
});
|
});
|
||||||
|
|
||||||
// Have express server static content( images, CSS, browser JS) from the public
|
|
||||||
// local folder. Shorter maxAge than /static-modules since this is the app's
|
|
||||||
// own JS/CSS, which changes on every deploy and isn't cache-busted/fingerprinted.
|
|
||||||
router.use('/static', express.static(path.join(__dirname, '../public'), {maxAge: '1h'}))
|
|
||||||
|
|
||||||
// Public health endpoint for container/orchestration healthchecks.
|
// Public health endpoint for container/orchestration healthchecks.
|
||||||
// Mounted at / (no auth) in app.js, so this is intentionally unauthenticated.
|
// Mounted at / (no auth) in app.js, so this is intentionally unauthenticated.
|
||||||
router.get('/health', function(req, res) {
|
router.get('/health', function(req, res) {
|
||||||
@@ -46,7 +47,7 @@ router.get('/health', function(req, res) {
|
|||||||
router.get('/tos', async function(req, res, next) {
|
router.get('/tos', async function(req, res, next) {
|
||||||
try {
|
try {
|
||||||
const tos = await Tos.getCurrent();
|
const tos = await Tos.getCurrent();
|
||||||
res.render('tos', {...values, tosHtml: marked(tos.content), tosUpdatedOnFmt: moment(tos.updated_on, 'x').format('MMMM YYYY')});
|
res.render('tos', {...values, tosHtml: xss(marked(tos.content)), tosUpdatedOnFmt: moment(tos.updated_on, 'x').format('MMMM YYYY')});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
@@ -54,27 +55,65 @@ router.get('/tos', async function(req, res, next) {
|
|||||||
|
|
||||||
// Admin dashboard (stats + recent/inactive users) and Notifications
|
// Admin dashboard (stats + recent/inactive users) and Notifications
|
||||||
// (broadcast + history) merged into one page.
|
// (broadcast + history) merged into one page.
|
||||||
router.get('/dashboard', function(req, res) {
|
router.get('/overview', function(req, res) {
|
||||||
res.render('dashboard', {...values});
|
res.render('overview', {...values});
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/admin', (req, res) => res.redirect(301, '/dashboard'));
|
router.get('/admin', (req, res) => res.redirect(301, '/overview'));
|
||||||
router.get('/notifications', (req, res) => res.redirect(301, '/dashboard'));
|
router.get('/notifications', (req, res) => res.redirect(301, '/overview'));
|
||||||
|
router.get('/dashboard', (req, res) => res.redirect(301, '/overview'));
|
||||||
|
router.get('/executive', (req, res) => res.redirect(301, '/overview'));
|
||||||
|
|
||||||
router.get('/invites', function(req, res) {
|
router.get('/conf', async function(req, res, next) {
|
||||||
res.render('invites', {...values});
|
const permission = require('../utils/permission');
|
||||||
|
try {
|
||||||
|
await permission.byGroup(req.user, ['app_sso_admin']);
|
||||||
|
res.render('conf', {...values});
|
||||||
|
} catch(err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
router.get('/directory', function(req, res) {
|
||||||
|
res.render('directory', {...values});
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/discovery', function(req, res, next) {
|
||||||
|
res.redirect('/directory');
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/plugins', function(req, res, next) {
|
||||||
|
res.redirect('/directory');
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/vault', function(req, res, next) {
|
||||||
|
res.render('vaultwarden', {...values});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Linkable deep-link to a single resource's modal, e.g. from the resource
|
||||||
|
// modal's app.modal `url` option. Mirrors /users/:uid below: no server-side
|
||||||
|
// use of :slug at all -- the client reads location.pathname itself and opens
|
||||||
|
// the matching resource's modal once the page's own data has loaded.
|
||||||
|
router.get('/directory/:slug', function(req, res) {
|
||||||
|
res.render('directory', {...values});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Route removed since it's now in directory
|
||||||
|
|
||||||
router.get('/onboarding', async function(req, res, next) {
|
router.get('/onboarding', async function(req, res, next) {
|
||||||
try {
|
try {
|
||||||
const tos = await Tos.getCurrent();
|
const tos = await Tos.getCurrent();
|
||||||
res.render('onboarding', {...values, tosHtml: marked(tos.content)});
|
res.render('onboarding', {...values, tosHtml: xss(marked(tos.content))});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/', async function(req, res, next) {
|
router.get('/', async function(req, res, next) {
|
||||||
|
res.render('landing', {...values});
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get('/profile', async function(req, res, next) {
|
||||||
res.render('profile', {...values});
|
res.render('profile', {...values});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -82,6 +121,10 @@ router.get('/users', async function(req, res, next) {
|
|||||||
res.render('users', {...values});
|
res.render('users', {...values});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
router.get('/conf', async function(req, res, next) {
|
||||||
|
res.render('conf', {...values});
|
||||||
|
});
|
||||||
|
|
||||||
router.get('/login', async function(req, res, next) {
|
router.get('/login', async function(req, res, next) {
|
||||||
res.render('login', {...values, redirect: req.query.redirect});
|
res.render('login', {...values, redirect: req.query.redirect});
|
||||||
});
|
});
|
||||||
@@ -92,7 +135,14 @@ router.get('/login', async function(req, res, next) {
|
|||||||
// hardcoded in a doc, so they're always right for *this* deployment.
|
// hardcoded in a doc, so they're always right for *this* deployment.
|
||||||
router.get('/integrations', function(req, res, next) {
|
router.get('/integrations', function(req, res, next) {
|
||||||
const issuer = ((conf.oauth && conf.oauth.issuer) || `${req.protocol}://${req.get('host')}`).replace(/\/$/, '');
|
const issuer = ((conf.oauth && conf.oauth.issuer) || `${req.protocol}://${req.get('host')}`).replace(/\/$/, '');
|
||||||
const ldapHost = issuer.replace(/^https?:\/\//, '').replace(/:\d+$/, '');
|
// The public-facing host (from the OAuth issuer). Used for OIDC links.
|
||||||
|
const issuerHost = issuer.replace(/^https?:\/\//, '').replace(/:\d+$/, '');
|
||||||
|
|
||||||
|
// The hostname advertised for direct LDAPS binds may be a separate,
|
||||||
|
// internal-only name so admins don't have to port-forward 636 publicly.
|
||||||
|
// Defaults to the issuer host to preserve prior behavior.
|
||||||
|
const ldapsHost = (conf.ldap && conf.ldap.ldapsHost) || issuerHost;
|
||||||
|
const ldapsPort = Number((conf.ldap && conf.ldap.ldapsPort) || 636) || 636;
|
||||||
|
|
||||||
const userBase = (conf.ldap && conf.ldap.userBase) || 'ou=people,dc=example,dc=com';
|
const userBase = (conf.ldap && conf.ldap.userBase) || 'ou=people,dc=example,dc=com';
|
||||||
const groupBase = (conf.ldap && conf.ldap.groupBase) || 'ou=groups,dc=example,dc=com';
|
const groupBase = (conf.ldap && conf.ldap.groupBase) || 'ou=groups,dc=example,dc=com';
|
||||||
@@ -105,8 +155,9 @@ router.get('/integrations', function(req, res, next) {
|
|||||||
...values,
|
...values,
|
||||||
issuer,
|
issuer,
|
||||||
discoveryUrl: `${issuer}/.well-known/openid-configuration`,
|
discoveryUrl: `${issuer}/.well-known/openid-configuration`,
|
||||||
ldapHost,
|
ldapHost: ldapsHost,
|
||||||
ldapsUrl: `ldaps://${ldapHost}:636`,
|
ldapsUrl: `ldaps://${ldapsHost}:${ldapsPort}`,
|
||||||
|
ldapsHostExplicit: !!(conf.ldap && conf.ldap.ldapsHost),
|
||||||
baseDn,
|
baseDn,
|
||||||
userBase,
|
userBase,
|
||||||
groupBase,
|
groupBase,
|
||||||
@@ -137,6 +188,8 @@ router.get('/token', function(req, res, next) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
router.get('/login/resetpassword/:token', async function(req, res, next){
|
router.get('/login/resetpassword/:token', async function(req, res, next){
|
||||||
let token = await PasswordResetToken.get(req.params.token);
|
let token = await PasswordResetToken.get(req.params.token);
|
||||||
|
|
||||||
|
|||||||
@@ -45,8 +45,11 @@ router.post('/', async function(req, res, next) {
|
|||||||
|
|
||||||
const client = await OAuthClient.add(req.body);
|
const client = await OAuthClient.add(req.body);
|
||||||
|
|
||||||
|
const result = client.toJSON ? client.toJSON() : { ...client };
|
||||||
|
result.client_id = client.client_id || client.id;
|
||||||
|
|
||||||
return res.json({
|
return res.json({
|
||||||
results: client,
|
results: result,
|
||||||
client_secret: client._raw_secret,
|
client_secret: client._raw_secret,
|
||||||
message: `OAuth client '${client.name}' created. Save the client secret — it will not be shown again.`,
|
message: `OAuth client '${client.name}' created. Save the client secret — it will not be shown again.`,
|
||||||
});
|
});
|
||||||
@@ -94,7 +97,7 @@ router.delete('/:client_id', async function(req, res, next) {
|
|||||||
await permission.byGroup(req.user, [ADMIN_GROUP]);
|
await permission.byGroup(req.user, [ADMIN_GROUP]);
|
||||||
|
|
||||||
const client = await OAuthClient.get(req.params.client_id);
|
const client = await OAuthClient.get(req.params.client_id);
|
||||||
await client.remove();
|
await client.delete();
|
||||||
|
|
||||||
return res.json({
|
return res.json({
|
||||||
client_id: req.params.client_id,
|
client_id: req.params.client_id,
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
const router = require('express').Router();
|
||||||
|
const conf = require('@simpleworkjs/conf');
|
||||||
|
const permission = require('../utils/permission');
|
||||||
|
|
||||||
|
router.use(async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
await permission.byGroup(req.user, ['app_sso_directory_admin', 'app_sso_admin']);
|
||||||
|
next();
|
||||||
|
} catch(err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const Redis = require('ioredis');
|
||||||
|
const connection = new Redis(process.env.REDIS_URL || 'redis://127.0.0.1:6379', { maxRetriesPerRequest: null });
|
||||||
|
const { initScheduler } = require('../services/scheduler');
|
||||||
|
|
||||||
|
router.get('/', async (req, res) => {
|
||||||
|
const plugins = conf.discovery && conf.discovery.plugins ? conf.discovery.plugins : {};
|
||||||
|
let overrides = {};
|
||||||
|
try {
|
||||||
|
const data = await connection.hgetall('discovery_plugins');
|
||||||
|
for (const [k, v] of Object.entries(data)) {
|
||||||
|
overrides[k] = JSON.parse(v);
|
||||||
|
}
|
||||||
|
} catch(e) {}
|
||||||
|
|
||||||
|
// Mask secrets before sending
|
||||||
|
const masked = JSON.parse(JSON.stringify(plugins));
|
||||||
|
for (const name in masked) {
|
||||||
|
masked[name] = { ...masked[name], ...(overrides[name] || {}) };
|
||||||
|
if (masked[name].tokenSecret) masked[name].tokenSecret = '********';
|
||||||
|
if (masked[name].password) masked[name].password = '********';
|
||||||
|
}
|
||||||
|
res.json({ results: masked });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.put('/:name', async (req, res) => {
|
||||||
|
const name = req.params.name;
|
||||||
|
const updates = req.body;
|
||||||
|
|
||||||
|
let current = {};
|
||||||
|
try {
|
||||||
|
const data = await connection.hget('discovery_plugins', name);
|
||||||
|
if (data) current = JSON.parse(data);
|
||||||
|
} catch(e) {}
|
||||||
|
|
||||||
|
if (updates.cron !== undefined) current.cron = updates.cron;
|
||||||
|
if (updates.enabled !== undefined) current.enabled = updates.enabled === true || updates.enabled === 'true';
|
||||||
|
|
||||||
|
await connection.hset('discovery_plugins', name, JSON.stringify(current));
|
||||||
|
|
||||||
|
// Re-init scheduler to apply changes
|
||||||
|
await initScheduler(conf.discovery).catch(console.error);
|
||||||
|
|
||||||
|
res.json({ success: true, message: 'Plugin updated' });
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -23,8 +23,10 @@ router.get('/', async function(req, res, next){
|
|||||||
|
|
||||||
router.get('/:name', async function(req, res, next){
|
router.get('/:name', async function(req, res, next){
|
||||||
try{
|
try{
|
||||||
|
// ORM models: list() on the redis adapter always returns full rows;
|
||||||
|
// detail is handled by serialization (isPrivate fields are excluded).
|
||||||
return res.json({
|
return res.json({
|
||||||
results: await tokens[req.params.name][req.query.detail ? "listDetail" : "list"]()
|
results: await tokens[req.params.name].list()
|
||||||
});
|
});
|
||||||
}catch(error){
|
}catch(error){
|
||||||
next(error);
|
next(error);
|
||||||
@@ -34,9 +36,13 @@ router.get('/:name', async function(req, res, next){
|
|||||||
|
|
||||||
router.get('/:name/:token', async function(req, res, next){
|
router.get('/:name/:token', async function(req, res, next){
|
||||||
try{
|
try{
|
||||||
return res.json({
|
const result = await tokens[req.params.name].get(req.params.token);
|
||||||
results: await tokens[req.params.name].get(req.params.token)
|
if (!result) {
|
||||||
});
|
const error = new Error('Token not found');
|
||||||
|
error.status = 404;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return res.json({ results: result });
|
||||||
}catch(error){
|
}catch(error){
|
||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ const router = require('express').Router();
|
|||||||
const {User} = require('../models/user');
|
const {User} = require('../models/user');
|
||||||
const {Group} = require('../models/group_ldap');
|
const {Group} = require('../models/group_ldap');
|
||||||
const permission = require('../utils/permission');
|
const permission = require('../utils/permission');
|
||||||
|
const {groupCns} = require('../utils/user_groups');
|
||||||
const {UserVerification} = require('../models/verification');
|
const {UserVerification} = require('../models/verification');
|
||||||
const {InviteToken} = require('../models/token');
|
const {InviteToken} = require('../models/token');
|
||||||
|
|
||||||
@@ -25,7 +26,7 @@ router.post('/', async function(req, res, next){
|
|||||||
req.body.created_by = req.user.uid
|
req.body.created_by = req.user.uid
|
||||||
req.body.manager = [req.user.dn];
|
req.body.manager = [req.user.dn];
|
||||||
|
|
||||||
const user = await User.add(req.body);
|
let user = await User.add(req.body);
|
||||||
const verif = await UserVerification.getOrCreate(user.uid);
|
const verif = await UserVerification.getOrCreate(user.uid);
|
||||||
const updates = { password_must_change: true };
|
const updates = { password_must_change: true };
|
||||||
if (req.body.tosAgree) updates.tos_accepted = true, updates.tos_accepted_at = Date.now();
|
if (req.body.tosAgree) updates.tos_accepted = true, updates.tos_accepted_at = Date.now();
|
||||||
@@ -38,12 +39,18 @@ router.post('/', async function(req, res, next){
|
|||||||
try {
|
try {
|
||||||
const group = await Group.get('app_sso_service_account');
|
const group = await Group.get('app_sso_service_account');
|
||||||
await group.addMember(user);
|
await group.addMember(user);
|
||||||
|
// User.add() already cached `user` (via its own internal
|
||||||
|
// User.get()) before this group membership existed, so the
|
||||||
|
// cached isServiceAccount would be stuck wrong for 5 minutes
|
||||||
|
// (the cache TTL) without this -- re-fetch after clearing.
|
||||||
|
User.clearCache();
|
||||||
|
user = await User.get(user.uid);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`user.add: failed to mark ${user.uid} as a service account:`, error.message);
|
console.error(`user.add: failed to mark ${user.uid} as a service account:`, error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.json({results: user});
|
return res.json({results: user, message: `User ${user.uid} created.`});
|
||||||
}catch(error){
|
}catch(error){
|
||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
@@ -68,7 +75,24 @@ router.delete('/:uid', async function(req, res, next){
|
|||||||
|
|
||||||
router.get('/me', async function(req, res, next){
|
router.get('/me', async function(req, res, next){
|
||||||
try{
|
try{
|
||||||
return res.json(await User.get({uid: req.user.uid}));
|
const user = JSON.parse(JSON.stringify(await User.get({uid: req.user.uid})));
|
||||||
|
|
||||||
|
// The shared client framework gates the UI on a single effective-rights
|
||||||
|
// flag (the OIDC-client apps send the same key). Here "admin" means
|
||||||
|
// membership in app_sso_admin or the cross-app app_super_admin group.
|
||||||
|
//
|
||||||
|
// Resolved via groupCns rather than read off `memberOf` directly: with
|
||||||
|
// nested groups, memberOf is only transitive when the directory carries
|
||||||
|
// the nestgroup overlay. Against a server without it, an admin who holds
|
||||||
|
// the group through nesting would get isAdmin=false here and silently
|
||||||
|
// lose the whole admin UI -- while still passing every server-side
|
||||||
|
// permission check, which resolves nesting properly. groupCns gives the
|
||||||
|
// same answer in both modes.
|
||||||
|
const groups = await groupCns(user);
|
||||||
|
user.groups = groups;
|
||||||
|
user.isAdmin = groups.includes('app_sso_admin') || groups.includes(permission.SUPER_ADMIN_GROUP);
|
||||||
|
|
||||||
|
return res.json(user);
|
||||||
}catch(error){
|
}catch(error){
|
||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
@@ -91,7 +115,7 @@ router.put('/password', async function(req, res, next){
|
|||||||
const verif = await UserVerification.getOrCreate(req.user.uid);
|
const verif = await UserVerification.getOrCreate(req.user.uid);
|
||||||
await verif.update({ password_must_change: false });
|
await verif.update({ password_must_change: false });
|
||||||
User.clearCache();
|
User.clearCache();
|
||||||
return res.json({results: result});
|
return res.json({results: result, message: 'Password changed.'});
|
||||||
}catch(error){
|
}catch(error){
|
||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
@@ -138,6 +162,41 @@ router.put('/:uid/active', async function(req, res, next){
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
router.get('/:uid/group-members', async function(req, res, next){
|
||||||
|
try{
|
||||||
|
await permission.byGroup(req.user, ['app_sso_admin']);
|
||||||
|
return res.json({results: await User.getPersonalGroupMembers(req.params.uid)});
|
||||||
|
}catch(error){
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.put('/:uid/group-member/:memberUid', async function(req, res, next){
|
||||||
|
try{
|
||||||
|
await permission.byGroup(req.user, ['app_sso_admin']);
|
||||||
|
await User.addPersonalGroupMember(req.params.uid, req.params.memberUid);
|
||||||
|
return res.json({
|
||||||
|
results: true,
|
||||||
|
message: `Added ${req.params.memberUid} to ${req.params.uid}'s group`
|
||||||
|
});
|
||||||
|
}catch(error){
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.delete('/:uid/group-member/:memberUid', async function(req, res, next){
|
||||||
|
try{
|
||||||
|
await permission.byGroup(req.user, ['app_sso_admin']);
|
||||||
|
await User.removePersonalGroupMember(req.params.uid, req.params.memberUid);
|
||||||
|
return res.json({
|
||||||
|
results: true,
|
||||||
|
message: `Removed ${req.params.memberUid} from ${req.params.uid}'s group`
|
||||||
|
});
|
||||||
|
}catch(error){
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
router.put('/:uid', async function(req, res, next){
|
router.put('/:uid', async function(req, res, next){
|
||||||
try{
|
try{
|
||||||
let user;
|
let user;
|
||||||
@@ -190,7 +249,7 @@ router.get('/invite', async function(req, res, next){
|
|||||||
try{
|
try{
|
||||||
await permission.byGroup(req.user, ['app_sso_admin', 'app_sso_invite']);
|
await permission.byGroup(req.user, ['app_sso_admin', 'app_sso_invite']);
|
||||||
const isAdmin = await permission.byGroup(req.user, ['app_sso_admin']).then(() => true).catch(() => false);
|
const isAdmin = await permission.byGroup(req.user, ['app_sso_admin']).then(() => true).catch(() => false);
|
||||||
const all = await InviteToken.listDetail();
|
const all = await InviteToken.list();
|
||||||
const visible = isAdmin ? all : all.filter(t => t.created_by === req.user.uid);
|
const visible = isAdmin ? all : all.filter(t => t.created_by === req.user.uid);
|
||||||
const results = visible.map(t => ({ token: t.token, ...t }));
|
const results = visible.map(t => ({ token: t.token, ...t }));
|
||||||
return res.json({ results });
|
return res.json({ results });
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
const router = require('express').Router();
|
||||||
|
const { Webhook } = require('../models/webhook');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
// GET /api/webhooks
|
||||||
|
router.get('/', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const hooks = await Webhook.list();
|
||||||
|
res.json({ results: hooks });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /api/webhooks
|
||||||
|
router.post('/', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { name, url, events, secret } = req.body;
|
||||||
|
const hook = await Webhook.create({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
name, url, events, secret,
|
||||||
|
created_on: Math.floor(Date.now() / 1000)
|
||||||
|
});
|
||||||
|
res.json({ results: hook });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// DELETE /api/webhooks/:id
|
||||||
|
router.delete('/:id', async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const hook = await Webhook.get(req.params.id);
|
||||||
|
if (!hook) return res.status(404).json({ error: 'Not found' });
|
||||||
|
await hook.delete();
|
||||||
|
res.json({ success: true });
|
||||||
|
} catch (err) { next(err); }
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
const { Resource, ResourceEdge, ResourceGroup } = require('../models/resource');
|
||||||
|
const { WebhookEmitter } = require('./webhook_emitter');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
class DiscoveryReconciler {
|
||||||
|
static async reconcile(sourceName, payload) {
|
||||||
|
const { resources = [], edges = [] } = payload;
|
||||||
|
let newDevices = 0;
|
||||||
|
|
||||||
|
for (const res of resources) {
|
||||||
|
if (!res.metadata) res.metadata = {};
|
||||||
|
|
||||||
|
let existing = null;
|
||||||
|
|
||||||
|
// Attempt matching by MAC if available
|
||||||
|
if (res.metadata.interfaces && res.metadata.interfaces.length > 0) {
|
||||||
|
const macs = res.metadata.interfaces.map(i => i.mac).filter(m => !!m);
|
||||||
|
if (macs.length > 0) {
|
||||||
|
const allRes = await Resource.list();
|
||||||
|
existing = allRes.find(r =>
|
||||||
|
r.metadata && r.metadata.interfaces &&
|
||||||
|
r.metadata.interfaces.some(i => macs.includes(i.mac))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback matching by IP if no MAC match (weaker)
|
||||||
|
let ipsToMatch = [];
|
||||||
|
if (res.metadata.interfaces) {
|
||||||
|
ipsToMatch = res.metadata.interfaces.map(i => i.ip).filter(i => !!i);
|
||||||
|
}
|
||||||
|
if (res.metadata.address) {
|
||||||
|
res.metadata.address.split(',').forEach(a => ipsToMatch.push(a.trim()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!existing && ipsToMatch.length > 0) {
|
||||||
|
const allRes = await Resource.list();
|
||||||
|
existing = allRes.find(r => {
|
||||||
|
if (!r.metadata) return false;
|
||||||
|
if (r.metadata.address) {
|
||||||
|
const addrs = r.metadata.address.split(',').map(a => a.trim());
|
||||||
|
if (addrs.some(a => ipsToMatch.includes(a))) return true;
|
||||||
|
}
|
||||||
|
if (r.metadata.interfaces && r.metadata.interfaces.some(i => ipsToMatch.includes(i.ip))) return true;
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback matching by Slug or Name
|
||||||
|
if (!existing && (res.slug || res.name)) {
|
||||||
|
const allRes = await Resource.list();
|
||||||
|
existing = allRes.find(r =>
|
||||||
|
(res.slug && r.slug === res.slug) ||
|
||||||
|
(res.name && r.name && r.name.toLowerCase() === res.name.toLowerCase())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
// Merge metadata
|
||||||
|
const mergedMeta = { ...existing.metadata, ...res.metadata };
|
||||||
|
|
||||||
|
// Merge interfaces cleanly
|
||||||
|
if (res.metadata.interfaces) {
|
||||||
|
const existingIntfs = existing.metadata.interfaces || [];
|
||||||
|
const newIntfs = res.metadata.interfaces;
|
||||||
|
// Simple union based on mac or ip
|
||||||
|
for (const ni of newIntfs) {
|
||||||
|
const idx = existingIntfs.findIndex(ei => (ni.mac && ei.mac === ni.mac) || (ni.ip && ei.ip === ni.ip));
|
||||||
|
if (idx >= 0) existingIntfs[idx] = { ...existingIntfs[idx], ...ni };
|
||||||
|
else existingIntfs.push(ni);
|
||||||
|
}
|
||||||
|
mergedMeta.interfaces = existingIntfs;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add discovery source
|
||||||
|
const sources = new Set(mergedMeta.discovery_sources || []);
|
||||||
|
sources.add(sourceName);
|
||||||
|
mergedMeta.discovery_sources = [...sources];
|
||||||
|
|
||||||
|
mergedMeta.last_seen = Date.now();
|
||||||
|
|
||||||
|
await existing.update({
|
||||||
|
name: res.name || existing.name,
|
||||||
|
description: res.description || existing.description,
|
||||||
|
metadata: mergedMeta,
|
||||||
|
updated_on: Math.floor(Date.now() / 1000)
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Create new
|
||||||
|
const sources = [sourceName];
|
||||||
|
res.metadata.discovery_sources = sources;
|
||||||
|
res.metadata.last_seen = Date.now();
|
||||||
|
|
||||||
|
const slug = res.slug || `${res.kind}-${crypto.randomBytes(4).toString('hex')}`;
|
||||||
|
|
||||||
|
const created = await Resource.create({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
kind: res.kind || 'unmanaged_device',
|
||||||
|
name: res.name || slug,
|
||||||
|
slug: slug,
|
||||||
|
metadata: res.metadata,
|
||||||
|
created_on: Math.floor(Date.now() / 1000)
|
||||||
|
});
|
||||||
|
|
||||||
|
newDevices++;
|
||||||
|
WebhookEmitter.emit('discovery.new_device', created.toJSON());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// We can handle edges similarly if needed, but for simplicity we assume edges are managed elsewhere
|
||||||
|
// or we just trust the plugins to give us explicit parent-child mappings by slug.
|
||||||
|
|
||||||
|
if (newDevices > 0) {
|
||||||
|
console.log(`[DiscoveryReconciler] Source ${sourceName} discovered ${newDevices} new devices.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async garbageCollect(staleMs = 7 * 24 * 60 * 60 * 1000) {
|
||||||
|
const allRes = await Resource.list();
|
||||||
|
const cutoff = Date.now() - staleMs;
|
||||||
|
let archived = 0;
|
||||||
|
|
||||||
|
for (const res of allRes) {
|
||||||
|
const meta = res.metadata || {};
|
||||||
|
const sources = meta.discovery_sources || [];
|
||||||
|
// Only garbage collect things that are exclusively auto-discovered
|
||||||
|
if (sources.length > 0 && !sources.includes('manual')) {
|
||||||
|
if (meta.last_seen && meta.last_seen < cutoff && meta.lifecycle_state !== 'archived') {
|
||||||
|
meta.lifecycle_state = 'archived';
|
||||||
|
await res.update({ metadata: meta, updated_on: Math.floor(Date.now() / 1000) });
|
||||||
|
archived++;
|
||||||
|
WebhookEmitter.emit('discovery.device_archived', res.toJSON());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (archived > 0) console.log(`[DiscoveryReconciler] Garbage collected ${archived} stale devices.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { DiscoveryReconciler };
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
const metrics = require('../utils/metrics');
|
||||||
|
|
||||||
|
function startLdapMonitor() {
|
||||||
|
const logFile = '/var/lib/ldap/slapd.log';
|
||||||
|
if (!fs.existsSync(logFile)) {
|
||||||
|
setTimeout(startLdapMonitor, 5000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tail = spawn('tail', ['-F', logFile]);
|
||||||
|
const connections = {}; // connID -> { ip, uid }
|
||||||
|
|
||||||
|
tail.stdout.on('data', (data) => {
|
||||||
|
const lines = data.toString().split('\n');
|
||||||
|
for (const line of lines) {
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
|
||||||
|
const connMatch = line.match(/conn=(\d+)/);
|
||||||
|
if (!connMatch) continue;
|
||||||
|
const conn = connMatch[1];
|
||||||
|
|
||||||
|
if (!connections[conn]) {
|
||||||
|
connections[conn] = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const ipMatch = line.match(/ACCEPT from IP=([^:]+)/);
|
||||||
|
if (ipMatch) {
|
||||||
|
connections[conn].ip = ipMatch[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
const bindMatch = line.match(/BIND dn="uid=([^,]+)/i) || line.match(/BIND dn="cn=([^,]+)/i);
|
||||||
|
if (bindMatch) {
|
||||||
|
connections[conn].uid = bindMatch[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
const resultMatch = line.match(/RESULT tag=\d+ err=(\d+)/);
|
||||||
|
if (resultMatch) {
|
||||||
|
const errCode = parseInt(resultMatch[1], 10);
|
||||||
|
const { ip, uid } = connections[conn];
|
||||||
|
if (errCode === 0 && uid) {
|
||||||
|
metrics.recordServiceUsage('LDAP Direct', uid);
|
||||||
|
} else if (errCode === 49 || errCode === 32) {
|
||||||
|
metrics.recordFailedLogin(ip, uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.includes('closed') || line.includes('UNBIND')) {
|
||||||
|
delete connections[conn];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
tail.on('error', (err) => {
|
||||||
|
console.error('Failed to start LDAP monitor', err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
startLdapMonitor();
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
const { Queue, Worker } = require('bullmq');
|
||||||
|
const { DiscoveryReconciler } = require('./discovery_reconciler');
|
||||||
|
const Redis = require('ioredis');
|
||||||
|
|
||||||
|
// Ensure Redis connection works for BullMQ
|
||||||
|
const redisOpts = { maxRetriesPerRequest: null };
|
||||||
|
const connection = new Redis(process.env.REDIS_URL || 'redis://127.0.0.1:6379', redisOpts);
|
||||||
|
|
||||||
|
const discoveryQueue = new Queue('discovery', { connection });
|
||||||
|
|
||||||
|
// Load plugins
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const pluginsDir = path.join(__dirname, '../plugins/discovery');
|
||||||
|
|
||||||
|
let plugins = {};
|
||||||
|
|
||||||
|
if (fs.existsSync(pluginsDir)) {
|
||||||
|
fs.readdirSync(pluginsDir).forEach(file => {
|
||||||
|
if (file.endsWith('.js')) {
|
||||||
|
const name = path.basename(file, '.js');
|
||||||
|
plugins[name] = require(path.join(pluginsDir, file));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const worker = new Worker('discovery', async job => {
|
||||||
|
if (job.name === 'run_plugin') {
|
||||||
|
const { pluginName, config } = job.data;
|
||||||
|
if (plugins[pluginName]) {
|
||||||
|
console.log(`[Scheduler] Running plugin: ${pluginName}`);
|
||||||
|
try {
|
||||||
|
const payload = await plugins[pluginName].discover(config);
|
||||||
|
await DiscoveryReconciler.reconcile(pluginName, payload);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[Scheduler] Plugin ${pluginName} failed:`, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (job.name === 'garbage_collect') {
|
||||||
|
console.log(`[Scheduler] Running garbage collection`);
|
||||||
|
await DiscoveryReconciler.garbageCollect();
|
||||||
|
}
|
||||||
|
}, { connection });
|
||||||
|
|
||||||
|
// Function to start scheduling
|
||||||
|
async function initScheduler(discoveryConfig) {
|
||||||
|
// Clear old repeatable jobs (BullMQ v6 uses JobSchedulers)
|
||||||
|
try {
|
||||||
|
const schedulers = await discoveryQueue.getJobSchedulers();
|
||||||
|
for (const job of schedulers) {
|
||||||
|
await discoveryQueue.removeJobScheduler(job.id);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.log('[Scheduler] Could not clear old job schedulers (may not be supported or none exist)');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedule Garbage Collection
|
||||||
|
await discoveryQueue.add('garbage_collect', {}, { repeat: { pattern: '0 0 * * *' } }); // Daily
|
||||||
|
|
||||||
|
// Load plugin overrides from Redis
|
||||||
|
let overrides = {};
|
||||||
|
try {
|
||||||
|
const data = await connection.hgetall('discovery_plugins');
|
||||||
|
for (const [k, v] of Object.entries(data)) {
|
||||||
|
overrides[k] = JSON.parse(v);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[Scheduler] Failed to load plugin overrides from Redis', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedule Plugins based on config + overrides
|
||||||
|
if (discoveryConfig && discoveryConfig.plugins) {
|
||||||
|
for (const [name, config] of Object.entries(discoveryConfig.plugins)) {
|
||||||
|
const mergedConfig = { ...config, ...(overrides[name] || {}) };
|
||||||
|
if (mergedConfig.enabled && plugins[name]) {
|
||||||
|
const cron = mergedConfig.cron || '0 * * * *'; // Default hourly
|
||||||
|
await discoveryQueue.add('run_plugin', { pluginName: name, config: mergedConfig }, { repeat: { pattern: cron } });
|
||||||
|
console.log(`[Scheduler] Scheduled plugin ${name} with cron ${cron}`);
|
||||||
|
|
||||||
|
// Also run once immediately
|
||||||
|
await discoveryQueue.add('run_plugin', { pluginName: name, config: mergedConfig });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { initScheduler, discoveryQueue, connection };
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
const { Webhook } = require('../models/webhook');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fetch = require('node-fetch');
|
||||||
|
|
||||||
|
class WebhookEmitter {
|
||||||
|
static async emit(event, payload) {
|
||||||
|
try {
|
||||||
|
const hooks = await Webhook.list({ where: { isActive: true } });
|
||||||
|
const matched = hooks.filter(h => !h.events || h.events.length === 0 || h.events.includes(event));
|
||||||
|
|
||||||
|
for (const hook of matched) {
|
||||||
|
this.sendPayload(hook, event, payload).catch(err => console.error(`Webhook ${hook.name} failed:`, err.message));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error emitting webhook:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static async sendPayload(hook, event, payload) {
|
||||||
|
const body = JSON.stringify({ event, payload, timestamp: Date.now() });
|
||||||
|
const headers = { 'Content-Type': 'application/json' };
|
||||||
|
|
||||||
|
if (hook.secret) {
|
||||||
|
const signature = crypto.createHmac('sha256', hook.secret).update(body).digest('hex');
|
||||||
|
headers['X-Theta-Signature'] = signature;
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(hook.url, { method: 'POST', body, headers, timeout: 5000 });
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Status ${res.status}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { WebhookEmitter };
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
const { init } = require('@simpleworkjs/orm');
|
||||||
|
const { Resource, ResourceEdge, ResourceGroup } = require('./models/resource');
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
try {
|
||||||
|
const models = await init({
|
||||||
|
conf: {
|
||||||
|
orm: {
|
||||||
|
dialect: 'sqlite',
|
||||||
|
storage: ':memory:', // Test in memory
|
||||||
|
logging: false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
models: [Resource, ResourceEdge, ResourceGroup]
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('ORM initialized successfully!');
|
||||||
|
|
||||||
|
const r1 = await models.Resource.create({
|
||||||
|
kind: 'proxmox_node',
|
||||||
|
name: 'pve1',
|
||||||
|
slug: 'pve1',
|
||||||
|
metadata: { ip: '10.0.0.1' }
|
||||||
|
});
|
||||||
|
|
||||||
|
const r2 = await models.Resource.create({
|
||||||
|
kind: 'container',
|
||||||
|
name: 'ct101',
|
||||||
|
slug: 'ct101',
|
||||||
|
metadata: { ip: '10.0.0.2' }
|
||||||
|
});
|
||||||
|
|
||||||
|
await models.ResourceEdge.create({
|
||||||
|
parentId: r1.id,
|
||||||
|
childId: r2.id,
|
||||||
|
relation: 'hosts'
|
||||||
|
});
|
||||||
|
|
||||||
|
const edges = await models.ResourceEdge.list();
|
||||||
|
console.log('Edges:', JSON.stringify(edges, null, 2));
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test();
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const { createProxyMiddleware } = require('http-proxy-middleware');
|
||||||
|
const app = express();
|
||||||
|
app.use('/', createProxyMiddleware({
|
||||||
|
target: 'http://localhost:8080',
|
||||||
|
on: {
|
||||||
|
proxyRes: (proxyRes, req, res) => {
|
||||||
|
delete proxyRes.headers['x-frame-options'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
app.listen(3004);
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
const proxmox = require('./plugins/discovery/proxmox');
|
||||||
|
const unifi = require('./plugins/discovery/unifi');
|
||||||
|
|
||||||
|
async function test() {
|
||||||
|
console.log("=== Running Proxmox Plugin ===");
|
||||||
|
try {
|
||||||
|
const pveData = await proxmox.discover({
|
||||||
|
url: 'https://dl380-0.internal.718it.biz:8006',
|
||||||
|
tokenId: 'root@pam!agy',
|
||||||
|
tokenSecret: '1e7c0e31-6767-4295-bcda-d7acf5df1d9a'
|
||||||
|
});
|
||||||
|
console.log(`Found ${pveData.resources.length} resources and ${pveData.edges.length} edges.`);
|
||||||
|
console.log("Sample resource:");
|
||||||
|
console.log(JSON.stringify(pveData.resources[0], null, 2));
|
||||||
|
console.log("Sample edge:");
|
||||||
|
console.log(JSON.stringify(pveData.edges[0], null, 2));
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Proxmox failed:", e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("\n=== Running Unifi Plugin ===");
|
||||||
|
try {
|
||||||
|
const unifiData = await unifi.discover({
|
||||||
|
url: 'https://unifi.718it.biz',
|
||||||
|
user: 'agy',
|
||||||
|
password: 'MyPassword!23'
|
||||||
|
});
|
||||||
|
console.log(`Found ${unifiData.resources.length} resources and ${unifiData.edges.length} edges.`);
|
||||||
|
console.log("Sample resource:");
|
||||||
|
console.log(JSON.stringify(unifiData.resources.find(r => r.kind === 'network_device'), null, 2));
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Unifi failed:", e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test();
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Self-service access requests, end to end: request -> approve -> the grant is
|
||||||
|
// real (visible through /api/discovery/me), plus the guards that keep the flow
|
||||||
|
// from being abused or double-applied.
|
||||||
|
//
|
||||||
|
// The seed `test` user is in app_sso_admin, so it is both the requester and an
|
||||||
|
// eligible approver here. That is unusual in production but exactly what makes
|
||||||
|
// a single-user test able to walk the whole loop.
|
||||||
|
|
||||||
|
const { login, request, app } = require('./setup');
|
||||||
|
|
||||||
|
let token;
|
||||||
|
let siteSlug;
|
||||||
|
let hostSlug;
|
||||||
|
let hostId;
|
||||||
|
let accessGroupCn;
|
||||||
|
|
||||||
|
// Unique per run: these create real LDAP groups and SQL rows, and a rerun must
|
||||||
|
// not collide with the previous run's leftovers.
|
||||||
|
const stamp = Date.now().toString(36);
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
token = await login();
|
||||||
|
|
||||||
|
siteSlug = `artest-site-${stamp}`;
|
||||||
|
const site = await request(app)
|
||||||
|
.post('/api/directory-admin/resources')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ name: `AR Test Site ${stamp}`, slug: siteSlug, kind: 'site' });
|
||||||
|
expect(site.status).toBe(200);
|
||||||
|
|
||||||
|
hostSlug = `artest-host-${stamp}`;
|
||||||
|
const host = await request(app)
|
||||||
|
.post('/api/directory-admin/resources')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({
|
||||||
|
name: `AR Test Host ${stamp}`,
|
||||||
|
slug: hostSlug,
|
||||||
|
kind: 'host',
|
||||||
|
parentSlug: siteSlug,
|
||||||
|
metadata: { ip: '10.99.99.9' },
|
||||||
|
});
|
||||||
|
expect(host.status).toBe(200);
|
||||||
|
hostId = host.body.results.id;
|
||||||
|
|
||||||
|
// Creating a host auto-provisions <site>_<slug>_access / _admin.
|
||||||
|
accessGroupCn = `${siteSlug}_${hostSlug}_access`;
|
||||||
|
const adminGroupCn = `${siteSlug}_${hostSlug}_admin`;
|
||||||
|
|
||||||
|
// The creator is seeded into both groups -- groupOfNames requires at least
|
||||||
|
// one member, so Group.add puts the owner's DN there -- and _admin is nested
|
||||||
|
// into _access, so membership of either grants access. A user who already
|
||||||
|
// has access cannot request it (correctly), so step out of both to be a
|
||||||
|
// legitimate requester. Removing only _access would leave the grant intact
|
||||||
|
// through the nesting, which is exactly the kind of thing these tests exist
|
||||||
|
// to catch.
|
||||||
|
for (const cn of [adminGroupCn, accessGroupCn]) {
|
||||||
|
await request(app)
|
||||||
|
.delete(`/api/group/${encodeURIComponent(cn)}/test`)
|
||||||
|
.set('auth-token', token);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Access requests — the request half', () => {
|
||||||
|
let requestId;
|
||||||
|
|
||||||
|
test('POST /api/access-requests creates a pending request on the member group', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/access-requests')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ slug: hostSlug, note: 'need it for testing' });
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.results).toBeDefined();
|
||||||
|
expect(res.body.results.status).toBe('pending');
|
||||||
|
expect(res.body.results.uid).toBe('test');
|
||||||
|
// Must target the _access group, never the _admin one: asking to use a
|
||||||
|
// resource may not silently escalate to administering it.
|
||||||
|
expect(res.body.results.groupCn).toBe(accessGroupCn);
|
||||||
|
requestId = res.body.results.id;
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a second request for the same resource is rejected', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/access-requests')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ slug: hostSlug });
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /api/access-requests/mine lists it with the resource attached', async () => {
|
||||||
|
const res = await request(app).get('/api/access-requests/mine').set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const found = res.body.results.find(r => r.id === requestId);
|
||||||
|
expect(found).toBeDefined();
|
||||||
|
expect(found.resource.slug).toBe(hostSlug);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /api/access-requests shows it to an approver', async () => {
|
||||||
|
const res = await request(app).get('/api/access-requests').set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.results.some(r => r.id === requestId)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('requesting an unknown resource is a 404', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/access-requests')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ slug: `no-such-resource-${stamp}` });
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Access requests — approval actually grants', () => {
|
||||||
|
let requestId;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const mine = await request(app).get('/api/access-requests/mine').set('auth-token', token);
|
||||||
|
const pending = mine.body.results.find(r => r.groupCn === accessGroupCn && r.status === 'pending');
|
||||||
|
requestId = pending && pending.id;
|
||||||
|
expect(requestId).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the resource is NOT in /api/discovery/me before approval', async () => {
|
||||||
|
const res = await request(app).get('/api/discovery/me').set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.results.some(r => r.id === hostId)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST /:id/approve marks it approved', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.post(`/api/access-requests/${requestId}/approve`)
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ decisionNote: 'ok' });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.results.status).toBe('approved');
|
||||||
|
expect(res.body.results.decidedBy).toBe('test');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('approving twice is rejected', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.post(`/api/access-requests/${requestId}/approve`)
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({});
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The payoff, and the regression guard for the user.groups bug: /me resolved
|
||||||
|
// groups off req.user.groups, which does not exist on a User (it carries
|
||||||
|
// memberOf), so this endpoint used to return only isPublic resources no
|
||||||
|
// matter what the caller was actually a member of.
|
||||||
|
test('the resource IS in /api/discovery/me after approval', async () => {
|
||||||
|
const res = await request(app).get('/api/discovery/me').set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const found = res.body.results.find(r => r.id === hostId);
|
||||||
|
expect(found).toBeDefined();
|
||||||
|
// And it answers "how do I reach it" rather than just naming the thing.
|
||||||
|
expect(found.resolvedAddress).toBe('10.99.99.9');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an already-granted resource cannot be requested again', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/access-requests')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ slug: hostSlug });
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Admin access visibility', () => {
|
||||||
|
test('GET /api/directory-admin/access-summary counts the host\'s groups + members', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.get('/api/directory-admin/access-summary')
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const summary = res.body.results[hostId];
|
||||||
|
expect(summary).toBeDefined();
|
||||||
|
// _access and _admin were both auto-created and linked.
|
||||||
|
expect(summary.groups.length).toBe(2);
|
||||||
|
expect(summary.groups.every(g => g.exists)).toBe(true);
|
||||||
|
// The approval above put `test` in the access group.
|
||||||
|
expect(summary.memberCount).toBeGreaterThanOrEqual(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /api/directory-admin/user-access/:uid answers the reverse question', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.get('/api/directory-admin/user-access/test')
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.results.uid).toBe('test');
|
||||||
|
const entry = res.body.results.resources.find(r => r.id === hostId);
|
||||||
|
expect(entry).toBeDefined();
|
||||||
|
expect(entry.groupCn).toBe(accessGroupCn);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('user-access for an unknown uid is a 404', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.get('/api/directory-admin/user-access/definitely-not-a-user')
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Access requests — withdrawal', () => {
|
||||||
|
test('a requester can withdraw their own pending request', async () => {
|
||||||
|
// A second resource, so this does not disturb the approved one above.
|
||||||
|
const slug = `artest-host2-${stamp}`;
|
||||||
|
const host = await request(app)
|
||||||
|
.post('/api/directory-admin/resources')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ name: `AR Test Host2 ${stamp}`, slug, kind: 'host', parentSlug: siteSlug });
|
||||||
|
expect(host.status).toBe(200);
|
||||||
|
|
||||||
|
// Same as the top-level setup: step out of the auto-created groups the
|
||||||
|
// creator is seeded into, or this is a request for access already held.
|
||||||
|
for (const cn of [`${siteSlug}_${slug}_admin`, `${siteSlug}_${slug}_access`]) {
|
||||||
|
await request(app)
|
||||||
|
.delete(`/api/group/${encodeURIComponent(cn)}/test`)
|
||||||
|
.set('auth-token', token);
|
||||||
|
}
|
||||||
|
|
||||||
|
const created = await request(app)
|
||||||
|
.post('/api/access-requests')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ slug });
|
||||||
|
expect(created.status).toBe(200);
|
||||||
|
|
||||||
|
const res = await request(app)
|
||||||
|
.delete(`/api/access-requests/${created.body.results.id}`)
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.results.status).toBe('cancelled');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const request = require('supertest');
|
||||||
|
const app = require('../app');
|
||||||
|
|
||||||
|
// Note: To test this properly, valid LDAP credentials are required in setup.js
|
||||||
|
// Currently tests are skipped or rely on valid auth token to avoid LDAP auth failures
|
||||||
|
describe.skip('Directory Admin API', () => {
|
||||||
|
let token;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
// A valid admin token is required
|
||||||
|
token = 'placeholder_token';
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST /api/directory-admin/resources requires hostId for services', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/directory-admin/resources')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({
|
||||||
|
name: 'Test Service',
|
||||||
|
slug: 'app_test_service',
|
||||||
|
kind: 'service'
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
expect(res.body.error).toContain('parent Host');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST /api/directory-admin/resources creates valid service with parent', async () => {
|
||||||
|
// This requires a valid host ID to exist first in a real test
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/directory-admin/resources')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({
|
||||||
|
name: 'Test Service',
|
||||||
|
slug: 'app_test_service',
|
||||||
|
kind: 'service',
|
||||||
|
hostId: 'some-uuid-here'
|
||||||
|
});
|
||||||
|
|
||||||
|
// In a fully mocked environment this would be 200
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Directory discovery API — security + contract regression coverage.
|
||||||
|
//
|
||||||
|
// These tests run under the jest + docker harness (redis + the test seed).
|
||||||
|
// They lock in the two fixes from the @simpleworkjs/directory-schema release:
|
||||||
|
// 1. /api/discovery/* returns the { results } envelope (not a bare array —
|
||||||
|
// the drift that made jump-host's `data.results || []` collapse to []).
|
||||||
|
// 2. No response path leaks secret metadata (e.g. an OAuth client's
|
||||||
|
// client_secret_hash), regardless of caller.
|
||||||
|
//
|
||||||
|
// The core assertions hold for any authenticated caller. The admin-projection
|
||||||
|
// assertion (fullMetadata for directory admins) additionally requires the `test`
|
||||||
|
// seed user to be a member of app_sso_directory_admin — see setup.js.
|
||||||
|
|
||||||
|
const { login, request, app } = require('./setup');
|
||||||
|
|
||||||
|
let token;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
token = await login();
|
||||||
|
});
|
||||||
|
|
||||||
|
function assertNoSecrets(results, path) {
|
||||||
|
for (const r of results || []) {
|
||||||
|
// toBeUndefined() in this jest version takes no message arg, so assert
|
||||||
|
// manually and throw with context — this also surfaces the leaked value
|
||||||
|
// if the projection ever regresses.
|
||||||
|
const secretHash = r.metadata && r.metadata.client_secret_hash;
|
||||||
|
if (secretHash !== undefined) {
|
||||||
|
throw new Error(
|
||||||
|
`client_secret_hash leaked from ${path} on ${r.slug || r.id} (value: ${JSON.stringify(secretHash)})`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (r.metadata) {
|
||||||
|
for (const k of Object.keys(r.metadata)) {
|
||||||
|
if (/secret|password|privatekey/i.test(k)) {
|
||||||
|
throw new Error(`secret-ish key "${k}" leaked from ${path} on ${r.slug || r.id}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Discovery — envelope + security', () => {
|
||||||
|
test('GET /api/discovery/resources returns 200 with { results } (not a bare array)', async () => {
|
||||||
|
const res = await request(app).get('/api/discovery/resources').set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(Array.isArray(res.body.results)).toBe(true);
|
||||||
|
expect(Array.isArray(res.body)).toBe(false); // never a bare array
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /api/discovery/resources never leaks client_secret_hash', async () => {
|
||||||
|
const res = await request(app).get('/api/discovery/resources').set('auth-token', token);
|
||||||
|
assertNoSecrets(res.body.results, '/resources');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /api/discovery/resources?group= returns 200 (regression: was 404)', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.get('/api/discovery/resources?group=host_web01_access')
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(Array.isArray(res.body.results)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /api/discovery/graph returns { results: { resources, edges } } and strips secrets', async () => {
|
||||||
|
const res = await request(app).get('/api/discovery/graph').set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.results).toBeDefined();
|
||||||
|
expect(Array.isArray(res.body.results.resources)).toBe(true);
|
||||||
|
assertNoSecrets(res.body.results.resources, '/graph');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /api/discovery/me returns 200 with { results } and strips secrets', async () => {
|
||||||
|
const res = await request(app).get('/api/discovery/me').set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(Array.isArray(res.body.results)).toBe(true);
|
||||||
|
assertNoSecrets(res.body.results, '/me');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /api/discovery/resources/:slug returns 200 + { results } for a known slug', async () => {
|
||||||
|
// Seed-dependent: pick the first slug from the list, then fetch it.
|
||||||
|
const list = await request(app).get('/api/discovery/resources').set('auth-token', token);
|
||||||
|
const slug = list.body.results[0] && list.body.results[0].slug;
|
||||||
|
if (!slug) return; // empty seed — skip rather than fail
|
||||||
|
const res = await request(app)
|
||||||
|
.get(`/api/discovery/resources/${encodeURIComponent(slug)}`)
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.results).toBeDefined();
|
||||||
|
expect(res.body.results.slug).toBe(slug);
|
||||||
|
assertNoSecrets([res.body.results], '/resources/:slug');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Discovery — admin projection (requires test user in app_sso_directory_admin)', () => {
|
||||||
|
// If the seed `test` user is a directory admin, /resources should keep
|
||||||
|
// admin-only (non-secret) metadata like redirect_uris/token_lifetime for
|
||||||
|
// them. If not, this assertion is skipped — the no-secrets assertion above
|
||||||
|
// already covers the security guarantee for every caller.
|
||||||
|
test('admin callers keep token_lifetime / redirect_uris (non-secret admin keys)', async () => {
|
||||||
|
const res = await request(app).get('/api/discovery/resources?kind=oauth').set('auth-token', token);
|
||||||
|
const oauth = (res.body.results || []).find(r => r.kind === 'oauth');
|
||||||
|
if (!oauth) return; // no oauth resource seeded
|
||||||
|
// Only meaningful if the caller is an admin; non-admins correctly get
|
||||||
|
// the public allowlist (no redirect_uris). We assert the absence of
|
||||||
|
// secrets regardless, and skip the positive admin check without a known
|
||||||
|
// admin seed.
|
||||||
|
expect(oauth.metadata && oauth.metadata.client_secret_hash).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,10 +2,11 @@
|
|||||||
|
|
||||||
// Flush all test-prefix Redis keys before each test run so state is always clean.
|
// Flush all test-prefix Redis keys before each test run so state is always clean.
|
||||||
// Uses model-redis's own bundled redis client since redis is not a top-level dep.
|
// Uses model-redis's own bundled redis client since redis is not a top-level dep.
|
||||||
const { createClient } = require('../node_modules/model-redis/node_modules/redis');
|
const { createClient } = require('redis');
|
||||||
|
|
||||||
module.exports = async function() {
|
module.exports = async function() {
|
||||||
const client = createClient();
|
const redisUrl = process.env.REDIS_URL || undefined;
|
||||||
|
const client = createClient(redisUrl ? { url: redisUrl } : {});
|
||||||
await client.connect();
|
await client.connect();
|
||||||
|
|
||||||
const keys = await client.keys('sso_manager_test_*');
|
const keys = await client.keys('sso_manager_test_*');
|
||||||
|
|||||||
@@ -151,6 +151,32 @@ describe('Groups — member management', () => {
|
|||||||
const members = Array.isArray(group.member) ? group.member : [group.member];
|
const members = Array.isArray(group.member) ? group.member : [group.member];
|
||||||
expect(members.some(dn => dn && dn.includes(MEMBER_UID))).toBe(false);
|
expect(members.some(dn => dn && dn.includes(MEMBER_UID))).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Regression: adding/removing a member here didn't clear User's LRU
|
||||||
|
// cache (ttl 5 minutes), so isServiceAccount -- derived from
|
||||||
|
// app_sso_service_account membership at GET /api/user/:uid time -- could
|
||||||
|
// stay wrong for up to 5 minutes after the group change. In production
|
||||||
|
// this hid a real person's account from the Users page's "People" tab
|
||||||
|
// (it filters out anything with isServiceAccount) for however long the
|
||||||
|
// stale cache entry lived, which looked exactly like the account had
|
||||||
|
// vanished.
|
||||||
|
test('PUT app_sso_service_account/:uid immediately flips isServiceAccount (no stale cache)', async () => {
|
||||||
|
const added = await request(app)
|
||||||
|
.put(`/api/group/app_sso_service_account/${MEMBER_UID}`)
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(added.status).toBe(200);
|
||||||
|
|
||||||
|
const afterAdd = await request(app).get(`/api/user/${MEMBER_UID}`).set('auth-token', token);
|
||||||
|
expect(afterAdd.body.results.isServiceAccount).toBeTruthy();
|
||||||
|
|
||||||
|
const removed = await request(app)
|
||||||
|
.delete(`/api/group/app_sso_service_account/${MEMBER_UID}`)
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(removed.status).toBe(200);
|
||||||
|
|
||||||
|
const afterRemove = await request(app).get(`/api/user/${MEMBER_UID}`).set('auth-token', token);
|
||||||
|
expect(afterRemove.body.results.isServiceAccount).toBeFalsy();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Groups — owner management', () => {
|
describe('Groups — owner management', () => {
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Nested groups: the API for putting a group inside a group, the cycle guard,
|
||||||
|
// and the thing that makes it worth doing -- membership resolving transitively
|
||||||
|
// through the chain.
|
||||||
|
//
|
||||||
|
// Fixture note that is easy to get wrong: groupOfNames requires at least one
|
||||||
|
// member, so whoever creates a group is seeded into it. `test` creates all
|
||||||
|
// three groups here and would therefore be a *direct* member of each, which
|
||||||
|
// would make "resolved via nesting" indistinguishable from "was already in it".
|
||||||
|
// Setup below strips that back so test's only direct membership is the
|
||||||
|
// innermost group -- and the strip has to happen after nesting, or removing the
|
||||||
|
// sole member would violate the objectClass.
|
||||||
|
|
||||||
|
const { login, request, app } = require('./setup');
|
||||||
|
|
||||||
|
let token;
|
||||||
|
const stamp = Date.now().toString(36);
|
||||||
|
const A = `nesttest-a-${stamp}`; // outermost
|
||||||
|
const B = `nesttest-b-${stamp}`; // middle
|
||||||
|
const C = `nesttest-c-${stamp}`; // innermost, holds the user
|
||||||
|
// A second group nested into A purely so that un-nesting B later does not
|
||||||
|
// empty A -- groupOfNames requires at least one member, and the API correctly
|
||||||
|
// refuses (409) rather than leaving an invalid entry behind.
|
||||||
|
const D = `nesttest-d-${stamp}`;
|
||||||
|
|
||||||
|
async function nest(parent, child) {
|
||||||
|
return request(app).put(`/api/group/${parent}/nested/${child}`).set('auth-token', token).send({});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
token = await login();
|
||||||
|
|
||||||
|
for (const cn of [A, B, C, D]) {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/group')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ name: cn, description: `nesting test ${cn}` });
|
||||||
|
expect([200, 201]).toContain(res.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
expect((await nest(A, B)).status).toBe(200);
|
||||||
|
expect((await nest(B, C)).status).toBe(200);
|
||||||
|
expect((await nest(A, D)).status).toBe(200);
|
||||||
|
|
||||||
|
// Now that A holds B and B holds C, neither would be left memberless.
|
||||||
|
for (const cn of [A, B]) {
|
||||||
|
const res = await request(app).delete(`/api/group/${cn}/test`).set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Nested groups — API guards', () => {
|
||||||
|
test('nesting the same pair twice is a 409, not a duplicate', async () => {
|
||||||
|
const res = await nest(A, B);
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a group cannot contain itself', async () => {
|
||||||
|
const res = await nest(A, A);
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The guard that matters: without it the resolver would silently return a
|
||||||
|
// depth-capped answer instead of an error anyone would notice.
|
||||||
|
test('a direct cycle is refused (A contains B, so B may not contain A)', async () => {
|
||||||
|
const res = await nest(B, A);
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
expect(res.body.message).toMatch(/loop/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an indirect cycle is refused too (A>B>C, so C may not contain A)', async () => {
|
||||||
|
const res = await nest(C, A);
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Nested groups — resolution', () => {
|
||||||
|
test('membership resolves through the whole chain', async () => {
|
||||||
|
const res = await request(app).get('/api/group?member=test').set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.results).toContain(C); // direct
|
||||||
|
expect(res.body.results).toContain(B); // via C
|
||||||
|
expect(res.body.results).toContain(A); // via B -> C
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /:group/effective separates direct members from nested ones', async () => {
|
||||||
|
const res = await request(app).get(`/api/group/${A}/effective`).set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const { direct, nestedGroups, effective } = res.body.results;
|
||||||
|
|
||||||
|
expect(nestedGroups.map(g => g.cn)).toContain(B);
|
||||||
|
// `direct` is users only -- a nested group must never be reported as one.
|
||||||
|
expect(direct.every(dn => !/,ou=groups,/i.test(dn))).toBe(true);
|
||||||
|
// test is not listed on A at all, yet is effectively a member two levels down.
|
||||||
|
expect(direct.some(dn => /cn=test,/i.test(dn))).toBe(false);
|
||||||
|
expect(effective.some(dn => /cn=test,/i.test(dn))).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Nested groups — un-nesting', () => {
|
||||||
|
test('DELETE removes the nesting and the membership it carried', async () => {
|
||||||
|
// Before: A holds B (which holds C, which holds test) and D.
|
||||||
|
const before = await request(app).get(`/api/group/${A}/effective`).set('auth-token', token);
|
||||||
|
expect(before.body.results.nestedGroups.map(g => g.cn)).toContain(B);
|
||||||
|
expect(before.body.results.effective.some(dn => /cn=test,/i.test(dn))).toBe(true);
|
||||||
|
|
||||||
|
const res = await request(app)
|
||||||
|
.delete(`/api/group/${A}/nested/${B}`)
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
|
const after = await request(app).get(`/api/group/${A}/effective`).set('auth-token', token);
|
||||||
|
expect(after.body.results.nestedGroups.map(g => g.cn)).not.toContain(B);
|
||||||
|
expect(after.body.results.nestedGroups.map(g => g.cn)).toContain(D); // untouched
|
||||||
|
|
||||||
|
// test still resolves to B and C directly/through C; only the A path via
|
||||||
|
// B is gone. It is deliberately NOT asserted that test loses A entirely:
|
||||||
|
// D is also nested in A and test created D, so that path remains -- which
|
||||||
|
// is itself a fair illustration of why "who can reach this" has to be
|
||||||
|
// computed rather than eyeballed.
|
||||||
|
const groups = await request(app).get('/api/group?member=test').set('auth-token', token);
|
||||||
|
expect(groups.body.results).toContain(C);
|
||||||
|
expect(groups.body.results).toContain(B);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('un-nesting the last member is refused rather than emptying the group', async () => {
|
||||||
|
// B now holds only C. Removing it would leave B with no members at all,
|
||||||
|
// which groupOfNames forbids.
|
||||||
|
const res = await request(app)
|
||||||
|
.delete(`/api/group/${B}/nested/${C}`)
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
expect(res.body.message).toMatch(/at least one member/i);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Regression guard: native alert()/confirm()/prompt() calls block all further
|
||||||
|
// browser events on the page (found live, mid browser-automation testing, on
|
||||||
|
// directory.ejs's "Rotate Client Secret" — it froze the tab entirely) and are
|
||||||
|
// visually inconsistent with the rest of the UI. Every call site was removed
|
||||||
|
// in favor of app.messages.action/confirm/toast and app.modal.open; this test
|
||||||
|
// keeps it that way.
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const ROOTS = ['views', 'public/js', 'public/lib/js'].map((d) => path.join(__dirname, '..', d));
|
||||||
|
|
||||||
|
// Matches a bare alert(/confirm(/prompt( call, but not app.messages.*,
|
||||||
|
// app.modal.*, or identifiers merely containing these words (e.g.
|
||||||
|
// "confirmation", ".confirmed").
|
||||||
|
const NATIVE_DIALOG_RE = /(^|[^.\w$])(alert|confirm|prompt)\s*\(/g;
|
||||||
|
|
||||||
|
function walk(dir) {
|
||||||
|
let files = [];
|
||||||
|
if (!fs.existsSync(dir)) return files;
|
||||||
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
const full = path.join(dir, entry.name);
|
||||||
|
if (entry.isDirectory()) files = files.concat(walk(full));
|
||||||
|
else if (/\.(ejs|js)$/.test(entry.name)) files.push(full);
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('no view or client-side script calls native alert()/confirm()/prompt()', () => {
|
||||||
|
const offenders = [];
|
||||||
|
for (const root of ROOTS) {
|
||||||
|
for (const file of walk(root)) {
|
||||||
|
const src = fs.readFileSync(file, 'utf8');
|
||||||
|
let m;
|
||||||
|
NATIVE_DIALOG_RE.lastIndex = 0;
|
||||||
|
while ((m = NATIVE_DIALOG_RE.exec(src))) {
|
||||||
|
const line = src.slice(0, m.index).split('\n').length;
|
||||||
|
offenders.push(`${path.relative(path.join(__dirname, '..'), file)}:${line} — ${m[2]}(`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(offenders).toEqual([]);
|
||||||
|
});
|
||||||
@@ -43,6 +43,114 @@ afterAll(async () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('OAuth client management API — /api/oauth/client', () => {
|
||||||
|
// Regression: the ORM Model.toJSON() strips non-schema fields, so the
|
||||||
|
// mapped client_id/scopes/etc. used to vanish from GET responses —
|
||||||
|
// client_id came back undefined and the theta-env bootstrap's rotate
|
||||||
|
// crashed with a 500. GET must expose client_id (and never the secret hash).
|
||||||
|
test('GET / list exposes client_id and hides client_secret_hash', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.get('/api/oauth/client/')
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const mine = res.body.results.find((c) => c.client_id === clientId);
|
||||||
|
expect(mine).toBeDefined();
|
||||||
|
expect(mine.client_id).toBe(clientId);
|
||||||
|
expect(mine).toHaveProperty('scopes');
|
||||||
|
expect(mine).not.toHaveProperty('client_secret_hash');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /:id exposes client_id', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.get(`/api/oauth/client/${clientId}`)
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.results.client_id).toBe(clientId);
|
||||||
|
expect(res.body.results).not.toHaveProperty('client_secret_hash');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('PUT persists — a changed name survives a fresh GET', async () => {
|
||||||
|
const created = await request(app)
|
||||||
|
.post('/api/oauth/client/')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ name: 'put-persist-test', redirect_uris: REDIRECT_URI });
|
||||||
|
expect(created.status).toBe(200);
|
||||||
|
const id = created.body.results.client_id;
|
||||||
|
|
||||||
|
const updated = await request(app)
|
||||||
|
.put(`/api/oauth/client/${id}`)
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ name: 'put-persist-test-renamed' });
|
||||||
|
expect(updated.status).toBe(200);
|
||||||
|
expect(updated.body.results.name).toBe('put-persist-test-renamed');
|
||||||
|
|
||||||
|
const fetched = await request(app).get(`/api/oauth/client/${id}`).set('auth-token', token);
|
||||||
|
expect(fetched.status).toBe(200);
|
||||||
|
expect(fetched.body.results.name).toBe('put-persist-test-renamed');
|
||||||
|
|
||||||
|
await request(app).delete(`/api/oauth/client/${id}`).set('auth-token', token);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Regression: this route called client.remove(), but OAuthClient wraps
|
||||||
|
// @simpleworkjs/orm's Resource model, whose instance method is .delete()
|
||||||
|
// — .remove() doesn't exist on it (unlike the model-redis Tables
|
||||||
|
// elsewhere in this app, e.g. api_token.js, which really do have
|
||||||
|
// .remove()). The route's try/catch turned the resulting TypeError into
|
||||||
|
// a plain 500 JSON response rather than a thrown exception, so every
|
||||||
|
// prior DELETE call in this file's cleanup hooks silently "succeeded"
|
||||||
|
// from Jest's point of view while leaving the client un-deleted.
|
||||||
|
test('DELETE persists — the client is actually gone, not just a 200', async () => {
|
||||||
|
const created = await request(app)
|
||||||
|
.post('/api/oauth/client/')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ name: 'delete-persist-test', redirect_uris: REDIRECT_URI });
|
||||||
|
expect(created.status).toBe(200);
|
||||||
|
const id = created.body.results.client_id;
|
||||||
|
|
||||||
|
const deleted = await request(app).delete(`/api/oauth/client/${id}`).set('auth-token', token);
|
||||||
|
expect(deleted.status).toBe(200);
|
||||||
|
|
||||||
|
const fetched = await request(app).get(`/api/oauth/client/${id}`).set('auth-token', token);
|
||||||
|
expect(fetched.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('list then rotate a client by its returned client_id (the bootstrap path)', async () => {
|
||||||
|
// Reproduces exactly what the theta-env bootstrap does: create, list,
|
||||||
|
// find by name, rotate by the client_id from the list response. Uses a
|
||||||
|
// throwaway client so the shared flow client's secret is untouched.
|
||||||
|
const created = await request(app)
|
||||||
|
.post('/api/oauth/client/')
|
||||||
|
.set('auth-token', token)
|
||||||
|
.send({ name: 'rotate-regression', redirect_uris: REDIRECT_URI });
|
||||||
|
expect(created.status).toBe(200);
|
||||||
|
|
||||||
|
const list = await request(app).get('/api/oauth/client/').set('auth-token', token);
|
||||||
|
const found = list.body.results.find((c) => c.name === 'rotate-regression');
|
||||||
|
expect(found).toBeDefined();
|
||||||
|
expect(found.client_id).toBeTruthy(); // was undefined before the fix
|
||||||
|
|
||||||
|
const rotated = await request(app)
|
||||||
|
.post(`/api/oauth/client/${found.client_id}/rotate`)
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(rotated.status).toBe(200);
|
||||||
|
expect(rotated.body.client_secret).toBeTruthy();
|
||||||
|
|
||||||
|
const deleted = await request(app).delete(`/api/oauth/client/${found.client_id}`).set('auth-token', token);
|
||||||
|
expect(deleted.status).toBe(200);
|
||||||
|
|
||||||
|
const afterDelete = await request(app).get(`/api/oauth/client/${found.client_id}`).set('auth-token', token);
|
||||||
|
expect(afterDelete.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /:id unknown id returns 404, not 500', async () => {
|
||||||
|
const res = await request(app)
|
||||||
|
.get('/api/oauth/client/00000000-0000-0000-0000-000000000000')
|
||||||
|
.set('auth-token', token);
|
||||||
|
expect(res.status).toBeGreaterThanOrEqual(400);
|
||||||
|
expect(res.status).toBeLessThan(500);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('OIDC Discovery', () => {
|
describe('OIDC Discovery', () => {
|
||||||
test('GET /.well-known/openid-configuration returns required fields', async () => {
|
test('GET /.well-known/openid-configuration returns required fields', async () => {
|
||||||
const res = await request(app).get('/.well-known/openid-configuration');
|
const res = await request(app).get('/.well-known/openid-configuration');
|
||||||
|
|||||||
@@ -1,112 +0,0 @@
|
|||||||
'use strict';
|
|
||||||
|
|
||||||
const { login, request, app } = require('./setup');
|
|
||||||
|
|
||||||
const TEST_CLIENT = {
|
|
||||||
name: 'Test Client',
|
|
||||||
description: 'Created by automated tests',
|
|
||||||
redirect_uris: 'https://test.example.com/callback',
|
|
||||||
scopes: 'openid profile email',
|
|
||||||
token_lifetime: { access_token: 3600, refresh_token: 86400 },
|
|
||||||
};
|
|
||||||
|
|
||||||
let token;
|
|
||||||
let clientId;
|
|
||||||
let clientSecret;
|
|
||||||
|
|
||||||
beforeAll(async () => {
|
|
||||||
token = await login();
|
|
||||||
});
|
|
||||||
|
|
||||||
afterAll(async () => {
|
|
||||||
if (clientId) {
|
|
||||||
await request(app)
|
|
||||||
.delete(`/api/oauth/client/${clientId}`)
|
|
||||||
.set('auth-token', token);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('OAuth Clients — POST /api/oauth/client/', () => {
|
|
||||||
test('creates a new client and returns one-time secret', async () => {
|
|
||||||
const res = await request(app)
|
|
||||||
.post('/api/oauth/client/')
|
|
||||||
.set('auth-token', token)
|
|
||||||
.send(TEST_CLIENT);
|
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(res.body).toHaveProperty('results');
|
|
||||||
expect(res.body).toHaveProperty('client_secret');
|
|
||||||
expect(res.body.results).toHaveProperty('client_id');
|
|
||||||
expect(res.body.results).toHaveProperty('name', TEST_CLIENT.name);
|
|
||||||
expect(res.body.results.client_id.length).toBeGreaterThan(0);
|
|
||||||
|
|
||||||
clientId = res.body.results.client_id;
|
|
||||||
clientSecret = res.body.client_secret;
|
|
||||||
});
|
|
||||||
|
|
||||||
test('requires oauth_admin group — 401 not shown here (see group membership)', () => {
|
|
||||||
// If test user is not in app_sso_oauth_admin, the test above will fail with 401.
|
|
||||||
// That itself is the correct behavior to verify.
|
|
||||||
expect(clientId).toBeDefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('OAuth Clients — GET /api/oauth/client/', () => {
|
|
||||||
test('lists clients including the test client', async () => {
|
|
||||||
const res = await request(app)
|
|
||||||
.get('/api/oauth/client/')
|
|
||||||
.set('auth-token', token);
|
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(Array.isArray(res.body.results)).toBe(true);
|
|
||||||
const found = res.body.results.find(c => c.client_id === clientId);
|
|
||||||
expect(found).toBeDefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('OAuth Clients — GET /api/oauth/client/:id', () => {
|
|
||||||
test('returns the test client by id', async () => {
|
|
||||||
const res = await request(app)
|
|
||||||
.get(`/api/oauth/client/${clientId}`)
|
|
||||||
.set('auth-token', token);
|
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(res.body.results).toHaveProperty('client_id', clientId);
|
|
||||||
expect(res.body.results).toHaveProperty('name', TEST_CLIENT.name);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('unknown client_id returns 404 or error', async () => {
|
|
||||||
const res = await request(app)
|
|
||||||
.get('/api/oauth/client/00000000-0000-0000-0000-000000000000')
|
|
||||||
.set('auth-token', token);
|
|
||||||
|
|
||||||
expect(res.status).toBeGreaterThanOrEqual(400);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('OAuth Clients — PUT /api/oauth/client/:id', () => {
|
|
||||||
test('updates the client description', async () => {
|
|
||||||
const res = await request(app)
|
|
||||||
.put(`/api/oauth/client/${clientId}`)
|
|
||||||
.set('auth-token', token)
|
|
||||||
.send({ description: 'Updated by test' });
|
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(res.body).toHaveProperty('message');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('OAuth Clients — POST /api/oauth/client/:id/rotate', () => {
|
|
||||||
test('rotates the client secret and returns a new one', async () => {
|
|
||||||
const res = await request(app)
|
|
||||||
.post(`/api/oauth/client/${clientId}/rotate`)
|
|
||||||
.set('auth-token', token);
|
|
||||||
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(res.body).toHaveProperty('client_secret');
|
|
||||||
expect(typeof res.body.client_secret).toBe('string');
|
|
||||||
expect(res.body.client_secret).not.toBe(clientSecret);
|
|
||||||
|
|
||||||
clientSecret = res.body.client_secret;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
require('./setup');
|
||||||
|
const { Resource } = require('../models/resource');
|
||||||
|
const { DiscoveryReconciler } = require('../services/discovery_reconciler');
|
||||||
|
|
||||||
|
describe('DiscoveryReconciler', () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
// Clear resources before each test
|
||||||
|
const all = await Resource.list();
|
||||||
|
for (const r of all) {
|
||||||
|
await r.delete();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create a new device if no MAC or IP matches', async () => {
|
||||||
|
const payload = {
|
||||||
|
resources: [{
|
||||||
|
kind: 'host',
|
||||||
|
name: 'New Host',
|
||||||
|
slug: 'new-host',
|
||||||
|
metadata: {
|
||||||
|
interfaces: [{ mac: '00:11:22:33:44:55', ip: '192.168.1.100' }]
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
};
|
||||||
|
|
||||||
|
await DiscoveryReconciler.reconcile('test-plugin', payload);
|
||||||
|
|
||||||
|
const all = await Resource.list();
|
||||||
|
expect(all).toHaveLength(1);
|
||||||
|
expect(all[0].name).toBe('New Host');
|
||||||
|
expect(all[0].metadata.discovery_sources).toContain('test-plugin');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should merge into an existing device if MAC matches', async () => {
|
||||||
|
// 1. Initial creation
|
||||||
|
await DiscoveryReconciler.reconcile('plugin-A', {
|
||||||
|
resources: [{
|
||||||
|
kind: 'unmanaged_device',
|
||||||
|
name: 'Old Host',
|
||||||
|
slug: 'old-host',
|
||||||
|
metadata: {
|
||||||
|
os: 'Linux',
|
||||||
|
interfaces: [{ mac: 'AA:BB:CC:DD:EE:FF', ip: '10.0.0.5' }]
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. Secondary discovery from a different plugin, same MAC but new IP
|
||||||
|
await DiscoveryReconciler.reconcile('plugin-B', {
|
||||||
|
resources: [{
|
||||||
|
kind: 'host',
|
||||||
|
name: 'Updated Host', // Name updates aren't overwritten in simple merge, but let's see
|
||||||
|
metadata: {
|
||||||
|
cpu_cores: 4,
|
||||||
|
interfaces: [{ mac: 'AA:BB:CC:DD:EE:FF', ip: '10.0.0.6' }]
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
|
||||||
|
const all = await Resource.list();
|
||||||
|
expect(all).toHaveLength(1); // Should have merged, not created a new one
|
||||||
|
|
||||||
|
const merged = all[0];
|
||||||
|
expect(merged.metadata.discovery_sources).toContain('plugin-A');
|
||||||
|
expect(merged.metadata.discovery_sources).toContain('plugin-B');
|
||||||
|
|
||||||
|
// Metadata should be merged
|
||||||
|
expect(merged.metadata.os).toBe('Linux');
|
||||||
|
expect(merged.metadata.cpu_cores).toBe(4);
|
||||||
|
|
||||||
|
// Interface array should be merged/updated
|
||||||
|
expect(merged.metadata.interfaces).toHaveLength(1);
|
||||||
|
expect(merged.metadata.interfaces[0].ip).toBe('10.0.0.6'); // Updated IP
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// findAncestorSiteSlug has no LDAP dependency (unlike most of this test
|
||||||
|
// suite, which needs a live LDAP server) -- it's pure Resource/ResourceEdge
|
||||||
|
// graph traversal against the ORM, so it's tested directly here rather than
|
||||||
|
// through the (LDAP-gated) directory-admin HTTP routes.
|
||||||
|
|
||||||
|
const { initORM } = require('../models');
|
||||||
|
const { Resource, ResourceEdge } = require('../models/resource');
|
||||||
|
|
||||||
|
const marker = 'test_site_slug_' + Date.now();
|
||||||
|
const created = [];
|
||||||
|
|
||||||
|
async function makeResource(kind, name) {
|
||||||
|
const r = await Resource.create({ kind, name, slug: `${marker}_${name}` });
|
||||||
|
created.push(r);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
await initORM();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
for (const r of created) {
|
||||||
|
try { await r.delete(); } catch (_) {}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Resource.findAncestorSiteSlug', () => {
|
||||||
|
test('returns the direct parent site\'s slug', async () => {
|
||||||
|
const site = await makeResource('site', 'site-direct');
|
||||||
|
const host = await makeResource('host', 'host-direct');
|
||||||
|
await ResourceEdge.create({ parentId: site.id, childId: host.id, relation: 'hosts' });
|
||||||
|
|
||||||
|
await expect(Resource.findAncestorSiteSlug(host.id)).resolves.toBe(site.slug);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('walks up through an intermediate host to find the owning site', async () => {
|
||||||
|
const site = await makeResource('site', 'site-nested');
|
||||||
|
const host = await makeResource('host', 'host-nested');
|
||||||
|
const service = await makeResource('service', 'service-nested');
|
||||||
|
await ResourceEdge.create({ parentId: site.id, childId: host.id, relation: 'hosts' });
|
||||||
|
await ResourceEdge.create({ parentId: host.id, childId: service.id, relation: 'hosts' });
|
||||||
|
|
||||||
|
await expect(Resource.findAncestorSiteSlug(service.id)).resolves.toBe(site.slug);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns null for a top-level resource with no site ancestor', async () => {
|
||||||
|
const host = await makeResource('host', 'host-orphan');
|
||||||
|
|
||||||
|
await expect(Resource.findAncestorSiteSlug(host.id)).resolves.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not loop forever on a cyclic parent chain', async () => {
|
||||||
|
const a = await makeResource('host', 'host-cycle-a');
|
||||||
|
const b = await makeResource('host', 'host-cycle-b');
|
||||||
|
await ResourceEdge.create({ parentId: a.id, childId: b.id, relation: 'hosts' });
|
||||||
|
await ResourceEdge.create({ parentId: b.id, childId: a.id, relation: 'hosts' });
|
||||||
|
|
||||||
|
await expect(Resource.findAncestorSiteSlug(a.id)).resolves.toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -3,6 +3,19 @@
|
|||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
const request = require('supertest');
|
const request = require('supertest');
|
||||||
const app = require('../app');
|
const app = require('../app');
|
||||||
|
const { initORM } = require('../models');
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
await initORM();
|
||||||
|
const { Token } = require('../models/token');
|
||||||
|
try {
|
||||||
|
if (Token.orm) {
|
||||||
|
await Token.orm.adapter(Token).Table.redisClient.flushDb();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('Could not flush Redis:', e.message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const TEST_CREDS = { uid: 'test', password: 'MyTestPassword!2' };
|
const TEST_CREDS = { uid: 'test', password: 'MyTestPassword!2' };
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
require('./setup');
|
||||||
|
const { Webhook } = require('../models/webhook');
|
||||||
|
const { WebhookEmitter } = require('../services/webhook_emitter');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
describe('WebhookEmitter', () => {
|
||||||
|
let webhook;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
// Clear webhooks before each test
|
||||||
|
const all = await Webhook.list();
|
||||||
|
for (const w of all) {
|
||||||
|
await w.delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
webhook = await Webhook.create({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
name: 'Test Webhook',
|
||||||
|
url: 'http://localhost:9999/dummy',
|
||||||
|
events: ['discovery.new_device'],
|
||||||
|
secret: 'mysecret',
|
||||||
|
created_on: Math.floor(Date.now() / 1000)
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not throw when emitting an event', async () => {
|
||||||
|
// We expect this to fail network connection but be caught gracefully by the emitter
|
||||||
|
await WebhookEmitter.emit('discovery.new_device', { name: 'Device1' });
|
||||||
|
// If it doesn't throw, test passes
|
||||||
|
expect(true).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||