bindarr icon indicating copy to clipboard operation
bindarr copied to clipboard

Feature request: OIDC / SSO login support (e.g. Authelia, Authentik, Keycloak)

Open JGHCode opened this issue 3 months ago • 5 comments

Summary

Would love to see OIDC login support in Bindarr, so it can sit behind a self-hosted identity provider (Authelia, Authentik, Keycloak, etc.) instead of needing a separate Bindarr-specific username/password.

I had a brief glance at auth.js / middleware/auth.js to get a feel for how this might fit in, and wanted to share some thoughts in case they're useful - but very much just a starting point. Would have tried to make it myself but figured this was better submitted as an issue rather than a contribution PR, since it touches the auth code and I figure that is something that should be somewhat off limits to unknown external contributors.

Why OIDC rather than reverse-proxy header auth

There are two common ways apps add SSO support: trusting a header set by a reverse proxy (forward-auth), or acting as a proper OIDC client. I initially considered the header approach given Bindarr's likely deployed behind Traefik/nginx for most self-hosters, but landed on OIDC as probably the better fit, since:

  • it doesn't depend on trusting network position or proxy configuration as the identity token is cryptographically verified, not inferred from "this header must mean Traefik set it". This makes it more secure.
  • it works the same regardless of reverse proxy choice (or no proxy at all) which means better adoption for the app.
  • it's the pattern other self-hosted apps in this space already use — e.g. RomM's, for example, has a compose that does exactly this against Authelia:
    - OIDC_ENABLED=true
    - OIDC_PROVIDER_NAME=Authelia
    - OIDC_CLIENT_ID=romm
    - OIDC_CLIENT_SECRET=${OIDC_PLAIN_SECRET}
    - OIDC_SERVER_APPLICATION_URL=${AUTH_URL}
    - OIDC_REDIRECT_URI=${ROM_BASE_URL}/api/oauth/openid
    - OIDC_USER_CLAIM=preferred_username
    
    Mirroring a similar env-var shape might make this feel familiar to anyone already running a stack with other self-hosted apps.

Rough shape of what's involved

Library: openid-client (npm) seems like a solid fit. This handles discovery, PKCE, and ID token signature verification, rather than anything needing to be hand-rolled.

New backend pieces:

  • A small module to run OIDC discovery against the issuer's .well-known/openid-configuration on startup when enabled, building a reusable client instance.
  • Two new routes in backend/src/routes/auth.js, e.g.:
    • GET /api/auth/oidc/login : redirect to the provider's authorization endpoint
    • GET /api/auth/oidc/callback : exchange the code for tokens, verify the ID token, map the configured claim (e.g. preferred_username) to an existing Bindarr user (or create one), then reuse the existing generateSession() so everything downstream, session table, authenticateToken middleware, etc. stays exactly as it is today

Env vars (borrowing RomM's naming as a reasonable starting point):

OIDC_ENABLED
OIDC_PROVIDER_NAME
OIDC_CLIENT_ID
OIDC_CLIENT_SECRET
OIDC_ISSUER_URL
OIDC_REDIRECT_URI
OIDC_USER_CLAIM

Frontend: extend the existing GET /api/auth/config response with oidcEnabled/oidcProviderName, and show a "Log in with OIDC" button on the login screen under the existing form (keeping local login as a fallback seems worth doing, so an IdP outage doesn't lock everyone out).

Open questions

  • Auto-provisioning: should a first-time OIDC login automatically create a Bindarr account, or should an admin need to pre-create/link one? Both seem reasonable, auto-provision is more convenient, pre-linking is more conservative for an invite-only app like this one. Maybe some mix of the two depending on admin settings?

Totally open to any of this being wrong or overcomplicated for what Bindarr actually needs - mainly wanted to put down what I found while poking around the auth code, in case it saves some initial research time either way. This would certainly bring the end user experience into alignment with what other self hosted apps already offer, reducing the login fatigue for my users by enabling single sign-on.

Am happy to test against a real Authelia instance once/if there's something to try.

JGHCode avatar Aug 21 '26 15:08 JGHCode

Hey, I'm completely unfamilar with OIDC but I agree that this is a great thing to work on implementing.

thenotoriousJeremy avatar Aug 21 '26 18:08 thenotoriousJeremy

Found a small bug in the current implementation so have fixed and created a pull request into the feature branch: #46

JGHCode avatar Aug 21 '26 21:08 JGHCode

I went through backend/src/routes/auth.js and backend/src/utils/oidc.js while fixing and testing this on real hardware (Authelia + Traefik). Overall the shape of this is solid - PKCE, HMAC-signed state tokens with TTL, timing-safe comparison, discovery caching - but I found one issue I'd treat as blocking, plus a few worth a look before merge into main.


Blocking: account takeover via username-only linking

// 2. Fallback: match by username and link oidc_sub
if (!user) {
  const existingUser = await db.get(`SELECT * FROM users WHERE username = ?`, [username]);
  if (existingUser) {
    await db.run(`UPDATE users SET oidc_sub = ? WHERE id = ?`, [sub, existingUser.id]);
    user = await db.get(`SELECT * FROM users WHERE id = ?`, [existingUser.id]);
  }
}

Any OIDC login whose username matches an existing local account gets silently and permanently linked to it - no password confirmation, no "you must already be logged in to link SSO," no notification to the account owner. Whoever completes that SSO login is now that user, full stop.

This is not usually an issue (indeed, often this is a feature) however this is especially sharp given that this project has an owner account that always has a fixed, predictable username (OWNER_USERNAME = 'admin'). Any IdP setup where an attacker can influence or predict what preferred_username (or whatever OIDC_USER_CLAIM points at) gets reported - self-registration enabled on the IdP side, LDAP/AD with a matching account, etc. - is a direct path to the admin account, not just a member one.

Suggestion: linking an existing account to an SSO identity probably shouldn't happen implicitly on first login without some further checks or balances. At the very least - any admin accounts should not allow silent linking. Either require the user to already be authenticated and explicitly link from Settings, or gate the fallback match on a verified email claim rather than username string equality. Probably the most elegant solution would be to require the user enter their existing accounts password before linking on first login with SSO if possible.


Worth addressing: ID token isn't signature-verified

// Decode JWT payload without verification (verification done by TLS + token_endpoint exchange).
function parseJwtPayload(token) { ... }

No signature check against the provider's JWKS, no aud check against OIDC_CLIENT_ID, no iss check, no exp/nbf. The comment's reasoning (TLS + direct token-endpoint exchange) narrows real-world exploitability somewhat, but it's a real gap from spec, and it's exactly what a library like openid-client would handle for free rather than hand-rolling. Particularly relevant if Authelia (or whatever IdP) ever serves more than one registered client - nothing here would catch a token issued for a different client_id ending up in this flow.

nonce generated but never validated

buildAuthorizationUrl generates a nonce, sends it to the IdP, and stores it in the state token - but exchangeCode never compares idTokenClaims.nonce against the stored value afterward. As-is it's collected but not enforced, which defeats its purpose (binding the ID token to this specific login attempt).

Session token passed via URL query string

return frontendRedirect({ oidc_token: token });

Lands the live session token in the browser URL after login - visible in server access logs, browser history, and potentially leaked via Referer on any cross-origin request before the query string is cleared. If the frontend immediately does history.replaceState after reading it, exposure is small; if not, worth tightening.

Smaller things to make it more robust

  • OIDC_DEFAULT_ROLE=admin makes every auto-provisioned SSO login an admin, not just the first — not a bug, but worth a loud callout in the docs/env example given how easy it'd be to leave set after initial setup. Maybe better to have 'admin_first_only' as an option that explicitly creates an admin for only the first SSO account that is logged in then downgrades to member for all future accounts.
  • error/error_description from the callback query string get redirected straight into the frontend as oidc_error. Since /oidc/callback is public and unauthenticated, that content isn't guaranteed to come from the real IdP - worth confirming the frontend renders it as plain text rather than assuming it's always trusted.

Happy to open these as separate follow-up issues if that's easier to track than one combined comment - let me know what's preferred. Tested against a live Authelia instance on arm64; the happy-path login itself worked cleanly, these are all things I found reading through the code rather than things I hit in normal testing.

JGHCode avatar Aug 21 '26 21:08 JGHCode

This is in on main now. Thank you for the write-up — the shape you sketched is essentially what got built, and it did save the research time.

What landed

#45, with a dependency-free client rather than openid-client: discovery against .well-known/openid-configuration, authorization-code flow with PKCE S256, HMAC-SHA256 signed state for CSRF, an oidc_sub column on users, and the session issued through the existing generateSession() — so the session table and authenticateToken are untouched, exactly as you suggested. Local login stays as a fallback. GET /api/auth/config gained oidcEnabled / oidcProviderName and the login screen shows the provider button under the form.

Env vars follow the RomM-ish naming you proposed: OIDC_ENABLED, OIDC_PROVIDER_NAME, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, OIDC_ISSUER_URL, OIDC_REDIRECT_URI, OIDC_USER_CLAIM, plus OIDC_SCOPES, OIDC_DEFAULT_ROLE and the two below.

Two fixes went in before it merged

#46 (thanks @JGHCode) — the token exchange was sending client_secret in the body and an HTTP Basic header at the same time, which most IdPs reject with a 400. OIDC_TOKEN_ENDPOINT_AUTH_METHOD now selects client_secret_basic (default), client_secret_post or none. Verified against a self-hosted Authentik.

#55 — the security hole @JGHCode spotted while testing that, and deliberately left out of scope. When no account matched on oidc_sub, the callback fell back to matching on username and bound the identity to whatever it found. The username is a claim the IdP sends, it gets lower-cased, and the Bindarr owner account is always admin. So on any IdP where a person can choose their own preferred_username, setting it to admin and signing in once handed them the owner account. No password involved anywhere.

That is now OIDC_ALLOW_USERNAME_LINK, default off. It cannot just be deleted — matching by username is how an install that predates SSO gets its existing accounts, and the collections behind them, onto the IdP — so the operator states whether their IdP's usernames can be trusted for it. With it off, an SSO login whose username is already taken is refused with a message naming the setting, rather than quietly handing the user a second empty admin-1 account. With it on, an account already bound to a different identity is still never re-bound.

There are three e2e cases covering that (F7-TC8 through F7-TC10), including the takeover attempt itself.

Your open question — auto-provisioning

Both, configurably: OIDC_AUTO_PROVISION (default true) creates a member account on first login, OIDC_DEFAULT_ROLE sets what they get, and with it off an unknown identity is told to ask an administrator. The first identity to sign in on an empty instance is bootstrapped as the owner.

This is on main but not tagged yet — it will be on ghcr.io/thenotoriousjeremy/bindarr:edge shortly, and I would genuinely welcome a report from an Authelia or Keycloak setup before it goes into a release. Closing as delivered; please open a new issue if your provider does something these three do not.

thenotoriousJeremy avatar Sep 10 '26 14:09 thenotoriousJeremy

Follow-up on this, since #45 shipped with a gap worth naming publicly rather than leaving in a PR description.

#56 is now merged. The ID token was being base64-decoded and used — parseJwtPayload is a JSON.parse of the middle segment — with nothing checking who issued it, who it was for, whether it had expired, or whether it belonged to the login in progress.

Four checks added:

  • nonce — the one that actually mattered. buildAuthorizationUrl has generated a nonce, sent it to the IdP and sealed it into the signed state token since day one. Nothing ever compared it to the claim coming back. A nonce that is generated and never checked is worse than no nonce: it reads as replay protection in review and provides none.
  • iss — plus getDiscovery now enforces Discovery §4.3, that the document's own issuer is the one we asked for. Without that, iss had nothing honest to be measured against.
  • aud — a valid, correctly signed token minted for a different client of the same IdP was accepted. Also checks azp where there are several audiences.
  • exp — was not checked at all. 60s of skew allowed, because container clocks drift.

OIDC_ISSUER_URL must now be https, loopback excepted. All four rest on the connection being trustworthy, and over plain HTTP none of them mean anything.

The signature is still not verified, deliberately: the token arrives from the token endpoint over a direct TLS back-channel, which OIDC Core §3.1.3.7 permits as a substitute. JWKS fetching, caching and rotation is a few hundred lines against a threat the transport already covers. If someone hits a provider where that reasoning does not hold, please open an issue and I will revisit.

@JGHCode — you found the first two problems here (#46 and the username-linking hole behind #55). Thank you, genuinely; that is three security-relevant fixes before this reached a release rather than after.

Still on main only, not tagged. ghcr.io/thenotoriousjeremy/bindarr:edge has all of it, and a report from a real Authelia or Keycloak setup is still the thing I would most like before this goes into a release.

thenotoriousJeremy avatar Sep 10 '26 14:09 thenotoriousJeremy